file_name
stringlengths 71
779k
| comments
stringlengths 20
182k
| code_string
stringlengths 20
36.9M
| __index_level_0__
int64 0
17.2M
| input_ids
sequence | attention_mask
sequence | labels
sequence |
---|---|---|---|---|---|---|
// Dependency file: @chainlink/contracts/src/v0.6/vendor/SafeMathChainlink.sol
// SPDX-License-Identifier: MIT
// pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMathChainlink {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, "SafeMath: division by zero");
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "SafeMath: modulo by zero");
return a % b;
}
}
// Dependency file: @chainlink/contracts/src/v0.6/interfaces/LinkTokenInterface.sol
// pragma solidity ^0.6.0;
interface LinkTokenInterface {
function allowance(address owner, address spender) external view returns (uint256 remaining);
function approve(address spender, uint256 value) external returns (bool success);
function balanceOf(address owner) external view returns (uint256 balance);
function decimals() external view returns (uint8 decimalPlaces);
function decreaseApproval(address spender, uint256 addedValue) external returns (bool success);
function increaseApproval(address spender, uint256 subtractedValue) external;
function name() external view returns (string memory tokenName);
function symbol() external view returns (string memory tokenSymbol);
function totalSupply() external view returns (uint256 totalTokensIssued);
function transfer(address to, uint256 value) external returns (bool success);
function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool success);
function transferFrom(address from, address to, uint256 value) external returns (bool success);
}
// Dependency file: @chainlink/contracts/src/v0.6/VRFRequestIDBase.sol
// pragma solidity ^0.6.0;
contract VRFRequestIDBase {
/**
* @notice returns the seed which is actually input to the VRF coordinator
*
* @dev To prevent repetition of VRF output due to repetition of the
* @dev user-supplied seed, that seed is combined in a hash with the
* @dev user-specific nonce, and the address of the consuming contract. The
* @dev risk of repetition is mostly mitigated by inclusion of a blockhash in
* @dev the final seed, but the nonce does protect against repetition in
* @dev requests which are included in a single block.
*
* @param _userSeed VRF seed input provided by user
* @param _requester Address of the requesting contract
* @param _nonce User-specific nonce at the time of the request
*/
function makeVRFInputSeed(bytes32 _keyHash, uint256 _userSeed,
address _requester, uint256 _nonce)
internal pure returns (uint256)
{
return uint256(keccak256(abi.encode(_keyHash, _userSeed, _requester, _nonce)));
}
/**
* @notice Returns the id for this request
* @param _keyHash The serviceAgreement ID to be used for this request
* @param _vRFInputSeed The seed to be passed directly to the VRF
* @return The id for this request
*
* @dev Note that _vRFInputSeed is not the seed passed by the consuming
* @dev contract, but the one generated by makeVRFInputSeed
*/
function makeRequestId(
bytes32 _keyHash, uint256 _vRFInputSeed) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(_keyHash, _vRFInputSeed));
}
}
// Dependency file: @chainlink/contracts/src/v0.6/VRFConsumerBase.sol
// pragma solidity ^0.6.0;
// import "@chainlink/contracts/src/v0.6/vendor/SafeMathChainlink.sol";
// import "@chainlink/contracts/src/v0.6/interfaces/LinkTokenInterface.sol";
// import "@chainlink/contracts/src/v0.6/VRFRequestIDBase.sol";
/** ****************************************************************************
* @notice Interface for contracts using VRF randomness
* *****************************************************************************
* @dev PURPOSE
*
* @dev Reggie the Random Oracle (not his real job) wants to provide randomness
* @dev to Vera the verifier in such a way that Vera can be sure he's not
* @dev making his output up to suit himself. Reggie provides Vera a public key
* @dev to which he knows the secret key. Each time Vera provides a seed to
* @dev Reggie, he gives back a value which is computed completely
* @dev deterministically from the seed and the secret key.
*
* @dev Reggie provides a proof by which Vera can verify that the output was
* @dev correctly computed once Reggie tells it to her, but without that proof,
* @dev the output is indistinguishable to her from a uniform random sample
* @dev from the output space.
*
* @dev The purpose of this contract is to make it easy for unrelated contracts
* @dev to talk to Vera the verifier about the work Reggie is doing, to provide
* @dev simple access to a verifiable source of randomness.
* *****************************************************************************
* @dev USAGE
*
* @dev Calling contracts must inherit from VRFConsumerBase, and can
* @dev initialize VRFConsumerBase's attributes in their constructor as
* @dev shown:
*
* @dev contract VRFConsumer {
* @dev constuctor(<other arguments>, address _vrfCoordinator, address _link)
* @dev VRFConsumerBase(_vrfCoordinator, _link) public {
* @dev <initialization with other arguments goes here>
* @dev }
* @dev }
*
* @dev The oracle will have given you an ID for the VRF keypair they have
* @dev committed to (let's call it keyHash), and have told you the minimum LINK
* @dev price for VRF service. Make sure your contract has sufficient LINK, and
* @dev call requestRandomness(keyHash, fee, seed), where seed is the input you
* @dev want to generate randomness from.
*
* @dev Once the VRFCoordinator has received and validated the oracle's response
* @dev to your request, it will call your contract's fulfillRandomness method.
*
* @dev The randomness argument to fulfillRandomness is the actual random value
* @dev generated from your seed.
*
* @dev The requestId argument is generated from the keyHash and the seed by
* @dev makeRequestId(keyHash, seed). If your contract could have concurrent
* @dev requests open, you can use the requestId to track which seed is
* @dev associated with which randomness. See VRFRequestIDBase.sol for more
* @dev details. (See "SECURITY CONSIDERATIONS" for principles to keep in mind,
* @dev if your contract could have multiple requests in flight simultaneously.)
*
* @dev Colliding `requestId`s are cryptographically impossible as long as seeds
* @dev differ. (Which is critical to making unpredictable randomness! See the
* @dev next section.)
*
* *****************************************************************************
* @dev SECURITY CONSIDERATIONS
*
* @dev A method with the ability to call your fulfillRandomness method directly
* @dev could spoof a VRF response with any random value, so it's critical that
* @dev it cannot be directly called by anything other than this base contract
* @dev (specifically, by the VRFConsumerBase.rawFulfillRandomness method).
*
* @dev For your users to trust that your contract's random behavior is free
* @dev from malicious interference, it's best if you can write it so that all
* @dev behaviors implied by a VRF response are executed *during* your
* @dev fulfillRandomness method. If your contract must store the response (or
* @dev anything derived from it) and use it later, you must ensure that any
* @dev user-significant behavior which depends on that stored value cannot be
* @dev manipulated by a subsequent VRF request.
*
* @dev Similarly, both miners and the VRF oracle itself have some influence
* @dev over the order in which VRF responses appear on the blockchain, so if
* @dev your contract could have multiple VRF requests in flight simultaneously,
* @dev you must ensure that the order in which the VRF responses arrive cannot
* @dev be used to manipulate your contract's user-significant behavior.
*
* @dev Since the ultimate input to the VRF is mixed with the block hash of the
* @dev block in which the request is made, user-provided seeds have no impact
* @dev on its economic security properties. They are only included for API
* @dev compatability with previous versions of this contract.
*
* @dev Since the block hash of the block which contains the requestRandomness
* @dev call is mixed into the input to the VRF *last*, a sufficiently powerful
* @dev miner could, in principle, fork the blockchain to evict the block
* @dev containing the request, forcing the request to be included in a
* @dev different block with a different hash, and therefore a different input
* @dev to the VRF. However, such an attack would incur a substantial economic
* @dev cost. This cost scales with the number of blocks the VRF oracle waits
* @dev until it calls responds to a request.
*/
abstract contract VRFConsumerBase is VRFRequestIDBase {
using SafeMathChainlink for uint256;
/**
* @notice fulfillRandomness handles the VRF response. Your contract must
* @notice implement it. See "SECURITY CONSIDERATIONS" above for important
* @notice principles to keep in mind when implementing your fulfillRandomness
* @notice method.
*
* @dev VRFConsumerBase expects its subcontracts to have a method with this
* @dev signature, and will call it once it has verified the proof
* @dev associated with the randomness. (It is triggered via a call to
* @dev rawFulfillRandomness, below.)
*
* @param requestId The Id initially returned by requestRandomness
* @param randomness the VRF output
*/
function fulfillRandomness(bytes32 requestId, uint256 randomness)
internal virtual;
/**
* @notice requestRandomness initiates a request for VRF output given _seed
*
* @dev The fulfillRandomness method receives the output, once it's provided
* @dev by the Oracle, and verified by the vrfCoordinator.
*
* @dev The _keyHash must already be registered with the VRFCoordinator, and
* @dev the _fee must exceed the fee specified during registration of the
* @dev _keyHash.
*
* @dev The _seed parameter is vestigial, and is kept only for API
* @dev compatibility with older versions. It can't *hurt* to mix in some of
* @dev your own randomness, here, but it's not necessary because the VRF
* @dev oracle will mix the hash of the block containing your request into the
* @dev VRF seed it ultimately uses.
*
* @param _keyHash ID of public key against which randomness is generated
* @param _fee The amount of LINK to send with the request
* @param _seed seed mixed into the input of the VRF.
*
* @return requestId unique ID for this request
*
* @dev The returned requestId can be used to distinguish responses to
* @dev concurrent requests. It is passed as the first argument to
* @dev fulfillRandomness.
*/
function requestRandomness(bytes32 _keyHash, uint256 _fee, uint256 _seed)
internal returns (bytes32 requestId)
{
LINK.transferAndCall(vrfCoordinator, _fee, abi.encode(_keyHash, _seed));
// This is the seed passed to VRFCoordinator. The oracle will mix this with
// the hash of the block containing this request to obtain the seed/input
// which is finally passed to the VRF cryptographic machinery.
uint256 vRFSeed = makeVRFInputSeed(_keyHash, _seed, address(this), nonces[_keyHash]);
// nonces[_keyHash] must stay in sync with
// VRFCoordinator.nonces[_keyHash][this], which was incremented by the above
// successful LINK.transferAndCall (in VRFCoordinator.randomnessRequest).
// This provides protection against the user repeating their input seed,
// which would result in a predictable/duplicate output, if multiple such
// requests appeared in the same block.
nonces[_keyHash] = nonces[_keyHash].add(1);
return makeRequestId(_keyHash, vRFSeed);
}
LinkTokenInterface immutable internal LINK;
address immutable private vrfCoordinator;
// Nonces for each VRF key from which randomness has been requested.
//
// Must stay in sync with VRFCoordinator[_keyHash][this]
mapping(bytes32 /* keyHash */ => uint256 /* nonce */) private nonces;
/**
* @param _vrfCoordinator address of VRFCoordinator contract
* @param _link address of LINK token contract
*
* @dev https://docs.chain.link/docs/link-token-contracts
*/
constructor(address _vrfCoordinator, address _link) public {
vrfCoordinator = _vrfCoordinator;
LINK = LinkTokenInterface(_link);
}
// rawFulfillRandomness is called by VRFCoordinator when it receives a valid VRF
// proof. rawFulfillRandomness then calls fulfillRandomness, after validating
// the origin of the call
function rawFulfillRandomness(bytes32 requestId, uint256 randomness) external {
require(msg.sender == vrfCoordinator, "Only VRFCoordinator can fulfill");
fulfillRandomness(requestId, randomness);
}
}
// Dependency file: @openzeppelin/contracts/token/ERC20/IERC20.sol
// pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// Dependency file: @openzeppelin/contracts/GSN/Context.sol
// pragma solidity ^0.6.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// Dependency file: @openzeppelin/contracts/access/Ownable.sol
// pragma solidity ^0.6.0;
// import "@openzeppelin/contracts/GSN/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// Dependency file: contracts/lib/Uint256ArrayUtils.sol
// pragma solidity 0.6.10;
/**
* @title Uint256ArrayUtils
* @author Prophecy
*
* Utility functions to handle uint256 Arrays
*/
library Uint256ArrayUtils {
/**
* Finds the index of the first occurrence of the given element.
* @param A The input array to search
* @param a The value to find
* @return Returns (index and isIn) for the first occurrence starting from index 0
*/
function indexOf(uint256[] memory A, uint256 a) internal pure returns (uint256, bool) {
uint256 length = A.length;
for (uint256 i = 0; i < length; i++) {
if (A[i] == a) {
return (i, true);
}
}
return (uint256(-1), false);
}
/**
* Returns true if the value is present in the list. Uses indexOf internally.
* @param A The input array to search
* @param a The value to find
* @return Returns isIn for the first occurrence starting from index 0
*/
function contains(uint256[] memory A, uint256 a) internal pure returns (bool) {
(, bool isIn) = indexOf(A, a);
return isIn;
}
/**
* Returns true if there are 2 elements that are the same in an array
* @param A The input array to search
* @return Returns boolean for the first occurrence of a duplicate
*/
function hasDuplicate(uint256[] memory A) internal pure returns(bool) {
require(A.length > 0, "A is empty");
for (uint256 i = 0; i < A.length - 1; i++) {
uint256 current = A[i];
for (uint256 j = i + 1; j < A.length; j++) {
if (current == A[j]) {
return true;
}
}
}
return false;
}
/**
* @param A The input array to search
* @param a The uint256 to remove
* @return Returns the array with the object removed.
*/
function remove(uint256[] memory A, uint256 a)
internal
pure
returns (uint256[] memory)
{
(uint256 index, bool isIn) = indexOf(A, a);
if (!isIn) {
revert("uint256 not in array.");
} else {
(uint256[] memory _A,) = pop(A, index);
return _A;
}
}
/**
* @param A The input array to search
* @param a The uint256 to remove
*/
function removeStorage(uint256[] storage A, uint256 a)
internal
{
(uint256 index, bool isIn) = indexOf(A, a);
if (!isIn) {
revert("uint256 not in array.");
} else {
uint256 lastIndex = A.length - 1; // If the array would be empty, the previous line would throw, so no underflow here
if (index != lastIndex) { A[index] = A[lastIndex]; }
A.pop();
}
}
/**
* Removes specified index from array
* @param A The input array to search
* @param index The index to remove
* @return Returns the new array and the removed entry
*/
function pop(uint256[] memory A, uint256 index)
internal
pure
returns (uint256[] memory, uint256)
{
uint256 length = A.length;
require(index < A.length, "Index must be < A length");
uint256[] memory newUint256s = new uint256[](length - 1);
for (uint256 i = 0; i < index; i++) {
newUint256s[i] = A[i];
}
for (uint256 j = index + 1; j < length; j++) {
newUint256s[j - 1] = A[j];
}
return (newUint256s, A[index]);
}
/**
* Returns the combination of the two arrays
* @param A The first array
* @param B The second array
* @return Returns A extended by B
*/
function extend(uint256[] memory A, uint256[] memory B) internal pure returns (uint256[] memory) {
uint256 aLength = A.length;
uint256 bLength = B.length;
uint256[] memory newUint256s = new uint256[](aLength + bLength);
for (uint256 i = 0; i < aLength; i++) {
newUint256s[i] = A[i];
}
for (uint256 j = 0; j < bLength; j++) {
newUint256s[aLength + j] = B[j];
}
return newUint256s;
}
/**
* Validate uint256 array is not empty and contains no duplicate elements.
*
* @param A Array of uint256
*/
function _validateLengthAndUniqueness(uint256[] memory A) internal pure {
require(A.length > 0, "Array length must be > 0");
require(!hasDuplicate(A), "Cannot duplicate uint256");
}
}
// Dependency file: contracts/lib/AddressArrayUtils.sol
// pragma solidity 0.6.10;
/**
* @title AddressArrayUtils
* @author Prophecy
*
* Utility functions to handle uint256 Arrays
*/
library AddressArrayUtils {
/**
* Finds the index of the first occurrence of the given element.
* @param A The input array to search
* @param a The value to find
* @return Returns (index and isIn) for the first occurrence starting from index 0
*/
function indexOf(address[] memory A, address a) internal pure returns (uint256, bool) {
uint256 length = A.length;
for (uint256 i = 0; i < length; i++) {
if (A[i] == a) {
return (i, true);
}
}
return (uint256(-1), false);
}
/**
* Returns true if the value is present in the list. Uses indexOf internally.
* @param A The input array to search
* @param a The value to find
* @return Returns isIn for the first occurrence starting from index 0
*/
function contains(address[] memory A, address a) internal pure returns (bool) {
(, bool isIn) = indexOf(A, a);
return isIn;
}
/**
* Returns true if there are 2 elements that are the same in an array
* @param A The input array to search
* @return Returns boolean for the first occurrence of a duplicate
*/
function hasDuplicate(address[] memory A) internal pure returns(bool) {
require(A.length > 0, "A is empty");
for (uint256 i = 0; i < A.length - 1; i++) {
address current = A[i];
for (uint256 j = i + 1; j < A.length; j++) {
if (current == A[j]) {
return true;
}
}
}
return false;
}
/**
* @param A The input array to search
* @param a The address to remove
* @return Returns the array with the object removed.
*/
function remove(address[] memory A, address a)
internal
pure
returns (address[] memory)
{
(uint256 index, bool isIn) = indexOf(A, a);
if (!isIn) {
revert("Address not in array.");
} else {
(address[] memory _A,) = pop(A, index);
return _A;
}
}
/**
* @param A The input array to search
* @param a The address to remove
*/
function removeStorage(address[] storage A, address a)
internal
{
(uint256 index, bool isIn) = indexOf(A, a);
if (!isIn) {
revert("Address not in array.");
} else {
uint256 lastIndex = A.length - 1; // If the array would be empty, the previous line would throw, so no underflow here
if (index != lastIndex) { A[index] = A[lastIndex]; }
A.pop();
}
}
/**
* Removes specified index from array
* @param A The input array to search
* @param index The index to remove
* @return Returns the new array and the removed entry
*/
function pop(address[] memory A, uint256 index)
internal
pure
returns (address[] memory, address)
{
uint256 length = A.length;
require(index < A.length, "Index must be < A length");
address[] memory newAddresses = new address[](length - 1);
for (uint256 i = 0; i < index; i++) {
newAddresses[i] = A[i];
}
for (uint256 j = index + 1; j < length; j++) {
newAddresses[j - 1] = A[j];
}
return (newAddresses, A[index]);
}
/**
* Returns the combination of the two arrays
* @param A The first array
* @param B The second array
* @return Returns A extended by B
*/
function extend(address[] memory A, address[] memory B) internal pure returns (address[] memory) {
uint256 aLength = A.length;
uint256 bLength = B.length;
address[] memory newAddresses = new address[](aLength + bLength);
for (uint256 i = 0; i < aLength; i++) {
newAddresses[i] = A[i];
}
for (uint256 j = 0; j < bLength; j++) {
newAddresses[aLength + j] = B[j];
}
return newAddresses;
}
/**
* Validate that address and uint array lengths match. Validate address array is not empty
* and contains no duplicate elements.
*
* @param A Array of addresses
* @param B Array of uint
*/
function validatePairsWithArray(address[] memory A, uint[] memory B) internal pure {
require(A.length == B.length, "Array length mismatch");
_validateLengthAndUniqueness(A);
}
/**
* Validate that address and bool array lengths match. Validate address array is not empty
* and contains no duplicate elements.
*
* @param A Array of addresses
* @param B Array of bool
*/
function validatePairsWithArray(address[] memory A, bool[] memory B) internal pure {
require(A.length == B.length, "Array length mismatch");
_validateLengthAndUniqueness(A);
}
/**
* Validate that address and string array lengths match. Validate address array is not empty
* and contains no duplicate elements.
*
* @param A Array of addresses
* @param B Array of strings
*/
function validatePairsWithArray(address[] memory A, string[] memory B) internal pure {
require(A.length == B.length, "Array length mismatch");
_validateLengthAndUniqueness(A);
}
/**
* Validate that address array lengths match, and calling address array are not empty
* and contain no duplicate elements.
*
* @param A Array of addresses
* @param B Array of addresses
*/
function validatePairsWithArray(address[] memory A, address[] memory B) internal pure {
require(A.length == B.length, "Array length mismatch");
_validateLengthAndUniqueness(A);
}
/**
* Validate that address and bytes array lengths match. Validate address array is not empty
* and contains no duplicate elements.
*
* @param A Array of addresses
* @param B Array of bytes
*/
function validatePairsWithArray(address[] memory A, bytes[] memory B) internal pure {
require(A.length == B.length, "Array length mismatch");
_validateLengthAndUniqueness(A);
}
/**
* Validate address array is not empty and contains no duplicate elements.
*
* @param A Array of addresses
*/
function _validateLengthAndUniqueness(address[] memory A) internal pure {
require(A.length > 0, "Array length must be > 0");
require(!hasDuplicate(A), "Cannot duplicate addresses");
}
}
// Dependency file: contracts/interfaces/IWETH.sol
// pragma solidity 0.6.10;
// import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @title IWETH
* @author Prophecy
*
* Interface for Wrapped Ether. This interface allows for interaction for wrapped ether's deposit and withdrawal
* functionality.
*/
interface IWETH is IERC20{
function deposit() external payable;
function withdraw(uint256 wad) external;
}
// Dependency file: contracts/interfaces/IController.sol
// pragma solidity ^0.6.10;
/**
* @title IController
* @author Prophecy
*/
interface IController {
/**
* Return WETH address.
*/
function getWeth() external view returns (address);
/**
* Getter for chanceToken
*/
function getChanceToken() external view returns (address);
/**
* Return VRF Key Hash.
*/
function getVrfKeyHash() external view returns (bytes32);
/**
* Return VRF Fee.
*/
function getVrfFee() external view returns (uint256);
/**
* Return Link Token address for VRF.
*/
function getLinkToken() external view returns (address);
/**
* Return VRF coordinator.
*/
function getVrfCoordinator() external view returns (address);
/**
* Return all pools addreses
*/
function getAllPools() external view returns (address[] memory);
}
// Dependency file: contracts/interfaces/IChanceToken.sol
// pragma solidity ^0.6.10;
/**
* @title IChanceToken
* @author Prophecy
*
* Interface for ChanceToken
*/
interface IChanceToken {
/**
* OWNER ALLOWED MINTER: Mint NFT
*/
function mint(address _account, uint256 _id, uint256 _amount) external;
/**
* OWNER ALLOWED BURNER: Burn NFT
*/
function burn(address _account, uint256 _id, uint256 _amount) external;
}
// Root file: contracts/ProphetPool.sol
pragma solidity ^0.6.10;
pragma experimental ABIEncoderV2;
// import { VRFConsumerBase } from "@chainlink/contracts/src/v0.6/VRFConsumerBase.sol";
// import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
// import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
// import { Uint256ArrayUtils } from "contracts/lib/Uint256ArrayUtils.sol";
// import { AddressArrayUtils } from "contracts/lib/AddressArrayUtils.sol";
// import { IWETH } from "contracts/interfaces/IWETH.sol";
// import { IController } from "contracts/interfaces/IController.sol";
// import { IChanceToken } from "contracts/interfaces/IChanceToken.sol";
/**
* @title ProphetPool
* @author Prophecy
*
* Smart contract that facilitates that draws lucky winners in the pool and distribute rewards to the winners.
* It should be whitelisted for the mintable role for ChanceToken(ERC1155)
*/
contract ProphetPool is VRFConsumerBase, Ownable {
using Uint256ArrayUtils for uint256[];
using AddressArrayUtils for address[];
/* ============ Structs ============ */
struct PoolConfig {
uint256 numOfWinners;
uint256 participantLimit;
uint256 enterAmount;
uint256 feePercentage;
uint256 randomSeed;
uint256 startedAt;
}
/* ============ Enums ============ */
enum PoolStatus { NOTSTARTED, INPROGRESS, CLOSED }
/* ============ Events ============ */
event FeeRecipientSet(address indexed _feeRecipient);
event MaxParticipationCompleted(address indexed _from);
event RandomNumberGenerated(uint256 indexed randomness);
event WinnersGenerated(uint256[] winnerIndexes);
event PoolSettled();
event PoolStarted(
uint256 participantLimit,
uint256 numOfWinners,
uint256 enterAmount,
uint256 feePercentage,
uint256 startedAt
);
event PoolReset();
event EnteredPool(address indexed _participant, uint256 _amount, uint256 indexed _participantIndex);
/* ============ State Variables ============ */
IController private controller;
address private feeRecipient;
string private poolName;
IERC20 private enterToken;
PoolStatus private poolStatus;
PoolConfig private poolConfig;
uint256 private chanceTokenId;
address[] private participants;
uint256[] private winnerIndexes;
uint256 private totalEnteredAmount;
uint256 private rewardPerParticipant;
bool internal isRNDGenerated;
uint256 internal randomResult;
bool internal areWinnersGenerated;
/* ============ Modifiers ============ */
modifier onlyValidPool() {
require(participants.length < poolConfig.participantLimit, "exceed max");
require(poolStatus == PoolStatus.INPROGRESS, "in progress");
_;
}
modifier onlyEOA() {
require(tx.origin == msg.sender, "should be EOA");
_;
}
/* ============ Constructor ============ */
/**
* Create the ProphetPool with Chainlink VRF configuration for Random number generation.
*
* @param _poolName Pool name
* @param _enterToken ERC20 token to enter the pool. If it's ETH pool, it should be WETH address
* @param _controller Controller
* @param _feeRecipient Where the fee go
* @param _chanceTokenId ERC1155 Token id for chance token
*/
constructor(
string memory _poolName,
address _enterToken,
address _controller,
address _feeRecipient,
uint256 _chanceTokenId
)
public
VRFConsumerBase(IController(_controller).getVrfCoordinator(), IController(_controller).getLinkToken())
{
poolName = _poolName;
enterToken = IERC20(_enterToken);
controller = IController(_controller);
feeRecipient = _feeRecipient;
chanceTokenId = _chanceTokenId;
poolStatus = PoolStatus.NOTSTARTED;
}
/* ============ External/Public Functions ============ */
/**
* Set the Pool Config, initializes an instance of and start the pool.
*
* @param _numOfWinners Number of winners in the pool
* @param _participantLimit Maximum number of paricipants
* @param _enterAmount Exact amount to enter this pool
* @param _feePercentage Manager fee of this pool
* @param _randomSeed Seed for Random Number Generation
*/
function setPoolRules(
uint256 _numOfWinners,
uint256 _participantLimit,
uint256 _enterAmount,
uint256 _feePercentage,
uint256 _randomSeed
) external onlyOwner {
require(poolStatus == PoolStatus.NOTSTARTED, "in progress");
require(_numOfWinners != 0, "invalid numOfWinners");
require(_numOfWinners < _participantLimit, "too much numOfWinners");
poolConfig = PoolConfig(
_numOfWinners,
_participantLimit,
_enterAmount,
_feePercentage,
_randomSeed,
block.timestamp
);
poolStatus = PoolStatus.INPROGRESS;
emit PoolStarted(
_participantLimit,
_numOfWinners,
_enterAmount,
_feePercentage,
block.timestamp
);
}
/**
* Set the Pool Config, initializes an instance of and start the pool.
*
* @param _feeRecipient Number of winners in the pool
*/
function setFeeRecipient(address _feeRecipient) external onlyOwner {
require(_feeRecipient != address(0), "invalid address");
feeRecipient = _feeRecipient;
emit FeeRecipientSet(feeRecipient);
}
/**
* Enter pool with ETH
*/
function enterPoolEth() external payable onlyValidPool onlyEOA returns (uint256) {
require(msg.value == poolConfig.enterAmount, "insufficient amount");
if (!_isEthPool()) {
revert("not accept ETH");
}
// wrap ETH to WETH
IWETH(controller.getWeth()).deposit{ value: msg.value }();
return _enterPool();
}
/**
* Enter pool with ERC20 token
*/
function enterPool() external onlyValidPool onlyEOA returns (uint256) {
enterToken.transferFrom(
msg.sender,
address(this),
poolConfig.enterAmount
);
return _enterPool();
}
/**
* Settle the pool, the winners are selected randomly and fee is transfer to the manager.
*/
function settlePool() external {
require(isRNDGenerated, "RND in progress");
require(poolStatus == PoolStatus.INPROGRESS, "pool in progress");
// generate winnerIndexes until the numOfWinners reach
uint256 newRandom = randomResult;
uint256 offset = 0;
while(winnerIndexes.length < poolConfig.numOfWinners) {
uint256 winningIndex = newRandom.mod(poolConfig.participantLimit);
if (!winnerIndexes.contains(winningIndex)) {
winnerIndexes.push(winningIndex);
}
offset = offset.add(1);
newRandom = _getRandomNumberBlockchain(offset, newRandom);
}
areWinnersGenerated = true;
emit WinnersGenerated(winnerIndexes);
// set pool CLOSED status
poolStatus = PoolStatus.CLOSED;
// transfer fees
uint256 feeAmount = totalEnteredAmount.mul(poolConfig.feePercentage).div(100);
rewardPerParticipant = (totalEnteredAmount.sub(feeAmount)).div(poolConfig.numOfWinners);
_transferEnterToken(feeRecipient, feeAmount);
// collectRewards();
emit PoolSettled();
}
/**
* The winners of the pool can call this function to transfer their winnings
* from the pool contract to their own address.
*/
function collectRewards() external {
require(poolStatus == PoolStatus.CLOSED, "not settled");
for (uint256 i = 0; i < poolConfig.participantLimit; i = i.add(1)) {
address player = participants[i];
if (winnerIndexes.contains(i)) {
// if winner
_transferEnterToken(player, rewardPerParticipant);
} else {
// if loser
IChanceToken(controller.getChanceToken()).mint(player, chanceTokenId, 1);
}
}
_resetPool();
}
/**
* The contract will receive Ether
*/
receive() external payable {}
/**
* Getter for controller
*/
function getController() external view returns (address) {
return address(controller);
}
/**
* Getter for fee recipient
*/
function getFeeRecipient() external view returns (address) {
return feeRecipient;
}
/**
* Getter for poolName
*/
function getPoolName() external view returns (string memory) {
return poolName;
}
/**
* Getter for enterToken
*/
function getEnterToken() external view returns (address) {
return address(enterToken);
}
/**
* Getter for chanceTokenId
*/
function getChanceTokenId() external view returns (uint256) {
return chanceTokenId;
}
/**
* Getter for poolStatus
*/
function getPoolStatus() external view returns (PoolStatus) {
return poolStatus;
}
/**
* Getter for poolConfig
*/
function getPoolConfig() external view returns (PoolConfig memory) {
return poolConfig;
}
/**
* Getter for totalEnteredAmount
*/
function getTotalEnteredAmount() external view returns (uint256) {
return totalEnteredAmount;
}
/**
* Getter for rewardPerParticipant
*/
function getRewardPerParticipant() external view returns (uint256) {
return rewardPerParticipant;
}
/**
* Get all participants
*/
function getParticipants() external view returns(address[] memory) {
return participants;
}
/**
* Get one participant by index
* @param _index Index of the participants array
*/
function getParticipant(uint256 _index) external view returns(address) {
return participants[_index];
}
/**
* Getter for winnerIndexes
*/
function getWinnerIndexes() external view returns(uint256[] memory) {
return winnerIndexes;
}
/**
* Get if the account is winner
*/
function isWinner(address _account) external view returns(bool) {
(uint256 index, bool isExist) = participants.indexOf(_account);
if (isExist) {
return winnerIndexes.contains(index);
} else {
return false;
}
}
/* ============ Private/Internal Functions ============ */
/**
* Participant enters the pool and enter amount is transferred from the user to the pool.
*/
function _enterPool() internal returns(uint256 _participantIndex) {
participants.push(msg.sender);
totalEnteredAmount = totalEnteredAmount.add(poolConfig.enterAmount);
if (participants.length == poolConfig.participantLimit) {
emit MaxParticipationCompleted(msg.sender);
_getRandomNumber(poolConfig.randomSeed);
}
_participantIndex = (participants.length).sub(1);
emit EnteredPool(msg.sender, poolConfig.enterAmount, _participantIndex);
}
/**
* Reset the pool, clears the existing state variable values and the pool can be initialized again.
*/
function _resetPool() internal {
poolStatus = PoolStatus.INPROGRESS;
delete totalEnteredAmount;
delete rewardPerParticipant;
isRNDGenerated = false;
randomResult = 0;
areWinnersGenerated = false;
delete winnerIndexes;
delete participants;
emit PoolReset();
uint256 tokenBalance = enterToken.balanceOf(address(this));
if (tokenBalance > 0) {
_transferEnterToken(feeRecipient, tokenBalance);
}
}
/**
* Transfer enterToken even it's ETH or ERC20.
*
* @param _to Offset to generate the random number
* @param _amount Random number to generate the other random number
*/
function _transferEnterToken(address _to, uint256 _amount) internal {
if (_isEthPool()) {
IWETH(controller.getWeth()).withdraw(_amount);
(bool status, ) = payable(_to).call{value: _amount}("");
require(status, "ETH not transferred");
} else {
enterToken.transfer(address(_to), _amount);
}
}
/**
* Check pool is ETH pool or not
*/
function _isEthPool() internal view returns (bool) {
return address(enterToken) == controller.getWeth();
}
/**
* Generate a random number based on the blockHash and random offset
*
* @param _offset Offset to generate the random number
* @param _randomness Random number to generate the other random number
*/
function _getRandomNumberBlockchain(uint256 _offset, uint256 _randomness)
internal
view
returns (uint256)
{
bytes32 baseHash = keccak256(
abi.encodePacked(
blockhash(block.number),
bytes32(_offset),
bytes32(_randomness)
)
);
return uint256(baseHash);
}
/**
* Calls ChainLink Oracle's inherited function for Random Number Generation.
* The contract must have enough LINK required for VRF.
*
* @param _userProvidedSeed Seed to generate the random number
*/
function _getRandomNumber(uint256 _userProvidedSeed)
internal
returns (bytes32 requestId)
{
require(
IERC20(controller.getLinkToken()).balanceOf(address(this)) >= controller.getVrfFee(),
"not enough LINK"
);
randomResult = 0;
isRNDGenerated = false;
return
requestRandomness(
controller.getVrfKeyHash(),
controller.getVrfFee(),
_userProvidedSeed
);
}
/**
* Callback function used by VRF Coordinator.
*
* @param _randomness Generated random number
*/
function fulfillRandomness(bytes32, uint256 _randomness) internal override {
randomResult = _randomness;
isRNDGenerated = true;
emit RandomNumberGenerated(_randomness);
}
} | * Check pool is ETH pool or not/ | function _isEthPool() internal view returns (bool) {
return address(enterToken) == controller.getWeth();
}
| 225,667 | [
1,
1564,
2845,
353,
512,
2455,
2845,
578,
486,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
389,
291,
41,
451,
2864,
1435,
2713,
1476,
1135,
261,
6430,
13,
288,
203,
3639,
327,
1758,
12,
2328,
1345,
13,
422,
2596,
18,
588,
59,
546,
5621,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/42/0xf18DbF837b646ae495d12bAC7cf8Cc9000F5E602/sources/MultiSigWallet.sol | Constants/ Storage/ | struct Transaction {
string name;
address destination;
uint value;
bytes data;
bool executed;
}
| 3,303,248 | [
1,
2918,
19,
225,
5235,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
1958,
5947,
288,
203,
3639,
533,
508,
31,
203,
3639,
1758,
2929,
31,
203,
3639,
2254,
460,
31,
203,
3639,
1731,
501,
31,
203,
3639,
1426,
7120,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.19;
contract Ownable {
address public owner;
address public ceoWallet;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor() public {
owner = msg.sender;
ceoWallet = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
// Interface for contracts conforming to ERC-721: Non-Fungible Tokens
contract ERC721 {
event Transfer(address indexed _from, address indexed _to, uint256 _tokenId);
event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId);
function balanceOf(address _owner) public view returns (uint256 _balance);
function ownerOf(uint256 _tokenId) public view returns (address _owner);
function transfer(address _to, uint256 _tokenId) public;
function approve(address _to, uint256 _tokenId) public;
function takeOwnership(uint256 _tokenId) public;
function totalSupply() public view returns (uint256 total);
}
contract CryptoRomeControl is Ownable {
bool public paused = false;
modifier whenNotPaused() {
require(!paused);
_;
}
modifier whenPaused {
require(paused);
_;
}
function transferWalletOwnership(address newWalletAddress) onlyOwner public {
require(newWalletAddress != address(0));
ceoWallet = newWalletAddress;
}
function pause() external onlyOwner whenNotPaused {
paused = true;
}
function unpause() public onlyOwner whenPaused {
paused = false;
}
}
contract Centurions is ERC721, CryptoRomeControl {
// Name and symbol of the non fungible token, as defined in ERC721.
string public constant name = "CryptoRomeCenturion";
string public constant symbol = "CROMEC";
struct Centurion {
uint256 level;
uint256 experience;
uint256 askingPrice;
}
uint256[50] public expForLevels = [
0, // 0
20,
50,
100,
200,
400, // 5
800,
1400,
2100,
3150,
4410, // 10
5740,
7460,
8950,
10740,
12880,
15460,
18550,
22260,
26710,
32050, // 20
38500,
46200,
55400,
66500,
79800,
95700,
115000,
138000,
166000,
200000, // 30
240000,
290000,
350000,
450000,
580000,
820000,
1150000,
1700000,
2600000,
3850000, // 40
5800000,
8750000,
13000000,
26000000,
52000000,
104000000,
208000000,
416000000,
850000000 // 49
];
Centurion[] internal allCenturionTokens;
string internal tokenURIs;
// Map of Centurion to the owner
mapping (uint256 => address) public centurionIndexToOwner;
mapping (address => uint256) ownershipTokenCount;
mapping (uint256 => address) centurionIndexToApproved;
modifier onlyOwnerOf(uint256 _tokenId) {
require(centurionIndexToOwner[_tokenId] == msg.sender);
_;
}
function getCenturion(uint256 _tokenId) external view
returns (
uint256 level,
uint256 experience,
uint256 askingPrice
) {
Centurion storage centurion = allCenturionTokens[_tokenId];
level = centurion.level;
experience = centurion.experience;
askingPrice = centurion.askingPrice;
}
function updateTokenUri(uint256 _tokenId, string _tokenURI) public whenNotPaused onlyOwner {
_setTokenURI(_tokenId, _tokenURI);
}
function createCenturion() public whenNotPaused onlyOwner returns (uint256) {
uint256 finalId = _createCenturion(msg.sender);
return finalId;
}
function issueCenturion(address _to) public whenNotPaused onlyOwner returns (uint256) {
uint256 finalId = _createCenturion(msg.sender);
_transfer(msg.sender, _to, finalId);
return finalId;
}
function listCenturion(uint256 _askingPrice) public whenNotPaused onlyOwner returns (uint256) {
uint256 finalId = _createCenturion(msg.sender);
allCenturionTokens[finalId].askingPrice = _askingPrice;
return finalId;
}
function sellCenturion(uint256 _tokenId, uint256 _askingPrice) onlyOwnerOf(_tokenId) whenNotPaused public {
allCenturionTokens[_tokenId].askingPrice = _askingPrice;
}
function cancelCenturionSale(uint256 _tokenId) onlyOwnerOf(_tokenId) whenNotPaused public {
allCenturionTokens[_tokenId].askingPrice = 0;
}
function purchaseCenturion(uint256 _tokenId) whenNotPaused public payable {
require(allCenturionTokens[_tokenId].askingPrice > 0);
require(msg.value >= allCenturionTokens[_tokenId].askingPrice);
allCenturionTokens[_tokenId].askingPrice = 0;
uint256 fee = devFee(msg.value);
ceoWallet.transfer(fee);
centurionIndexToOwner[_tokenId].transfer(SafeMath.sub(address(this).balance, fee));
_transfer(centurionIndexToOwner[_tokenId], msg.sender, _tokenId);
}
function _transfer(address _from, address _to, uint256 _tokenId) internal {
ownershipTokenCount[_to] = SafeMath.add(ownershipTokenCount[_to], 1);
centurionIndexToOwner[_tokenId] = _to;
if (_from != address(0)) {
// clear any previously approved ownership exchange
ownershipTokenCount[_from] = SafeMath.sub(ownershipTokenCount[_from], 1);
delete centurionIndexToApproved[_tokenId];
}
}
function _createCenturion(address _owner) internal returns (uint) {
Centurion memory _centurion = Centurion({
level: 1,
experience: 0,
askingPrice: 0
});
uint256 newCenturionId = allCenturionTokens.push(_centurion) - 1;
// Only 1000 centurions should ever exist (0-999)
require(newCenturionId < 1000);
_transfer(0, _owner, newCenturionId);
return newCenturionId;
}
function devFee(uint256 amount) internal pure returns(uint256){
return SafeMath.div(SafeMath.mul(amount, 3), 100);
}
// Functions for ERC721 Below:
// Check is address has approval to transfer centurion.
function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) {
return centurionIndexToApproved[_tokenId] == _claimant;
}
function exists(uint256 _tokenId) public view returns (bool) {
address owner = centurionIndexToOwner[_tokenId];
return owner != address(0);
}
function addExperience(uint256 _tokenId, uint256 _exp) public whenNotPaused onlyOwner returns (uint256) {
require(exists(_tokenId));
allCenturionTokens[_tokenId].experience = SafeMath.add(allCenturionTokens[_tokenId].experience, _exp);
for (uint256 i = allCenturionTokens[_tokenId].level; i < 50; i++) {
if (allCenturionTokens[_tokenId].experience >= expForLevels[i]) {
allCenturionTokens[_tokenId].level = allCenturionTokens[_tokenId].level + 1;
} else {
break;
}
}
return allCenturionTokens[_tokenId].level;
}
function tokenURI(uint256 _tokenId) public view returns (string) {
require(exists(_tokenId));
return tokenURIs;
}
function _setTokenURI(uint256 _tokenId, string _uri) internal {
require(exists(_tokenId));
tokenURIs = _uri;
}
// Sets a centurion as approved for transfer to another address.
function _approve(uint256 _tokenId, address _approved) internal {
centurionIndexToApproved[_tokenId] = _approved;
}
// Returns the number of Centurions owned by a specific address.
function balanceOf(address _owner) public view returns (uint256 count) {
return ownershipTokenCount[_owner];
}
// Transfers a Centurion to another address. If transferring to a smart
// contract ensure that it is aware of ERC-721.
function transfer(address _to, uint256 _tokenId) public onlyOwnerOf(_tokenId) whenNotPaused {
require(_to != address(0));
require(_to != address(this));
_transfer(msg.sender, _to, _tokenId);
emit Transfer(msg.sender, _to, _tokenId);
}
// Permit another address the right to transfer a specific Centurion via
// transferFrom().
function approve(address _to, uint256 _tokenId) public onlyOwnerOf(_tokenId) whenNotPaused {
_approve(_tokenId, _to);
emit Approval(msg.sender, _to, _tokenId);
}
// Transfer a Centurion owned by another address, for which the calling address
// has previously been granted transfer approval by the owner.
function takeOwnership(uint256 _tokenId) public {
require(centurionIndexToApproved[_tokenId] == msg.sender);
address owner = ownerOf(_tokenId);
_transfer(owner, msg.sender, _tokenId);
emit Transfer(owner, msg.sender, _tokenId);
}
// 1000 Centurions will ever exist
function totalSupply() public view returns (uint) {
return allCenturionTokens.length;
}
function ownerOf(uint256 _tokenId) public view returns (address owner)
{
owner = centurionIndexToOwner[_tokenId];
require(owner != address(0));
}
// List of all Centurion IDs assigned to an address.
function tokensOfOwner(address _owner) external view returns(uint256[] ownerTokens) {
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
return new uint256[](0);
} else {
uint256[] memory result = new uint256[](tokenCount);
uint256 totalCenturions = totalSupply();
uint256 resultIndex = 0;
uint256 centurionId;
for (centurionId = 0; centurionId < totalCenturions; centurionId++) {
if (centurionIndexToOwner[centurionId] == _owner) {
result[resultIndex] = centurionId;
resultIndex++;
}
}
return result;
}
}
}
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
} | 1000 Centurions will ever exist | function totalSupply() public view returns (uint) {
return allCenturionTokens.length;
}
| 7,238,858 | [
1,
18088,
22321,
295,
1115,
903,
14103,
1005,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
2078,
3088,
1283,
1435,
1071,
1476,
1135,
261,
11890,
13,
288,
203,
3639,
327,
777,
15897,
295,
285,
5157,
18,
2469,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0x80EE473654F4928b7893D852742CD4eFEBFb1A31/sources/POOH.sol | there will be no leftover eth in the contract | (success, ) = address(OperationWallet).call{value: address(this).balance}("");
| 2,663,987 | [
1,
18664,
903,
506,
1158,
29709,
13750,
316,
326,
6835,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
261,
4768,
16,
262,
273,
1758,
12,
2988,
16936,
2934,
1991,
95,
1132,
30,
1758,
12,
2211,
2934,
12296,
97,
2932,
8863,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0x46baF37b504e24DB0Edd92Cdd5089f737c759a3C/sources/home/vadim/code/skale-manager/contracts/thirdparty/ECDH.sol | * @title ECDH @dev This contract performs Elliptic-curve Diffie-Hellman key exchange to support the DKG process./ | contract ECDH {
using SafeMath for uint256;
uint256 constant private _GX = 0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798;
uint256 constant private _GY = 0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8;
uint256 constant private _N = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F;
uint256 constant private _A = 0;
Modifications Copyright (C) 2018 SKALE Labs
function publicKey(uint256 privKey) external pure returns (uint256 qx, uint256 qy) {
uint256 x;
uint256 y;
uint256 z;
(x, y, z) = ecMul(
privKey,
_GX,
_GY,
1
);
z = inverse(z);
qx = mulmod(x, z, _N);
qy = mulmod(y, z, _N);
}
function deriveKey(
uint256 privKey,
uint256 pubX,
uint256 pubY
)
external
pure
returns (uint256 qx, uint256 qy)
{
uint256 x;
uint256 y;
uint256 z;
(x, y, z) = ecMul(
privKey,
pubX,
pubY,
1
);
z = inverse(z);
qx = mulmod(x, z, _N);
qy = mulmod(y, z, _N);
}
function jAdd(
uint256 x1,
uint256 z1,
uint256 x2,
uint256 z2
)
public
pure
returns (uint256 x3, uint256 z3)
{
(x3, z3) = (addmod(mulmod(z2, x1, _N), mulmod(x2, z1, _N), _N), mulmod(z1, z2, _N));
}
function jSub(
uint256 x1,
uint256 z1,
uint256 x2,
uint256 z2
)
public
pure
returns (uint256 x3, uint256 z3)
{
(x3, z3) = (addmod(mulmod(z2, x1, _N), mulmod(_N.sub(x2), z1, _N), _N), mulmod(z1, z2, _N));
}
function jMul(
uint256 x1,
uint256 z1,
uint256 x2,
uint256 z2
)
public
pure
returns (uint256 x3, uint256 z3)
{
(x3, z3) = (mulmod(x1, x2, _N), mulmod(z1, z2, _N));
}
function jDiv(
uint256 x1,
uint256 z1,
uint256 x2,
uint256 z2
)
public
pure
returns (uint256 x3, uint256 z3)
{
(x3, z3) = (mulmod(x1, z2, _N), mulmod(z1, x2, _N));
}
function inverse(uint256 a) public pure returns (uint256 invA) {
uint256 t = 0;
uint256 newT = 1;
uint256 r = _N;
uint256 newR = a;
uint256 q;
while (newR != 0) {
q = r.div(newR);
(t, newT) = (newT, addmod(t, (_N.sub(mulmod(q, newT, _N))), _N));
(r, newR) = (newR, r % newR);
}
return t;
}
function inverse(uint256 a) public pure returns (uint256 invA) {
uint256 t = 0;
uint256 newT = 1;
uint256 r = _N;
uint256 newR = a;
uint256 q;
while (newR != 0) {
q = r.div(newR);
(t, newT) = (newT, addmod(t, (_N.sub(mulmod(q, newT, _N))), _N));
(r, newR) = (newR, r % newR);
}
return t;
}
function ecAdd(
uint256 x1,
uint256 y1,
uint256 z1,
uint256 x2,
uint256 y2,
uint256 z2
)
public
pure
returns (uint256 x3, uint256 y3, uint256 z3)
{
uint256 ln;
uint256 lz;
uint256 da;
uint256 db;
if ((x1 == 0) && (y1 == 0)) {
return (x2, y2, z2);
}
if ((x2 == 0) && (y2 == 0)) {
return (x1, y1, z1);
}
if ((x1 == x2) && (y1 == y2)) {
(ln, lz) = jMul(x1, z1, x1, z1);
(ln, lz) = jMul(ln,lz,3,1);
(ln, lz) = jAdd(ln,lz,_A,1);
(da, db) = jMul(y1,z1,2,1);
(ln, lz) = jSub(y2,z2,y1,z1);
(da, db) = jSub(x2,z2,x1,z1);
}
(ln, lz) = jDiv(ln,lz,da,db);
(x3, da) = jMul(ln,lz,ln,lz);
(x3, da) = jSub(x3,da,x1,z1);
(x3, da) = jSub(x3,da,x2,z2);
(y3, db) = jSub(x1,z1,x3,da);
(y3, db) = jMul(y3,db,ln,lz);
(y3, db) = jSub(y3,db,y1,z1);
if (da != db) {
x3 = mulmod(x3, db, _N);
y3 = mulmod(y3, da, _N);
z3 = mulmod(da, db, _N);
z3 = da;
}
}
function ecAdd(
uint256 x1,
uint256 y1,
uint256 z1,
uint256 x2,
uint256 y2,
uint256 z2
)
public
pure
returns (uint256 x3, uint256 y3, uint256 z3)
{
uint256 ln;
uint256 lz;
uint256 da;
uint256 db;
if ((x1 == 0) && (y1 == 0)) {
return (x2, y2, z2);
}
if ((x2 == 0) && (y2 == 0)) {
return (x1, y1, z1);
}
if ((x1 == x2) && (y1 == y2)) {
(ln, lz) = jMul(x1, z1, x1, z1);
(ln, lz) = jMul(ln,lz,3,1);
(ln, lz) = jAdd(ln,lz,_A,1);
(da, db) = jMul(y1,z1,2,1);
(ln, lz) = jSub(y2,z2,y1,z1);
(da, db) = jSub(x2,z2,x1,z1);
}
(ln, lz) = jDiv(ln,lz,da,db);
(x3, da) = jMul(ln,lz,ln,lz);
(x3, da) = jSub(x3,da,x1,z1);
(x3, da) = jSub(x3,da,x2,z2);
(y3, db) = jSub(x1,z1,x3,da);
(y3, db) = jMul(y3,db,ln,lz);
(y3, db) = jSub(y3,db,y1,z1);
if (da != db) {
x3 = mulmod(x3, db, _N);
y3 = mulmod(y3, da, _N);
z3 = mulmod(da, db, _N);
z3 = da;
}
}
function ecAdd(
uint256 x1,
uint256 y1,
uint256 z1,
uint256 x2,
uint256 y2,
uint256 z2
)
public
pure
returns (uint256 x3, uint256 y3, uint256 z3)
{
uint256 ln;
uint256 lz;
uint256 da;
uint256 db;
if ((x1 == 0) && (y1 == 0)) {
return (x2, y2, z2);
}
if ((x2 == 0) && (y2 == 0)) {
return (x1, y1, z1);
}
if ((x1 == x2) && (y1 == y2)) {
(ln, lz) = jMul(x1, z1, x1, z1);
(ln, lz) = jMul(ln,lz,3,1);
(ln, lz) = jAdd(ln,lz,_A,1);
(da, db) = jMul(y1,z1,2,1);
(ln, lz) = jSub(y2,z2,y1,z1);
(da, db) = jSub(x2,z2,x1,z1);
}
(ln, lz) = jDiv(ln,lz,da,db);
(x3, da) = jMul(ln,lz,ln,lz);
(x3, da) = jSub(x3,da,x1,z1);
(x3, da) = jSub(x3,da,x2,z2);
(y3, db) = jSub(x1,z1,x3,da);
(y3, db) = jMul(y3,db,ln,lz);
(y3, db) = jSub(y3,db,y1,z1);
if (da != db) {
x3 = mulmod(x3, db, _N);
y3 = mulmod(y3, da, _N);
z3 = mulmod(da, db, _N);
z3 = da;
}
}
function ecAdd(
uint256 x1,
uint256 y1,
uint256 z1,
uint256 x2,
uint256 y2,
uint256 z2
)
public
pure
returns (uint256 x3, uint256 y3, uint256 z3)
{
uint256 ln;
uint256 lz;
uint256 da;
uint256 db;
if ((x1 == 0) && (y1 == 0)) {
return (x2, y2, z2);
}
if ((x2 == 0) && (y2 == 0)) {
return (x1, y1, z1);
}
if ((x1 == x2) && (y1 == y2)) {
(ln, lz) = jMul(x1, z1, x1, z1);
(ln, lz) = jMul(ln,lz,3,1);
(ln, lz) = jAdd(ln,lz,_A,1);
(da, db) = jMul(y1,z1,2,1);
(ln, lz) = jSub(y2,z2,y1,z1);
(da, db) = jSub(x2,z2,x1,z1);
}
(ln, lz) = jDiv(ln,lz,da,db);
(x3, da) = jMul(ln,lz,ln,lz);
(x3, da) = jSub(x3,da,x1,z1);
(x3, da) = jSub(x3,da,x2,z2);
(y3, db) = jSub(x1,z1,x3,da);
(y3, db) = jMul(y3,db,ln,lz);
(y3, db) = jSub(y3,db,y1,z1);
if (da != db) {
x3 = mulmod(x3, db, _N);
y3 = mulmod(y3, da, _N);
z3 = mulmod(da, db, _N);
z3 = da;
}
}
} else {
function ecAdd(
uint256 x1,
uint256 y1,
uint256 z1,
uint256 x2,
uint256 y2,
uint256 z2
)
public
pure
returns (uint256 x3, uint256 y3, uint256 z3)
{
uint256 ln;
uint256 lz;
uint256 da;
uint256 db;
if ((x1 == 0) && (y1 == 0)) {
return (x2, y2, z2);
}
if ((x2 == 0) && (y2 == 0)) {
return (x1, y1, z1);
}
if ((x1 == x2) && (y1 == y2)) {
(ln, lz) = jMul(x1, z1, x1, z1);
(ln, lz) = jMul(ln,lz,3,1);
(ln, lz) = jAdd(ln,lz,_A,1);
(da, db) = jMul(y1,z1,2,1);
(ln, lz) = jSub(y2,z2,y1,z1);
(da, db) = jSub(x2,z2,x1,z1);
}
(ln, lz) = jDiv(ln,lz,da,db);
(x3, da) = jMul(ln,lz,ln,lz);
(x3, da) = jSub(x3,da,x1,z1);
(x3, da) = jSub(x3,da,x2,z2);
(y3, db) = jSub(x1,z1,x3,da);
(y3, db) = jMul(y3,db,ln,lz);
(y3, db) = jSub(y3,db,y1,z1);
if (da != db) {
x3 = mulmod(x3, db, _N);
y3 = mulmod(y3, da, _N);
z3 = mulmod(da, db, _N);
z3 = da;
}
}
} else {
function ecDouble(
uint256 x1,
uint256 y1,
uint256 z1
)
public
pure
returns (uint256 x3, uint256 y3, uint256 z3)
{
(x3, y3, z3) = ecAdd(
x1,
y1,
z1,
x1,
y1,
z1
);
}
function ecMul(
uint256 d,
uint256 x1,
uint256 y1,
uint256 z1
)
public
pure
returns (uint256 x3, uint256 y3, uint256 z3)
{
uint256 remaining = d;
uint256 px = x1;
uint256 py = y1;
uint256 pz = z1;
uint256 acx = 0;
uint256 acy = 0;
uint256 acz = 1;
if (d == 0) {
return (0, 0, 1);
}
while (remaining != 0) {
if ((remaining & 1) != 0) {
(acx, acy, acz) = ecAdd(
acx,
acy,
acz,
px,
py,
pz
);
}
remaining = remaining.div(2);
(px, py, pz) = ecDouble(px, py, pz);
}
(x3, y3, z3) = (acx, acy, acz);
}
function ecMul(
uint256 d,
uint256 x1,
uint256 y1,
uint256 z1
)
public
pure
returns (uint256 x3, uint256 y3, uint256 z3)
{
uint256 remaining = d;
uint256 px = x1;
uint256 py = y1;
uint256 pz = z1;
uint256 acx = 0;
uint256 acy = 0;
uint256 acz = 1;
if (d == 0) {
return (0, 0, 1);
}
while (remaining != 0) {
if ((remaining & 1) != 0) {
(acx, acy, acz) = ecAdd(
acx,
acy,
acz,
px,
py,
pz
);
}
remaining = remaining.div(2);
(px, py, pz) = ecDouble(px, py, pz);
}
(x3, y3, z3) = (acx, acy, acz);
}
function ecMul(
uint256 d,
uint256 x1,
uint256 y1,
uint256 z1
)
public
pure
returns (uint256 x3, uint256 y3, uint256 z3)
{
uint256 remaining = d;
uint256 px = x1;
uint256 py = y1;
uint256 pz = z1;
uint256 acx = 0;
uint256 acy = 0;
uint256 acz = 1;
if (d == 0) {
return (0, 0, 1);
}
while (remaining != 0) {
if ((remaining & 1) != 0) {
(acx, acy, acz) = ecAdd(
acx,
acy,
acz,
px,
py,
pz
);
}
remaining = remaining.div(2);
(px, py, pz) = ecDouble(px, py, pz);
}
(x3, y3, z3) = (acx, acy, acz);
}
function ecMul(
uint256 d,
uint256 x1,
uint256 y1,
uint256 z1
)
public
pure
returns (uint256 x3, uint256 y3, uint256 z3)
{
uint256 remaining = d;
uint256 px = x1;
uint256 py = y1;
uint256 pz = z1;
uint256 acx = 0;
uint256 acy = 0;
uint256 acz = 1;
if (d == 0) {
return (0, 0, 1);
}
while (remaining != 0) {
if ((remaining & 1) != 0) {
(acx, acy, acz) = ecAdd(
acx,
acy,
acz,
px,
py,
pz
);
}
remaining = remaining.div(2);
(px, py, pz) = ecDouble(px, py, pz);
}
(x3, y3, z3) = (acx, acy, acz);
}
}
| 4,341,220 | [
1,
7228,
16501,
225,
1220,
6835,
11199,
10426,
549,
21507,
17,
16683,
13008,
1385,
17,
44,
1165,
4728,
498,
7829,
358,
2865,
326,
31176,
43,
1207,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
7773,
16501,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
203,
565,
2254,
5034,
5381,
3238,
389,
43,
60,
273,
374,
92,
7235,
5948,
6028,
27,
26897,
29,
5528,
9676,
2226,
2539,
37,
7677,
29286,
1441,
28,
7301,
38,
8642,
3103,
29,
38,
4488,
2290,
22,
40,
1441,
6030,
40,
29,
6162,
42,
6030,
3600,
38,
2313,
42,
28,
4033,
10689,
31,
203,
565,
2254,
5034,
5381,
3238,
389,
20564,
273,
374,
92,
8875,
23,
1880,
37,
4700,
5558,
37,
23,
39,
8749,
2539,
9793,
24,
22201,
4488,
20,
41,
17506,
28,
37,
28,
16894,
4033,
38,
6334,
28,
37,
9470,
2539,
9803,
2733,
39,
9462,
40,
6840,
2246,
38,
2163,
40,
24,
38,
28,
31,
203,
565,
2254,
5034,
5381,
3238,
389,
50,
225,
273,
374,
6356,
8998,
8998,
8998,
8998,
8998,
8998,
8998,
8998,
8998,
8998,
8998,
8998,
8998,
8090,
8998,
4488,
22,
42,
31,
203,
565,
2254,
5034,
5381,
3238,
389,
37,
225,
273,
374,
31,
203,
203,
203,
565,
3431,
6640,
25417,
261,
39,
13,
14863,
12038,
37,
900,
511,
5113,
203,
203,
565,
445,
12085,
12,
11890,
5034,
22849,
13,
3903,
16618,
1135,
261,
11890,
5034,
1043,
92,
16,
2254,
5034,
1043,
93,
13,
288,
203,
3639,
2254,
5034,
619,
31,
203,
3639,
2254,
5034,
677,
31,
203,
3639,
2254,
5034,
998,
31,
203,
3639,
261,
92,
16,
677,
16,
998,
13,
273,
6557,
27860,
12,
203,
5411,
22849,
16,
203,
5411,
389,
43,
60,
16,
203,
5411,
389,
20564,
16,
203,
5411,
404,
203,
2
] |
pragma solidity ^0.4.8;
//代币合约
contract token {
string public name = "cao token"; //代币名称
string public symbol = "CAO"; //代币符号比如'$'
uint8 public decimals = 18; //代币单位,展示的小数点后面多少个0,和以太币一样后面是是18个0
uint256 public totalSupply; //代币总量,这里没有做限制,你也可以限定
//地址对应的余额
mapping (address => uint256) public balanceOf;
event Transfer(address indexed from, address indexed to, uint256 value); //转帐通知事件
/* 初始化合约,并且把初始的所有代币都给这合约的创建者
* @param _owned 合约的管理者
* @param tokenName 代币名称
* @param tokenSymbol 代币符号
*/
function token(address _owned, string tokenName, string tokenSymbol) public {
//合约的创建者获得的所有代币
balanceOf[_owned] = totalSupply;
name = tokenName;
symbol = tokenSymbol;
}
/**
* 转帐,具体可以根据自己的需求来实现
* @param _to address 接受代币的地址
* @param _value uint256 接受代币的数量
*/
function transfer(address _to, uint256 _value) public{
//从发送者减掉发送额
balanceOf[msg.sender] -= _value;
//给接收者加上相同的量
balanceOf[_to] += _value;
//通知任何监听该交易的客户端
Transfer(msg.sender, _to, _value);
}
/**
* 增加代币,并将代币发送给捐赠新用户,即所谓的增发,本文固定总量,
* @param _to address 接受代币的地址
* @param _amount uint256 接受代币的数量
*/
function issue(address _to, uint256 _amount) public{
totalSupply = totalSupply + _amount;
balanceOf[_to] += _amount;
//通知任何监听该交易的客户端
Transfer(this, _to, _amount);
}
}
/**
* 众筹合约
*/
contract CAOsale is token {
address public beneficiary = msg.sender; //受益人地址,测试时为合约创建者,自己发自己
uint public fundingGoal; //众筹目标,单位是ether
uint public amountRaised; //已筹集金额数量, 单位是wei
uint public deadline; //截止时间
uint public price; //代币价格
bool public fundingGoalReached = false; //达成众筹目标,默认未完成
bool public crowdsaleClosed = false; //众筹关闭,默认不关闭
mapping(address => uint256) public balance; //保存众筹地址
//记录已接收的eth通知
event GoalReached(address _beneficiary, uint _amountRaised);
//转帐时事件
event FundTransfer(address _backer, uint _amount, bool _isContribution);
/**
* 初始化构造函数
* @param fundingGoalInEthers 众筹以太币总量
* @param durationInMinutes 众筹截止,单位是分钟
* @param tokenName 代币名称
* @param tokenSymbol 代币符号
*/
// 在初始化众筹合约构造函数的时候,我们会将众筹合约的帐户地址,
// 传递给代币做为管理地址,这里使用的是关键字this表示当前合约的地址,
// 也可以传递给某个人,初始创建时奖励给这个人指定量的代币。
function CAOsale(
uint fundingGoalInEthers,
uint durationInMinutes,
string tokenName,
string tokenSymbol
) public token(this, tokenName, tokenSymbol){
fundingGoal = fundingGoalInEthers * 1 ether;
deadline = now + durationInMinutes * 1 minutes;
price = 0.00001 ether; //1个以太币可以买 1 个代币
}
// 在众筹合约中,用于设置众筹以太币总量、众筹截止时间、以太币和代币的兑换比例,
// 如果不使用单位进行声明换算,默认在以太坊中,所有的单位都是wei,1 ether=10^18 wei:
/**
* 默认函数
*
* 默认函数,可以向合约直接打款
*/
function () payable public{
//判断是否关闭众筹
//如果关闭,则禁止打款.
require(!crowdsaleClosed);
// if (!crowdsaleClosed) throw; 这个是老写法,版本大坑啊!
uint amount = msg.value;
//捐款人的金额累加
balance[msg.sender] += amount;
//捐款总额累加
amountRaised += amount;
//转帐操作,转多少代币给捐款人
issue(msg.sender, amount / price * 10 ** uint256(decimals));
FundTransfer(msg.sender, amount, true);
}
/**
* 判断是否已经过了众筹截止限期
*/
modifier afterDeadline() {
// if (this == msg.sender && now >= deadline) _; 并且该方法只能被创建者调用,严格一点
if (now >= deadline) _;
}
/**
* 检测众筹目标是否完成
*/
function checkGoalReached() afterDeadline public{
if (amountRaised >= fundingGoal){
//达成众筹目标
fundingGoalReached = true;
GoalReached(beneficiary, amountRaised);
}
//关闭众筹,禁止打款
crowdsaleClosed = true;
}
/**
* 收回资金
* 检查是否达到了目标或时间限制,如果有,并且达到了资金目标,
* 将全部金额发送给受益人。如果没有达到目标,每个贡献者都可以退出
* 他们贡献的金额
*/
function safeWithdrawal() afterDeadline public{
//如果没有达成众筹目标,清空代币
if (!fundingGoalReached) {
//获取合约调用者已捐款余额
uint amount = balance[msg.sender];
if (amount > 0) {
//返回合约发起者所有余额
//transfer是自带的方法,就是朝msg.sender转入数量的意思.类似方法还有 send
//文档具体地址:http://solidity.readthedocs.io/en/develop/types.html#members-of-addresses
msg.sender.transfer(amount);
FundTransfer(msg.sender, amount, false);
balance[msg.sender] = 0;
}
}
//如果达成众筹目标,并且合约调用者是受益人
if (fundingGoalReached && beneficiary == msg.sender) {
//将所有捐款从合约中给受益人
beneficiary.transfer(amountRaised);
FundTransfer(beneficiary, amount, false);
}
}
} | * 判断是否已经过了众筹截止限期/ if (this == msg.sender && now >= deadline) _; 并且该方法只能被创建者调用,严格一点 | modifier afterDeadline() {
if (now >= deadline) _;
}
| 601,523 | [
1,
166,
235,
102,
167,
249,
260,
167,
251,
112,
166,
243,
104,
166,
120,
115,
168,
124,
242,
169,
128,
234,
165,
123,
233,
165,
125,
250,
168,
260,
122,
167,
235,
108,
167,
260,
100,
170,
252,
243,
167,
255,
258,
19,
309,
261,
2211,
422,
1234,
18,
15330,
597,
2037,
1545,
14096,
13,
389,
31,
225,
166,
122,
119,
165,
121,
247,
169,
112,
103,
167,
249,
122,
167,
116,
248,
166,
242,
108,
169,
230,
126,
169,
100,
109,
166,
235,
254,
166,
124,
123,
169,
227,
232,
169,
113,
230,
168,
247,
106,
16,
165,
121,
103,
167,
259,
125,
165,
121,
227,
168,
229,
122,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
9606,
1839,
15839,
1435,
288,
203,
3639,
309,
261,
3338,
1545,
14096,
13,
389,
31,
203,
3639,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0x489dC359F9f1799FBf388abf91cFe7cb37736D6a/sources/contracts/PToken.sol | * @notice Get the current allowance from `owner` for `spender` @param owner The address of the account which owns the tokens to be spent @param spender The address of the account which may transfer tokens @return The number of tokens allowed to be spent (-1 means infinite)/ | function allowance(address owner, address spender) external view override returns (uint256) {
return transferAllowances[owner][spender];
}
| 8,387,160 | [
1,
967,
326,
783,
1699,
1359,
628,
1375,
8443,
68,
364,
1375,
87,
1302,
264,
68,
225,
3410,
1021,
1758,
434,
326,
2236,
1492,
29065,
326,
2430,
358,
506,
26515,
225,
17571,
264,
1021,
1758,
434,
326,
2236,
1492,
2026,
7412,
2430,
327,
1021,
1300,
434,
2430,
2935,
358,
506,
26515,
24927,
21,
4696,
14853,
13176,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
1699,
1359,
12,
2867,
3410,
16,
1758,
17571,
264,
13,
3903,
1476,
3849,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
7412,
7009,
6872,
63,
8443,
6362,
87,
1302,
264,
15533,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.18;
// File: contracts-origin/AetherAccessControl.sol
/// @title A facet of AetherCore that manages special access privileges.
/// @dev See the AetherCore contract documentation to understand how the various contract facets are arranged.
contract AetherAccessControl {
// This facet controls access control for Laputa. There are four roles managed here:
//
// - The CEO: The CEO can reassign other roles and change the addresses of our dependent smart
// contracts. It is also the only role that can unpause the smart contract. It is initially
// set to the address that created the smart contract in the AetherCore constructor.
//
// - The CFO: The CFO can withdraw funds from AetherCore and its auction contracts.
//
// - The COO: The COO can release properties to auction.
//
// It should be noted that these roles are distinct without overlap in their access abilities, the
// abilities listed for each role above are exhaustive. In particular, while the CEO can assign any
// address to any role, the CEO address itself doesn't have the ability to act in those roles. This
// restriction is intentional so that we aren't tempted to use the CEO address frequently out of
// convenience. The less we use an address, the less likely it is that we somehow compromise the
// account.
/// @dev Emited when contract is upgraded - See README.md for updgrade plan
event ContractUpgrade(address newContract);
// The addresses of the accounts (or contracts) that can execute actions within each roles.
address public ceoAddress;
address public cfoAddress;
address public cooAddress;
// @dev Keeps track whether the contract is paused. When that is true, most actions are blocked
bool public paused = false;
/// @dev Access modifier for CEO-only functionality
modifier onlyCEO() {
require(msg.sender == ceoAddress);
_;
}
/// @dev Access modifier for CFO-only functionality
modifier onlyCFO() {
require(msg.sender == cfoAddress);
_;
}
/// @dev Access modifier for COO-only functionality
modifier onlyCOO() {
require(msg.sender == cooAddress);
_;
}
modifier onlyCLevel() {
require(
msg.sender == cooAddress ||
msg.sender == ceoAddress ||
msg.sender == cfoAddress
);
_;
}
/// @dev Assigns a new address to act as the CEO. Only available to the current CEO.
/// @param _newCEO The address of the new CEO
function setCEO(address _newCEO) public onlyCEO {
require(_newCEO != address(0));
ceoAddress = _newCEO;
}
/// @dev Assigns a new address to act as the CFO. Only available to the current CEO.
/// @param _newCFO The address of the new CFO
function setCFO(address _newCFO) public onlyCEO {
require(_newCFO != address(0));
cfoAddress = _newCFO;
}
/// @dev Assigns a new address to act as the COO. Only available to the current CEO.
/// @param _newCOO The address of the new COO
function setCOO(address _newCOO) public onlyCEO {
require(_newCOO != address(0));
cooAddress = _newCOO;
}
function withdrawBalance() external onlyCFO {
cfoAddress.transfer(this.balance);
}
/*** Pausable functionality adapted from OpenZeppelin ***/
/// @dev Modifier to allow actions only when the contract IS NOT paused
modifier whenNotPaused() {
require(!paused);
_;
}
/// @dev Modifier to allow actions only when the contract IS paused
modifier whenPaused {
require(paused);
_;
}
/// @dev Called by any "C-level" role to pause the contract. Used only when
/// a bug or exploit is detected and we need to limit damage.
function pause() public onlyCLevel whenNotPaused {
paused = true;
}
/// @dev Unpauses the smart contract. Can only be called by the CEO, since
/// one reason we may pause the contract is when CFO or COO accounts are
/// compromised.
function unpause() public onlyCEO whenPaused {
// can't unpause if contract was upgraded
paused = false;
}
}
// File: contracts-origin/AetherBase.sol
/// @title Base contract for Aether. Holds all common structs, events and base variables.
/// @author Project Aether (https://www.aether.city)
/// @dev See the PropertyCore contract documentation to understand how the various contract facets are arranged.
contract AetherBase is AetherAccessControl {
/*** EVENTS ***/
/// @dev The Construct event is fired whenever a property updates.
event Construct (
address indexed owner,
uint256 propertyId,
PropertyClass class,
uint8 x,
uint8 y,
uint8 z,
uint8 dx,
uint8 dz,
string data
);
/// @dev Transfer event as defined in current draft of ERC721. Emitted every
/// time a property ownership is assigned.
event Transfer(
address indexed from,
address indexed to,
uint256 indexed tokenId
);
/*** DATA ***/
enum PropertyClass { DISTRICT, BUILDING, UNIT }
/// @dev The main Property struct. Every property in Aether is represented
/// by a variant of this structure.
struct Property {
uint32 parent;
PropertyClass class;
uint8 x;
uint8 y;
uint8 z;
uint8 dx;
uint8 dz;
}
/*** STORAGE ***/
/// @dev Ensures that property occupies unique part of the universe.
bool[100][100][100] public world;
/// @dev An array containing the Property struct for all properties in existence. The ID
/// of each property is actually an index into this array.
Property[] properties;
/// @dev An array containing the district addresses in existence.
uint256[] districts;
/// @dev A measure of world progression.
uint256 public progress;
/// @dev The fee associated with constructing a unit property.
uint256 public unitCreationFee = 0.05 ether;
/// @dev Keeps track whether updating data is paused.
bool public updateEnabled = true;
/// @dev A mapping from property IDs to the address that owns them. All properties have
/// some valid owner address, even gen0 properties are created with a non-zero owner.
mapping (uint256 => address) public propertyIndexToOwner;
/// @dev A mapping from property IDs to the data that is stored on them.
mapping (uint256 => string) public propertyIndexToData;
/// @dev A mapping from owner address to count of tokens that address owns.
/// Used internally inside balanceOf() to resolve ownership count.
mapping (address => uint256) ownershipTokenCount;
/// @dev Mappings between property nodes.
mapping (uint256 => uint256) public districtToBuildingsCount;
mapping (uint256 => uint256[]) public districtToBuildings;
mapping (uint256 => uint256) public buildingToUnitCount;
mapping (uint256 => uint256[]) public buildingToUnits;
/// @dev A mapping from building propertyId to unit construction privacy.
mapping (uint256 => bool) public buildingIsPublic;
/// @dev A mapping from PropertyIDs to an address that has been approved to call
/// transferFrom(). Each Property can only have one approved address for transfer
/// at any time. A zero value means no approval is outstanding.
mapping (uint256 => address) public propertyIndexToApproved;
/// @dev Assigns ownership of a specific Property to an address.
function _transfer(address _from, address _to, uint256 _tokenId) internal {
// since the number of properties is capped to 2^32
// there is no way to overflow this
ownershipTokenCount[_to]++;
// transfer ownership
propertyIndexToOwner[_tokenId] = _to;
// When creating new properties _from is 0x0, but we can't account that address.
if (_from != address(0)) {
ownershipTokenCount[_from]--;
// clear any previously approved ownership exchange
delete propertyIndexToApproved[_tokenId];
}
// Emit the transfer event.
Transfer(_from, _to, _tokenId);
}
function _createUnit(
uint256 _parent,
uint256 _x,
uint256 _y,
uint256 _z,
address _owner
)
internal
returns (uint)
{
require(_x == uint256(uint8(_x)));
require(_y == uint256(uint8(_y)));
require(_z == uint256(uint8(_z)));
require(!world[_x][_y][_z]);
world[_x][_y][_z] = true;
return _createProperty(
_parent,
PropertyClass.UNIT,
_x,
_y,
_z,
0,
0,
_owner
);
}
function _createBuilding(
uint256 _parent,
uint256 _x,
uint256 _y,
uint256 _z,
uint256 _dx,
uint256 _dz,
address _owner,
bool _public
)
internal
returns (uint)
{
require(_x == uint256(uint8(_x)));
require(_y == uint256(uint8(_y)));
require(_z == uint256(uint8(_z)));
require(_dx == uint256(uint8(_dx)));
require(_dz == uint256(uint8(_dz)));
// Looping over world space.
for(uint256 i = 0; i < _dx; i++) {
for(uint256 j = 0; j <_dz; j++) {
if (world[_x + i][0][_z + j]) {
revert();
}
world[_x + i][0][_z + j] = true;
}
}
uint propertyId = _createProperty(
_parent,
PropertyClass.BUILDING,
_x,
_y,
_z,
_dx,
_dz,
_owner
);
districtToBuildingsCount[_parent]++;
districtToBuildings[_parent].push(propertyId);
buildingIsPublic[propertyId] = _public;
return propertyId;
}
function _createDistrict(
uint256 _x,
uint256 _z,
uint256 _dx,
uint256 _dz
)
internal
returns (uint)
{
require(_x == uint256(uint8(_x)));
require(_z == uint256(uint8(_z)));
require(_dx == uint256(uint8(_dx)));
require(_dz == uint256(uint8(_dz)));
uint propertyId = _createProperty(
districts.length,
PropertyClass.DISTRICT,
_x,
0,
_z,
_dx,
_dz,
cooAddress
);
districts.push(propertyId);
return propertyId;
}
/// @dev An internal method that creates a new property and stores it. This
/// method doesn't do any checking and should only be called when the
/// input data is known to be valid. Will generate both a Construct event
/// and a Transfer event.
function _createProperty(
uint256 _parent,
PropertyClass _class,
uint256 _x,
uint256 _y,
uint256 _z,
uint256 _dx,
uint256 _dz,
address _owner
)
internal
returns (uint)
{
require(_x == uint256(uint8(_x)));
require(_y == uint256(uint8(_y)));
require(_z == uint256(uint8(_z)));
require(_dx == uint256(uint8(_dx)));
require(_dz == uint256(uint8(_dz)));
require(_parent == uint256(uint32(_parent)));
require(uint256(_class) <= 3);
Property memory _property = Property({
parent: uint32(_parent),
class: _class,
x: uint8(_x),
y: uint8(_y),
z: uint8(_z),
dx: uint8(_dx),
dz: uint8(_dz)
});
uint256 _tokenId = properties.push(_property) - 1;
// It's never going to happen, 4 billion properties is A LOT, but
// let's just be 100% sure we never let this happen.
require(_tokenId <= 4294967295);
Construct(
_owner,
_tokenId,
_property.class,
_property.x,
_property.y,
_property.z,
_property.dx,
_property.dz,
""
);
// This will assign ownership, and also emit the Transfer event as
// per ERC721 draft
_transfer(0, _owner, _tokenId);
return _tokenId;
}
/// @dev Computing height of a building with respect to city progression.
function _computeHeight(
uint256 _x,
uint256 _z,
uint256 _height
) internal view returns (uint256) {
uint256 x = _x < 50 ? 50 - _x : _x - 50;
uint256 z = _z < 50 ? 50 - _z : _z - 50;
uint256 distance = x > z ? x : z;
if (distance > progress) {
return 1;
}
uint256 scale = 100 - (distance * 100) / progress ;
uint256 height = 2 * progress * _height * scale / 10000;
return height > 0 ? height : 1;
}
/// @dev Convenience function to see if this building has room for a unit.
function canCreateUnit(uint256 _buildingId)
public
view
returns(bool)
{
Property storage _property = properties[_buildingId];
if (_property.class == PropertyClass.BUILDING &&
(buildingIsPublic[_buildingId] ||
propertyIndexToOwner[_buildingId] == msg.sender)
) {
uint256 totalVolume = _property.dx * _property.dz *
(_computeHeight(_property.x, _property.z, _property.y) - 1);
uint256 totalUnits = buildingToUnitCount[_buildingId];
return totalUnits < totalVolume;
}
return false;
}
/// @dev This internal function skips all validation checks. Ensure that
// canCreateUnit() is required before calling this method.
function _createUnitHelper(uint256 _buildingId, address _owner)
internal
returns(uint256)
{
// Grab a reference to the property in storage.
Property storage _property = properties[_buildingId];
uint256 totalArea = _property.dx * _property.dz;
uint256 index = buildingToUnitCount[_buildingId];
// Calculate next location.
uint256 y = index / totalArea + 1;
uint256 intermediate = index % totalArea;
uint256 z = intermediate / _property.dx;
uint256 x = intermediate % _property.dx;
uint256 unitId = _createUnit(
_buildingId,
x + _property.x,
y,
z + _property.z,
_owner
);
buildingToUnitCount[_buildingId]++;
buildingToUnits[_buildingId].push(unitId);
// Return the new unit's ID.
return unitId;
}
/// @dev Update allows for setting a building privacy.
function updateBuildingPrivacy(uint _tokenId, bool _public) public {
require(propertyIndexToOwner[_tokenId] == msg.sender);
buildingIsPublic[_tokenId] = _public;
}
/// @dev Update allows for setting the data associated to a property.
function updatePropertyData(uint _tokenId, string _data) public {
require(updateEnabled);
address _owner = propertyIndexToOwner[_tokenId];
require(msg.sender == _owner);
propertyIndexToData[_tokenId] = _data;
Property memory _property = properties[_tokenId];
Construct(
_owner,
_tokenId,
_property.class,
_property.x,
_property.y,
_property.z,
_property.dx,
_property.dz,
_data
);
}
}
// File: contracts-origin/ERC721Draft.sol
/// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens
/// @author Dieter Shirley <[email protected]> (https://github.com/dete)
contract ERC721 {
function implementsERC721() public pure returns (bool);
function totalSupply() public view returns (uint256 total);
function balanceOf(address _owner) public view returns (uint256 balance);
function ownerOf(uint256 _tokenId) public view returns (address owner);
function approve(address _to, uint256 _tokenId) public;
function transferFrom(address _from, address _to, uint256 _tokenId) public;
function transfer(address _to, uint256 _tokenId) public;
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
// Optional
// function name() public view returns (string name);
// function symbol() public view returns (string symbol);
// function tokensOfOwner(address _owner) external view returns (uint256[] tokenIds);
// function tokenMetadata(uint256 _tokenId) public view returns (string infoUrl);
}
// File: contracts-origin/AetherOwnership.sol
/// @title The facet of the Aether core contract that manages ownership, ERC-721 (draft) compliant.
/// @dev Ref: https://github.com/ethereum/EIPs/issues/721
/// See the PropertyCore contract documentation to understand how the various contract facets are arranged.
contract AetherOwnership is AetherBase, ERC721 {
/// @notice Name and symbol of the non fungible token, as defined in ERC721.
string public name = "Aether";
string public symbol = "AETH";
function implementsERC721() public pure returns (bool)
{
return true;
}
// Internal utility functions: These functions all assume that their input arguments
// are valid. We leave it to public methods to sanitize their inputs and follow
// the required logic.
/// @dev Checks if a given address is the current owner of a particular Property.
/// @param _claimant the address we are validating against.
/// @param _tokenId property id, only valid when > 0
function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) {
return propertyIndexToOwner[_tokenId] == _claimant;
}
/// @dev Checks if a given address currently has transferApproval for a particular Property.
/// @param _claimant the address we are confirming property is approved for.
/// @param _tokenId property id, only valid when > 0
function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) {
return propertyIndexToApproved[_tokenId] == _claimant;
}
/// @dev Marks an address as being approved for transferFrom(), overwriting any previous
/// approval. Setting _approved to address(0) clears all transfer approval.
/// NOTE: _approve() does NOT send the Approval event. This is intentional because
/// _approve() and transferFrom() are used together for putting Properties on auction, and
/// there is no value in spamming the log with Approval events in that case.
function _approve(uint256 _tokenId, address _approved) internal {
propertyIndexToApproved[_tokenId] = _approved;
}
/// @dev Transfers a property owned by this contract to the specified address.
/// Used to rescue lost properties. (There is no "proper" flow where this contract
/// should be the owner of any Property. This function exists for us to reassign
/// the ownership of Properties that users may have accidentally sent to our address.)
/// @param _propertyId - ID of property
/// @param _recipient - Address to send the property to
function rescueLostProperty(uint256 _propertyId, address _recipient) public onlyCOO whenNotPaused {
require(_owns(this, _propertyId));
_transfer(this, _recipient, _propertyId);
}
/// @notice Returns the number of Properties owned by a specific address.
/// @param _owner The owner address to check.
/// @dev Required for ERC-721 compliance
function balanceOf(address _owner) public view returns (uint256 count) {
return ownershipTokenCount[_owner];
}
/// @notice Transfers a Property to another address. If transferring to a smart
/// contract be VERY CAREFUL to ensure that it is aware of ERC-721 (or
/// Laputa specifically) or your Property may be lost forever. Seriously.
/// @param _to The address of the recipient, can be a user or contract.
/// @param _tokenId The ID of the Property to transfer.
/// @dev Required for ERC-721 compliance.
function transfer(
address _to,
uint256 _tokenId
)
public
whenNotPaused
{
// Safety check to prevent against an unexpected 0x0 default.
require(_to != address(0));
// You can only send your own property.
require(_owns(msg.sender, _tokenId));
// Reassign ownership, clear pending approvals, emit Transfer event.
_transfer(msg.sender, _to, _tokenId);
}
/// @notice Grant another address the right to transfer a specific Property via
/// transferFrom(). This is the preferred flow for transfering NFTs to contracts.
/// @param _to The address to be granted transfer approval. Pass address(0) to
/// clear all approvals.
/// @param _tokenId The ID of the Property that can be transferred if this call succeeds.
/// @dev Required for ERC-721 compliance.
function approve(
address _to,
uint256 _tokenId
)
public
whenNotPaused
{
// Only an owner can grant transfer approval.
require(_owns(msg.sender, _tokenId));
// Register the approval (replacing any previous approval).
_approve(_tokenId, _to);
// Emit approval event.
Approval(msg.sender, _to, _tokenId);
}
/// @notice Transfer a Property owned by another address, for which the calling address
/// has previously been granted transfer approval by the owner.
/// @param _from The address that owns the Property to be transfered.
/// @param _to The address that should take ownership of the Property. Can be any address,
/// including the caller.
/// @param _tokenId The ID of the Property to be transferred.
/// @dev Required for ERC-721 compliance.
function transferFrom(
address _from,
address _to,
uint256 _tokenId
)
public
whenNotPaused
{
// Check for approval and valid ownership
require(_approvedFor(msg.sender, _tokenId));
require(_owns(_from, _tokenId));
// Reassign ownership (also clears pending approvals and emits Transfer event).
_transfer(_from, _to, _tokenId);
}
/// @notice Returns the total number of Properties currently in existence.
/// @dev Required for ERC-721 compliance.
function totalSupply() public view returns (uint) {
return properties.length;
}
function totalDistrictSupply() public view returns(uint count) {
return districts.length;
}
/// @notice Returns the address currently assigned ownership of a given Property.
/// @dev Required for ERC-721 compliance.
function ownerOf(uint256 _tokenId)
public
view
returns (address owner)
{
owner = propertyIndexToOwner[_tokenId];
require(owner != address(0));
}
/// @notice Returns a list of all Property IDs assigned to an address.
/// @param _owner The owner whose Properties we are interested in.
/// @dev This method MUST NEVER be called by smart contract code. First, it's fairly
/// expensive (it walks the entire Kitty array looking for cats belonging to owner),
/// but it also returns a dynamic array, which is only supported for web3 calls, and
/// not contract-to-contract calls.
function tokensOfOwner(address _owner) external view returns(uint256[] ownerTokens) {
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
// Return an empty array
return new uint256[](0);
} else {
uint256[] memory result = new uint256[](tokenCount);
uint256 totalProperties = totalSupply();
uint256 resultIndex = 0;
// We count on the fact that all properties have IDs starting at 1 and increasing
// sequentially up to the totalProperties count.
uint256 tokenId;
for (tokenId = 1; tokenId <= totalProperties; tokenId++) {
if (propertyIndexToOwner[tokenId] == _owner) {
result[resultIndex] = tokenId;
resultIndex++;
}
}
return result;
}
}
}
// File: contracts-origin/Auction/ClockAuctionBase.sol
/// @title Auction Core
/// @dev Contains models, variables, and internal methods for the auction.
contract ClockAuctionBase {
// Represents an auction on an NFT
struct Auction {
// Current owner of NFT
address seller;
// Price (in wei) at beginning of auction
uint128 startingPrice;
// Price (in wei) at end of auction
uint128 endingPrice;
// Duration (in seconds) of auction
uint64 duration;
// Time when auction started
// NOTE: 0 if this auction has been concluded
uint64 startedAt;
}
// Reference to contract tracking NFT ownership
ERC721 public nonFungibleContract;
// Cut owner takes on each auction, measured in basis points (1/100 of a percent).
// Values 0-10,000 map to 0%-100%
uint256 public ownerCut;
// Map from token ID to their corresponding auction.
mapping (uint256 => Auction) tokenIdToAuction;
event AuctionCreated(uint256 tokenId, uint256 startingPrice, uint256 endingPrice, uint256 duration);
event AuctionSuccessful(uint256 tokenId, uint256 totalPrice, address winner);
event AuctionCancelled(uint256 tokenId);
/// @dev DON'T give me your money.
function() external {}
// Modifiers to check that inputs can be safely stored with a certain
// number of bits. We use constants and multiple modifiers to save gas.
modifier canBeStoredWith64Bits(uint256 _value) {
require(_value <= 18446744073709551615);
_;
}
modifier canBeStoredWith128Bits(uint256 _value) {
require(_value < 340282366920938463463374607431768211455);
_;
}
/// @dev Returns true if the claimant owns the token.
/// @param _claimant - Address claiming to own the token.
/// @param _tokenId - ID of token whose ownership to verify.
function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) {
return (nonFungibleContract.ownerOf(_tokenId) == _claimant);
}
/// @dev Escrows the NFT, assigning ownership to this contract.
/// Throws if the escrow fails.
/// @param _owner - Current owner address of token to escrow.
/// @param _tokenId - ID of token whose approval to verify.
function _escrow(address _owner, uint256 _tokenId) internal {
// it will throw if transfer fails
nonFungibleContract.transferFrom(_owner, this, _tokenId);
}
/// @dev Transfers an NFT owned by this contract to another address.
/// Returns true if the transfer succeeds.
/// @param _receiver - Address to transfer NFT to.
/// @param _tokenId - ID of token to transfer.
function _transfer(address _receiver, uint256 _tokenId) internal {
// it will throw if transfer fails
nonFungibleContract.transfer(_receiver, _tokenId);
}
/// @dev Adds an auction to the list of open auctions. Also fires the
/// AuctionCreated event.
/// @param _tokenId The ID of the token to be put on auction.
/// @param _auction Auction to add.
function _addAuction(uint256 _tokenId, Auction _auction) internal {
// Require that all auctions have a duration of
// at least one minute. (Keeps our math from getting hairy!)
require(_auction.duration >= 1 minutes);
tokenIdToAuction[_tokenId] = _auction;
AuctionCreated(
uint256(_tokenId),
uint256(_auction.startingPrice),
uint256(_auction.endingPrice),
uint256(_auction.duration)
);
}
/// @dev Cancels an auction unconditionally.
function _cancelAuction(uint256 _tokenId, address _seller) internal {
_removeAuction(_tokenId);
_transfer(_seller, _tokenId);
AuctionCancelled(_tokenId);
}
/// @dev Computes the price and transfers winnings.
/// Does NOT transfer ownership of token.
function _bid(uint256 _tokenId, uint256 _bidAmount)
internal
returns (uint256)
{
// Get a reference to the auction struct
Auction storage auction = tokenIdToAuction[_tokenId];
// Explicitly check that this auction is currently live.
// (Because of how Ethereum mappings work, we can't just count
// on the lookup above failing. An invalid _tokenId will just
// return an auction object that is all zeros.)
require(_isOnAuction(auction));
// Check that the incoming bid is higher than the current
// price
uint256 price = _currentPrice(auction);
require(_bidAmount >= price);
// Grab a reference to the seller before the auction struct
// gets deleted.
address seller = auction.seller;
// The bid is good! Remove the auction before sending the fees
// to the sender so we can't have a reentrancy attack.
_removeAuction(_tokenId);
// Transfer proceeds to seller (if there are any!)
if (price > 0) {
// Calculate the auctioneer's cut.
// (NOTE: _computeCut() is guaranteed to return a
// value <= price, so this subtraction can't go negative.)
uint256 auctioneerCut = _computeCut(price);
uint256 sellerProceeds = price - auctioneerCut;
// NOTE: Doing a transfer() in the middle of a complex
// method like this is generally discouraged because of
// reentrancy attacks and DoS attacks if the seller is
// a contract with an invalid fallback function. We explicitly
// guard against reentrancy attacks by removing the auction
// before calling transfer(), and the only thing the seller
// can DoS is the sale of their own asset! (And if it's an
// accident, they can call cancelAuction(). )
seller.transfer(sellerProceeds);
}
// Tell the world!
AuctionSuccessful(_tokenId, price, msg.sender);
return price;
}
/// @dev Removes an auction from the list of open auctions.
/// @param _tokenId - ID of NFT on auction.
function _removeAuction(uint256 _tokenId) internal {
delete tokenIdToAuction[_tokenId];
}
/// @dev Returns true if the NFT is on auction.
/// @param _auction - Auction to check.
function _isOnAuction(Auction storage _auction) internal view returns (bool) {
return (_auction.startedAt > 0);
}
/// @dev Returns current price of an NFT on auction. Broken into two
/// functions (this one, that computes the duration from the auction
/// structure, and the other that does the price computation) so we
/// can easily test that the price computation works correctly.
function _currentPrice(Auction storage _auction)
internal
view
returns (uint256)
{
uint256 secondsPassed = 0;
// A bit of insurance against negative values (or wraparound).
// Probably not necessary (since Ethereum guarnatees that the
// now variable doesn't ever go backwards).
if (now > _auction.startedAt) {
secondsPassed = now - _auction.startedAt;
}
return _computeCurrentPrice(
_auction.startingPrice,
_auction.endingPrice,
_auction.duration,
secondsPassed
);
}
/// @dev Computes the current price of an auction. Factored out
/// from _currentPrice so we can run extensive unit tests.
/// When testing, make this function public and turn on
/// `Current price computation` test suite.
function _computeCurrentPrice(
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration,
uint256 _secondsPassed
)
internal
pure
returns (uint256)
{
// NOTE: We don't use SafeMath (or similar) in this function because
// all of our public functions carefully cap the maximum values for
// time (at 64-bits) and currency (at 128-bits). _duration is
// also known to be non-zero (see the require() statement in
// _addAuction())
if (_secondsPassed >= _duration) {
// We've reached the end of the dynamic pricing portion
// of the auction, just return the end price.
return _endingPrice;
} else {
// Starting price can be higher than ending price (and often is!), so
// this delta can be negative.
int256 totalPriceChange = int256(_endingPrice) - int256(_startingPrice);
// This multiplication can't overflow, _secondsPassed will easily fit within
// 64-bits, and totalPriceChange will easily fit within 128-bits, their product
// will always fit within 256-bits.
int256 currentPriceChange = totalPriceChange * int256(_secondsPassed) / int256(_duration);
// currentPriceChange can be negative, but if so, will have a magnitude
// less that _startingPrice. Thus, this result will always end up positive.
int256 currentPrice = int256(_startingPrice) + currentPriceChange;
return uint256(currentPrice);
}
}
/// @dev Computes owner's cut of a sale.
/// @param _price - Sale price of NFT.
function _computeCut(uint256 _price) internal view returns (uint256) {
// NOTE: We don't use SafeMath (or similar) in this function because
// all of our entry functions carefully cap the maximum values for
// currency (at 128-bits), and ownerCut <= 10000 (see the require()
// statement in the ClockAuction constructor). The result of this
// function is always guaranteed to be <= _price.
return _price * ownerCut / 10000;
}
}
// File: zeppelin-solidity/contracts/ownership/Ownable.sol
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) onlyOwner {
if (newOwner != address(0)) {
owner = newOwner;
}
}
}
// File: zeppelin-solidity/contracts/lifecycle/Pausable.sol
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev modifier to allow actions only when the contract IS paused
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev modifier to allow actions only when the contract IS NOT paused
*/
modifier whenPaused {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused returns (bool) {
paused = true;
Pause();
return true;
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused returns (bool) {
paused = false;
Unpause();
return true;
}
}
// File: contracts-origin/Auction/ClockAuction.sol
/// @title Clock auction for non-fungible tokens.
contract ClockAuction is Pausable, ClockAuctionBase {
/// @dev Constructor creates a reference to the NFT ownership contract
/// and verifies the owner cut is in the valid range.
/// @param _nftAddress - address of a deployed contract implementing
/// the Nonfungible Interface.
/// @param _cut - percent cut the owner takes on each auction, must be
/// between 0-10,000.
function ClockAuction(address _nftAddress, uint256 _cut) public {
require(_cut <= 10000);
ownerCut = _cut;
ERC721 candidateContract = ERC721(_nftAddress);
require(candidateContract.implementsERC721());
nonFungibleContract = candidateContract;
}
/// @dev Remove all Ether from the contract, which is the owner's cuts
/// as well as any Ether sent directly to the contract address.
/// Always transfers to the NFT contract, but can be called either by
/// the owner or the NFT contract.
function withdrawBalance() external {
address nftAddress = address(nonFungibleContract);
require(
msg.sender == owner ||
msg.sender == nftAddress
);
nftAddress.transfer(this.balance);
}
/// @dev Creates and begins a new auction.
/// @param _tokenId - ID of token to auction, sender must be owner.
/// @param _startingPrice - Price of item (in wei) at beginning of auction.
/// @param _endingPrice - Price of item (in wei) at end of auction.
/// @param _duration - Length of time to move between starting
/// price and ending price (in seconds).
/// @param _seller - Seller, if not the message sender
function createAuction(
uint256 _tokenId,
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration,
address _seller
)
public
whenNotPaused
canBeStoredWith128Bits(_startingPrice)
canBeStoredWith128Bits(_endingPrice)
canBeStoredWith64Bits(_duration)
{
require(_owns(msg.sender, _tokenId));
_escrow(msg.sender, _tokenId);
Auction memory auction = Auction(
_seller,
uint128(_startingPrice),
uint128(_endingPrice),
uint64(_duration),
uint64(now)
);
_addAuction(_tokenId, auction);
}
/// @dev Bids on an open auction, completing the auction and transferring
/// ownership of the NFT if enough Ether is supplied.
/// @param _tokenId - ID of token to bid on.
function bid(uint256 _tokenId)
public
payable
whenNotPaused
{
// _bid will throw if the bid or funds transfer fails
_bid(_tokenId, msg.value);
_transfer(msg.sender, _tokenId);
}
/// @dev Cancels an auction that hasn't been won yet.
/// Returns the NFT to original owner.
/// @notice This is a state-modifying function that can
/// be called while the contract is paused.
/// @param _tokenId - ID of token on auction
function cancelAuction(uint256 _tokenId)
public
{
Auction storage auction = tokenIdToAuction[_tokenId];
require(_isOnAuction(auction));
address seller = auction.seller;
require(msg.sender == seller);
_cancelAuction(_tokenId, seller);
}
/// @dev Cancels an auction when the contract is paused.
/// Only the owner may do this, and NFTs are returned to
/// the seller. This should only be used in emergencies.
/// @param _tokenId - ID of the NFT on auction to cancel.
function cancelAuctionWhenPaused(uint256 _tokenId)
whenPaused
onlyOwner
public
{
Auction storage auction = tokenIdToAuction[_tokenId];
require(_isOnAuction(auction));
_cancelAuction(_tokenId, auction.seller);
}
/// @dev Returns auction info for an NFT on auction.
/// @param _tokenId - ID of NFT on auction.
function getAuction(uint256 _tokenId)
public
view
returns
(
address seller,
uint256 startingPrice,
uint256 endingPrice,
uint256 duration,
uint256 startedAt
) {
Auction storage auction = tokenIdToAuction[_tokenId];
require(_isOnAuction(auction));
return (
auction.seller,
auction.startingPrice,
auction.endingPrice,
auction.duration,
auction.startedAt
);
}
/// @dev Returns the current price of an auction.
/// @param _tokenId - ID of the token price we are checking.
function getCurrentPrice(uint256 _tokenId)
public
view
returns (uint256)
{
Auction storage auction = tokenIdToAuction[_tokenId];
require(_isOnAuction(auction));
return _currentPrice(auction);
}
}
// File: contracts-origin/Auction/AetherClockAuction.sol
/// @title Clock auction modified for sale of property
contract AetherClockAuction is ClockAuction {
// @dev Sanity check that allows us to ensure that we are pointing to the
// right auction in our setSaleAuctionAddress() call.
bool public isAetherClockAuction = true;
// Tracks last 5 sale price of gen0 property sales
uint256 public saleCount;
uint256[5] public lastSalePrices;
// Delegate constructor
function AetherClockAuction(address _nftAddr, uint256 _cut) public
ClockAuction(_nftAddr, _cut) {}
/// @dev Creates and begins a new auction.
/// @param _tokenId - ID of token to auction, sender must be owner.
/// @param _startingPrice - Price of item (in wei) at beginning of auction.
/// @param _endingPrice - Price of item (in wei) at end of auction.
/// @param _duration - Length of auction (in seconds).
/// @param _seller - Seller, if not the message sender
function createAuction(
uint256 _tokenId,
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration,
address _seller
)
public
canBeStoredWith128Bits(_startingPrice)
canBeStoredWith128Bits(_endingPrice)
canBeStoredWith64Bits(_duration)
{
require(msg.sender == address(nonFungibleContract));
_escrow(_seller, _tokenId);
Auction memory auction = Auction(
_seller,
uint128(_startingPrice),
uint128(_endingPrice),
uint64(_duration),
uint64(now)
);
_addAuction(_tokenId, auction);
}
/// @dev Updates lastSalePrice if seller is the nft contract
/// Otherwise, works the same as default bid method.
function bid(uint256 _tokenId)
public
payable
{
// _bid verifies token ID size
address seller = tokenIdToAuction[_tokenId].seller;
uint256 price = _bid(_tokenId, msg.value);
_transfer(msg.sender, _tokenId);
// If not a gen0 auction, exit
if (seller == address(nonFungibleContract)) {
// Track gen0 sale prices
lastSalePrices[saleCount % 5] = price;
saleCount++;
}
}
function averageSalePrice() public view returns (uint256) {
uint256 sum = 0;
for (uint256 i = 0; i < 5; i++) {
sum += lastSalePrices[i];
}
return sum / 5;
}
}
// File: contracts-origin/AetherAuction.sol
/// @title Handles creating auctions for sale and siring of properties.
/// This wrapper of ReverseAuction exists only so that users can create
/// auctions with only one transaction.
contract AetherAuction is AetherOwnership{
/// @dev The address of the ClockAuction contract that handles sales of Aether. This
/// same contract handles both peer-to-peer sales as well as the gen0 sales which are
/// initiated every 15 minutes.
AetherClockAuction public saleAuction;
/// @dev Sets the reference to the sale auction.
/// @param _address - Address of sale contract.
function setSaleAuctionAddress(address _address) public onlyCEO {
AetherClockAuction candidateContract = AetherClockAuction(_address);
// NOTE: verify that a contract is what we expect
require(candidateContract.isAetherClockAuction());
// Set the new contract address
saleAuction = candidateContract;
}
/// @dev Put a property up for auction.
/// Does some ownership trickery to create auctions in one tx.
function createSaleAuction(
uint256 _propertyId,
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration
)
public
whenNotPaused
{
// Auction contract checks input sizes
// If property is already on any auction, this will throw
// because it will be owned by the auction contract.
require(_owns(msg.sender, _propertyId));
_approve(_propertyId, saleAuction);
// Sale auction throws if inputs are invalid and clears
// transfer and sire approval after escrowing the property.
saleAuction.createAuction(
_propertyId,
_startingPrice,
_endingPrice,
_duration,
msg.sender
);
}
/// @dev Transfers the balance of the sale auction contract
/// to the AetherCore contract. We use two-step withdrawal to
/// prevent two transfer calls in the auction bid function.
function withdrawAuctionBalances() external onlyCOO {
saleAuction.withdrawBalance();
}
}
// File: contracts-origin/AetherConstruct.sol
// Auction wrapper functions
/// @title all functions related to creating property
contract AetherConstruct is AetherAuction {
uint256 public districtLimit = 16;
uint256 public startingPrice = 1 ether;
uint256 public auctionDuration = 1 days;
/// @dev Units can be contructed within public and owned buildings.
function createUnit(uint256 _buildingId)
public
payable
returns(uint256)
{
require(canCreateUnit(_buildingId));
require(msg.value >= unitCreationFee);
if (msg.value > unitCreationFee)
msg.sender.transfer(msg.value - unitCreationFee);
uint256 propertyId = _createUnitHelper(_buildingId, msg.sender);
return propertyId;
}
/// @dev Creation of unit properties. Only callable by COO
function createUnitOmni(
uint32 _buildingId,
address _owner
)
public
onlyCOO
{
if (_owner == address(0)) {
_owner = cooAddress;
}
require(canCreateUnit(_buildingId));
_createUnitHelper(_buildingId, _owner);
}
/// @dev Creation of building properties. Only callable by COO
function createBuildingOmni(
uint32 _districtId,
uint8 _x,
uint8 _y,
uint8 _z,
uint8 _dx,
uint8 _dz,
address _owner,
bool _open
)
public
onlyCOO
{
if (_owner == address(0)) {
_owner = cooAddress;
}
_createBuilding(_districtId, _x, _y, _z, _dx, _dz, _owner, _open);
}
/// @dev Creation of district properties, up to a limit. Only callable by COO
function createDistrictOmni(
uint8 _x,
uint8 _z,
uint8 _dx,
uint8 _dz
)
public
onlyCOO
{
require(districts.length < districtLimit);
_createDistrict(_x, _z, _dx, _dz);
}
/// @dev Creates a new property with the given details and
/// creates an auction for it. Only callable by COO.
function createBuildingAuction(
uint32 _districtId,
uint8 _x,
uint8 _y,
uint8 _z,
uint8 _dx,
uint8 _dz,
bool _open
) public onlyCOO {
uint256 propertyId = _createBuilding(_districtId, _x, _y, _z, _dx, _dz, address(this), _open);
_approve(propertyId, saleAuction);
saleAuction.createAuction(
propertyId,
_computeNextPrice(),
0,
auctionDuration,
address(this)
);
}
/// @dev Updates the minimum payment required for calling createUnit(). Can only
/// be called by the COO address.
function setUnitCreationFee(uint256 _value) public onlyCOO {
unitCreationFee = _value;
}
/// @dev Update world progression factor allowing for buildings to grow taller
// as the city expands. Only callable by COO.
function setProgress(uint256 _progress) public onlyCOO {
require(_progress <= 100);
require(_progress > progress);
progress = _progress;
}
/// @dev Set property data updates flag. Only callable by COO.
function setUpdateState(bool _updateEnabled) public onlyCOO {
updateEnabled = _updateEnabled;
}
/// @dev Computes the next auction starting price, given the average of the past
/// 5 prices + 50%.
function _computeNextPrice() internal view returns (uint256) {
uint256 avePrice = saleAuction.averageSalePrice();
// sanity check to ensure we don't overflow arithmetic (this big number is 2^128-1).
require(avePrice < 340282366920938463463374607431768211455);
uint256 nextPrice = avePrice + (avePrice / 2);
// We never auction for less than starting price
if (nextPrice < startingPrice) {
nextPrice = startingPrice;
}
return nextPrice;
}
}
// File: contracts-origin/AetherCore.sol
/// @title Aether: A city on the Ethereum blockchain.
/// @author Axiom Zen (https://www.axiomzen.co)
contract AetherCore is AetherConstruct {
// This is the main Aether contract. In order to keep our code seperated into logical sections,
// we've broken it up in two ways. The auctions are seperate since their logic is somewhat complex
// and there's always a risk of subtle bugs. By keeping them in their own contracts, we can upgrade
// them without disrupting the main contract that tracks property ownership.
//
// Secondly, we break the core contract into multiple files using inheritence, one for each major
// facet of functionality of Aether. This allows us to keep related code bundled together while still
// avoiding a single giant file with everything in it. The breakdown is as follows:
//
// - AetherBase: This is where we define the most fundamental code shared throughout the core
// functionality. This includes our main data storage, constants and data types, plus
// internal functions for managing these items.
//
// - AetherAccessControl: This contract manages the various addresses and constraints for operations
// that can be executed only by specific roles. Namely CEO, CFO and COO.
//
// - AetherOwnership: This provides the methods required for basic non-fungible token
// transactions, following the draft ERC-721 spec (https://github.com/ethereum/EIPs/issues/721).
//
// - AetherAuction: Here we have the public methods for auctioning or bidding on property.
// The actual auction functionality is handled in two sibling contracts while auction
// creation and bidding is mostly mediated through this facet of the core contract.
//
// - AetherConstruct: This final facet contains the functionality we use for creating new gen0 cats.
// the community is new).
// Set in case the core contract is broken and an upgrade is required
address public newContractAddress;
/// @notice Creates the main Aether smart contract instance.
function AetherCore() public {
// Starts paused.
paused = true;
// the creator of the contract is the initial CEO
ceoAddress = msg.sender;
// the creator of the contract is also the initial COO
cooAddress = msg.sender;
}
/// @dev Used to mark the smart contract as upgraded, in case there is a serious
/// breaking bug. This method does nothing but keep track of the new contract and
/// emit a message indicating that the new address is set. It's up to clients of this
/// contract to update to the new contract address in that case. (This contract will
/// be paused indefinitely if such an upgrade takes place.)
/// @param _v2Address new address
function setNewAddress(address _v2Address) public onlyCEO whenPaused {
// See README.md for updgrade plan
newContractAddress = _v2Address;
ContractUpgrade(_v2Address);
}
/// @notice No tipping!
/// @dev Reject all Ether from being sent here, unless it's from one of the
/// two auction contracts. (Hopefully, we can prevent user accidents.)
function() external payable {
require(
msg.sender == address(saleAuction)
);
}
/// @notice Returns all the relevant information about a specific property.
/// @param _id The ID of the property of interest.
function getProperty(uint256 _id)
public
view
returns (
uint32 parent,
uint8 class,
uint8 x,
uint8 y,
uint8 z,
uint8 dx,
uint8 dz,
uint8 height
) {
Property storage property = properties[_id];
parent = uint32(property.parent);
class = uint8(property.class);
height = uint8(property.y);
if (property.class == PropertyClass.BUILDING) {
y = uint8(_computeHeight(property.x, property.z, property.y));
} else {
y = uint8(property.y);
}
x = uint8(property.x);
z = uint8(property.z);
dx = uint8(property.dx);
dz = uint8(property.dz);
}
/// @dev Override unpause so it requires all external contract addresses
/// to be set before contract can be unpaused. Also, we can't have
/// newContractAddress set either, because then the contract was upgraded.
function unpause() public onlyCEO whenPaused {
require(saleAuction != address(0));
require(newContractAddress == address(0));
// Actually unpause the contract.
super.unpause();
}
} | @dev Mappings between property nodes. | mapping (uint256 => uint256) public districtToBuildingsCount;
| 1,090,813 | [
1,
7742,
3086,
1272,
2199,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
2874,
261,
11890,
5034,
516,
2254,
5034,
13,
1071,
1015,
5792,
774,
3116,
899,
1380,
31,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.4;
contract Token {
/// @return total amount of tokens
function totalSupply() constant returns (uint256 supply) {}
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner) constant returns (uint256 balance) {}
/// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _value) returns (bool success) {}
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {}
/// @notice `msg.sender` approves `_addr` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of wei to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint256 _value) returns (bool success) {}
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {}
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
contract StandardToken is Token {
function transfer(address _to, uint256 _value) returns (bool success) {
//Default assumes totalSupply can't be over max (2^256 - 1).
//If your token leaves out totalSupply and can issue more tokens as time goes on, you need to check if it doesn't wrap.
//Replace the if with this one instead.
//if (balances[msg.sender] >= _value && balances[_to] + _value > balances[_to]) {
if (balances[msg.sender] >= _value && _value > 0) {
balances[msg.sender] -= _value;
balances[_to] += _value;
Transfer(msg.sender, _to, _value);
return true;
} else { return false; }
}
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
//same as above. Replace this line with the following if you want to protect against wrapping uints.
//if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value > balances[_to]) {
if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) {
balances[_to] += _value;
balances[_from] -= _value;
allowed[_from][msg.sender] -= _value;
Transfer(_from, _to, _value);
return true;
} else { return false; }
}
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
function approve(address _spender, uint256 _value) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
uint256 public totalSupply;
}
contract HashnodeTestCoin is StandardToken { // CHANGE THIS. Update the contract name.
/* Public variables of the token */
/*
NOTE:
The following variables are OPTIONAL vanities. One does not have to include them.
They allow one to customise the token contract & in no way influences the core functionality.
Some wallets/interfaces might not even bother to look at this information.
*/
string public name; // Token Name
uint8 public decimals; // How many decimals to show. To be standard complicant keep it 18
string public symbol; // An identifier: eg SBX, XPR etc..
string public version = 'H1.0';
uint256 public unitsOneEthCanBuy; // How many units of your coin can be bought by 1 ETH?
uint256 public totalEthInWei; // WEI is the smallest unit of ETH (the equivalent of cent in USD or satoshi in BTC). We'll store the total ETH raised via our ICO here.
address public fundsWallet; // Where should the raised ETH go?
// This is a constructor function
// which means the following function name has to match the contract name declared above
function HashnodeTestCoin() {
balances[msg.sender] = 90000000000000000000000000; // Give the creator all initial tokens. This is set to 1000 for example. If you want your initial tokens to be X and your decimal is 5, set this value to X * 100000. (CHANGE THIS)
totalSupply = 90000000000000000000000000; // Update total supply (1000 for example) (CHANGE THIS)
name = "Precious"; // Set the name for display purposes (CHANGE THIS)
decimals = 18; // Amount of decimals for display purposes (CHANGE THIS)
symbol = "PRE"; // Set the symbol for display purposes (CHANGE THIS)
unitsOneEthCanBuy = 10; // Set the price of your token for the ICO (CHANGE THIS)
fundsWallet = msg.sender; // The owner of the contract gets ETH
}
function() payable{
totalEthInWei = totalEthInWei + msg.value;
uint256 amount = msg.value * unitsOneEthCanBuy;
if (balances[fundsWallet] < amount) {
return;
}
balances[fundsWallet] = balances[fundsWallet] - amount;
balances[msg.sender] = balances[msg.sender] + amount;
Transfer(fundsWallet, msg.sender, amount); // Broadcast a message to the blockchain
//Transfer ether to fundsWallet
fundsWallet.transfer(msg.value);
}
/* Approves and then calls the receiving contract */
function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
//call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this.
//receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData)
//it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead.
if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; }
return true;
}
} | Set the symbol for display purposes (CHANGE THIS)
| symbol = "PRE"; | 14,410,787 | [
1,
694,
326,
3273,
364,
2562,
13694,
261,
14473,
20676,
13,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
3273,
273,
315,
3670,
14432,
4766,
2868,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.3;
import "../openzeppelin-solidity/contracts/Ownable.sol";
import "../openzeppelin-solidity/contracts/SafeMath.sol";
import "../openzeppelin-solidity/contracts/SafeERC20.sol";
import "../openzeppelin-solidity/contracts/ReentrancyGuard.sol";
import "./NonTransferrableToken.sol";
import "../interfaces/ITokenAllocator.sol";
/**
* A contract that lets its beneficiaries receive tokens proportional to
* their predetermined, non-transferrable share.
*/
contract TokenAllocator is
Ownable,
ITokenAllocator,
NonTransferrableToken,
ReentrancyGuard
{
using SafeMath for uint256;
using SafeERC20 for IERC20;
/**
* If true, the cap table cannot be altered
*/
bool public isLocked;
// Token allocated to beneficiaries.
IERC20 private immutable _token;
/**
* Total number of tokens in the contract after the last redemption
*/
uint256 public balanceAfterLastRedemption;
/**
* Total number of tokens this contract has ever received
*/
uint256 public totalTokensReceived;
/**
* Value of `totalTokensReceived` at the last time this
* beneficiary redeemed tokens. This is used to calculate
* the marginal additional tokens that this user has.
*/
mapping(address => uint256) public totalTokensReceivedAtLastRedemption;
constructor(
string memory name_,
string memory symbol_,
uint8 decimals_,
address owner_,
address token_
) NonTransferrableToken(name_, symbol_, decimals_) {
transferOwnership(owner_);
_token = IERC20(token_);
}
function token() external view override returns (address) {
return address(_token);
}
function totalSupply()
public
view
override(NonTransferrableToken, ITokenAllocator)
returns (uint256)
{
return NonTransferrableToken.totalSupply();
}
function balanceOf(address _account)
public
view
override(NonTransferrableToken, ITokenAllocator)
returns (uint256)
{
return NonTransferrableToken.balanceOf(_account);
}
modifier notLocked {
require(!isLocked, "TokenAllocator: beneficiaries are locked");
_;
}
/**
* Add a beneficiary to the splitter.
*/
function addBeneficiary(address _address, uint256 _shares)
external
notLocked
onlyOwner
{
require(_shares > 0, "TokenAllocator: shares must be greater than 0");
require(
balanceOf(_address) == 0,
"TokenAllocator: beneficiary already added"
);
_setBalance(_address, _shares);
emit BeneficiaryAdded(_address, _shares);
}
/**
* Locks in the beneficiaries, preventing them from being modified in the future.
*/
function lockBeneficiaries() external onlyOwner notLocked {
require(totalSupply() > 0, "TokenAllocator: must have beneficiaries");
isLocked = true;
emit BeneficiariesLocked();
renounceOwnership();
}
function earned(address _account)
external
view
override
returns (uint256 amount)
{
(amount, ) = _earned(_account);
}
/**
* Computes the number of tokens that can be received
* and the new `totalTokensReceived`.
*/
function _earned(address _account)
private
view
returns (uint256 amount, uint256 totalTokens)
{
require(isLocked, "TokenAllocator: beneficiaries must be locked");
uint256 shares = balanceOf(_account);
require(shares > 0, "TokenAllocator: not a beneficiary");
// check if there are new tokens sent to the contract
uint256 newBalance = _token.balanceOf(address(this));
if (balanceAfterLastRedemption != newBalance) {
// if so, update totalTokensReceived
totalTokens = totalTokensReceived.add(newBalance).sub(
balanceAfterLastRedemption
);
} else {
totalTokens = totalTokensReceived;
}
// Check to see if we have tokens to redeem
uint256 changeSinceLastRedemption =
totalTokens.sub(totalTokensReceivedAtLastRedemption[_account]);
if (changeSinceLastRedemption > 0) {
// If so, transfer
amount = changeSinceLastRedemption.mul(shares).div(totalSupply());
}
}
/**
* Redeem tokens if the sender is the beneficiary
*/
function getReward() external override nonReentrant returns (uint256) {
(uint256 amount, uint256 totalTokens) = _earned(msg.sender);
if (amount == 0) {
// Do nothing if there are no tokens to redeem
return 0;
}
totalTokensReceived = totalTokens;
// Transfer tokens
_token.safeTransfer(msg.sender, amount);
// Update beneficiary state
balanceAfterLastRedemption = _token.balanceOf(address(this));
totalTokensReceivedAtLastRedemption[msg.sender] = totalTokensReceived;
emit Redeemed(msg.sender, amount);
return amount;
}
}
| * Total number of tokens in the contract after the last redemption/* Total number of tokens this contract has ever received/* Value of `totalTokensReceived` at the last time this beneficiary redeemed tokens. This is used to calculate the marginal additional tokens that this user has./ | ) NonTransferrableToken(name_, symbol_, decimals_) {
transferOwnership(owner_);
_token = IERC20(token_);
}
| 2,546,094 | [
1,
5269,
1300,
434,
2430,
316,
326,
6835,
1839,
326,
1142,
283,
19117,
375,
19,
10710,
1300,
434,
2430,
333,
6835,
711,
14103,
5079,
19,
1445,
434,
1375,
4963,
5157,
8872,
68,
622,
326,
1142,
813,
333,
27641,
74,
14463,
814,
283,
24903,
329,
2430,
18,
1220,
353,
1399,
358,
4604,
326,
26533,
3312,
2430,
716,
333,
729,
711,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
262,
3858,
5912,
354,
7119,
1345,
12,
529,
67,
16,
3273,
67,
16,
15105,
67,
13,
288,
203,
3639,
7412,
5460,
12565,
12,
8443,
67,
1769,
203,
3639,
389,
2316,
273,
467,
654,
39,
3462,
12,
2316,
67,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.3;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../lib/ABDKMath64x64.sol";
import "../interfaces/IAssimilator.sol";
import "../interfaces/IOracle.sol";
contract TrybToUsdAssimilator is IAssimilator {
using ABDKMath64x64 for int128;
using ABDKMath64x64 for uint256;
using SafeMath for uint256;
IOracle private constant oracle = IOracle(0xB09fC5fD3f11Cf9eb5E1C5Dba43114e3C9f477b5);
IERC20 private constant usdc = IERC20(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48);
IERC20 private constant tryb = IERC20(0x2C537E5624e4af88A7ae4060C022609376C8D0EB);
uint256 private constant DECIMALS = 1e6;
function getRate() public view override returns (uint256) {
(, int256 price, , , ) = oracle.latestRoundData();
return uint256(price);
}
// takes raw tryb amount, transfers it in, calculates corresponding numeraire amount and returns it
function intakeRawAndGetBalance(uint256 _amount) external override returns (int128 amount_, int128 balance_) {
bool _transferSuccess = tryb.transferFrom(msg.sender, address(this), _amount);
require(_transferSuccess, "Curve/TRYB-transfer-from-failed");
uint256 _balance = tryb.balanceOf(address(this));
uint256 _rate = getRate();
balance_ = ((_balance * _rate) / 1e8).divu(DECIMALS);
amount_ = ((_amount * _rate) / 1e8).divu(DECIMALS);
}
// takes raw tryb amount, transfers it in, calculates corresponding numeraire amount and returns it
function intakeRaw(uint256 _amount) external override returns (int128 amount_) {
bool _transferSuccess = tryb.transferFrom(msg.sender, address(this), _amount);
require(_transferSuccess, "Curve/tryb-transfer-from-failed");
uint256 _rate = getRate();
amount_ = ((_amount * _rate) / 1e8).divu(DECIMALS);
}
// takes a numeraire amount, calculates the raw amount of tryb, transfers it in and returns the corresponding raw amount
function intakeNumeraire(int128 _amount) external override returns (uint256 amount_) {
uint256 _rate = getRate();
amount_ = (_amount.mulu(DECIMALS) * 1e8) / _rate;
bool _transferSuccess = tryb.transferFrom(msg.sender, address(this), amount_);
require(_transferSuccess, "Curve/TRYB-transfer-from-failed");
}
// takes a numeraire account, calculates the raw amount of tryb, transfers it in and returns the corresponding raw amount
function intakeNumeraireLPRatio(
uint256 _baseWeight,
uint256 _quoteWeight,
address _addr,
int128 _amount
) external override returns (uint256 amount_) {
uint256 _trybBal = tryb.balanceOf(_addr);
if (_trybBal <= 0) return 0;
uint256 _usdcBal = usdc.balanceOf(_addr).mul(DECIMALS).div(_quoteWeight);
// Rate is in 1e6
uint256 _rate = _usdcBal.mul(DECIMALS).div(_trybBal.mul(DECIMALS).div(_baseWeight));
amount_ = (_amount.mulu(DECIMALS) * 1e6) / _rate;
bool _transferSuccess = tryb.transferFrom(msg.sender, address(this), amount_);
require(_transferSuccess, "Curve/TRYB-transfer-from-failed");
}
// takes a raw amount of tryb and transfers it out, returns numeraire value of the raw amount
function outputRawAndGetBalance(address _dst, uint256 _amount)
external
override
returns (int128 amount_, int128 balance_)
{
uint256 _rate = getRate();
uint256 _trybAmount = ((_amount) * _rate) / 1e8;
bool _transferSuccess = tryb.transfer(_dst, _trybAmount);
require(_transferSuccess, "Curve/TRYB-transfer-failed");
uint256 _balance = tryb.balanceOf(address(this));
amount_ = _trybAmount.divu(DECIMALS);
balance_ = ((_balance * _rate) / 1e8).divu(DECIMALS);
}
// takes a raw amount of tryb and transfers it out, returns numeraire value of the raw amount
function outputRaw(address _dst, uint256 _amount) external override returns (int128 amount_) {
uint256 _rate = getRate();
uint256 _trybAmount = (_amount * _rate) / 1e8;
bool _transferSuccess = tryb.transfer(_dst, _trybAmount);
require(_transferSuccess, "Curve/TRYB-transfer-failed");
amount_ = _trybAmount.divu(DECIMALS);
}
// takes a numeraire value of tryb, figures out the raw amount, transfers raw amount out, and returns raw amount
function outputNumeraire(address _dst, int128 _amount) external override returns (uint256 amount_) {
uint256 _rate = getRate();
amount_ = (_amount.mulu(DECIMALS) * 1e8) / _rate;
bool _transferSuccess = tryb.transfer(_dst, amount_);
require(_transferSuccess, "Curve/TRYB-transfer-failed");
}
// takes a numeraire amount and returns the raw amount
function viewRawAmount(int128 _amount) external view override returns (uint256 amount_) {
uint256 _rate = getRate();
amount_ = (_amount.mulu(DECIMALS) * 1e8) / _rate;
}
// takes a numeraire amount and returns the raw amount without the rate
function viewRawAmountLPRatio(
uint256 _baseWeight,
uint256 _quoteWeight,
address _addr,
int128 _amount
) external view override returns (uint256 amount_) {
uint256 _trybBal = tryb.balanceOf(_addr);
if (_trybBal <= 0) return 0;
uint256 _usdcBal = usdc.balanceOf(_addr).mul(DECIMALS).div(_quoteWeight);
// Rate is in 1e6
uint256 _rate = _usdcBal.mul(DECIMALS).div(_trybBal.mul(DECIMALS).div(_baseWeight));
amount_ = (_amount.mulu(DECIMALS) * 1e6) / _rate;
}
// takes a raw amount and returns the numeraire amount
function viewNumeraireAmount(uint256 _amount) external view override returns (int128 amount_) {
uint256 _rate = getRate();
amount_ = ((_amount * _rate) / 1e8).divu(DECIMALS);
}
// views the numeraire value of the current balance of the reserve, in this case tryb
function viewNumeraireBalance(address _addr) external view override returns (int128 balance_) {
uint256 _rate = getRate();
uint256 _balance = tryb.balanceOf(_addr);
if (_balance <= 0) return ABDKMath64x64.fromUInt(0);
balance_ = ((_balance * _rate) / 1e8).divu(DECIMALS);
}
// views the numeraire value of the current balance of the reserve, in this case tryb
function viewNumeraireAmountAndBalance(address _addr, uint256 _amount)
external
view
override
returns (int128 amount_, int128 balance_)
{
uint256 _rate = getRate();
amount_ = ((_amount * _rate) / 1e8).divu(DECIMALS);
uint256 _balance = tryb.balanceOf(_addr);
balance_ = ((_balance * _rate) / 1e8).divu(DECIMALS);
}
// views the numeraire value of the current balance of the reserve, in this case tryb
// instead of calculating with chainlink's "rate" it'll be determined by the existing
// token ratio. This is in here to prevent LPs from losing out on future oracle price updates
function viewNumeraireBalanceLPRatio(
uint256 _baseWeight,
uint256 _quoteWeight,
address _addr
) external view override returns (int128 balance_) {
uint256 _trybBal = tryb.balanceOf(_addr);
if (_trybBal <= 0) return ABDKMath64x64.fromUInt(0);
uint256 _usdcBal = usdc.balanceOf(_addr).mul(DECIMALS).div(_quoteWeight);
// Rate is in 1e6
uint256 _rate = _usdcBal.mul(DECIMALS).div(_trybBal.mul(DECIMALS).div(_baseWeight));
balance_ = ((_trybBal * _rate) / 1e6).divu(DECIMALS);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: BSD-4-Clause
/*
* ABDK Math 64.64 Smart Contract Library. Copyright © 2019 by ABDK Consulting.
* Author: Mikhail Vladimirov <[email protected]>
*/
pragma solidity ^0.7.0;
/**
* Smart contract library of mathematical functions operating with signed
* 64.64-bit fixed point numbers. Signed 64.64-bit fixed point number is
* basically a simple fraction whose numerator is signed 128-bit integer and
* denominator is 2^64. As long as denominator is always the same, there is no
* need to store it, thus in Solidity signed 64.64-bit fixed point numbers are
* represented by int128 type holding only the numerator.
*/
library ABDKMath64x64 {
/*
* Minimum value signed 64.64-bit fixed point number may have.
*/
int128 private constant MIN_64x64 = -0x80000000000000000000000000000000;
/*
* Maximum value signed 64.64-bit fixed point number may have.
*/
int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
/**
* Convert signed 256-bit integer number into signed 64.64-bit fixed point
* number. Revert on overflow.
*
* @param x signed 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function fromInt (int256 x) internal pure returns (int128) {
require (x >= -0x8000000000000000 && x <= 0x7FFFFFFFFFFFFFFF);
return int128 (x << 64);
}
/**
* Convert signed 64.64 fixed point number into signed 64-bit integer number
* rounding down.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64-bit integer number
*/
function toInt (int128 x) internal pure returns (int64) {
return int64 (x >> 64);
}
/**
* Convert unsigned 256-bit integer number into signed 64.64-bit fixed point
* number. Revert on overflow.
*
* @param x unsigned 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function fromUInt (uint256 x) internal pure returns (int128) {
require (x <= 0x7FFFFFFFFFFFFFFF);
return int128 (x << 64);
}
/**
* Convert signed 64.64 fixed point number into unsigned 64-bit integer
* number rounding down. Revert on underflow.
*
* @param x signed 64.64-bit fixed point number
* @return unsigned 64-bit integer number
*/
function toUInt (int128 x) internal pure returns (uint64) {
require (x >= 0);
return uint64 (x >> 64);
}
/**
* Convert signed 128.128 fixed point number into signed 64.64-bit fixed point
* number rounding down. Revert on overflow.
*
* @param x signed 128.128-bin fixed point number
* @return signed 64.64-bit fixed point number
*/
function from128x128 (int256 x) internal pure returns (int128) {
int256 result = x >> 64;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
/**
* Convert signed 64.64 fixed point number into signed 128.128 fixed point
* number.
*
* @param x signed 64.64-bit fixed point number
* @return signed 128.128 fixed point number
*/
function to128x128 (int128 x) internal pure returns (int256) {
return int256 (x) << 64;
}
/**
* Calculate x + y. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function add (int128 x, int128 y) internal pure returns (int128) {
int256 result = int256(x) + y;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
/**
* Calculate x - y. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function sub (int128 x, int128 y) internal pure returns (int128) {
int256 result = int256(x) - y;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
/**
* Calculate x * y rounding down. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function mul (int128 x, int128 y) internal pure returns (int128) {
int256 result = int256(x) * y >> 64;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
/**
* Calculate x * y rounding towards zero, where x is signed 64.64 fixed point
* number and y is signed 256-bit integer number. Revert on overflow.
*
* @param x signed 64.64 fixed point number
* @param y signed 256-bit integer number
* @return signed 256-bit integer number
*/
function muli (int128 x, int256 y) internal pure returns (int256) {
if (x == MIN_64x64) {
require (y >= -0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF &&
y <= 0x1000000000000000000000000000000000000000000000000);
return -y << 63;
} else {
bool negativeResult = false;
if (x < 0) {
x = -x;
negativeResult = true;
}
if (y < 0) {
y = -y; // We rely on overflow behavior here
negativeResult = !negativeResult;
}
uint256 absoluteResult = mulu (x, uint256 (y));
if (negativeResult) {
require (absoluteResult <=
0x8000000000000000000000000000000000000000000000000000000000000000);
return -int256 (absoluteResult); // We rely on overflow behavior here
} else {
require (absoluteResult <=
0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return int256 (absoluteResult);
}
}
}
/**
* Calculate x * y rounding down, where x is signed 64.64 fixed point number
* and y is unsigned 256-bit integer number. Revert on overflow.
*
* @param x signed 64.64 fixed point number
* @param y unsigned 256-bit integer number
* @return unsigned 256-bit integer number
*/
function mulu (int128 x, uint256 y) internal pure returns (uint256) {
if (y == 0) return 0;
require (x >= 0);
uint256 lo = (uint256 (x) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64;
uint256 hi = uint256 (x) * (y >> 128);
require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
hi <<= 64;
require (hi <=
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - lo);
return hi + lo;
}
/**
* Calculate x / y rounding towards zero. Revert on overflow or when y is
* zero.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function div (int128 x, int128 y) internal pure returns (int128) {
require (y != 0);
int256 result = (int256 (x) << 64) / y;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
/**
* Calculate x / y rounding towards zero, where x and y are signed 256-bit
* integer numbers. Revert on overflow or when y is zero.
*
* @param x signed 256-bit integer number
* @param y signed 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function divi (int256 x, int256 y) internal pure returns (int128) {
require (y != 0);
bool negativeResult = false;
if (x < 0) {
x = -x; // We rely on overflow behavior here
negativeResult = true;
}
if (y < 0) {
y = -y; // We rely on overflow behavior here
negativeResult = !negativeResult;
}
uint128 absoluteResult = divuu (uint256 (x), uint256 (y));
if (negativeResult) {
require (absoluteResult <= 0x80000000000000000000000000000000);
return -int128 (absoluteResult); // We rely on overflow behavior here
} else {
require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return int128 (absoluteResult); // We rely on overflow behavior here
}
}
/**
* Calculate x / y rounding towards zero, where x and y are unsigned 256-bit
* integer numbers. Revert on overflow or when y is zero.
*
* @param x unsigned 256-bit integer number
* @param y unsigned 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function divu (uint256 x, uint256 y) internal pure returns (int128) {
require (y != 0);
uint128 result = divuu (x, y);
require (result <= uint128 (MAX_64x64));
return int128 (result);
}
/**
* Calculate -x. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function neg (int128 x) internal pure returns (int128) {
require (x != MIN_64x64);
return -x;
}
/**
* Calculate |x|. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function abs (int128 x) internal pure returns (int128) {
require (x != MIN_64x64);
return x < 0 ? -x : x;
}
/**
* Calculate 1 / x rounding towards zero. Revert on overflow or when x is
* zero.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function inv (int128 x) internal pure returns (int128) {
require (x != 0);
int256 result = int256 (0x100000000000000000000000000000000) / x;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
/**
* Calculate arithmetics average of x and y, i.e. (x + y) / 2 rounding down.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function avg (int128 x, int128 y) internal pure returns (int128) {
return int128 ((int256 (x) + int256 (y)) >> 1);
}
/**
* Calculate geometric average of x and y, i.e. sqrt (x * y) rounding down.
* Revert on overflow or in case x * y is negative.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function gavg (int128 x, int128 y) internal pure returns (int128) {
int256 m = int256 (x) * int256 (y);
require (m >= 0);
require (m <
0x4000000000000000000000000000000000000000000000000000000000000000);
return int128 (sqrtu (uint256 (m)));
}
/**
* Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number
* and y is unsigned 256-bit integer number. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y uint256 value
* @return signed 64.64-bit fixed point number
*/
function pow (int128 x, uint256 y) internal pure returns (int128) {
uint256 absoluteResult;
bool negativeResult = false;
if (x >= 0) {
absoluteResult = powu (uint256 (x) << 63, y);
} else {
// We rely on overflow behavior here
absoluteResult = powu (uint256 (uint128 (-x)) << 63, y);
negativeResult = y & 1 > 0;
}
absoluteResult >>= 63;
if (negativeResult) {
require (absoluteResult <= 0x80000000000000000000000000000000);
return -int128 (absoluteResult); // We rely on overflow behavior here
} else {
require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return int128 (absoluteResult); // We rely on overflow behavior here
}
}
/**
* Calculate sqrt (x) rounding down. Revert if x < 0.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function sqrt (int128 x) internal pure returns (int128) {
require (x >= 0);
return int128 (sqrtu (uint256 (x) << 64));
}
/**
* Calculate binary logarithm of x. Revert if x <= 0.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function log_2 (int128 x) internal pure returns (int128) {
require (x > 0);
int256 msb = 0;
int256 xc = x;
if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; }
if (xc >= 0x100000000) { xc >>= 32; msb += 32; }
if (xc >= 0x10000) { xc >>= 16; msb += 16; }
if (xc >= 0x100) { xc >>= 8; msb += 8; }
if (xc >= 0x10) { xc >>= 4; msb += 4; }
if (xc >= 0x4) { xc >>= 2; msb += 2; }
if (xc >= 0x2) msb += 1; // No need to shift xc anymore
int256 result = msb - 64 << 64;
uint256 ux = uint256 (x) << uint256 (127 - msb);
for (int256 bit = 0x8000000000000000; bit > 0; bit >>= 1) {
ux *= ux;
uint256 b = ux >> 255;
ux >>= 127 + b;
result += bit * int256 (b);
}
return int128 (result);
}
/**
* Calculate natural logarithm of x. Revert if x <= 0.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function ln (int128 x) internal pure returns (int128) {
require (x > 0);
return int128 (
uint256 (log_2 (x)) * 0xB17217F7D1CF79ABC9E3B39803F2F6AF >> 128);
}
/**
* Calculate binary exponent of x. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function exp_2 (int128 x) internal pure returns (int128) {
require (x < 0x400000000000000000); // Overflow
if (x < -0x400000000000000000) return 0; // Underflow
uint256 result = 0x80000000000000000000000000000000;
if (x & 0x8000000000000000 > 0)
result = result * 0x16A09E667F3BCC908B2FB1366EA957D3E >> 128;
if (x & 0x4000000000000000 > 0)
result = result * 0x1306FE0A31B7152DE8D5A46305C85EDEC >> 128;
if (x & 0x2000000000000000 > 0)
result = result * 0x1172B83C7D517ADCDF7C8C50EB14A791F >> 128;
if (x & 0x1000000000000000 > 0)
result = result * 0x10B5586CF9890F6298B92B71842A98363 >> 128;
if (x & 0x800000000000000 > 0)
result = result * 0x1059B0D31585743AE7C548EB68CA417FD >> 128;
if (x & 0x400000000000000 > 0)
result = result * 0x102C9A3E778060EE6F7CACA4F7A29BDE8 >> 128;
if (x & 0x200000000000000 > 0)
result = result * 0x10163DA9FB33356D84A66AE336DCDFA3F >> 128;
if (x & 0x100000000000000 > 0)
result = result * 0x100B1AFA5ABCBED6129AB13EC11DC9543 >> 128;
if (x & 0x80000000000000 > 0)
result = result * 0x10058C86DA1C09EA1FF19D294CF2F679B >> 128;
if (x & 0x40000000000000 > 0)
result = result * 0x1002C605E2E8CEC506D21BFC89A23A00F >> 128;
if (x & 0x20000000000000 > 0)
result = result * 0x100162F3904051FA128BCA9C55C31E5DF >> 128;
if (x & 0x10000000000000 > 0)
result = result * 0x1000B175EFFDC76BA38E31671CA939725 >> 128;
if (x & 0x8000000000000 > 0)
result = result * 0x100058BA01FB9F96D6CACD4B180917C3D >> 128;
if (x & 0x4000000000000 > 0)
result = result * 0x10002C5CC37DA9491D0985C348C68E7B3 >> 128;
if (x & 0x2000000000000 > 0)
result = result * 0x1000162E525EE054754457D5995292026 >> 128;
if (x & 0x1000000000000 > 0)
result = result * 0x10000B17255775C040618BF4A4ADE83FC >> 128;
if (x & 0x800000000000 > 0)
result = result * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB >> 128;
if (x & 0x400000000000 > 0)
result = result * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9 >> 128;
if (x & 0x200000000000 > 0)
result = result * 0x10000162E43F4F831060E02D839A9D16D >> 128;
if (x & 0x100000000000 > 0)
result = result * 0x100000B1721BCFC99D9F890EA06911763 >> 128;
if (x & 0x80000000000 > 0)
result = result * 0x10000058B90CF1E6D97F9CA14DBCC1628 >> 128;
if (x & 0x40000000000 > 0)
result = result * 0x1000002C5C863B73F016468F6BAC5CA2B >> 128;
if (x & 0x20000000000 > 0)
result = result * 0x100000162E430E5A18F6119E3C02282A5 >> 128;
if (x & 0x10000000000 > 0)
result = result * 0x1000000B1721835514B86E6D96EFD1BFE >> 128;
if (x & 0x8000000000 > 0)
result = result * 0x100000058B90C0B48C6BE5DF846C5B2EF >> 128;
if (x & 0x4000000000 > 0)
result = result * 0x10000002C5C8601CC6B9E94213C72737A >> 128;
if (x & 0x2000000000 > 0)
result = result * 0x1000000162E42FFF037DF38AA2B219F06 >> 128;
if (x & 0x1000000000 > 0)
result = result * 0x10000000B17217FBA9C739AA5819F44F9 >> 128;
if (x & 0x800000000 > 0)
result = result * 0x1000000058B90BFCDEE5ACD3C1CEDC823 >> 128;
if (x & 0x400000000 > 0)
result = result * 0x100000002C5C85FE31F35A6A30DA1BE50 >> 128;
if (x & 0x200000000 > 0)
result = result * 0x10000000162E42FF0999CE3541B9FFFCF >> 128;
if (x & 0x100000000 > 0)
result = result * 0x100000000B17217F80F4EF5AADDA45554 >> 128;
if (x & 0x80000000 > 0)
result = result * 0x10000000058B90BFBF8479BD5A81B51AD >> 128;
if (x & 0x40000000 > 0)
result = result * 0x1000000002C5C85FDF84BD62AE30A74CC >> 128;
if (x & 0x20000000 > 0)
result = result * 0x100000000162E42FEFB2FED257559BDAA >> 128;
if (x & 0x10000000 > 0)
result = result * 0x1000000000B17217F7D5A7716BBA4A9AE >> 128;
if (x & 0x8000000 > 0)
result = result * 0x100000000058B90BFBE9DDBAC5E109CCE >> 128;
if (x & 0x4000000 > 0)
result = result * 0x10000000002C5C85FDF4B15DE6F17EB0D >> 128;
if (x & 0x2000000 > 0)
result = result * 0x1000000000162E42FEFA494F1478FDE05 >> 128;
if (x & 0x1000000 > 0)
result = result * 0x10000000000B17217F7D20CF927C8E94C >> 128;
if (x & 0x800000 > 0)
result = result * 0x1000000000058B90BFBE8F71CB4E4B33D >> 128;
if (x & 0x400000 > 0)
result = result * 0x100000000002C5C85FDF477B662B26945 >> 128;
if (x & 0x200000 > 0)
result = result * 0x10000000000162E42FEFA3AE53369388C >> 128;
if (x & 0x100000 > 0)
result = result * 0x100000000000B17217F7D1D351A389D40 >> 128;
if (x & 0x80000 > 0)
result = result * 0x10000000000058B90BFBE8E8B2D3D4EDE >> 128;
if (x & 0x40000 > 0)
result = result * 0x1000000000002C5C85FDF4741BEA6E77E >> 128;
if (x & 0x20000 > 0)
result = result * 0x100000000000162E42FEFA39FE95583C2 >> 128;
if (x & 0x10000 > 0)
result = result * 0x1000000000000B17217F7D1CFB72B45E1 >> 128;
if (x & 0x8000 > 0)
result = result * 0x100000000000058B90BFBE8E7CC35C3F0 >> 128;
if (x & 0x4000 > 0)
result = result * 0x10000000000002C5C85FDF473E242EA38 >> 128;
if (x & 0x2000 > 0)
result = result * 0x1000000000000162E42FEFA39F02B772C >> 128;
if (x & 0x1000 > 0)
result = result * 0x10000000000000B17217F7D1CF7D83C1A >> 128;
if (x & 0x800 > 0)
result = result * 0x1000000000000058B90BFBE8E7BDCBE2E >> 128;
if (x & 0x400 > 0)
result = result * 0x100000000000002C5C85FDF473DEA871F >> 128;
if (x & 0x200 > 0)
result = result * 0x10000000000000162E42FEFA39EF44D91 >> 128;
if (x & 0x100 > 0)
result = result * 0x100000000000000B17217F7D1CF79E949 >> 128;
if (x & 0x80 > 0)
result = result * 0x10000000000000058B90BFBE8E7BCE544 >> 128;
if (x & 0x40 > 0)
result = result * 0x1000000000000002C5C85FDF473DE6ECA >> 128;
if (x & 0x20 > 0)
result = result * 0x100000000000000162E42FEFA39EF366F >> 128;
if (x & 0x10 > 0)
result = result * 0x1000000000000000B17217F7D1CF79AFA >> 128;
if (x & 0x8 > 0)
result = result * 0x100000000000000058B90BFBE8E7BCD6D >> 128;
if (x & 0x4 > 0)
result = result * 0x10000000000000002C5C85FDF473DE6B2 >> 128;
if (x & 0x2 > 0)
result = result * 0x1000000000000000162E42FEFA39EF358 >> 128;
if (x & 0x1 > 0)
result = result * 0x10000000000000000B17217F7D1CF79AB >> 128;
result >>= uint256 (63 - (x >> 64));
require (result <= uint256 (MAX_64x64));
return int128 (result);
}
/**
* Calculate natural exponent of x. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function exp (int128 x) internal pure returns (int128) {
require (x < 0x400000000000000000); // Overflow
if (x < -0x400000000000000000) return 0; // Underflow
return exp_2 (
int128 (int256 (x) * 0x171547652B82FE1777D0FFDA0D23A7D12 >> 128));
}
/**
* Calculate x / y rounding towards zero, where x and y are unsigned 256-bit
* integer numbers. Revert on overflow or when y is zero.
*
* @param x unsigned 256-bit integer number
* @param y unsigned 256-bit integer number
* @return unsigned 64.64-bit fixed point number
*/
function divuu (uint256 x, uint256 y) private pure returns (uint128) {
require (y != 0);
uint256 result;
if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
result = (x << 64) / y;
else {
uint256 msb = 192;
uint256 xc = x >> 192;
if (xc >= 0x100000000) { xc >>= 32; msb += 32; }
if (xc >= 0x10000) { xc >>= 16; msb += 16; }
if (xc >= 0x100) { xc >>= 8; msb += 8; }
if (xc >= 0x10) { xc >>= 4; msb += 4; }
if (xc >= 0x4) { xc >>= 2; msb += 2; }
if (xc >= 0x2) msb += 1; // No need to shift xc anymore
result = (x << 255 - msb) / ((y - 1 >> msb - 191) + 1);
require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
uint256 hi = result * (y >> 128);
uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
uint256 xh = x >> 192;
uint256 xl = x << 64;
if (xl < lo) xh -= 1;
xl -= lo; // We rely on overflow behavior here
lo = hi << 128;
if (xl < lo) xh -= 1;
xl -= lo; // We rely on overflow behavior here
assert (xh == hi >> 128);
result += xl / y;
}
require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return uint128 (result);
}
/**
* Calculate x^y assuming 0^0 is 1, where x is unsigned 129.127 fixed point
* number and y is unsigned 256-bit integer number. Revert on overflow.
*
* @param x unsigned 129.127-bit fixed point number
* @param y uint256 value
* @return unsigned 129.127-bit fixed point number
*/
function powu (uint256 x, uint256 y) private pure returns (uint256) {
if (y == 0) return 0x80000000000000000000000000000000;
else if (x == 0) return 0;
else {
int256 msb = 0;
uint256 xc = x;
if (xc >= 0x100000000000000000000000000000000) { xc >>= 128; msb += 128; }
if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; }
if (xc >= 0x100000000) { xc >>= 32; msb += 32; }
if (xc >= 0x10000) { xc >>= 16; msb += 16; }
if (xc >= 0x100) { xc >>= 8; msb += 8; }
if (xc >= 0x10) { xc >>= 4; msb += 4; }
if (xc >= 0x4) { xc >>= 2; msb += 2; }
if (xc >= 0x2) msb += 1; // No need to shift xc anymore
int256 xe = msb - 127;
if (xe > 0) x >>= uint256 (xe);
else x <<= uint256 (-xe);
uint256 result = 0x80000000000000000000000000000000;
int256 re = 0;
while (y > 0) {
if (y & 1 > 0) {
result = result * x;
y -= 1;
re += xe;
if (result >=
0x8000000000000000000000000000000000000000000000000000000000000000) {
result >>= 128;
re += 1;
} else result >>= 127;
if (re < -127) return 0; // Underflow
require (re < 128); // Overflow
} else {
x = x * x;
y >>= 1;
xe <<= 1;
if (x >=
0x8000000000000000000000000000000000000000000000000000000000000000) {
x >>= 128;
xe += 1;
} else x >>= 127;
if (xe < -127) return 0; // Underflow
require (xe < 128); // Overflow
}
}
if (re > 0) result <<= uint256 (re);
else if (re < 0) result >>= uint256 (-re);
return result;
}
}
/**
* Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer
* number.
*
* @param x unsigned 256-bit integer number
* @return unsigned 128-bit integer number
*/
function sqrtu (uint256 x) private pure returns (uint128) {
if (x == 0) return 0;
else {
uint256 xx = x;
uint256 r = 1;
if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; }
if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; }
if (xx >= 0x100000000) { xx >>= 32; r <<= 16; }
if (xx >= 0x10000) { xx >>= 16; r <<= 8; }
if (xx >= 0x100) { xx >>= 8; r <<= 4; }
if (xx >= 0x10) { xx >>= 4; r <<= 2; }
if (xx >= 0x8) { r <<= 1; }
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1; // Seven iterations should be enough
uint256 r1 = x / r;
return uint128 (r < r1 ? r : r1);
}
}
}
// SPDX-License-Identifier: MIT
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.3;
interface IAssimilator {
function getRate() external view returns (uint256);
function intakeRaw(uint256 amount) external returns (int128);
function intakeRawAndGetBalance(uint256 amount) external returns (int128, int128);
function intakeNumeraire(int128 amount) external returns (uint256);
function intakeNumeraireLPRatio(
uint256,
uint256,
address,
int128
) external returns (uint256);
function outputRaw(address dst, uint256 amount) external returns (int128);
function outputRawAndGetBalance(address dst, uint256 amount) external returns (int128, int128);
function outputNumeraire(address dst, int128 amount) external returns (uint256);
function viewRawAmount(int128) external view returns (uint256);
function viewRawAmountLPRatio(
uint256,
uint256,
address,
int128
) external view returns (uint256);
function viewNumeraireAmount(uint256) external view returns (int128);
function viewNumeraireBalanceLPRatio(
uint256,
uint256,
address
) external view returns (int128);
function viewNumeraireBalance(address) external view returns (int128);
function viewNumeraireAmountAndBalance(address, uint256) external view returns (int128, int128);
}
// SPDX-License-Identifier: MIT
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.3;
interface IOracle {
function acceptOwnership() external;
function accessController() external view returns (address);
function aggregator() external view returns (address);
function confirmAggregator(address _aggregator) external;
function decimals() external view returns (uint8);
function description() external view returns (string memory);
function getAnswer(uint256 _roundId) external view returns (int256);
function getRoundData(uint80 _roundId)
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
function getTimestamp(uint256 _roundId) external view returns (uint256);
function latestAnswer() external view returns (int256);
function latestRound() external view returns (uint256);
function latestRoundData()
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
function latestTimestamp() external view returns (uint256);
function owner() external view returns (address);
function phaseAggregators(uint16) external view returns (address);
function phaseId() external view returns (uint16);
function proposeAggregator(address _aggregator) external;
function proposedAggregator() external view returns (address);
function proposedGetRoundData(uint80 _roundId)
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
function proposedLatestRoundData()
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
function setController(address _accessController) external;
function transferOwnership(address _to) external;
function version() external view returns (uint256);
} | takes raw tryb amount, transfers it in, calculates corresponding numeraire amount and returns it | function intakeRawAndGetBalance(uint256 _amount) external override returns (int128 amount_, int128 balance_) {
bool _transferSuccess = tryb.transferFrom(msg.sender, address(this), _amount);
require(_transferSuccess, "Curve/TRYB-transfer-from-failed");
uint256 _balance = tryb.balanceOf(address(this));
uint256 _rate = getRate();
balance_ = ((_balance * _rate) / 1e8).divu(DECIMALS);
amount_ = ((_amount * _rate) / 1e8).divu(DECIMALS);
}
| 6,028,521 | [
1,
88,
3223,
1831,
775,
70,
3844,
16,
29375,
518,
316,
16,
17264,
4656,
818,
6070,
577,
3844,
471,
1135,
518,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
509,
911,
4809,
14042,
13937,
12,
11890,
5034,
389,
8949,
13,
3903,
3849,
1135,
261,
474,
10392,
3844,
67,
16,
509,
10392,
11013,
67,
13,
288,
203,
3639,
1426,
389,
13866,
4510,
273,
775,
70,
18,
13866,
1265,
12,
3576,
18,
15330,
16,
1758,
12,
2211,
3631,
389,
8949,
1769,
203,
203,
3639,
2583,
24899,
13866,
4510,
16,
315,
9423,
19,
17805,
38,
17,
13866,
17,
2080,
17,
7307,
8863,
203,
203,
3639,
2254,
5034,
389,
12296,
273,
775,
70,
18,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
203,
3639,
2254,
5034,
389,
5141,
273,
4170,
340,
5621,
203,
203,
3639,
11013,
67,
273,
14015,
67,
12296,
380,
389,
5141,
13,
342,
404,
73,
28,
2934,
2892,
89,
12,
23816,
55,
1769,
203,
203,
3639,
3844,
67,
273,
14015,
67,
8949,
380,
389,
5141,
13,
342,
404,
73,
28,
2934,
2892,
89,
12,
23816,
55,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/11155111/0x3F41573edFF86e8d0924B2126F96Ae3c21cC6244/sources/src/verifier.sol | We'll use mIn to save d2 We'll use mIn + 64 to save d3 We'll use mIn + 128 to save d4 | function calculateD(pMem) {
let _pD:= add(pMem, pD)
let gamma := mload(add(pMem, pGamma))
let mIn := mload(0x40)
g1_setC(_pD, Qcx, Qcy)
g1_mulAccC(_pD, Qmx, Qmy, mulmod(calldataload(pEval_a), calldataload(pEval_b), q))
g1_mulAccC(_pD, Qlx, Qly, calldataload(pEval_a))
g1_mulAccC(_pD, Qrx, Qry, calldataload(pEval_b))
g1_mulAccC(_pD, Qox, Qoy, calldataload(pEval_c))
let betaxi := mload(add(pMem, pBetaXi))
let val1 := addmod(
addmod(calldataload(pEval_a), betaxi, q),
gamma, q)
let val2 := addmod(
addmod(
calldataload(pEval_b),
mulmod(betaxi, k1, q),
q), gamma, q)
let val3 := addmod(
addmod(
calldataload(pEval_c),
mulmod(betaxi, k2, q),
q), gamma, q)
let d2a := mulmod(
mulmod(mulmod(val1, val2, q), val3, q),
mload(add(pMem, pAlpha)),
q
)
let d2b := mulmod(
mload(add(pMem, pEval_l1)),
mload(add(pMem, pAlpha2)),
q
)
g1_calldataSet(add(mIn, 192), pZ)
g1_mulSet(
mIn,
add(mIn, 192),
addmod(addmod(d2a, d2b, q), mload(add(pMem, pU)), q))
val1 := addmod(
addmod(
calldataload(pEval_a),
mulmod(mload(add(pMem, pBeta)), calldataload(pEval_s1), q),
q), gamma, q)
val2 := addmod(
addmod(
calldataload(pEval_b),
mulmod(mload(add(pMem, pBeta)), calldataload(pEval_s2), q),
q), gamma, q)
val3 := mulmod(
mulmod(mload(add(pMem, pAlpha)), mload(add(pMem, pBeta)), q),
calldataload(pEval_zw), q)
g1_mulSetC(
add(mIn, 64),
S3x,
S3y,
mulmod(mulmod(val1, val2, q), val3, q))
g1_calldataSet(add(mIn, 128), pT1)
g1_mulAccC(add(mIn, 128), calldataload(pT2), calldataload(add(pT2, 32)), mload(add(pMem, pXin)))
let xin2 := mulmod(mload(add(pMem, pXin)), mload(add(pMem, pXin)), q)
g1_mulAccC(add(mIn, 128), calldataload(pT3), calldataload(add(pT3, 32)) , xin2)
g1_mulSetC(add(mIn, 128), mload(add(mIn, 128)), mload(add(mIn, 160)), mload(add(pMem, pZh)))
mstore(add(add(mIn, 64), 32), mod(sub(qf, mload(add(add(mIn, 64), 32))), qf))
mstore(add(mIn, 160), mod(sub(qf, mload(add(mIn, 160))), qf))
g1_acc(_pD, mIn)
g1_acc(_pD, add(mIn, 64))
g1_acc(_pD, add(mIn, 128))
}
| 3,802,480 | [
1,
3218,
5614,
999,
312,
382,
358,
1923,
302,
22,
1660,
5614,
999,
312,
382,
397,
5178,
358,
1923,
302,
23,
1660,
5614,
999,
312,
382,
397,
8038,
358,
1923,
302,
24,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
5411,
445,
4604,
40,
12,
84,
3545,
13,
288,
203,
7734,
2231,
389,
84,
40,
30,
33,
527,
12,
84,
3545,
16,
293,
40,
13,
203,
7734,
2231,
9601,
519,
312,
945,
12,
1289,
12,
84,
3545,
16,
293,
31300,
3719,
203,
7734,
2231,
312,
382,
519,
312,
945,
12,
20,
92,
7132,
13,
203,
203,
7734,
314,
21,
67,
542,
39,
24899,
84,
40,
16,
2238,
71,
92,
16,
2238,
2431,
13,
203,
7734,
314,
21,
67,
16411,
8973,
39,
24899,
84,
40,
16,
2238,
11023,
16,
2238,
4811,
16,
14064,
1711,
12,
1991,
72,
3145,
6189,
12,
84,
13904,
67,
69,
3631,
745,
72,
3145,
6189,
12,
84,
13904,
67,
70,
3631,
1043,
3719,
203,
7734,
314,
21,
67,
16411,
8973,
39,
24899,
84,
40,
16,
2238,
80,
92,
16,
2238,
715,
16,
745,
72,
3145,
6189,
12,
84,
13904,
67,
69,
3719,
203,
7734,
314,
21,
67,
16411,
8973,
39,
24899,
84,
40,
16,
2238,
20122,
16,
2238,
1176,
16,
745,
72,
3145,
6189,
12,
84,
13904,
67,
70,
3719,
203,
7734,
314,
21,
67,
16411,
8973,
39,
24899,
84,
40,
16,
2238,
2409,
16,
2238,
13372,
16,
745,
72,
3145,
6189,
12,
84,
13904,
67,
71,
3719,
2398,
203,
203,
7734,
2231,
2701,
651,
77,
519,
312,
945,
12,
1289,
12,
84,
3545,
16,
293,
38,
1066,
60,
77,
3719,
203,
7734,
2231,
1244,
21,
519,
527,
1711,
12,
203,
10792,
527,
1711,
12,
1991,
72,
3145,
6189,
12,
84,
13904,
67,
69,
3631,
2701,
651,
77,
16,
1043,
3631,
2
] |
/*
FoxyDen.sol
https://foxy.farm/
/\ /\
//\\_//\\ ____
\_ _/ / /
/ * * \ /^^^]
\_\O/_/ [ ]
/ \_ [ / The early bird gets the worm, and the early fox gets the bird
\ \_ / /
[ [ / \/ _/
_[ [ \ /_/
https://t.me/foxyfarm
*/
pragma solidity ^0.6.8;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin/contracts/math/SafeMath.sol
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity ^0.6.5;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol
pragma solidity ^0.6.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: @openzeppelin/contracts/utils/EnumerableSet.sol
pragma solidity ^0.6.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256`
* (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint256(_at(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// File: @openzeppelin/contracts/GSN/Context.sol
pragma solidity ^0.6.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: @openzeppelin/contracts/token/ERC20/ERC20.sol
pragma solidity ^0.6.0;
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
pragma solidity ^0.6.5;
// FoxyFarm with Governance.
contract FoxyFarm is ERC20("Foxy.farm", "FOXY"), Ownable {
// foxy is an exact copy of SUSHI
using SafeMath for uint256;
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
return super.transfer(recipient, amount);
}
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
return super.transferFrom(sender, recipient, amount);
}
/// @notice Creates `_amount` token to `_to`. Must only be called by the owner (FoxyDen).
function mint(address _to, uint256 _amount) public onlyOwner {
_mint(_to, _amount);
_moveDelegates(address(0), _delegates[_to], _amount);
}
// Copied and modified from YAM code:
// https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol
// https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol
// Which is copied and modified from COMPOUND:
// https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol
/// @notice A record of each accounts delegate
mapping (address => address) internal _delegates;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint256 votes;
}
/// @notice A record of votes checkpoints for each account, by index
mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
/// @notice The number of checkpoints for each account
mapping (address => uint32) public numCheckpoints;
/// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
/// @notice The EIP-712 typehash for the delegation struct used by the contract
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
/// @notice A record of states for signing / validating signatures
mapping (address => uint) public nonces;
/// @notice An event thats emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/// @notice An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegator The address to get delegatee for
*/
function delegates(address delegator)
external
view
returns (address)
{
return _delegates[delegator];
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) external {
return _delegate(msg.sender, delegatee);
}
/**
* @notice Delegates votes from signatory to `delegatee`
* @param delegatee The address to delegate votes to
* @param nonce The contract state required to match the signature
* @param expiry The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function delegateBySig(
address delegatee,
uint nonce,
uint expiry,
uint8 v,
bytes32 r,
bytes32 s
)
external
{
bytes32 domainSeparator = keccak256(
abi.encode(
DOMAIN_TYPEHASH,
keccak256(bytes(name())),
getChainId(),
address(this)
)
);
bytes32 structHash = keccak256(
abi.encode(
DELEGATION_TYPEHASH,
delegatee,
nonce,
expiry
)
);
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
domainSeparator,
structHash
)
);
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "FOXY::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "FOXY::delegateBySig: invalid nonce");
require(now <= expiry, "FOXY::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function getCurrentVotes(address account)
external
view
returns (uint256)
{
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
require(blockNumber < block.number, "FOXY::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function _delegate(address delegator, address delegatee)
internal
{
address currentDelegate = _delegates[delegator];
uint256 delegatorBalance = balanceOf(delegator); // balance of underlying FOXYs (not scaled);
_delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
// decrease old representative
uint32 srcRepNum = numCheckpoints[srcRep];
uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint256 srcRepNew = srcRepOld.sub(amount);
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
// increase new representative
uint32 dstRepNum = numCheckpoints[dstRep];
uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint256 dstRepNew = dstRepOld.add(amount);
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(
address delegatee,
uint32 nCheckpoints,
uint256 oldVotes,
uint256 newVotes
)
internal
{
uint32 blockNumber = safe32(block.number, "FOXY::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function getChainId() internal pure returns (uint) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
}
// File: contracts/FoxyDen.sol
pragma solidity ^0.6.5;
interface IMigratorDen {
// Perform LP token migration from legacy UniswapV2 to FOXYSwap.
// Take the current LP token address and return the new LP token address.
// Migrator should have full access to the caller's LP token.
// Return the new LP token address.
//
// XXX Migrator must have allowance access to UniswapV2 LP tokens.
// FOXYSwap must mint EXACTLY the same amount of FOXYSwap LP tokens or
// else something bad will happen. Traditional UniswapV2 does not
// do that so be careful!
function migrate(IERC20 token) external returns (IERC20);
}
// FoxyDen is an exact copy of SushiSwap
// we have commented an few lines to remove the dev fund
// the rest is exactly the same
// FoxyDen is the master of FOXY. He can make FOXY and he is a fair guy.
//
// Note that it's ownable and the owner wields tremendous power. The ownership
// will be transferred to a governance smart contract once FOXY is sufficiently
// distributed and the community can show to govern itself.
//
// Have fun reading it. Hopefully it's bug-free. God bless.
contract FoxyDen is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Info of each user.
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
//
// We do some fancy math here. Basically, any point in time, the amount of FOXYs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accFOXYPerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accFOXYPerShare` (and `lastRewardBlock`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
// Info of each pool.
struct PoolInfo {
IERC20 lpToken; // Address of LP token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. FOXYs to distribute per block.
uint256 lastRewardBlock; // Last block number that FOXYs distribution occurs.
uint256 accFOXYPerShare; // Accumulated FOXYs per share, times 1e12. See below.
bool taxable; // Accumulated FOXYs per share, times 1e12. See below.
}
// The FOXY TOKEN
FoxyFarm public foxy;
address private devaddr;
// Block number when bonus FOXY period ends.
uint256 public bonusEndBlock;
// FOXY tokens created per block.
uint256 public foxyPerBlock;
// Bonus multiplier for early foxy makers.
uint256 public constant BONUS_MULTIPLIER = 10;
// The migrator contract. It has a lot of power. Can only be set through governance (owner).
IMigratorDen public migrator;
// Info of each pool.
PoolInfo[] public poolInfo;
// Info of each user that stakes LP tokens.
mapping (uint256 => mapping (address => UserInfo)) public userInfo;
// Total allocation poitns. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint = 0;
// The block number when FOXY mining starts.
uint256 public startBlock;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount);
constructor(
FoxyFarm _foxy,
address _devaddr,
uint256 _foxyPerBlock,
uint256 _startBlock,
uint256 _bonusEndBlock
) public {
foxy = _foxy;
devaddr = _devaddr;
foxyPerBlock = _foxyPerBlock;
bonusEndBlock = _bonusEndBlock;
startBlock = _startBlock;
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
// Add a new lp to the pool. Can only be called by the owner.
// XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do.
function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate, bool _taxable, uint256 _startBlock) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock = _startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accFOXYPerShare: 0,
taxable: _taxable
}));
}
// Update the given pool's FOXY allocation point. Can only be called by the owner.
function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate, bool _taxable, uint256 _startBlock) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint;
poolInfo[_pid].taxable = _taxable;
poolInfo[_pid].lastRewardBlock = _startBlock;
}
function setBonusEndBlock(uint256 _bonusEndBlock) public onlyOwner {
bonusEndBlock = _bonusEndBlock;
}
// Set the migrator contract. Can only be called by the owner.
function setMigrator(IMigratorDen _migrator) public onlyOwner {
migrator = _migrator;
}
// Migrate lp token to another lp contract. Can be called by anyone. We trust that migrator contract is good.
function migrate(uint256 _pid) public {
require(address(migrator) != address(0), "migrate: no migrator");
PoolInfo storage pool = poolInfo[_pid];
IERC20 lpToken = pool.lpToken;
uint256 bal = lpToken.balanceOf(address(this));
lpToken.safeApprove(address(migrator), bal);
IERC20 newLpToken = migrator.migrate(lpToken);
require(bal == newLpToken.balanceOf(address(this)), "migrate: bad");
pool.lpToken = newLpToken;
}
// Return reward multiplier over the given _from to _to block.
function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) {
if (_to <= bonusEndBlock) {
return _to.sub(_from).mul(BONUS_MULTIPLIER);
} else if (_from >= bonusEndBlock) {
return _to.sub(_from);
} else {
return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add(
_to.sub(bonusEndBlock)
);
}
}
// View function to see pending FOXYs on frontend.
function pendingFOXY(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accFOXYPerShare = pool.accFOXYPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 foxyReward = multiplier.mul(foxyPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accFOXYPerShare = accFOXYPerShare.add(foxyReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accFOXYPerShare).div(1e12).sub(user.rewardDebt);
}
// Update reward variables for all pools. Be careful of gas spending!
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 foxyReward = multiplier.mul(foxyPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
foxy.mint(address(this), foxyReward);
pool.accFOXYPerShare = pool.accFOXYPerShare.add(foxyReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
// Deposit LP tokens to FoxyDen for FOXY allocation.
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accFOXYPerShare).div(1e12).sub(user.rewardDebt);
safeFOXYTransfer(msg.sender, pending);
}
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount);
user.rewardDebt = user.amount.mul(pool.accFOXYPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
// Withdraw LP tokens from FoxyDen.
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accFOXYPerShare).div(1e12).sub(user.rewardDebt);
safeFOXYTransfer(msg.sender, pending);
user.amount = user.amount.sub(_amount);
user.rewardDebt = user.amount.mul(pool.accFOXYPerShare).div(1e12);
if (pool.taxable) {
pool.lpToken.safeTransfer(address(msg.sender), _amount);
emit Withdraw(devaddr, _pid, _amount.mul(25).div(10000));
emit Withdraw(msg.sender, _pid, _amount.sub(_amount.mul(25).div(10000)));
} else {
pool.lpToken.safeTransfer(address(msg.sender), _amount);
emit Withdraw(msg.sender, _pid, _amount);
}
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
pool.lpToken.safeTransfer(address(msg.sender), user.amount);
emit EmergencyWithdraw(msg.sender, _pid, user.amount);
user.amount = 0;
user.rewardDebt = 0;
}
// Safe foxy transfer function, just in case if rounding error causes pool to not have enough FOXYs.
function safeFOXYTransfer(address _to, uint256 _amount) internal {
uint256 foxyBal = foxy.balanceOf(address(this));
if (_amount > foxyBal) {
foxy.transfer(_to, foxyBal);
} else {
foxy.transfer(_to, _amount);
}
}
} | FoxyFarm with Governance. foxy is an exact copy of SUSHI | contract FoxyFarm is ERC20("Foxy.farm", "FOXY"), Ownable {
using SafeMath for uint256;
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
return super.transfer(recipient, amount);
}
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
return super.transferFrom(sender, recipient, amount);
}
function mint(address _to, uint256 _amount) public onlyOwner {
_mint(_to, _amount);
_moveDelegates(address(0), _delegates[_to], _amount);
}
mapping (address => address) internal _delegates;
struct Checkpoint {
uint32 fromBlock;
uint256 votes;
}
mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
mapping (address => uint32) public numCheckpoints;
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
mapping (address => uint) public nonces;
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
function delegates(address delegator)
external
view
returns (address)
{
return _delegates[delegator];
}
function delegate(address delegatee) external {
return _delegate(msg.sender, delegatee);
}
function delegateBySig(
address delegatee,
uint nonce,
uint expiry,
uint8 v,
bytes32 r,
bytes32 s
)
external
{
bytes32 domainSeparator = keccak256(
abi.encode(
DOMAIN_TYPEHASH,
keccak256(bytes(name())),
getChainId(),
address(this)
)
);
bytes32 structHash = keccak256(
abi.encode(
DELEGATION_TYPEHASH,
delegatee,
nonce,
expiry
)
);
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
domainSeparator,
structHash
)
);
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "FOXY::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "FOXY::delegateBySig: invalid nonce");
require(now <= expiry, "FOXY::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
function getCurrentVotes(address account)
external
view
returns (uint256)
{
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
require(blockNumber < block.number, "FOXY::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
lower = center;
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
require(blockNumber < block.number, "FOXY::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
lower = center;
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
require(blockNumber < block.number, "FOXY::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
lower = center;
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
require(blockNumber < block.number, "FOXY::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
lower = center;
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
require(blockNumber < block.number, "FOXY::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
lower = center;
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
require(blockNumber < block.number, "FOXY::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
lower = center;
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
} else if (cp.fromBlock < blockNumber) {
} else {
function _delegate(address delegator, address delegatee)
internal
{
address currentDelegate = _delegates[delegator];
_delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
uint32 srcRepNum = numCheckpoints[srcRep];
uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint256 srcRepNew = srcRepOld.sub(amount);
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
uint32 dstRepNum = numCheckpoints[dstRep];
uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint256 dstRepNew = dstRepOld.add(amount);
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
uint32 srcRepNum = numCheckpoints[srcRep];
uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint256 srcRepNew = srcRepOld.sub(amount);
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
uint32 dstRepNum = numCheckpoints[dstRep];
uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint256 dstRepNew = dstRepOld.add(amount);
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
uint32 srcRepNum = numCheckpoints[srcRep];
uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint256 srcRepNew = srcRepOld.sub(amount);
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
uint32 dstRepNum = numCheckpoints[dstRep];
uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint256 dstRepNew = dstRepOld.add(amount);
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
uint32 srcRepNum = numCheckpoints[srcRep];
uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint256 srcRepNew = srcRepOld.sub(amount);
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
uint32 dstRepNum = numCheckpoints[dstRep];
uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint256 dstRepNew = dstRepOld.add(amount);
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(
address delegatee,
uint32 nCheckpoints,
uint256 oldVotes,
uint256 newVotes
)
internal
{
uint32 blockNumber = safe32(block.number, "FOXY::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function _writeCheckpoint(
address delegatee,
uint32 nCheckpoints,
uint256 oldVotes,
uint256 newVotes
)
internal
{
uint32 blockNumber = safe32(block.number, "FOXY::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
} else {
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function getChainId() internal pure returns (uint) {
uint256 chainId;
return chainId;
}
assembly { chainId := chainid() }
}
| 15,212,783 | [
1,
42,
83,
1698,
42,
4610,
598,
611,
1643,
82,
1359,
18,
18261,
1698,
353,
392,
5565,
1610,
434,
11726,
2664,
45,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
478,
83,
1698,
42,
4610,
353,
4232,
39,
3462,
2932,
42,
83,
1698,
18,
74,
4610,
3113,
315,
3313,
8546,
6,
3631,
14223,
6914,
288,
203,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
203,
565,
445,
7412,
12,
2867,
8027,
16,
2254,
5034,
3844,
13,
1071,
5024,
3849,
1135,
261,
6430,
13,
288,
203,
3639,
327,
2240,
18,
13866,
12,
20367,
16,
3844,
1769,
203,
565,
289,
203,
203,
565,
445,
7412,
1265,
12,
2867,
5793,
16,
1758,
8027,
16,
2254,
5034,
3844,
13,
1071,
5024,
3849,
1135,
261,
6430,
13,
288,
21281,
3639,
327,
2240,
18,
13866,
1265,
12,
15330,
16,
8027,
16,
3844,
1769,
203,
565,
289,
203,
203,
565,
445,
312,
474,
12,
2867,
389,
869,
16,
2254,
5034,
389,
8949,
13,
1071,
1338,
5541,
288,
203,
3639,
389,
81,
474,
24899,
869,
16,
389,
8949,
1769,
203,
3639,
389,
8501,
15608,
815,
12,
2867,
12,
20,
3631,
389,
3771,
1332,
815,
63,
67,
869,
6487,
389,
8949,
1769,
203,
565,
289,
203,
203,
203,
203,
565,
2874,
261,
2867,
516,
1758,
13,
2713,
389,
3771,
1332,
815,
31,
203,
565,
1958,
25569,
288,
203,
3639,
2254,
1578,
628,
1768,
31,
203,
3639,
2254,
5034,
19588,
31,
203,
565,
289,
203,
203,
203,
203,
203,
203,
203,
203,
203,
565,
2874,
261,
2867,
516,
2874,
261,
11890,
1578,
516,
25569,
3719,
1071,
26402,
31,
203,
565,
2874,
261,
2867,
516,
2254,
1578,
13,
1071,
818,
1564,
4139,
31,
203,
565,
1731,
1578,
1071,
5381,
27025,
67,
2399,
2
] |
pragma solidity 0.5.10;
import "./Base.sol";
import "../interface/IRole.sol";
/**
@title This manages the roles to access to the platform.
@author StablePay <[email protected]>
@notice This smart contract manages the roles for each address who access to the platform.
*/
contract Role is Base, IRole {
/** Constants */
string internal constant ROLE_NAME = "Role";
uint16 internal constant TOTAL_OWNERS_MIN = 1;
/** Properties */
uint16 public ownersCounter = 1;
/** Events */
/** Modifier */
/**
@notice It checks whether this smart contract is the last version.
@dev It checks getting the address for the contract name 'Role'.
@dev If it is not the last version, it throws a require error.
*/
modifier onlyLatestRole() {
require(
address(this) ==
_storage.getAddress(
keccak256(abi.encodePacked(CONTRACT_NAME, ROLE_NAME))
),
"Only the latest version contract."
);
_;
}
/** Constructor */
/**
@notice It creates a new Role instance associated to an Eternal Storage implementation.
@param storageAddress the Eternal Storage implementation.
@dev The Eternal Storage implementation must implement the IStorage interface.
*/
constructor(address storageAddress) public Base(storageAddress) {}
/**
@notice It transfers the ownership of the platform to another address.
@dev After transfering ownership, if the execution was as expected, the sender must call the 'deleteOwner' function.
@param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner)
external
onlyLatestRole()
onlyOwner()
nonReentrant()
{
// Legit address?
require(newOwner != address(0x0), "New owner must be != 0x0.");
// Check the role exists
roleCheck("owner", msg.sender);
// Add new owner
_storage.setBool(
keccak256(abi.encodePacked("access.role", "owner", newOwner)),
true
);
setTotalOwners(getTotalOwners() + 1);
emit OwnershipTransferred(msg.sender, newOwner);
}
/**
@notice It removes the owner from the platform.
@dev It needs to be executed after transfering the ownership to a new address.
*/
function deleteOwner() external onlyLatestRole() onlyOwner() nonReentrant() {
roleCheck("owner", msg.sender);
uint16 currentTotalOwners = getTotalOwners();
require(
currentTotalOwners > TOTAL_OWNERS_MIN,
"Platform must have at least one owner."
);
_storage.deleteBool(
keccak256(abi.encodePacked("access.role", "owner", msg.sender))
);
setTotalOwners(currentTotalOwners - 1);
emit OwnerRemoved(address(this), msg.sender, now);
}
function getTotalOwners() internal view returns (uint16) {
return ownersCounter;
}
function setTotalOwners(uint16 newTotalOwners) internal {
ownersCounter = newTotalOwners;
}
/** Admin Role Methods */
/**
@notice It adds a role to a specific address.
@dev The sender must be a super user (owner or admin) only.
@param aRole the role name to give to the address.
@param anAddress the address which will receive the role.
*/
function adminRoleAdd(string calldata aRole, address anAddress)
external
onlyLatestRole()
onlySuperUser()
nonReentrant()
{
roleAdd(aRole, anAddress);
}
/**
@notice It removes a role to a specific address.
@dev The sender must be a super user (owner or admin).
@param aRole the role name to remove from the address.
@param anAddress the address which will be removed from the role.
*/
function adminRoleRemove(string calldata aRole, address anAddress)
external
onlyLatestRole()
onlySuperUser()
nonReentrant()
{
roleRemove(aRole, anAddress);
}
/** Internal Role Methods */
/**
@notice It gives a role to a specific address.
@param _role the role name to give to the address.
@param _address the address which will receive the role.
*/
function roleAdd(string memory _role, address _address) internal {
// Legit address?
require(_address != address(0x0), "Address != 0x0.");
require(
keccak256(abi.encodePacked(_role)) != keccak256(""),
"Role must not be empty."
);
// Only one owner to rule them all
require(
keccak256(abi.encodePacked(_role)) != keccak256("owner"),
"Only one owner."
);
// Add it
_storage.setBool(
keccak256(abi.encodePacked("access.role", _role, _address)),
true
);
// Log it
emit RoleAdded(_address, _role);
}
/**
@notice It removes a role to a specific address.
@param _role the role name to remove from the address.
@param _address the address which will be removed from the role.
*/
function roleRemove(string memory _role, address _address) internal {
// Only an owner can transfer their access
require(!roleHas("owner", _address), "Only owner can transfer their access.");
// Remove from storage
_storage.deleteBool(keccak256(abi.encodePacked("access.role", _role, _address)));
// Log it
emit RoleRemoved(_address, _role);
}
}
| / Only an owner can transfer their access Remove from storage Log it | function roleRemove(string memory _role, address _address) internal {
require(!roleHas("owner", _address), "Only owner can transfer their access.");
_storage.deleteBool(keccak256(abi.encodePacked("access.role", _role, _address)));
emit RoleRemoved(_address, _role);
}
| 12,545,282 | [
1,
19,
5098,
392,
3410,
848,
7412,
3675,
2006,
3581,
628,
2502,
1827,
518,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
2478,
3288,
12,
1080,
3778,
389,
4615,
16,
1758,
389,
2867,
13,
2713,
288,
203,
3639,
2583,
12,
5,
4615,
5582,
2932,
8443,
3113,
389,
2867,
3631,
315,
3386,
3410,
848,
7412,
3675,
2006,
1199,
1769,
203,
3639,
389,
5697,
18,
3733,
7464,
12,
79,
24410,
581,
5034,
12,
21457,
18,
3015,
4420,
329,
2932,
3860,
18,
4615,
3113,
389,
4615,
16,
389,
2867,
3719,
1769,
203,
3639,
3626,
6204,
10026,
24899,
2867,
16,
389,
4615,
1769,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
//Address: 0xb3f1c771e232516aceae118dce40fa3199504931
//Contract name: HumaniqICO
//Balance: 0 Ether
//Verification Date: 5/8/2017
//Transacion Count: 8196
// CODE STARTS HERE
pragma solidity ^0.4.6;
/**
* Math operations with safety checks
*/
contract SafeMath {
function mul(uint a, uint b) internal returns (uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint a, uint b) internal returns (uint) {
assert(b > 0);
uint c = a / b;
assert(a == b * c + a % b);
return c;
}
function sub(uint a, uint b) internal returns (uint) {
assert(b <= a);
return a - b;
}
function add(uint a, uint b) internal returns (uint) {
uint c = a + b;
assert(c >= a);
return c;
}
function assert(bool assertion) internal {
if (!assertion) {
throw;
}
}
}
/// Implements ERC 20 Token standard: https://github.com/ethereum/EIPs/issues/20
/// @title Abstract token contract - Functions to be implemented by token contracts.
contract AbstractToken {
// This is not an abstract function, because solc won't recognize generated getter functions for public variables as functions
function totalSupply() constant returns (uint256 supply) {}
function balanceOf(address owner) constant returns (uint256 balance);
function transfer(address to, uint256 value) returns (bool success);
function transferFrom(address from, address to, uint256 value) returns (bool success);
function approve(address spender, uint256 value) returns (bool success);
function allowance(address owner, address spender) constant returns (uint256 remaining);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
event Issuance(address indexed to, uint256 value);
}
contract StandardToken is AbstractToken {
/*
* Data structures
*/
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
uint256 public totalSupply;
/*
* Read and write storage functions
*/
/// @dev Transfers sender's tokens to a given address. Returns success.
/// @param _to Address of token receiver.
/// @param _value Number of tokens to transfer.
function transfer(address _to, uint256 _value) returns (bool success) {
if (balances[msg.sender] >= _value && balances[_to] + _value > balances[_to]) {
balances[msg.sender] -= _value;
balances[_to] += _value;
Transfer(msg.sender, _to, _value);
return true;
}
else {
return false;
}
}
/// @dev Allows allowed third party to transfer tokens from one address to another. Returns success.
/// @param _from Address from where tokens are withdrawn.
/// @param _to Address to where tokens are sent.
/// @param _value Number of tokens to transfer.
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value > balances[_to]) {
balances[_to] += _value;
balances[_from] -= _value;
allowed[_from][msg.sender] -= _value;
Transfer(_from, _to, _value);
return true;
}
else {
return false;
}
}
/// @dev Returns number of tokens owned by given address.
/// @param _owner Address of token owner.
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
/// @dev Sets approved amount of tokens for spender. Returns success.
/// @param _spender Address of allowed account.
/// @param _value Number of approved tokens.
function approve(address _spender, uint256 _value) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/*
* Read storage functions
*/
/// @dev Returns number of allowed tokens for given address.
/// @param _owner Address of token owner.
/// @param _spender Address of token spender.
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
/// @title Token contract - Implements Standard Token Interface with HumaniQ features.
/// @author Evgeny Yurtaev - <[email protected]>
/// @author Alexey Bashlykov - <[email protected]>
contract HumaniqToken is StandardToken, SafeMath {
/*
* External contracts
*/
address public minter;
/*
* Token meta data
*/
string constant public name = "Humaniq";
string constant public symbol = "HMQ";
uint8 constant public decimals = 8;
// Address of the founder of Humaniq.
address public founder = 0xc890b1f532e674977dfdb791cafaee898dfa9671;
// Multisig address of the founders
address public multisig = 0xa2c9a7578e2172f32a36c5c0e49d64776f9e7883;
// Address where all tokens created during ICO stage initially allocated
address constant public allocationAddressICO = 0x1111111111111111111111111111111111111111;
// Address where all tokens created during preICO stage initially allocated
address constant public allocationAddressPreICO = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
// 31 820 314 tokens were minted during preICO
uint constant public preICOSupply = mul(31820314, 100000000);
// 131 038 286 tokens were minted during ICO
uint constant public ICOSupply = mul(131038286, 100000000);
// Max number of tokens that can be minted
uint public maxTotalSupply;
/*
* Modifiers
*/
modifier onlyFounder() {
// Only founder is allowed to do this action.
if (msg.sender != founder) {
throw;
}
_;
}
modifier onlyMinter() {
// Only minter is allowed to proceed.
if (msg.sender != minter) {
throw;
}
_;
}
/*
* Contract functions
*/
/// @dev Crowdfunding contract issues new tokens for address. Returns success.
/// @param _for Address of receiver.
/// @param tokenCount Number of tokens to issue.
function issueTokens(address _for, uint tokenCount)
external
payable
onlyMinter
returns (bool)
{
if (tokenCount == 0) {
return false;
}
if (add(totalSupply, tokenCount) > maxTotalSupply) {
throw;
}
totalSupply = add(totalSupply, tokenCount);
balances[_for] = add(balances[_for], tokenCount);
Issuance(_for, tokenCount);
return true;
}
/// @dev Function to change address that is allowed to do emission.
/// @param newAddress Address of new emission contract.
function changeMinter(address newAddress)
public
onlyFounder
returns (bool)
{
// Forbid previous emission contract to distribute tokens minted during ICO stage
delete allowed[allocationAddressICO][minter];
minter = newAddress;
// Allow emission contract to distribute tokens minted during ICO stage
allowed[allocationAddressICO][minter] = balanceOf(allocationAddressICO);
}
/// @dev Function to change founder address.
/// @param newAddress Address of new founder.
function changeFounder(address newAddress)
public
onlyFounder
returns (bool)
{
founder = newAddress;
}
/// @dev Function to change multisig address.
/// @param newAddress Address of new multisig.
function changeMultisig(address newAddress)
public
onlyFounder
returns (bool)
{
multisig = newAddress;
}
/// @dev Contract constructor function sets initial token balances.
function HumaniqToken(address founderAddress)
{
// Set founder address
founder = founderAddress;
// Allocate all created tokens during ICO stage to allocationAddressICO.
balances[allocationAddressICO] = ICOSupply;
// Allocate all created tokens during preICO stage to allocationAddressPreICO.
balances[allocationAddressPreICO] = preICOSupply;
// Allow founder to distribute tokens minted during preICO stage
allowed[allocationAddressPreICO][founder] = preICOSupply;
// Give 14 percent of all tokens to founders.
balances[multisig] = div(mul(ICOSupply, 14), 86);
// Set correct totalSupply and limit maximum total supply.
totalSupply = add(ICOSupply, balances[multisig]);
totalSupply = add(totalSupply, preICOSupply);
maxTotalSupply = mul(totalSupply, 5);
}
}
/// @title HumaniqICO contract - Takes funds from users and issues tokens.
/// @author Evgeny Yurtaev - <[email protected]>
/// @author Alexey Bashlykov - <[email protected]>
contract HumaniqICO is SafeMath {
/*
* External contracts
*/
HumaniqToken public humaniqToken;
// Address of the founder of Humaniq.
address public founder = 0xc890b1f532e674977dfdb791cafaee898dfa9671;
// Address where all tokens created during ICO stage initially allocated
address public allocationAddress = 0x1111111111111111111111111111111111111111;
// Start date of the ICO
uint public startDate = 1491433200; // 2017-04-05 23:00:00 UTC
// End date of the ICO
uint public endDate = 1493247600; // 2017-04-26 23:00:00 UTC
// Token price without discount during the ICO stage
uint public baseTokenPrice = 10000000; // 0.001 ETH, considering 8 decimal places
// Number of tokens distributed to investors
uint public tokensDistributed = 0;
/*
* Modifiers
*/
modifier onlyFounder() {
// Only founder is allowed to do this action.
if (msg.sender != founder) {
throw;
}
_;
}
modifier minInvestment(uint investment) {
// User has to send at least the ether value of one token.
if (investment < baseTokenPrice) {
throw;
}
_;
}
/// @dev Returns current bonus
function getCurrentBonus()
public
constant
returns (uint)
{
return getBonus(now);
}
/// @dev Returns bonus for the specific moment
/// @param timestamp Time of investment (in seconds)
function getBonus(uint timestamp)
public
constant
returns (uint)
{
if (timestamp > endDate) {
throw;
}
if (startDate > timestamp) {
return 1499; // 49.9%
}
uint icoDuration = timestamp - startDate;
if (icoDuration >= 16 days) {
return 1000; // 0%
} else if (icoDuration >= 9 days) {
return 1125; // 12.5%
} else if (icoDuration >= 2 days) {
return 1250; // 25%
} else {
return 1499; // 49.9%
}
}
function calculateTokens(uint investment, uint timestamp)
public
constant
returns (uint)
{
// calculate discountedPrice
uint discountedPrice = div(mul(baseTokenPrice, 1000), getBonus(timestamp));
// Token count is rounded down. Sent ETH should be multiples of baseTokenPrice.
return div(investment, discountedPrice);
}
/// @dev Issues tokens for users who made BTC purchases.
/// @param beneficiary Address the tokens will be issued to.
/// @param investment Invested amount in Wei
/// @param timestamp Time of investment (in seconds)
function fixInvestment(address beneficiary, uint investment, uint timestamp)
external
onlyFounder
minInvestment(investment)
returns (uint)
{
// Calculate number of tokens to mint
uint tokenCount = calculateTokens(investment, timestamp);
// Update fund's and user's balance and total supply of tokens.
tokensDistributed = add(tokensDistributed, tokenCount);
// Distribute tokens.
if (!humaniqToken.transferFrom(allocationAddress, beneficiary, tokenCount)) {
// Tokens could not be issued.
throw;
}
return tokenCount;
}
/// @dev Contract constructor
function HumaniqICO(address tokenAddress, address founderAddress) {
// Set token address
humaniqToken = HumaniqToken(tokenAddress);
// Set founder address
founder = founderAddress;
}
/// @dev Fallback function
function () payable {
throw;
}
}
| @dev Contract constructor Set token address Set founder address | function HumaniqICO(address tokenAddress, address founderAddress) {
humaniqToken = HumaniqToken(tokenAddress);
founder = founderAddress;
}
| 1,759,158 | [
1,
8924,
3885,
1000,
1147,
1758,
1000,
284,
465,
765,
1758,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
670,
6925,
18638,
2871,
51,
12,
2867,
1147,
1887,
16,
1758,
284,
465,
765,
1887,
13,
288,
203,
3639,
8672,
18638,
1345,
273,
670,
6925,
18638,
1345,
12,
2316,
1887,
1769,
203,
203,
3639,
284,
465,
765,
273,
284,
465,
765,
1887,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.24;
// EPM Library Usage
import "openzeppelin-solidity/contracts/ownership/Ownable.sol";
import "./Proxy.sol";
/** @title A managment contract to store and manage all Campains for the platform.
* This enables users to create new campagins and then other users can fund them.
* Users can only fund campains that are currently running(have started and not
* finished). If a user withdraws from a campaign, they can only do so if it does
* not result in the campaign no longer getting funded.
* @author Chris Maree - SoIdarity
*/
contract CampaignManager is Ownable, Proxy{
/** @dev store the current state of the Camaign.
*/
enum State{NotStarted, Running, Funded, UnderFunded}
/** @dev define the standard properties of a Campaign
* @notice the doners are a mapping of addresses to uints. This enables each
* donar to donate more than one time and for a record to be kept. Moreover,
* if a doner removes their donation, a negative value can be stored here to
* indicate the withdrawl
* @notice the donersAddresses is used to store an array of all donars that
* contributed as maps are not itterable by populated keys
*/
struct Campaign {
address manager;
uint startingTime;
uint endingTime;
uint balance;
uint goal;
uint cap;
State state;
mapping(address=>int[]) doners;
address[] donersAddresses;
string ipfsHash;
}
/** @dev store the total number of campaigns. Useful for retreving all of them **/
uint public campaignCount;
/**
* @dev Stop the creation of new campagins
*/
bool public emergencyStop_stopCreation = false;
/**
* @dev stops the fundion of existing campagins
*/
bool public emergencyStop_stopFunding = false;
/** @dev store all campaigns as a mapping to their unique ID **/
mapping(uint => Campaign) public campaigns;
/**
* @dev Verify the times spesified for the campaign are valid
* @param _startingTime of the campaign (unix time stamp)
* @param _endingTime of the campaign (unix time stamp)
*/
modifier validNewCampaignTime(uint _startingTime,uint _endingTime){
require(_startingTime >= now, "Firstly, Start time must be larger than the current time");
require(_endingTime > _startingTime,"Secondly, the end time should be more than the starting time");
_;
}
/**
* @dev Verify the goals and cap for the campaign are valid
* @notice if the cap is set to zero, it is uncapped
* @param _goal value of the campaign (in ETH)
* @param _cap value of the campaign (in ETH)
*/
modifier validNewCampaignFunding(uint _goal,uint _cap) {
if(_cap != 0){
require(_cap > _goal, "Cap should be larger than goal to be valid");
}
_;
}
/**
* @dev Verify the current time is past the start time of the camaign
* @param _campaignID unique identifer of the campaign
*/
modifier campaignHasStarted(uint _campaignID) {
require(now > campaigns[_campaignID].startingTime, "Current time must be larger than starting time for project to start");
_;
}
/**
* @dev checks if the campaign is yet to start
* @param _campaignID unique identifer of the campaign
*/
modifier campaignNotStarted(uint _campaignID){
require(now < campaigns[_campaignID].startingTime, "Current time should be less than the starting time");
_;
}
/**
* @dev checks if the campain has ended (current time more than end time)
* @param _campaignID unique identifer of the campaign
*/
modifier campaignEnded(uint _campaignID){
require(now > campaigns[_campaignID].endingTime, "Current time must be bigger than the end time for the campaign to have ended");
_;
}
/**
* @dev Verify the current time is not past the end time of the camaign
* @param _campaignID unique identifer of the campaign
*/
modifier campaignHasNotEnded(uint _campaignID) {
require(now < campaigns[_campaignID].endingTime, "Current time must be less than the end time for the campaign to have not ended");
_;
}
/**
* @dev checks if the campain has Succeeded (donation > than goal)
* @param _campaignID unique identifer of the campaign
*/
modifier campaignSucceeded(uint _campaignID){
require(campaigns[_campaignID].balance > campaigns[_campaignID].goal, "The balance of the campaign must be more than the goal");
_;
}
/**
* @dev checks if the campain has failed (donation < than goal)
* @param _campaignID unique identifer of the campaign
*/
modifier campaignUnsuccessful(uint _campaignID) {
require(now > campaigns[_campaignID].endingTime,"The campaign must have ended firstly to check if a campaign is unsuccessful");
require(
campaigns[_campaignID].balance < campaigns[_campaignID].goal,
"Secondly, the campaign must have a balance less than the goal to be unsuccessful");
_;
}
/**
* @dev checks if a campain has been funded, and therefore paid out.
* @notice This assertion prevents manager's from withdrawing twice from a fund.
* @param _campaignID unique identifer of the campaign
*/
modifier campaignNotFunded(uint _campaignID){
require(campaigns[_campaignID].state != State.Funded,"The state of the campaign must be not funded to define an unfunded campaign");
_;
}
/**
* @dev Verify that the donation will not cause the campaign to exceed its cap
* @notice this function takes into account the current balance and the donation
* @param _campaignID unique identifer of the campaign
*/
modifier campaignWillNotExceedCap(uint _campaignID) {
require(
campaigns[_campaignID].balance + msg.value <= campaigns[_campaignID].cap,
"The value of the donation + the current balance of the fund must be less than the cap to not exceed the cap");
_;
}
/**
* @dev Verify that the donation will not cause the campaign to drop below
* its goal. This prevents someone from making a campaign that would succeed,
* fail due to cancelling their contribution
* @notice value is required as the user has the choice to either cancle or
* reduce their donation.
* @param _campaignID unique identifer of the campaign
* @param _value is the amount that the donar wants to reduce their donation by
*/
modifier campaignWillNotDropBelowGoal(uint _campaignID, uint _value) {
// We only need to do this check if the campaign has been funded thus far, with the balance being more than the goal
if(campaigns[_campaignID].balance>campaigns[_campaignID].goal){
require(
campaigns[_campaignID].balance-_value > campaigns[_campaignID].goal,
"The value of the campaign balance after the reduction will be more than the goal");
}
_;
}
/**
* @dev Verify that the reduction from a donation will not cause the donation
* to drop below zero, and as such enabling the user to take out more than
* they deposited. Moreover, this check ensures that a user who did not donate
* cant withdraw as this assert will fail as their total donation balance will
* be zero.
* @notice the function needs to check the total donation for the user by
* summing over all previous donations
* @param _campaignID unique identifer of the campaign
* @param _value is the amount that the donar wants to reduce their donation by
*/
modifier adequetDonationToReduce(uint _campaignID, uint _value){
int totalDonation = 0;
for (uint i = 0; i < campaigns[_campaignID].doners[msg.sender].length; i++){
totalDonation += campaigns[_campaignID].doners[msg.sender][i];
}
require(
totalDonation-int(_value) >= 0,
"The sum of all donations for a particular user should be more than 0 to enable any kind of donation reduction");
_;
}
/**
* @dev checks that the caller of the function is the campaign's manager;
* This is the person that create the campaign.
* @param _campaignID unique identifer of the campaign
*/
modifier onlyManager(uint _campaignID){
require(msg.sender == campaigns[_campaignID].manager,"The caller should be equal to the manager");
_;
}
/**
* @dev checks if a caller of the function is a Contributer to the campaign
* @notice If they have contributed, there will be some items within the
* doners array representing donations.
* @param _campaignID unique identifer of the campaign
*/
modifier onlyContributer(uint _campaignID){
require(campaigns[_campaignID].doners[msg.sender].length > 0,"The caller should have contributed at least once to the campaign");
_;
}
/**
* @dev Prevents the creation of new campaigns
*/
modifier emergencyStop_Creation(){
require(emergencyStop_stopCreation == false, "The emergency stop creation is active");
_;
}
/**
* @dev Prevents the funding of new campaigns
*/
modifier emergencyStop_Funding(){
require(emergencyStop_stopFunding == false, "The emergency stop funding is active");
_;
}
/** @dev Assign owner and reset campaign */
constructor()
public {
owner = msg.sender;
campaignCount = 0;
}
function enableEmergencyStop_Creation()
public
onlyOwner
{
emergencyStop_stopCreation = true;
}
function enableEmergencyStop_Funding()
public
onlyOwner
{
emergencyStop_stopFunding = true;
}
/**
* @dev Generate a new campaign struct and store it. Assign manager and values
* @notice this sets the inital value of the State to NotStarted
* @param _startingTime unix time stamp of when the campaign will start
* @param _endingTime unix time stamp of when the campaign will end
* @param _goal value of the campaign (in ETH).
* @param _cap value of the campaign (in ETH)
* @param _ipfsHash represents the campain information on IPFS in a hash
*/
function createCampaign(
uint _startingTime,
uint _endingTime,
uint _goal,
uint _cap,
string _ipfsHash
)
public
validNewCampaignTime(_startingTime,_endingTime)
validNewCampaignFunding(_goal,_cap)
emergencyStop_Creation
returns(uint)
{
address[] memory emptydonersAddresses;
campaigns[campaignCount] = Campaign({
manager: msg.sender,
startingTime: _startingTime,
endingTime: _endingTime,
balance: 0,
goal: _goal,
cap: _cap,
state: State.NotStarted,
donersAddresses: emptydonersAddresses,
ipfsHash: _ipfsHash
});
campaignCount += 1;
return campaignCount;
}
/**
* @dev Enable anyone to donate to a campaign. The campaign must have started,
* have not finished and not exceeded it's cap to be able to deposit.
* @notice this changes the state of a campaign from NotStarted -> Running
* @param _campaignID unique identifer of the campaign
*/
function fundCampaign(uint _campaignID)
public
payable
campaignHasStarted(_campaignID)
campaignHasNotEnded(_campaignID)
campaignWillNotExceedCap(_campaignID)
emergencyStop_Funding
{
campaigns[_campaignID].balance += msg.value;
// Need to implicity typecast the msg.value for as donars can be
// negative when withdrawing
campaigns[_campaignID].doners[msg.sender].push(int(msg.value));
// There is no point in storing a doners address multiple times in the
//donersAddresses array so only add if you this is your first contribution
// if(campaigns[_campaignID].doners[msg.sender].length==0){
campaigns[_campaignID].donersAddresses.push(msg.sender);
// }
if (campaigns[_campaignID].state != State.Running){
campaigns[_campaignID].state = State.Running;
}
}
/**
* @dev Enable any donar to reduce their donation. The campaign must have,
* started have not finished and their reduction must not make a project that
* would succeed fail due to the reduction.
* @notice we dont need to check the state of the campain as you would only
* call this function if you had at some point donated and the check is done
* there (function fundCampaign).
* @param _campaignID unique identifer of the campaign
* @param _value the amount bywhich the campaign is reduced
*/
function reduceDontation(uint _campaignID, uint _value)
public
campaignHasStarted(_campaignID)
campaignHasNotEnded(_campaignID)
campaignWillNotDropBelowGoal(_campaignID, _value)
adequetDonationToReduce(_campaignID, _value)
{
campaigns[_campaignID].balance -= _value;
// store the reduction in the doners respective array as a negative value
// preserving a history of reductions. The sum of this array is their
// respective donation
campaigns[_campaignID].doners[msg.sender].push(-int(_value));
msg.sender.transfer(_value); //refund the user for the Ether they sent in
}
/**
* @dev Enable the campaign manager to withdraw the funds donated after the
* period is finished. The state of the campaign.state defines if the ownerc
* @notice The campaign state changes from Running -> Funded
* @param _campaignID unique identifer of the campaign
*/
function withdrawCampaignFunds(uint _campaignID)
public
onlyManager(_campaignID)
campaignEnded(_campaignID)
campaignSucceeded(_campaignID)
campaignNotFunded(_campaignID)
{
// Note that we dont have to change the balance of the campaign as we
// prevent double withdraws by checking the state of the campaign.
// Leaving the balance within the campaign enables an easy way to sender
// the total funds sent to the campaign.
campaigns[_campaignID].state = State.Funded;
msg.sender.transfer(campaigns[_campaignID].balance);
}
/**
* @dev Enables someone who contributed to a failed campaign to get back
* their contributions back. This is a sum of all their contributions
* period is finished.
* @notice The campaign state changes from Running -> Failed
* @param _campaignID unique identifer of the campaign
*/
function refundFailedCampaign(uint _campaignID)
public
onlyContributer(_campaignID)
campaignEnded(_campaignID)
campaignUnsuccessful(_campaignID)
{
uint totalContributed = 0;
for (uint i = 0;i < campaigns[_campaignID].doners[msg.sender].length; i++){
totalContributed += uint(campaigns[_campaignID].doners[msg.sender][i]);
}
// Take away their whole contribution from their profile. This means
// that if they try redraw again the sum total == 0. The require is here
// to ensure that if the user calls again the function will not preform
// a transaction of 0 ether and will throw
require(totalContributed > 0, "The total contribution for the user should be positive");
campaigns[_campaignID].doners[msg.sender].push(-int(totalContributed));
msg.sender.transfer(totalContributed);
}
/**
* @dev Enables a fund manager to update the ipfs hash on an entry in the
* case they change it.
* @notice They can ONLY do this before a fund is sstarted.
* @param _campaignID unique identifer of the campaign
* @param _newHash defines the new IPFS hash for the campaign
*/
function updateIpfsHash(uint _campaignID, string _newHash)
public
onlyManager(_campaignID)
campaignNotStarted(_campaignID)
{
campaigns[_campaignID].ipfsHash = _newHash;
}
function fetchCampaign(uint _campaignID)
public
view
returns
(address manager,
uint startingTime,
uint endingTime,
uint balance,
uint goal,
uint cap,
State state,
address[] donersAddresses,
string ipfsHash)
{
manager = campaigns[_campaignID].manager;
startingTime = campaigns[_campaignID].startingTime;
endingTime = campaigns[_campaignID].endingTime;
balance = campaigns[_campaignID].balance;
goal = campaigns[_campaignID].goal;
cap = campaigns[_campaignID].cap;
state = campaigns[_campaignID].state;
donersAddresses = campaigns[_campaignID].donersAddresses;
ipfsHash = campaigns[_campaignID].ipfsHash;
return (manager, startingTime, endingTime, balance, goal, cap, state, donersAddresses, ipfsHash);
}
} | * @dev Verify the goals and cap for the campaign are valid @notice if the cap is set to zero, it is uncapped @param _goal value of the campaign (in ETH) @param _cap value of the campaign (in ETH)/ | modifier validNewCampaignFunding(uint _goal,uint _cap) {
if(_cap != 0){
require(_cap > _goal, "Cap should be larger than goal to be valid");
}
_;
}
| 5,542,237 | [
1,
8097,
326,
1960,
1031,
471,
3523,
364,
326,
8965,
854,
923,
225,
309,
326,
3523,
353,
444,
358,
3634,
16,
518,
353,
6301,
438,
1845,
225,
389,
27354,
460,
434,
326,
8965,
261,
267,
512,
2455,
13,
225,
389,
5909,
460,
434,
326,
8965,
261,
267,
512,
2455,
13176,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
9606,
923,
1908,
13432,
42,
14351,
12,
11890,
389,
27354,
16,
11890,
389,
5909,
13,
288,
203,
3639,
309,
24899,
5909,
480,
374,
15329,
203,
5411,
2583,
24899,
5909,
405,
389,
27354,
16,
315,
4664,
1410,
506,
10974,
2353,
17683,
358,
506,
923,
8863,
203,
3639,
289,
203,
3639,
389,
31,
203,
565,
289,
203,
377,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
//Address: 0x16a53260f47252d68abf70be7e96dd8813728198
//Contract name: CentrallyIssuedToken
//Balance: 0 Ether
//Verification Date: 5/22/2018
//Transacion Count: 1
// CODE STARTS HERE
pragma solidity ^0.4.18;
// File: zeppelin-solidity/contracts/math/SafeMath.sol
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
// File: zeppelin-solidity/contracts/token/ERC20Basic.sol
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
// File: zeppelin-solidity/contracts/token/ERC20.sol
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: contracts/StandardToken.sol
/**
* Standard ERC20 token with Short Hand Attack and approve() race condition mitigation.
*
* Based on code by FirstBlood:
* https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20 {
mapping(address => uint) balances;
mapping (address => mapping (address => uint)) allowed;
// Interface marker
bool public constant isToken = true;
/**
*
* Fix for the ERC20 short address attack
*
* http://vessenes.com/the-erc20-short-address-attack-explained/
*/
modifier onlyPayloadSize(uint size) {
if(msg.data.length < size + 4) {
revert();
}
_;
}
function transfer(address _to, uint _value) onlyPayloadSize(2 * 32) public returns (bool success) {
balances[msg.sender] = SafeMath.sub(balances[msg.sender], _value);
balances[_to] = SafeMath.add(balances[_to], _value);
Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint _value) public returns (bool success) {
var _allowance = allowed[_from][msg.sender];
// Check is not needed because safeSub(_allowance, _value) will already throw if this condition is not met
// if (_value > _allowance) throw;
balances[_to] = SafeMath.add(balances[_to], _value);
balances[_from] = SafeMath.sub(balances[_from], _value);
allowed[_from][msg.sender] = SafeMath.sub(_allowance, _value);
Transfer(_from, _to, _value);
return true;
}
function balanceOf(address _owner) public view returns (uint balance) {
return balances[_owner];
}
function approve(address _spender, uint _value) public returns (bool success) {
// To change the approve amount you first have to reduce the addresses`
// allowance to zero by calling `approve(_spender, 0)` if it is not
// already 0 to mitigate the race condition described here:
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
if ((_value != 0) && (allowed[msg.sender][_spender] != 0)) revert();
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public view returns (uint remaining) {
return allowed[_owner][_spender];
}
}
// File: contracts/BurnableToken.sol
/**
* A trait that allows any token owner to decrease the token supply.
*
* We add a Burned event to differentiate from normal transfers.
* However, we still try to support some legacy Ethereum ecocsystem,
* as ERC-20 has not standardized on the burn event yet.
*
*/
contract BurnableToken is StandardToken {
address public constant BURN_ADDRESS = 0;
/** How many tokens we burned */
event Burned(address burner, uint burnedAmount);
/**
* Burn extra tokens from a balance.
*
*/
function burn(uint burnAmount) public {
address burner = msg.sender;
balances[burner] = SafeMath.sub(balances[burner], burnAmount);
totalSupply = SafeMath.sub(totalSupply, burnAmount);
Burned(burner, burnAmount);
// Keep token balance tracking services happy by sending the burned amount to
// "burn address", so that it will show up as a ERC-20 transaction
// in etherscan, etc. as there is no standarized burn event yet
Transfer(burner, BURN_ADDRESS, burnAmount);
}
}
// File: zeppelin-solidity/contracts/ownership/Ownable.sol
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
// File: contracts/Haltable.sol
/*
* Haltable
*
* Abstract contract that allows children to implement an
* emergency stop mechanism. Differs from Pausable by causing a throw
* instead of return when in halt mode.
*
*
* Originally envisioned in FirstBlood ICO contract.
*/
contract Haltable is Ownable {
bool public halted;
modifier stopInEmergency {
require (!halted);
_;
}
modifier onlyInEmergency {
require (halted);
_;
}
// called by the owner on emergency, triggers stopped state
function halt() external onlyOwner {
halted = true;
}
// called by the owner on end of emergency, returns to normal state
function unhalt() external onlyOwner onlyInEmergency {
halted = false;
}
}
// File: contracts/HaltableToken.sol
contract HaltableToken is StandardToken, Haltable {
function HaltableToken (address _owner) public {
owner = _owner;
}
function transfer(address _to, uint _value) stopInEmergency public returns (bool success) {
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint _value) stopInEmergency public returns (bool success) {
return super.transferFrom(_from, _to, _value);
}
function approve(address _spender, uint _value) stopInEmergency public returns (bool success) {
return super.approve(_spender, _value);
}
}
// File: contracts/UpgradeAgent.sol
/**
* Upgrade agent interface inspired by Lunyr.
*
* Upgrade agent transfers tokens to a new contract.
* Upgrade agent itself can be the token contract, or just a middle man contract doing the heavy lifting.
*/
contract UpgradeAgent {
uint public originalSupply;
/** Interface marker */
function isUpgradeAgent() public pure returns (bool) {
return true;
}
function upgradeFrom(address _from, uint256 _value) public;
}
// File: contracts/UpgradeableToken.sol
/**
* A token upgrade mechanism where users can opt-in amount of tokens to the next smart contract revision.
*
* First envisioned by Golem and Lunyr projects.
*/
contract UpgradeableToken is StandardToken {
/** Contract / person who can set the upgrade path. This can be the same as team multisig wallet, as what it is with its default value. */
address public upgradeMaster;
/** The next contract where the tokens will be migrated. */
UpgradeAgent public upgradeAgent;
/** How many tokens we have upgraded by now. */
uint256 public totalUpgraded;
/**
* Upgrade states.
*
* - NotAllowed: The child contract has not reached a condition where the upgrade can bgun
* - WaitingForAgent: Token allows upgrade, but we don't have a new agent yet
* - ReadyToUpgrade: The agent is set, but not a single token has been upgraded yet
* - Upgrading: Upgrade agent is set and the balance holders can upgrade their tokens
*
*/
enum UpgradeState {Unknown, NotAllowed, WaitingForAgent, ReadyToUpgrade, Upgrading}
/**
* Somebody has upgraded some of his tokens.
*/
event Upgrade(address indexed _from, address indexed _to, uint256 _value);
/**
* New upgrade agent available.
*/
event UpgradeAgentSet(address agent);
/**
* Do not allow construction without upgrade master set.
*/
function UpgradeableToken(address _upgradeMaster) public {
upgradeMaster = _upgradeMaster;
}
/**
* Allow the token holder to upgrade some of their tokens to a new contract.
*/
function upgrade(uint256 value) public {
UpgradeState state = getUpgradeState();
if (!(state == UpgradeState.ReadyToUpgrade || state == UpgradeState.Upgrading)) {
// Called in a bad state
revert();
}
// Validate input value.
if (value == 0) revert();
balances[msg.sender] = SafeMath.sub(balances[msg.sender], value);
// Take tokens out from circulation
totalSupply = SafeMath.sub(totalSupply, value);
totalUpgraded = SafeMath.add(totalUpgraded, value);
// Upgrade agent reissues the tokens
upgradeAgent.upgradeFrom(msg.sender, value);
Upgrade(msg.sender, upgradeAgent, value);
}
/**
* Set an upgrade agent that handles
*/
function setUpgradeAgent(address agent) external {
if (!canUpgrade()) {
// The token is not yet in a state that we could think upgrading
revert();
}
if (agent == 0x0) revert();
// Only a master can designate the next agent
if (msg.sender != upgradeMaster) revert();
// Upgrade has already begun for an agent
if (getUpgradeState() == UpgradeState.Upgrading) revert();
upgradeAgent = UpgradeAgent(agent);
// Bad interface
if(!upgradeAgent.isUpgradeAgent()) revert();
// Make sure that token supplies match in source and target
if (upgradeAgent.originalSupply() != totalSupply) revert();
UpgradeAgentSet(upgradeAgent);
}
/**
* Get the state of the token upgrade.
*/
function getUpgradeState() public constant returns(UpgradeState) {
if(!canUpgrade()) return UpgradeState.NotAllowed;
else if(address(upgradeAgent) == 0x00) return UpgradeState.WaitingForAgent;
else if(totalUpgraded == 0) return UpgradeState.ReadyToUpgrade;
else return UpgradeState.Upgrading;
}
/**
* Change the upgrade master.
*
* This allows us to set a new owner for the upgrade mechanism.
*/
function setUpgradeMaster(address master) public {
require (master != 0x0);
require (msg.sender == upgradeMaster);
upgradeMaster = master;
}
/**
* Child contract can enable to provide the condition when the upgrade can begun.
*/
function canUpgrade() public pure returns(bool) {
return true;
}
}
// File: contracts/CentrallyIssuedToken.sol
/**
* Centrally issued Ethereum token.
*
* We mix in burnable and upgradeable traits.
*
* Token supply is created in the token contract creation and allocated to owner.
* The owner can then transfer from its supply to crowdsale participants.
* The owner, or anybody, can burn any excessive tokens they are holding.
*
*/
contract CentrallyIssuedToken is BurnableToken, UpgradeableToken, HaltableToken {
string public name;
string public symbol;
uint public decimals;
function CentrallyIssuedToken(address _owner, string _name, string _symbol, uint _totalSupply, uint _decimals) public HaltableToken(_owner) UpgradeableToken(_owner) {
name = _name;
symbol = _symbol;
totalSupply = _totalSupply;
decimals = _decimals;
// Allocate initial balance to the owner
balances[_owner] = _totalSupply;
// Transfer(0, _owner, _totalSupply);
}
}
| * Centrally issued Ethereum token. We mix in burnable and upgradeable traits. Token supply is created in the token contract creation and allocated to owner. The owner can then transfer from its supply to crowdsale participants. The owner, or anybody, can burn any excessive tokens they are holding./ | contract CentrallyIssuedToken is BurnableToken, UpgradeableToken, HaltableToken {
string public name;
string public symbol;
uint public decimals;
function CentrallyIssuedToken(address _owner, string _name, string _symbol, uint _totalSupply, uint _decimals) public HaltableToken(_owner) UpgradeableToken(_owner) {
name = _name;
symbol = _symbol;
totalSupply = _totalSupply;
decimals = _decimals;
balances[_owner] = _totalSupply;
}
}
| 15,795,602 | [
1,
39,
8230,
1230,
16865,
512,
18664,
379,
1147,
18,
1660,
6843,
316,
18305,
429,
471,
8400,
429,
18370,
18,
3155,
14467,
353,
2522,
316,
326,
1147,
6835,
6710,
471,
11977,
358,
3410,
18,
1021,
3410,
848,
1508,
7412,
628,
2097,
14467,
358,
276,
492,
2377,
5349,
22346,
18,
1021,
3410,
16,
578,
1281,
3432,
16,
848,
18305,
1281,
23183,
688,
2430,
2898,
854,
19918,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
385,
8230,
1230,
7568,
5957,
1345,
353,
605,
321,
429,
1345,
16,
17699,
429,
1345,
16,
670,
287,
2121,
1345,
288,
203,
203,
225,
533,
1071,
508,
31,
203,
225,
533,
1071,
3273,
31,
203,
225,
2254,
1071,
15105,
31,
203,
203,
203,
225,
445,
385,
8230,
1230,
7568,
5957,
1345,
12,
2867,
389,
8443,
16,
533,
389,
529,
16,
533,
389,
7175,
16,
2254,
389,
4963,
3088,
1283,
16,
2254,
389,
31734,
13,
1071,
670,
287,
2121,
1345,
24899,
8443,
13,
17699,
429,
1345,
24899,
8443,
13,
288,
203,
565,
508,
273,
389,
529,
31,
203,
565,
3273,
273,
389,
7175,
31,
203,
565,
2078,
3088,
1283,
273,
389,
4963,
3088,
1283,
31,
203,
565,
15105,
273,
389,
31734,
31,
203,
203,
565,
324,
26488,
63,
67,
8443,
65,
273,
389,
4963,
3088,
1283,
31,
203,
225,
289,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
import '@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol';
import '@openzeppelin/contracts/utils/math/Math.sol';
import '@openzeppelin/contracts/access/Ownable.sol';
import './Readable.sol';
contract RidottoVesting is Ownable, Readable {
using SafeERC20 for IERC20;
IERC20 immutable public RDT;
uint128 constant public HUNDRED_PERCENT = 1000;
uint32 public TGEdate = 1632846600; // Tuesday, 28 September 2021 16:30:00
bool public paused;
uint constant LOCK_TYPES = 9;
enum LockType {
Private,
IDO,
Team,
Rewards,
Marketing,
Advisor,
Ecosystem,
BugBounty,
Reserve
}
struct LockConfig {
uint32 releasedAtStart;
uint32 cliff;
uint32 duration;
uint32 period;
}
struct Lock {
uint128 balance;
uint128 claimed;
}
struct DB {
mapping(LockType => LockConfig) config;
mapping(address => Lock[LOCK_TYPES]) locks;
}
DB internal db;
constructor(IERC20 rdt, address newOwner) {
RDT = rdt;
db.config[LockType.Private] = LockConfig(25, 3 * months, 9 * months, 3 * months);
db.config[LockType.IDO] = LockConfig(330, 1 * month, 3 * months, 1);
db.config[LockType.Team] = LockConfig(0, 6 * months, 18 * months, 1);
db.config[LockType.Rewards] = LockConfig(35, 1 * month, 12 * months, 1);
db.config[LockType.Marketing] = LockConfig(0, 1 * month, 6 * months, 1);
db.config[LockType.Advisor] = LockConfig(0, 6 * months, 18 * months, 1);
db.config[LockType.Ecosystem] = LockConfig(0, 5 * month, 18 * months, 1);
db.config[LockType.BugBounty] = LockConfig(0, 6 * month, 36 * months, 1);
db.config[LockType.Reserve] = LockConfig(0, 1 * month, 12 * months, 1);
transferOwnership(newOwner);
}
function getUserInfo(address who) external view returns(Lock[9] memory) {
return db.locks[who];
}
function calcualteReleased(uint128 amount, uint32 releaseStart, LockConfig memory config)
private view returns(uint128) {
// Assumes that releaseStart already reached.
uint128 atStart = amount * uint128(config.releasedAtStart) / HUNDRED_PERCENT;
if (not(reached(releaseStart + config.cliff))) {
return atStart;
}
uint128 period = config.period;
uint128 periods = uint128(since(releaseStart)) / period;
uint128 released = atStart + ((amount - atStart) * periods * period / config.duration);
return uint128(Math.min(amount, released));
}
function calcualteClaimable(uint128 released, uint128 claimed) private pure returns(uint128) {
if (released < claimed) {
return 0;
}
return released - claimed;
}
function availableToClaim(address who) public view returns(uint128) {
uint32 releaseStart = TGEdate;
if (not(reached(releaseStart))) {
return 0;
}
Lock[LOCK_TYPES] memory userLocks = db.locks[who];
uint128 claimable = 0;
for (uint8 i = 0; i < LOCK_TYPES; i++) {
claimable += calcualteClaimable(
calcualteReleased(userLocks[i].balance, releaseStart, db.config[LockType(i)]),
userLocks[i].claimed
);
}
return claimable;
}
function balanceOf(address who) external view returns(uint) {
Lock[LOCK_TYPES] memory userLocks = db.locks[who];
uint128 balances = 0;
uint128 claimed = 0;
for (uint8 i = 0; i < LOCK_TYPES; i++) {
balances += userLocks[i].balance;
claimed += userLocks[i].claimed;
}
if (claimed > balances) {
return 0;
}
return balances - claimed;
}
function assign(LockType[] calldata lockTypes, address[] calldata tos, uint128[] calldata amounts)
external onlyOwner {
uint len = lockTypes.length;
require(len == tos.length, 'Invalid tos input');
require(len == amounts.length, 'Invalid amounts input');
for (uint i = 0; i < len; i++) {
LockType lockType = lockTypes[i];
address to = tos[i];
uint128 amount = amounts[i];
db.locks[to][uint8(lockType)].balance += amount;
emit LockAssigned(to, amount, lockType);
}
}
function revoke(LockType[] calldata lockTypes, address[] calldata whos)
external onlyOwner {
uint len = lockTypes.length;
require(len == whos.length, 'Invalid input');
for (uint i = 0; i < len; i++) {
LockType lockType = lockTypes[i];
address who = whos[i];
Lock memory lock = db.locks[who][uint8(lockType)];
uint128 amount = lock.balance - uint128(Math.min(lock.balance, lock.claimed));
delete db.locks[who][uint8(lockType)];
emit LockRevoked(who, amount, lockType);
}
}
function setTGEdate(uint32 timestamp) external onlyOwner {
TGEdate = timestamp;
emit TGEdateSet(timestamp);
}
function pause() external onlyOwner {
paused = true;
emit Paused();
}
function unpause() external onlyOwner {
paused = false;
emit Unpaused();
}
function claim() external {
require(not(paused), 'Paused');
uint32 releaseStart = TGEdate;
require(reached(releaseStart), 'Release not started');
Lock[LOCK_TYPES] memory userLocks = db.locks[msg.sender];
uint128 claimableSum = 0;
for (uint8 i = 0; i < LOCK_TYPES; i++) {
uint128 claimable = calcualteClaimable(
calcualteReleased(userLocks[i].balance, releaseStart, db.config[LockType(i)]),
userLocks[i].claimed
);
if (claimable == 0) {
continue;
}
db.locks[msg.sender][i].claimed = userLocks[i].claimed + claimable;
claimableSum += claimable;
emit Claimed(msg.sender, claimable, LockType(i));
}
require(claimableSum > 0, 'Nothing to claim');
RDT.safeTransfer(msg.sender, claimableSum);
}
function recover(IERC20 token, address to, uint amount) external onlyOwner {
token.safeTransfer(to, amount);
emit Recovered(token, to, amount);
}
event TGEdateSet(uint timestamp);
event LockAssigned(address user, uint amount, LockType lockType);
event LockRevoked(address user, uint amount, LockType lockType);
event Claimed(address user, uint amount, LockType lockType);
event Paused();
event Unpaused();
event Recovered(IERC20 token, address to, uint amount);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds up instead
* of rounding down.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b - 1) / b can overflow on addition, so we distribute.
return a / b + (a % b == 0 ? 0 : 1);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
contract Readable {
uint32 constant month = 30 days;
uint32 constant months = month;
function since(uint _timestamp) internal view returns(uint) {
if (not(passed(_timestamp))) {
return 0;
}
return block.timestamp - _timestamp;
}
function till(uint _timestamp) internal view returns(uint) {
if (passed(_timestamp)) {
return 0;
}
return _timestamp - block.timestamp;
}
function passed(uint _timestamp) internal view returns(bool) {
return _timestamp < block.timestamp;
}
function reached(uint _timestamp) internal view returns(bool) {
return _timestamp <= block.timestamp;
}
function not(bool _condition) internal pure returns(bool) {
return !_condition;
}
}
library ExtraMath {
function toUInt32(uint _a) internal pure returns(uint32) {
require(_a <= type(uint32).max, 'uint32 overflow');
return uint32(_a);
}
function toUInt88(uint _a) internal pure returns(uint88) {
require(_a <= type(uint88).max, 'uint88 overflow');
return uint88(_a);
}
function toUInt128(uint _a) internal pure returns(uint128) {
require(_a <= type(uint128).max, 'uint128 overflow');
return uint128(_a);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
| Tuesday, 28 September 2021 16:30:00
| uint32 public TGEdate = 1632846600; | 1,409,215 | [
1,
56,
3610,
2881,
16,
9131,
3265,
337,
2558,
26599,
21,
2872,
30,
5082,
30,
713,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
2254,
1578,
1071,
399,
7113,
712,
273,
2872,
1578,
5193,
6028,
713,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.10;
import {ICollectNFT} from '../interfaces/ICollectNFT.sol';
import {ILensHub} from '../interfaces/ILensHub.sol';
import {Errors} from '../libraries/Errors.sol';
import {Events} from '../libraries/Events.sol';
import {LensNFTBase} from './base/LensNFTBase.sol';
/**
* @title CollectNFT
* @author Lens Protocol
*
* @notice This is the NFT contract that is minted upon collecting a given publication. It is cloned upon
* the first collect for a given publication, and the token URI points to the original publication's contentURI.
*/
contract CollectNFT is LensNFTBase, ICollectNFT {
address public immutable HUB;
uint256 internal _profileId;
uint256 internal _pubId;
uint256 internal _tokenIdCounter;
bool private _initialized;
// We create the CollectNFT with the pre-computed HUB address before deploying the hub proxy in order
// to initialize the hub proxy at construction.
constructor(address hub) {
if (hub == address(0)) revert Errors.InitParamsInvalid();
HUB = hub;
_initialized = true;
}
/// @inheritdoc ICollectNFT
function initialize(
uint256 profileId,
uint256 pubId,
string calldata name,
string calldata symbol
) external override {
if (_initialized) revert Errors.Initialized();
_initialized = true;
_profileId = profileId;
_pubId = pubId;
super._initialize(name, symbol);
emit Events.CollectNFTInitialized(profileId, pubId, block.timestamp);
}
/// @inheritdoc ICollectNFT
function mint(address to) external override returns (uint256) {
if (msg.sender != HUB) revert Errors.NotHub();
unchecked {
uint256 tokenId = ++_tokenIdCounter;
_mint(to, tokenId);
return tokenId;
}
}
/// @inheritdoc ICollectNFT
function getSourcePublicationPointer() external view override returns (uint256, uint256) {
return (_profileId, _pubId);
}
function tokenURI(uint256 tokenId) public view override returns (string memory) {
if (!_exists(tokenId)) revert Errors.TokenDoesNotExist();
return ILensHub(HUB).getContentURI(_profileId, _pubId);
}
/**
* @dev Upon transfers, we emit the transfer event in the hub.
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal override {
super._beforeTokenTransfer(from, to, tokenId);
ILensHub(HUB).emitCollectNFTTransferEvent(_profileId, _pubId, tokenId, from, to);
}
}
| * @dev Upon transfers, we emit the transfer event in the hub./ | function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal override {
super._beforeTokenTransfer(from, to, tokenId);
ILensHub(HUB).emitCollectNFTTransferEvent(_profileId, _pubId, tokenId, from, to);
}
| 5,436,295 | [
1,
57,
500,
29375,
16,
732,
3626,
326,
7412,
871,
316,
326,
11891,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
389,
5771,
1345,
5912,
12,
203,
3639,
1758,
628,
16,
203,
3639,
1758,
358,
16,
203,
3639,
2254,
5034,
1147,
548,
203,
565,
262,
2713,
3849,
288,
203,
3639,
2240,
6315,
5771,
1345,
5912,
12,
2080,
16,
358,
16,
1147,
548,
1769,
203,
3639,
467,
48,
773,
8182,
12,
44,
3457,
2934,
18356,
10808,
50,
4464,
5912,
1133,
24899,
5040,
548,
16,
389,
10174,
548,
16,
1147,
548,
16,
628,
16,
358,
1769,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/137/0x64864ab26D530CE268c5EEE5f064F3397a0ADfFC/sources/Magnetar.sol | tax on total amount for liquidity for next prediction and burn
| uint256 tax = _rewardBalance[id] - rewardAmount; | 3,529,632 | [
1,
8066,
603,
2078,
3844,
364,
4501,
372,
24237,
364,
1024,
8239,
471,
18305,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
2254,
5034,
5320,
273,
389,
266,
2913,
13937,
63,
350,
65,
300,
19890,
6275,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.8.1;
contract Token{
address Owner;
string public tokenName = "Akash";
string public symbol = "Ak";
uint public decimals = 18;
uint public totalSupply = 2100000;
mapping(address => uint)public balanceOf;
mapping(address => mapping(address =>uint))public allowance;
//The Transfer Function Is Used To Transfer The Token From Msg Sender Account to Another Account.....
constructor() {
Owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
}
function transfer(address _to , uint _amount)public returns(bool success){
require(balanceOf[msg.sender] >= _amount ,"The Token Balance Is Less Then The _amount");
balanceOf[msg.sender] = balanceOf[msg.sender] - _amount;
balanceOf[_to] = balanceOf[_to] + _amount;
return true;
}
function fromTransfer(address _from , address _to ,uint _amount)public returns(bool success){
require(balanceOf[_from]>=_amount,"The Balance In From Account Is less Then The Amount");
balanceOf[_from ] = balanceOf[_from] - _amount;
balanceOf[_to] = balanceOf[_to] + _amount;
}
//Give The Number Of The Approvance From The Account to spender Account....
function approve(address _spender , uint _amount)public returns(bool success){
//require(allowance[msg.sender][_spender] > _amount,"The Amount Of Token Is Less The The _amount");
allowance[msg.sender][_spender] = _amount;
return true;
}
} | The Transfer Function Is Used To Transfer The Token From Msg Sender Account to Another Account..... | contract Token{
address Owner;
string public tokenName = "Akash";
string public symbol = "Ak";
uint public decimals = 18;
uint public totalSupply = 2100000;
mapping(address => uint)public balanceOf;
mapping(address => mapping(address =>uint))public allowance;
constructor() {
Owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
}
function transfer(address _to , uint _amount)public returns(bool success){
require(balanceOf[msg.sender] >= _amount ,"The Token Balance Is Less Then The _amount");
balanceOf[msg.sender] = balanceOf[msg.sender] - _amount;
balanceOf[_to] = balanceOf[_to] + _amount;
return true;
}
function fromTransfer(address _from , address _to ,uint _amount)public returns(bool success){
require(balanceOf[_from]>=_amount,"The Balance In From Account Is less Then The Amount");
balanceOf[_from ] = balanceOf[_from] - _amount;
balanceOf[_to] = balanceOf[_to] + _amount;
}
function approve(address _spender , uint _amount)public returns(bool success){
allowance[msg.sender][_spender] = _amount;
return true;
}
} | 13,106,305 | [
1,
1986,
12279,
4284,
2585,
10286,
2974,
12279,
1021,
3155,
6338,
8671,
15044,
6590,
358,
432,
24413,
6590,
838,
2777,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
3155,
95,
203,
203,
565,
1758,
16837,
31,
203,
565,
533,
1071,
1147,
461,
273,
315,
37,
79,
961,
14432,
203,
565,
533,
1071,
3273,
273,
315,
37,
79,
14432,
203,
565,
2254,
1071,
15105,
273,
6549,
31,
203,
565,
2254,
1071,
2078,
3088,
1283,
273,
9035,
11706,
31,
203,
203,
565,
2874,
12,
2867,
516,
2254,
13,
482,
11013,
951,
31,
203,
565,
2874,
12,
2867,
516,
2874,
12,
2867,
516,
11890,
3719,
482,
1699,
1359,
31,
203,
565,
3885,
1435,
288,
203,
3639,
16837,
273,
1234,
18,
15330,
31,
203,
3639,
11013,
951,
63,
3576,
18,
15330,
65,
273,
2078,
3088,
1283,
31,
203,
565,
289,
203,
565,
445,
7412,
12,
2867,
389,
869,
269,
2254,
389,
8949,
13,
482,
1135,
12,
6430,
2216,
15329,
203,
3639,
2583,
12,
12296,
951,
63,
3576,
18,
15330,
65,
1545,
389,
8949,
269,
6,
1986,
3155,
30918,
2585,
17304,
9697,
1021,
389,
8949,
8863,
203,
3639,
11013,
951,
63,
3576,
18,
15330,
65,
273,
11013,
951,
63,
3576,
18,
15330,
65,
300,
389,
8949,
31,
203,
3639,
11013,
951,
63,
67,
869,
65,
273,
11013,
951,
63,
67,
869,
65,
397,
389,
8949,
31,
203,
3639,
327,
638,
31,
203,
565,
289,
203,
565,
445,
628,
5912,
12,
2867,
389,
2080,
269,
1758,
389,
869,
269,
11890,
389,
8949,
13,
482,
1135,
12,
6430,
2216,
15329,
203,
3639,
2583,
12,
12296,
951,
63,
67,
2080,
65,
34,
33,
67,
8949,
10837,
1986,
30918,
657,
6338,
6590,
2585,
5242,
9697,
1021,
16811,
8863,
203,
3639,
2
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/Math.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/utils/EnumerableSet.sol";
import "./libraries/DecimalsConverter.sol";
import "./interfaces/IContractsRegistry.sol";
import "./interfaces/IPolicyBookFacade.sol";
import "./interfaces/IPolicyBook.sol";
import "./interfaces/IPolicyBookRegistry.sol";
import "./interfaces/IShieldMining.sol";
import "./interfaces/IUserLeveragePool.sol";
import "./interfaces/ILeveragePortfolioView.sol";
import "./interfaces/ILeveragePortfolio.sol";
import "./abstract/AbstractDependant.sol";
import "./Globals.sol";
contract ShieldMining is IShieldMining, OwnableUpgradeable, ReentrancyGuard, AbstractDependant {
using SafeMath for uint256;
using SafeERC20 for IERC20;
using Address for address;
using EnumerableSet for EnumerableSet.UintSet;
using Counters for Counters.Counter;
using Math for uint256;
address public policyBookFabric;
IPolicyBookRegistry public policyBookRegistry;
mapping(address => ShieldMiningInfo) public shieldMiningInfo;
mapping(address => mapping(address => uint256)) public userRewardPerTokenPaid;
mapping(address => mapping(address => uint256)) internal _rewards;
/// @dev block number to reward per block (to substrate) //deprecated
mapping(address => mapping(uint256 => uint256)) public endOfRewards;
// new state post v2
Counters.Counter public lastDepositId;
mapping(address => EnumerableSet.UintSet) private _usersDepositsId;
mapping(uint256 => ShieldMiningDeposit) public usersDeposits;
ILeveragePortfolioView public leveragePortfolioView;
mapping(address => EnumerableSet.UintSet) internal lastBlockWithRewardList;
mapping(address => uint256) public userleveragepoolsParticipatedAmounts;
address public bmiCoverStakingAddress;
mapping(address => uint256) public userleveragepoolsTotalSupply;
event ShieldMiningAssociated(address indexed policyBook, address indexed shieldToken);
event ShieldMiningFilled(
address indexed policyBook,
address indexed shieldToken,
address indexed depositor,
uint256 amount,
uint256 lastBlockWithReward
);
event ShieldMiningClaimed(address indexed user, address indexed policyBook, uint256 reward);
event ShieldMiningRecovered(address indexed policyBook, uint256 amount);
modifier shieldMiningEnabled(address _policyBook) {
require(
address(shieldMiningInfo[_policyBook].rewardsToken) != address(0),
"SM: no shield mining associated"
);
_;
}
modifier updateReward(
address _policyBook,
address _userLeveragePool,
address account
) {
_updateReward(_policyBook, _userLeveragePool, account);
_;
}
modifier onlyBMICoverStaking() {
require(
bmiCoverStakingAddress == _msgSender(),
"SM: Caller is not BMICoverStaking contract"
);
_;
}
function __ShieldMining_init() external initializer {
__Ownable_init();
}
function setDependencies(IContractsRegistry _contractsRegistry)
external
override
onlyInjectorOrZero
{
policyBookRegistry = IPolicyBookRegistry(
_contractsRegistry.getPolicyBookRegistryContract()
);
policyBookFabric = _contractsRegistry.getPolicyBookFabricContract();
leveragePortfolioView = ILeveragePortfolioView(
_contractsRegistry.getLeveragePortfolioViewContract()
);
bmiCoverStakingAddress = _contractsRegistry.getBMICoverStakingContract();
}
function blocksWithRewardsPassed(address _policyBook) public view override returns (uint256) {
uint256 from = shieldMiningInfo[_policyBook].lastUpdateBlock;
uint256 to =
Math.min(block.number, shieldMiningInfo[_policyBook].nearestLastBlocksWithReward);
return from >= to ? 0 : to.sub(from);
}
function rewardPerToken(address _policyBook) public view override returns (uint256) {
uint256 totalPoolStaked = shieldMiningInfo[_policyBook].totalSupply;
if (totalPoolStaked == 0) {
return shieldMiningInfo[_policyBook].rewardPerTokenStored;
}
uint256 accumulatedReward =
blocksWithRewardsPassed(_policyBook)
.mul(getCurrentRewardPerBlock(_policyBook))
.mul(DECIMALS18)
.div(totalPoolStaked);
return shieldMiningInfo[_policyBook].rewardPerTokenStored.add(accumulatedReward);
}
function earned(
address _policyBook,
address _userLeveragePool,
address _account
) public view override returns (uint256) {
address _userPool = _userLeveragePool != address(0) ? _userLeveragePool : _policyBook;
uint256 rewardsDifference =
rewardPerToken(_policyBook).sub(userRewardPerTokenPaid[_account][_userPool]);
uint256 userLiquidity;
if (_userLeveragePool == address(0)) {
userLiquidity = IPolicyBookFacade(IPolicyBook(_policyBook).policyBookFacade())
.userLiquidity(_account);
} else {
userLiquidity = IUserLeveragePool(_userLeveragePool).userLiquidity(_account);
uint256 totalSupply = userleveragepoolsTotalSupply[_userLeveragePool];
if (totalSupply > 0) {
userLiquidity = userLiquidity
.mul(userleveragepoolsParticipatedAmounts[_userLeveragePool])
.div(totalSupply);
}
}
uint256 newlyAccumulated = userLiquidity.mul(rewardsDifference).div(DECIMALS18);
return _rewards[_account][_userPool].add(newlyAccumulated);
}
function updateTotalSupply(
address _policyBook,
address _userLeveragePool,
address _liquidityProvider
) external override updateReward(_policyBook, _userLeveragePool, _liquidityProvider) {
require(
policyBookRegistry.isPolicyBookFacade(_msgSender()) ||
policyBookRegistry.isPolicyBook(_policyBook),
"SM: No access"
);
uint256 _participatedLeverageAmounts;
IPolicyBook _coveragePool = IPolicyBook(_policyBook);
IPolicyBookFacade _policyFacade = IPolicyBookFacade(_coveragePool.policyBookFacade());
uint256 _userLeveragePoolsCount = _policyFacade.countUserLeveragePools();
if (_userLeveragePoolsCount > 0) {
address[] memory _userLeverageArr =
_policyFacade.listUserLeveragePools(0, _userLeveragePoolsCount);
uint256 _participatedLeverageAmount;
for (uint256 i = 0; i < _userLeverageArr.length; i++) {
_participatedLeverageAmount = clacParticipatedLeverageAmount(
_userLeverageArr[i],
_coveragePool
);
userleveragepoolsParticipatedAmounts[
_userLeverageArr[i]
] = _participatedLeverageAmount;
_participatedLeverageAmounts = _participatedLeverageAmounts.add(
_participatedLeverageAmount
);
userleveragepoolsTotalSupply[_userLeverageArr[i]] = IERC20(_userLeverageArr[i])
.totalSupply();
}
}
shieldMiningInfo[_policyBook].totalSupply = _participatedLeverageAmounts.add(
IERC20(_policyBook).totalSupply()
);
}
function clacParticipatedLeverageAmount(address _userLeveragePool, IPolicyBook _coveragePool)
internal
view
returns (uint256)
{
IPolicyBookFacade _policyFacade = IPolicyBookFacade(_coveragePool.policyBookFacade());
uint256 _poolUtilizationRation;
uint256 _coverageLiq = _coveragePool.totalLiquidity();
if (_coverageLiq > 0) {
_poolUtilizationRation = _coveragePool.totalCoverTokens().mul(PERCENTAGE_100).div(
_coverageLiq
);
}
return
_policyFacade
.LUuserLeveragePool(_userLeveragePool)
.mul(leveragePortfolioView.calcM(_poolUtilizationRation, _userLeveragePool))
.div(PERCENTAGE_100);
}
function associateShieldMining(address _policyBook, address _shieldMiningToken)
external
override
{
require(_msgSender() == policyBookFabric || _msgSender() == owner(), "SM: no access");
require(policyBookRegistry.isPolicyBook(_policyBook), "SM: Not a PolicyBook");
// should revert with "Address: not a contract" if it's an account
_shieldMiningToken.functionCall(
abi.encodeWithSignature("totalSupply()", ""),
"SM: is not an ERC20"
);
delete shieldMiningInfo[_policyBook];
shieldMiningInfo[_policyBook].totalSupply = IERC20(_policyBook).totalSupply();
shieldMiningInfo[_policyBook].rewardsToken = IERC20(_shieldMiningToken);
shieldMiningInfo[_policyBook].decimals = ERC20(_shieldMiningToken).decimals();
emit ShieldMiningAssociated(_policyBook, _shieldMiningToken);
}
///@dev amount should be in decimal18
function fillShieldMining(
address _policyBook,
uint256 _amount,
uint256 _duration
) external override shieldMiningEnabled(_policyBook) {
require(_duration >= 22 && _duration <= 366, "SM: out of minimum/maximum duration");
uint256 _tokenDecimals = shieldMiningInfo[_policyBook].decimals;
uint256 tokenLiquidity = DecimalsConverter.convertFrom18(_amount, _tokenDecimals);
require(tokenLiquidity > 0, "SM: amount is zero");
uint256 _blocksAmount = _duration.mul(BLOCKS_PER_DAY).sub(1);
uint256 _rewardPerBlock = _amount.div(_blocksAmount);
shieldMiningInfo[_policyBook].rewardsToken.safeTransferFrom(
_msgSender(),
address(this),
tokenLiquidity
);
shieldMiningInfo[_policyBook].rewardTokensLocked = shieldMiningInfo[_policyBook]
.rewardTokensLocked
.add(_amount);
uint256 _lastBlockWithReward =
_setRewards(_policyBook, _rewardPerBlock, block.number, _blocksAmount);
lastDepositId.increment();
_usersDepositsId[_msgSender()].add(lastDepositId.current());
usersDeposits[lastDepositId.current()] = ShieldMiningDeposit(
_policyBook,
_amount,
_duration,
_rewardPerBlock,
block.number,
_lastBlockWithReward
);
emit ShieldMiningFilled(
_policyBook,
address(shieldMiningInfo[_policyBook].rewardsToken),
_msgSender(),
_amount,
shieldMiningInfo[_policyBook].lastBlockWithReward
);
}
function getRewardFor(
address _user,
address _policyBook,
address _userLeveragePool
)
public
override
nonReentrant
updateReward(_policyBook, _userLeveragePool, _user)
onlyBMICoverStaking
{
_getReward(_user, _policyBook, _userLeveragePool);
}
function getRewardFor(address _user, address _userLeveragePool)
public
override
nonReentrant
onlyBMICoverStaking
{
_getRewardFromLeverage(_user, _userLeveragePool, true);
}
function getReward(address _policyBook, address _userLeveragePool)
public
override
nonReentrant
updateReward(_policyBook, _userLeveragePool, _msgSender())
{
_getReward(_msgSender(), _policyBook, _userLeveragePool);
}
function getReward(address _userLeveragePool) public override nonReentrant {
_getRewardFromLeverage(_msgSender(), _userLeveragePool, false);
}
function _getRewardFromLeverage(
address _user,
address _userLeveragePool,
bool isRewardFor
) internal {
ILeveragePortfolio userLeveragePool = ILeveragePortfolio(_userLeveragePool);
address[] memory _coveragePools =
userLeveragePool.listleveragedCoveragePools(
0,
userLeveragePool.countleveragedCoveragePools()
);
for (uint256 i = 0; i < _coveragePools.length; i++) {
if (getShieldTokenAddress(_coveragePools[i]) != address(0)) {
if (isRewardFor) {
getRewardFor(_user, _coveragePools[i], _userLeveragePool);
} else {
getReward(_coveragePools[i], _userLeveragePool);
}
}
}
}
function _getReward(
address _user,
address _policyBook,
address _userLeveragePool
) internal {
address _userPool = _userLeveragePool != address(0) ? _userLeveragePool : _policyBook;
uint256 reward = _rewards[_user][_userPool];
if (reward > 0) {
delete _rewards[_user][_userPool];
uint256 _tokenDecimals = shieldMiningInfo[_policyBook].decimals;
// transfer profit to the user
shieldMiningInfo[_policyBook].rewardsToken.safeTransfer(
_user,
DecimalsConverter.convertFrom18(reward, _tokenDecimals)
);
shieldMiningInfo[_policyBook].rewardTokensLocked = shieldMiningInfo[_policyBook]
.rewardTokensLocked
.sub(reward);
emit ShieldMiningClaimed(_user, _policyBook, reward);
}
}
function recoverNonLockedRewardTokens(address _policyBook) public onlyOwner {
uint256 _tokenDecimals = shieldMiningInfo[_policyBook].decimals;
uint256 _futureRewardTokens = _getFutureRewardTokens(_policyBook);
uint256 tokenBalance =
DecimalsConverter.convertTo18(
shieldMiningInfo[_policyBook].rewardsToken.balanceOf(address(this)),
_tokenDecimals
);
if (tokenBalance > _futureRewardTokens) {
uint256 nonLockedTokens = tokenBalance.sub(_futureRewardTokens);
shieldMiningInfo[_policyBook].rewardsToken.safeTransfer(
owner(),
DecimalsConverter.convertFrom18(nonLockedTokens, _tokenDecimals)
);
emit ShieldMiningRecovered(_policyBook, nonLockedTokens);
}
}
function getShieldTokenAddress(address _policyBook) public view override returns (address) {
return address(shieldMiningInfo[_policyBook].rewardsToken);
}
function getShieldMiningInfo(address _policyBook)
external
view
override
returns (
address _rewardsToken,
uint256 _decimals,
uint256 _firstBlockWithReward,
uint256 _lastBlockWithReward,
uint256 _lastUpdateBlock,
uint256 _nearestLastBlocksWithReward,
uint256 _rewardTokensLocked,
uint256 _rewardPerTokenStored,
uint256 _rewardPerBlock,
uint256 _tokenPerDay,
uint256 _totalSupply
)
{
_rewardsToken = address(shieldMiningInfo[_policyBook].rewardsToken);
_decimals = shieldMiningInfo[_policyBook].decimals;
_firstBlockWithReward = shieldMiningInfo[_policyBook].firstBlockWithReward;
_lastBlockWithReward = shieldMiningInfo[_policyBook].lastBlockWithReward;
_lastUpdateBlock = shieldMiningInfo[_policyBook].lastUpdateBlock;
_nearestLastBlocksWithReward = shieldMiningInfo[_policyBook].nearestLastBlocksWithReward;
_rewardPerTokenStored = shieldMiningInfo[_policyBook].rewardPerTokenStored;
_rewardPerBlock = getCurrentRewardPerBlock(_policyBook);
_tokenPerDay = _rewardPerBlock.mul(BLOCKS_PER_DAY);
_totalSupply = shieldMiningInfo[_policyBook].totalSupply;
_rewardTokensLocked = shieldMiningInfo[_policyBook].rewardTokensLocked;
}
function getDepositList(
address _account,
uint256 _offset,
uint256 _limit
) external view override returns (ShieldMiningDeposit[] memory _depositsList) {
uint256 nbOfDeposit = _usersDepositsId[_account].length();
uint256 to = (_offset.add(_limit)).min(nbOfDeposit).max(_offset);
uint256 size = to.sub(_offset);
_depositsList = new ShieldMiningDeposit[](size);
for (uint256 i = _offset; i < to; i++) {
ShieldMiningDeposit memory smd = usersDeposits[_usersDepositsId[_account].at(i)];
_depositsList[i].policyBook = smd.policyBook;
_depositsList[i].amount = smd.amount;
_depositsList[i].duration = smd.duration;
_depositsList[i].depositRewardPerBlock = smd.depositRewardPerBlock;
_depositsList[i].startBlock = smd.startBlock;
_depositsList[i].endBlock = smd.endBlock;
}
}
/// @notice get count of user deposits
function countUsersDeposits(address _account) external view override returns (uint256) {
return _usersDepositsId[_account].length();
}
function _setRewards(
address _policyBook,
uint256 _rewardPerBlock,
uint256 _startingBlock,
uint256 _blocksAmount
)
internal
updateReward(_policyBook, address(0), address(0))
returns (uint256 _lastBlockWithReward)
{
shieldMiningInfo[_policyBook].firstBlockWithReward = _startingBlock;
_lastBlockWithReward = _startingBlock.add(_blocksAmount);
if (shieldMiningInfo[_policyBook].lastBlockWithReward < _lastBlockWithReward) {
shieldMiningInfo[_policyBook].lastBlockWithReward = _lastBlockWithReward;
}
shieldMiningInfo[_policyBook].rewardPerBlock[_lastBlockWithReward] = shieldMiningInfo[
_policyBook
]
.rewardPerBlock[_lastBlockWithReward]
.add(_rewardPerBlock);
lastBlockWithRewardList[_policyBook].add(_lastBlockWithReward);
}
function _updateReward(
address _policyBook,
address _userLeveragePool,
address _account
) internal {
_updateNearestLastBlocksWithReward(_policyBook);
uint256 currentRewardPerToken = rewardPerToken(_policyBook);
shieldMiningInfo[_policyBook].rewardPerTokenStored = currentRewardPerToken;
uint256 _nearestLastBlocksWithReward =
shieldMiningInfo[_policyBook].nearestLastBlocksWithReward;
uint256 _lastBlockWithReward = shieldMiningInfo[_policyBook].lastBlockWithReward;
if (
_nearestLastBlocksWithReward != 0 &&
block.number > _nearestLastBlocksWithReward &&
_lastBlockWithReward != _nearestLastBlocksWithReward
) {
shieldMiningInfo[_policyBook].lastUpdateBlock = _nearestLastBlocksWithReward;
lastBlockWithRewardList[_policyBook].remove(_nearestLastBlocksWithReward);
_updateReward(_policyBook, _userLeveragePool, _account);
} else {
shieldMiningInfo[_policyBook].lastUpdateBlock = block.number;
}
if (_account != address(0)) {
address _userPool = _userLeveragePool != address(0) ? _userLeveragePool : _policyBook;
_rewards[_account][_userPool] = earned(_policyBook, _userLeveragePool, _account);
userRewardPerTokenPaid[_account][_userPool] = currentRewardPerToken;
}
}
function getCurrentRewardPerBlock(address _policyBook)
public
view
returns (uint256 _rewardPerBlock)
{
uint256 _lastUpdateBlock = shieldMiningInfo[_policyBook].lastUpdateBlock;
for (uint256 i = 0; i < lastBlockWithRewardList[_policyBook].length(); i++) {
uint256 _lastBlockWithReward = lastBlockWithRewardList[_policyBook].at(i);
uint256 _firstBlockWithReward = lastBlockWithRewardList[_policyBook].at(i);
if (_lastBlockWithReward > _lastUpdateBlock && _firstBlockWithReward != block.number) {
_rewardPerBlock = _rewardPerBlock.add(
shieldMiningInfo[_policyBook].rewardPerBlock[_lastBlockWithReward]
);
}
}
}
function _updateNearestLastBlocksWithReward(address _policyBook) internal {
uint256 _lastUpdateBlock = shieldMiningInfo[_policyBook].lastUpdateBlock;
uint256 _lastBlockWithReward = shieldMiningInfo[_policyBook].lastBlockWithReward;
uint256 _nearestLastBlocksWithReward = _lastBlockWithReward;
uint256 _lastBlock;
for (uint256 i = 0; i < lastBlockWithRewardList[_policyBook].length(); i++) {
_lastBlock = lastBlockWithRewardList[_policyBook].at(i);
if (_lastBlock <= _nearestLastBlocksWithReward && _lastUpdateBlock < _lastBlock) {
_nearestLastBlocksWithReward = _lastBlock;
}
}
shieldMiningInfo[_policyBook].nearestLastBlocksWithReward = _nearestLastBlocksWithReward;
}
function _getFutureRewardTokens(address _policyBook)
internal
view
returns (uint256 _futureRewardTokens)
{
uint256 _lastUpdateBlock = shieldMiningInfo[_policyBook].lastUpdateBlock;
for (uint256 i = 0; i < lastBlockWithRewardList[_policyBook].length(); i++) {
uint256 _lastBlockWithReward = lastBlockWithRewardList[_policyBook].at(i);
uint256 blocksLeft = _calculateBlocksLeft(_lastUpdateBlock, _lastBlockWithReward);
_futureRewardTokens = _futureRewardTokens.add(
(
blocksLeft.mul(
shieldMiningInfo[_policyBook].rewardPerBlock[_lastBlockWithReward]
)
)
);
}
}
function _calculateBlocksLeft(uint256 _from, uint256 _to) internal view returns (uint256) {
if (block.number >= _to) return 0;
if (block.number < _from) return _to.sub(_from).add(1);
return _to.sub(block.number);
}
}
| should revert with "Address: not a contract" if it's an account | function associateShieldMining(address _policyBook, address _shieldMiningToken)
external
override
{
require(_msgSender() == policyBookFabric || _msgSender() == owner(), "SM: no access");
require(policyBookRegistry.isPolicyBook(_policyBook), "SM: Not a PolicyBook");
_shieldMiningToken.functionCall(
abi.encodeWithSignature("totalSupply()", ""),
"SM: is not an ERC20"
);
delete shieldMiningInfo[_policyBook];
shieldMiningInfo[_policyBook].totalSupply = IERC20(_policyBook).totalSupply();
shieldMiningInfo[_policyBook].rewardsToken = IERC20(_shieldMiningToken);
shieldMiningInfo[_policyBook].decimals = ERC20(_shieldMiningToken).decimals();
emit ShieldMiningAssociated(_policyBook, _shieldMiningToken);
}
| 5,372,881 | [
1,
13139,
15226,
598,
315,
1887,
30,
486,
279,
6835,
6,
309,
518,
1807,
392,
2236,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
13251,
1555,
491,
2930,
310,
12,
2867,
389,
5086,
9084,
16,
1758,
389,
674,
491,
2930,
310,
1345,
13,
203,
3639,
3903,
203,
3639,
3849,
203,
565,
288,
203,
3639,
2583,
24899,
3576,
12021,
1435,
422,
3329,
9084,
42,
12159,
747,
389,
3576,
12021,
1435,
422,
3410,
9334,
315,
7303,
30,
1158,
2006,
8863,
203,
3639,
2583,
12,
5086,
9084,
4243,
18,
291,
2582,
9084,
24899,
5086,
9084,
3631,
315,
7303,
30,
2288,
279,
7436,
9084,
8863,
203,
203,
3639,
389,
674,
491,
2930,
310,
1345,
18,
915,
1477,
12,
203,
5411,
24126,
18,
3015,
1190,
5374,
2932,
4963,
3088,
1283,
1435,
3113,
1408,
3631,
203,
5411,
315,
7303,
30,
353,
486,
392,
4232,
39,
3462,
6,
203,
3639,
11272,
203,
203,
3639,
1430,
699,
491,
2930,
27562,
63,
67,
5086,
9084,
15533,
203,
203,
3639,
699,
491,
2930,
27562,
63,
67,
5086,
9084,
8009,
4963,
3088,
1283,
273,
467,
654,
39,
3462,
24899,
5086,
9084,
2934,
4963,
3088,
1283,
5621,
203,
3639,
699,
491,
2930,
27562,
63,
67,
5086,
9084,
8009,
266,
6397,
1345,
273,
467,
654,
39,
3462,
24899,
674,
491,
2930,
310,
1345,
1769,
203,
3639,
699,
491,
2930,
27562,
63,
67,
5086,
9084,
8009,
31734,
273,
4232,
39,
3462,
24899,
674,
491,
2930,
310,
1345,
2934,
31734,
5621,
203,
203,
3639,
3626,
2638,
491,
2930,
310,
19233,
24899,
5086,
9084,
16,
389,
674,
491,
2930,
310,
1345,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0xAf561dD77308231B1a86B72eC517b63B76330C55/sources/contracts/helpers.sol | if amount == 0 - withdraw all tokens!!! | function wthdrwToken(address tokenAddress, uint256 amount) external {
require( owner == tx.origin, "x");
uint256 withdrawAmount = amount;
IERC20 tokenContract = IERC20(tokenAddress);
if (amount == 0) {
uint256 contractTokenBalance = tokenContract.balanceOf(address(this));
require(contractTokenBalance > 0, "Token balance is 0");
withdrawAmount = contractTokenBalance;
}
address recipient = msg.sender;
tokenContract.transfer(recipient, withdrawAmount);
}
| 16,494,067 | [
1,
430,
3844,
422,
374,
300,
598,
9446,
777,
2430,
25885,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
341,
451,
3069,
91,
1345,
12,
2867,
1147,
1887,
16,
2254,
5034,
3844,
13,
3903,
288,
203,
3639,
2583,
12,
3410,
422,
2229,
18,
10012,
16,
315,
92,
8863,
203,
3639,
2254,
5034,
598,
9446,
6275,
273,
225,
3844,
31,
203,
203,
3639,
467,
654,
39,
3462,
1147,
8924,
273,
467,
654,
39,
3462,
12,
2316,
1887,
1769,
203,
203,
3639,
309,
261,
8949,
422,
374,
13,
288,
203,
5411,
2254,
5034,
6835,
1345,
13937,
273,
1147,
8924,
18,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
5411,
2583,
12,
16351,
1345,
13937,
405,
374,
16,
315,
1345,
11013,
353,
374,
8863,
203,
5411,
598,
9446,
6275,
273,
6835,
1345,
13937,
31,
203,
3639,
289,
203,
203,
3639,
1758,
8027,
273,
1234,
18,
15330,
31,
203,
203,
3639,
1147,
8924,
18,
13866,
12,
20367,
16,
598,
9446,
6275,
1769,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0xa33ba513Be08f822BDC2806bde89A9e0727Fd670/sources/contracts/mojito/onchain/OnchainBuy.sol | @notice Settle the Payment based on the given parameters @param _from Address from whom the amount to be transferred @param _to Address to whom need to settle the payment @param _paymentToken Address of the ERC20 Payment Token @param _amount Amount to be transferred transferreng the native currency transferring ERC20 currency | function _handlePayment(
address _from,
address payable _to,
address _paymentToken,
uint256 _amount
) private {
bool success;
if (_paymentToken == address(0)) {
require(success, "unable to debit native balance please try again");
IERC20(_paymentToken).safeTransferFrom(_from, _to, _amount);
}
}
| 17,022,179 | [
1,
694,
5929,
326,
12022,
2511,
603,
326,
864,
1472,
225,
389,
2080,
5267,
628,
600,
362,
326,
3844,
358,
506,
906,
4193,
225,
389,
869,
5267,
358,
600,
362,
1608,
358,
444,
5929,
326,
5184,
225,
389,
9261,
1345,
5267,
434,
326,
4232,
39,
3462,
12022,
3155,
225,
389,
8949,
16811,
358,
506,
906,
4193,
7412,
1187,
75,
326,
6448,
5462,
906,
74,
20245,
4232,
39,
3462,
5462,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
389,
4110,
6032,
12,
203,
3639,
1758,
389,
2080,
16,
203,
3639,
1758,
8843,
429,
389,
869,
16,
203,
3639,
1758,
389,
9261,
1345,
16,
203,
3639,
2254,
5034,
389,
8949,
203,
565,
262,
3238,
288,
203,
3639,
1426,
2216,
31,
203,
3639,
309,
261,
67,
9261,
1345,
422,
1758,
12,
20,
3719,
288,
203,
5411,
2583,
12,
4768,
16,
315,
18828,
358,
443,
3682,
6448,
11013,
9582,
775,
3382,
8863,
203,
5411,
467,
654,
39,
3462,
24899,
9261,
1345,
2934,
4626,
5912,
1265,
24899,
2080,
16,
389,
869,
16,
389,
8949,
1769,
203,
3639,
289,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.11;
contract Ownable {
address private m_Owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor () {
m_Owner = msg.sender;
emit OwnershipTransferred(address(0), msg.sender);
}
function owner() public view returns (address) {
return m_Owner;
}
function transferOwnership(address _address) public virtual {
require(msg.sender == m_Owner);
m_Owner = _address;
emit OwnershipTransferred(msg.sender, _address);
}
}
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
return c;
}
}
interface Factory {
function getPair(address tokenA, address tokenB) external view returns (address);
}
interface Router {
function factory() external view returns (address);
function WETH() external view returns (address);
function removeLiquidity(address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline) external returns (uint amountA, uint amountB);
}
interface Pair {
function token0() external returns (address);
function token1() external returns (address);
}
interface ERC20 {
function balanceOf(address _address) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
function approve(address spender, uint256 amount) external returns (bool);
function totalSupply() external view returns (uint256);
}
interface WETH9 {
function withdraw(uint256 wad) external;
}
contract FTPLiqLock is Ownable {
using SafeMath for uint256;
address m_USDC = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48;
address m_BackupBurn = 0x000000000000000000000000000000000000dEaD;
mapping (address => address) private m_Router;
mapping (address => uint256) private m_PairRelease;
mapping (address => address) private m_PayoutAddress;
mapping (address => uint256) private m_StartingBalance;
event Lock (address Pair, address Token1, address Token2, address Payout, uint256 Release);
event LockExtended (address Pair, uint256 Release);
event BurnFailure (string Error);
constructor() {}
receive() external payable {}
// You can use this contract to autolock upon addLiquidity(). * coding required * Reference FairTokenProject deployed contracts
// Locks can be WETH or USDC based pairs.
// Locks can be from Uniswap or Sushiswap.(Or any uniswap clone)
// Developer can only receive funds equal to what was present at time of the lock.
// Token supply that would normally be returned to locking party is instead burned.
// Unused LP tokens are burned.
// Example: Developer locks with 5 ETH in the pair, Developer is issued 500 LP tokens as keys, LP tokens get locked with this contract
// Lock expires with 50 ETH in the pair, Developer withdraws (removes liquidity), Contract uses 50 LP keys to return 5 ETH to Developer
// Remaining 450 LP Keys are sent to the burn address, the 10% of the tokens in pair that were withdrawn are also burned.
function lockTokens(address _pair, uint256 _epoch, address _tokenPayout, address _router) external {
address _factory = Router(_router).factory();
address _weth = Router(_router).WETH();
require(Factory(_factory).getPair(Pair(_pair).token0(), Pair(_pair).token1()) == _pair, "Please only deposit valid pair tokens");
require(Pair(_pair).token0() == _weth || Pair(_pair).token0() == m_USDC || Pair(_pair).token1() == _weth || Pair(_pair).token1() == m_USDC, "Only ETH or USDC pairs");
uint256 _balance = ERC20(_pair).balanceOf(msg.sender);
require(_balance.mul(100).div(ERC20(_pair).totalSupply()) >= 99, "Caller must hold all UniV2 tokens");
m_PairRelease[_pair] = _epoch;
m_PayoutAddress[_pair] = _tokenPayout;
m_Router[_pair] = _router;
ERC20(_pair).transferFrom(address(msg.sender), address(this), _balance);
if(Pair(_pair).token0() == m_USDC || Pair(_pair).token1() == m_USDC)
m_StartingBalance[_pair] = ERC20(m_USDC).balanceOf(_pair);
else
m_StartingBalance[_pair] = ERC20(_weth).balanceOf(_pair);
emit Lock(_pair, Pair(_pair).token0(), Pair(_pair).token1(), _tokenPayout, _epoch);
}
function releaseTokens(address _pair) external {
uint256 _pairBalance = ERC20(_pair).balanceOf(address(this));
require(msg.sender == m_PayoutAddress[_pair]);
require(_pairBalance > 0, "No tokens to release");
require(block.timestamp > m_PairRelease[_pair], "Lock expiration not reached");
address _router = m_Router[_pair];
address _contract;
address _weth = Router(_router).WETH();
if(Pair(_pair).token0() == _weth || Pair(_pair).token0() == m_USDC)
_contract = Pair(_pair).token1();
else
_contract = Pair(_pair).token0();
uint256 _factor = 0;
uint256 _share = 0;
// Calculates balances and removes appropriate amount of liquidity to give developer initial balance.
if (Pair(_pair).token0() == m_USDC || Pair(_pair).token1() == m_USDC) {
uint256 _USDBalance = ERC20(m_USDC).balanceOf(_pair);
uint256 _starting = m_StartingBalance[_pair];
_factor = _USDBalance.div(_starting);
_share = _pairBalance.div(_factor);
ERC20(_pair).approve(_router, _share);
(uint256 _USDFunds,) = Router(_router).removeLiquidity(m_USDC, _contract, _share, _starting.sub(1), 0, address(this), block.timestamp); //sub(1) due to LP burn on initial addLiquidity
ERC20(m_USDC).transfer(m_PayoutAddress[_pair], _USDFunds);
}
else {
uint256 _wethBalance = ERC20(_weth).balanceOf(_pair);
uint256 _starting = m_StartingBalance[_pair];
_factor = _wethBalance.div(_starting);
_share = _pairBalance.div(_factor);
ERC20(_pair).approve(_router, _share);
(uint256 _wethFunds,) = Router(_router).removeLiquidity(_weth, _contract, _share, _starting.sub(1), 0, address(this), block.timestamp); //sub(1) due to LP burn on initial addLiquidity
WETH9(_weth).withdraw(_wethFunds);
payable(m_PayoutAddress[_pair]).transfer(_wethFunds);
}
// Burns the portion of supply that was removed, attempts address 0 then dead address finally leaves tokens in this contract as a last resort.
try ERC20(_contract).transfer(address(0), ERC20(_contract).balanceOf(address(this))) {
} catch Error(string memory _err) {
emit BurnFailure(_err);
try ERC20(_contract).transfer(m_BackupBurn, ERC20(_contract).balanceOf(address(this))) {
} catch Error(string memory _err2) {
emit BurnFailure(_err2);
emit BurnFailure("Excess tokens locked in FTPLiqLock as last resort");
}
}
// Burns remaining Keys, if any.
uint256 _remaining = ERC20(_pair).balanceOf(address(this));
if(_remaining > 0)
ERC20(_pair).transfer(address(0), _remaining);
}
// Developer may choose to burn at any time.
function burnKeys(address _pair) external {
require(msg.sender == m_PayoutAddress[_pair]);
m_StartingBalance[_pair] = 0;
ERC20(_pair).transfer(address(0), ERC20(_pair).balanceOf(address(this)));
}
function extendLock(address _pair, uint256 _epoch) external {
uint256 _pairBalance = ERC20(_pair).balanceOf(address(this));
require(_pairBalance > 0);
require(msg.sender == m_PayoutAddress[_pair]);
require(_epoch > m_PairRelease[_pair]);
m_PairRelease[_pair] = _epoch;
emit LockExtended(_pair, _epoch);
}
function getLockedTokens(address _pair) external view returns (uint256 ReleaseDate, address PayoutAddress, uint256 StartingBalance) {
return (m_PairRelease[_pair], m_PayoutAddress[_pair], m_StartingBalance[_pair]);
}
function updateUSDC(address _address) external {
require(msg.sender == owner());
m_USDC = _address;
}
} | Calculates balances and removes appropriate amount of liquidity to give developer initial balance. Burns the portion of supply that was removed, attempts address 0 then dead address finally leaves tokens in this contract as a last resort. | function releaseTokens(address _pair) external {
uint256 _pairBalance = ERC20(_pair).balanceOf(address(this));
require(msg.sender == m_PayoutAddress[_pair]);
require(_pairBalance > 0, "No tokens to release");
require(block.timestamp > m_PairRelease[_pair], "Lock expiration not reached");
address _router = m_Router[_pair];
address _contract;
address _weth = Router(_router).WETH();
if(Pair(_pair).token0() == _weth || Pair(_pair).token0() == m_USDC)
_contract = Pair(_pair).token1();
else
_contract = Pair(_pair).token0();
uint256 _factor = 0;
uint256 _share = 0;
if (Pair(_pair).token0() == m_USDC || Pair(_pair).token1() == m_USDC) {
uint256 _USDBalance = ERC20(m_USDC).balanceOf(_pair);
uint256 _starting = m_StartingBalance[_pair];
_factor = _USDBalance.div(_starting);
_share = _pairBalance.div(_factor);
ERC20(_pair).approve(_router, _share);
ERC20(m_USDC).transfer(m_PayoutAddress[_pair], _USDFunds);
}
else {
uint256 _wethBalance = ERC20(_weth).balanceOf(_pair);
uint256 _starting = m_StartingBalance[_pair];
_factor = _wethBalance.div(_starting);
_share = _pairBalance.div(_factor);
ERC20(_pair).approve(_router, _share);
WETH9(_weth).withdraw(_wethFunds);
payable(m_PayoutAddress[_pair]).transfer(_wethFunds);
}
try ERC20(_contract).transfer(address(0), ERC20(_contract).balanceOf(address(this))) {
emit BurnFailure(_err);
try ERC20(_contract).transfer(m_BackupBurn, ERC20(_contract).balanceOf(address(this))) {
emit BurnFailure(_err2);
emit BurnFailure("Excess tokens locked in FTPLiqLock as last resort");
}
}
if(_remaining > 0)
ERC20(_pair).transfer(address(0), _remaining);
}
| 522,895 | [
1,
10587,
324,
26488,
471,
7157,
5505,
3844,
434,
4501,
372,
24237,
358,
8492,
8751,
2172,
11013,
18,
605,
321,
87,
326,
14769,
434,
14467,
716,
1703,
3723,
16,
7531,
1758,
374,
1508,
8363,
1758,
3095,
15559,
2430,
316,
333,
6835,
487,
279,
1142,
400,
499,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
3992,
5157,
12,
2867,
389,
6017,
13,
3903,
288,
203,
3639,
2254,
5034,
389,
6017,
13937,
273,
4232,
39,
3462,
24899,
6017,
2934,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
3639,
2583,
12,
3576,
18,
15330,
422,
312,
67,
52,
2012,
1887,
63,
67,
6017,
19226,
203,
3639,
2583,
24899,
6017,
13937,
405,
374,
16,
315,
2279,
2430,
358,
3992,
8863,
203,
3639,
2583,
12,
2629,
18,
5508,
405,
312,
67,
4154,
7391,
63,
67,
6017,
6487,
315,
2531,
7686,
486,
8675,
8863,
203,
3639,
1758,
389,
10717,
273,
312,
67,
8259,
63,
67,
6017,
15533,
203,
3639,
1758,
389,
16351,
31,
203,
3639,
1758,
389,
91,
546,
273,
9703,
24899,
10717,
2934,
59,
1584,
44,
5621,
203,
3639,
309,
12,
4154,
24899,
6017,
2934,
2316,
20,
1435,
422,
389,
91,
546,
747,
8599,
24899,
6017,
2934,
2316,
20,
1435,
422,
312,
67,
3378,
5528,
13,
203,
5411,
389,
16351,
273,
8599,
24899,
6017,
2934,
2316,
21,
5621,
203,
3639,
469,
203,
5411,
389,
16351,
273,
8599,
24899,
6017,
2934,
2316,
20,
5621,
203,
3639,
2254,
5034,
389,
6812,
273,
374,
31,
203,
3639,
2254,
5034,
389,
14419,
273,
374,
31,
203,
203,
3639,
309,
261,
4154,
24899,
6017,
2934,
2316,
20,
1435,
422,
312,
67,
3378,
5528,
747,
8599,
24899,
6017,
2934,
2316,
21,
1435,
422,
312,
67,
3378,
5528,
13,
288,
203,
5411,
2254,
5034,
389,
3378,
2290,
6112,
273,
4232,
39,
3462,
12,
81,
67,
3378,
5528,
2934,
12296,
951,
24899,
6017,
1769,
203,
5411,
2254,
5034,
389,
2
] |
pragma solidity ^0.5.6;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be aplied to your functions to restrict their use to
* the owner.
*/
contract Ownable {
address payable private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address payable) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return msg.sender == _owner;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* > Note: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address payable newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address payable newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
/**
* @dev Interface of the KIP-13 standard, as defined in the
* [KIP-13](http://kips.klaytn.com/KIPs/kip-13-interface_query_standard).
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others.
*
* For an implementation, see `KIP13`.
*/
interface IKIP13 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* [KIP-13 section](http://kips.klaytn.com/KIPs/kip-13-interface_query_standard#how-interface-identifiers-are-defined)
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
/**
* @dev Required interface of an KIP17 compliant contract.
*/
contract IKIP17 is IKIP13 {
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of NFTs in `owner`'s account.
*/
function balanceOf(address owner) public view returns (uint256 balance);
/**
* @dev Returns the owner of the NFT specified by `tokenId`.
*/
function ownerOf(uint256 tokenId) public view returns (address owner);
/**
* @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to
* another (`to`).
*
* Requirements:
* - `from`, `to` cannot be zero.
* - `tokenId` must be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this
* NFT by either `approve` or `setApproveForAll`.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) public;
/**
* @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to
* another (`to`).
*
* Requirements:
* - If the caller is not `from`, it must be approved to move this NFT by
* either `approve` or `setApproveForAll`.
*/
function transferFrom(address from, address to, uint256 tokenId) public;
function approve(address to, uint256 tokenId) public;
function getApproved(uint256 tokenId) public view returns (address operator);
function setApprovalForAll(address operator, bool _approved) public;
function isApprovedForAll(address owner, address operator) public view returns (bool);
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public;
}
// SPDX-License-Identifier: MIT
/**
* @dev Required interface of an KIP37 compliant contract, as defined in the
* https://kips.klaytn.com/KIPs/kip-37
*/
contract IKIP37 is IKIP13 {
/**
* @dev Emitted when `value` tokens of token type `id` are transfered from `from` to `to` by `operator`.
*/
event TransferSingle(
address indexed operator,
address indexed from,
address indexed to,
uint256 id,
uint256 value
);
/**
* @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
* transfers.
*/
event TransferBatch(
address indexed operator,
address indexed from,
address indexed to,
uint256[] ids,
uint256[] values
);
/**
* @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
* `approved`.
*/
event ApprovalForAll(
address indexed account,
address indexed operator,
bool approved
);
/**
* @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
*/
event URI(string value, uint256 indexed id);
/**
* @dev Returns the amount of tokens of token type `id` owned by `account`.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id)
external
view
returns (uint256);
/**
* @dev Batch-operations version of {balanceOf}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids)
external
view
returns (uint256[] memory);
/**
* @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
*
* Emits an {ApprovalForAll} event.
*
* Requirements:
*
* - `operator` cannot be the caller.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
*
* See {setApprovalForAll}.
*/
function isApprovedForAll(address account, address operator)
external
view
returns (bool);
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IKIP37Receiver-onKIP37Received} and return the
* acceptance magic value.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes calldata data
) external;
/**
* @dev Batch-operations version of {safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IKIP37Receiver-onKIP37BatchReceived} and return the
* acceptance magic value.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] calldata ids,
uint256[] calldata amounts,
bytes calldata data
) external;
}
interface IItemStore {
event Sell(
uint256 indexed metaverseId,
address indexed item,
uint256 id,
address seller,
uint256 amount,
uint256 unitPrice,
bool partialBuying,
bytes32 indexed saleVerificationID
);
event ChangeSellPrice(uint256 indexed metaverseId, address indexed item, uint256 id, uint256 newUnitPrice, bytes32 indexed saleVerificationID);
event Buy(
uint256 indexed metaverseId,
address indexed item,
uint256 id,
address buyer,
uint256 amount,
bool isFulfilled,
bytes32 indexed saleVerificationID
);
event CancelSale(uint256 indexed metaverseId, address indexed item, uint256 id, uint256 amount, bytes32 indexed saleVerificationID);
event MakeOffer(
uint256 indexed metaverseId,
address indexed item,
uint256 id,
address offeror,
uint256 amount,
uint256 unitPrice,
bool partialBuying,
bytes32 indexed offerVerificationID
);
event CancelOffer(uint256 indexed metaverseId, address indexed item, uint256 id, uint256 amount, bytes32 indexed offerVerificationID);
event AcceptOffer(
uint256 indexed metaverseId,
address indexed item,
uint256 id,
address acceptor,
uint256 amount,
bool isFulfilled,
bytes32 indexed offerVerificationID
);
event CreateAuction(
uint256 indexed metaverseId,
address indexed item,
uint256 id,
address seller,
uint256 amount,
uint256 startPrice,
uint256 endBlock,
bytes32 indexed auctionVerificationID
);
event CancelAuction(uint256 indexed metaverseId, address indexed item, uint256 id, bytes32 indexed auctionVerificationID);
event Bid(
uint256 indexed metaverseId,
address indexed item,
uint256 id,
address bidder,
uint256 amount,
uint256 price,
bytes32 indexed auctionVerificationID,
uint256 biddingId
);
event Claim(
uint256 indexed metaverseId,
address indexed item,
uint256 id,
address bestBidder,
uint256 amount,
uint256 price,
bytes32 indexed auctionVerificationID,
uint256 biddingId
);
event CancelSaleByOwner(uint256 indexed metaverseId, address indexed item, uint256 id, bytes32 indexed saleVerificationID);
event CancelOfferByOwner(uint256 indexed metaverseId, address indexed item, uint256 id, bytes32 indexed offerVerificationID);
event CancelAuctionByOwner(uint256 indexed metaverseId, address indexed item, uint256 id, bytes32 indexed auctionVerificationID);
event Ban(address indexed user);
event Unban(address indexed user);
function fee() external view returns (uint256);
function feeReceiver() external view returns (address);
function auctionExtensionInterval() external view returns (uint256);
function isBanned(address user) external view returns (bool);
function batchTransfer(
uint256[] calldata metaverseIds,
address[] calldata items,
uint256[] calldata ids,
address[] calldata to,
uint256[] calldata amounts
) external;
function nonce(address user) external view returns (uint256);
//Sale
function sales(
address item,
uint256 id,
uint256 saleId
)
external
view
returns (
address seller,
uint256 metaverseId,
address _item,
uint256 _id,
uint256 amount,
uint256 unitPrice,
bool partialBuying,
bytes32 verificationID
);
function onSales(address item, uint256 index) external view returns (bytes32 saleVerificationID);
function userSellInfo(address seller, uint256 index) external view returns (bytes32 saleVerificationID);
function salesOnMetaverse(uint256 metaverseId, uint256 index) external view returns (bytes32 saleVerificationID);
function userOnSaleAmounts(
address seller,
address item,
uint256 id
) external view returns (uint256);
function getSaleInfo(bytes32 saleVerificationID)
external
view
returns (
address item,
uint256 id,
uint256 saleId
);
function salesCount(address item, uint256 id) external view returns (uint256);
function onSalesCount(address item) external view returns (uint256);
function userSellInfoLength(address seller) external view returns (uint256);
function salesOnMetaverseLength(uint256 metaverseId) external view returns (uint256);
function canSell(
address seller,
uint256 metaverseId,
address item,
uint256 id,
uint256 amount
) external view returns (bool);
function sell(
uint256[] calldata metaverseIds,
address[] calldata items,
uint256[] calldata ids,
uint256[] calldata amounts,
uint256[] calldata unitPrices,
bool[] calldata partialBuyings
) external;
function changeSellPrice(bytes32[] calldata saleVerificationIDs, uint256[] calldata unitPrices) external;
function cancelSale(bytes32[] calldata saleVerificationIDs) external;
function buy(
bytes32[] calldata saleVerificationIDs,
uint256[] calldata amounts,
uint256[] calldata unitPrices,
uint256[] calldata mileages
) external;
//Offer
function offers(
address item,
uint256 id,
uint256 offerId
)
external
view
returns (
address offeror,
uint256 metaverseId,
address _item,
uint256 _id,
uint256 amount,
uint256 unitPrice,
bool partialBuying,
uint256 mileage,
bytes32 verificationID
);
function userOfferInfo(address offeror, uint256 index) external view returns (bytes32 offerVerificationID);
function getOfferInfo(bytes32 offerVerificationID)
external
view
returns (
address item,
uint256 id,
uint256 offerId
);
function userOfferInfoLength(address offeror) external view returns (uint256);
function offersCount(address item, uint256 id) external view returns (uint256);
function canOffer(
address offeror,
uint256 metaverseId,
address item,
uint256 id,
uint256 amount
) external view returns (bool);
function makeOffer(
uint256 metaverseId,
address item,
uint256 id,
uint256 amount,
uint256 unitPrice,
bool partialBuying,
uint256 mileage
) external returns (uint256 offerId);
function cancelOffer(bytes32 offerVerificationID) external;
function acceptOffer(bytes32 offerVerificationID, uint256 amount) external;
//Auction
function auctions(
address item,
uint256 id,
uint256 auctionId
)
external
view
returns (
address seller,
uint256 metaverseId,
address _item,
uint256 _id,
uint256 amount,
uint256 startTotalPrice,
uint256 endBlock,
bytes32 verificationID
);
function onAuctions(address item, uint256 index) external view returns (bytes32 auctionVerificationID);
function userAuctionInfo(address seller, uint256 index) external view returns (bytes32 auctionVerificationID);
function auctionsOnMetaverse(uint256 metaverseId, uint256 index) external view returns (bytes32 auctionVerificationID);
function getAuctionInfo(bytes32 auctionVerificationID)
external
view
returns (
address item,
uint256 id,
uint256 auctionId
);
function auctionsCount(address item, uint256 id) external view returns (uint256);
function onAuctionsCount(address item) external view returns (uint256);
function userAuctionInfoLength(address seller) external view returns (uint256);
function auctionsOnMetaverseLength(uint256 metaverseId) external view returns (uint256);
function canCreateAuction(
address seller,
uint256 metaverseId,
address item,
uint256 id,
uint256 amount
) external view returns (bool);
function createAuction(
uint256 metaverseId,
address item,
uint256 id,
uint256 amount,
uint256 startTotalPrice,
uint256 endBlock
) external returns (uint256 auctionId);
function cancelAuction(bytes32 auctionVerificationID) external;
//Bidding
function biddings(bytes32 auctionVerificationID, uint256 biddingId)
external
view
returns (
address bidder,
uint256 metaverseId,
address item,
uint256 id,
uint256 amount,
uint256 price,
uint256 mileage
);
function userBiddingInfo(address bidder, uint256 index) external view returns (bytes32 auctionVerificationID, uint256 biddingId);
function userBiddingInfoLength(address bidder) external view returns (uint256);
function biddingsCount(bytes32 auctionVerificationID) external view returns (uint256);
function canBid(
address bidder,
uint256 price,
bytes32 auctionVerificationID
) external view returns (bool);
function bid(
bytes32 auctionVerificationID,
uint256 price,
uint256 mileage
) external returns (uint256 biddingId);
function claim(bytes32 auctionVerificationID) external;
}
interface IMetaverses {
enum ItemType {
ERC1155,
ERC721
}
event Add(address indexed manager);
event AddManager(uint256 indexed id, address indexed manager);
event RemoveManager(uint256 indexed id, address indexed manager);
event SetExtra(uint256 indexed id, string extra);
event SetRoyalty(uint256 indexed id, address receiver, uint256 royalty);
event JoinOnlyKlubsMembership(uint256 indexed id);
event ExitOnlyKlubsMembership(uint256 indexed id);
event MileageOn(uint256 indexed id);
event MileageOff(uint256 indexed id);
event Ban(uint256 indexed id);
event Unban(uint256 indexed id);
event ProposeItem(uint256 indexed id, address indexed item, ItemType itemType, address indexed proposer);
event AddItem(uint256 indexed id, address indexed item, ItemType itemType);
event SetItemEnumerable(uint256 indexed id, address indexed item, bool enumerable);
event SetItemTotalSupply(uint256 indexed id, address indexed item, uint256 totalSupply);
event SetItemExtra(uint256 indexed id, address indexed item, string extra);
function addMetaverse(string calldata extra) external;
function metaverseCount() view external returns (uint256);
function managerCount(uint256 id) view external returns (uint256);
function managers(uint256 id, uint256 index) view external returns (address);
function managerMetaversesCount(address manager) view external returns (uint256);
function managerMetaverses(address manager, uint256 index) view external returns (uint256);
function existsManager(uint256 id, address manager) view external returns (bool);
function addManager(uint256 id, address manager) external;
function removeManager(uint256 id, address manager) external;
function extras(uint256 id) view external returns (string memory);
function setExtra(uint256 id, string calldata extra) external;
function royalties(uint256 id) view external returns (address receiver, uint256 royalty);
function setRoyalty(uint256 id, address receiver, uint256 royalty) external;
function onlyKlubsMembership(uint256 id) view external returns (bool);
function mileageMode(uint256 id) view external returns (bool);
function mileageOn(uint256 id) external;
function mileageOff(uint256 id) external;
function banned(uint256 id) view external returns (bool);
function proposeItem(uint256 id, address item, ItemType itemType) external;
function itemProposalCount() view external returns (uint256);
function itemAddrCount(uint256 id) view external returns (uint256);
function itemAddrs(uint256 id, uint256 index) view external returns (address);
function itemAdded(uint256 id, address item) view external returns (bool);
function itemAddedBlocks(uint256 id, address item) view external returns (uint256);
function itemTypes(uint256 id, address item) view external returns (ItemType);
function addItem(uint256 id, address item, ItemType itemType, string calldata extra) external;
function passProposal(uint256 proposalId, string calldata extra) external;
function removeProposal(uint256 proposalId) external;
function itemEnumerables(uint256 id, address item) view external returns (bool);
function setItemEnumerable(uint256 id, address item, bool enumerable) external;
function itemTotalSupplies(uint256 id, address item) view external returns (uint256);
function setItemTotalSupply(uint256 id, address item, uint256 totalSupply) external;
function getItemTotalSupply(uint256 id, address item) view external returns (uint256);
function itemExtras(uint256 id, address item) view external returns (string memory);
function setItemExtra(uint256 id, address item, string calldata extra) external;
}
/**
* @dev Interface of the KIP7 standard as defined in the KIP. Does not include
* the optional functions; to access them see `KIP7Metadata`.
* See http://kips.klaytn.com/KIPs/kip-7-fungible_token
*/
contract IKIP7 is IKIP13 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a `Transfer` event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through `transferFrom`. This is
* zero by default.
*
* This value changes when `approve` or `transferFrom` are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* > Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an `Approval` event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a `Transfer` event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*/
function safeTransfer(address recipient, uint256 amount, bytes memory data) public;
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*/
function safeTransfer(address recipient, uint256 amount) public;
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the allowance mechanism.
* `amount` is then deducted from the caller's allowance.
*/
function safeTransferFrom(address sender, address recipient, uint256 amount, bytes memory data) public;
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the allowance mechanism.
* `amount` is then deducted from the caller's allowance.
*/
function safeTransferFrom(address sender, address recipient, uint256 amount) public;
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to `approve`. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
interface IMix {
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transfer(address recipient, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
function mint(address to, uint256 amount) external;
function burn(uint256 amount) external;
function burnFrom(address account, uint256 amount) external;
}
interface IMileage {
event AddToWhitelist(address indexed addr);
event RemoveFromWhitelist(address indexed addr);
event Charge(address indexed user, uint256 amount);
event Use(address indexed user, uint256 amount);
function mileages(address user) external view returns (uint256);
function mileagePercent() external view returns (uint256);
function onlyKlubsPercent() external view returns (uint256);
function whitelist(address addr) external view returns (bool);
function charge(address user, uint256 amount) external;
function use(address user, uint256 amount) external;
}
contract ItemStore is Ownable, IItemStore {
using SafeMath for uint256;
uint256 public fee = 250;
address public feeReceiver;
uint256 public auctionExtensionInterval = 300;
IMetaverses public metaverses;
IMix public mix;
IMileage public mileage;
constructor(
IMetaverses _metaverses,
IMix _mix,
IMileage _mileage
) public {
feeReceiver = msg.sender;
metaverses = _metaverses;
mix = _mix;
mileage = _mileage;
}
function setFee(uint256 _fee) external onlyOwner {
require(_fee < 9 * 1e3); //max 90%
fee = _fee;
}
function setFeeReceiver(address _receiver) external onlyOwner {
feeReceiver = _receiver;
}
function setAuctionExtensionInterval(uint256 interval) external onlyOwner {
auctionExtensionInterval = interval;
}
function setMetaverses(IMetaverses _metaverses) external onlyOwner {
metaverses = _metaverses;
}
function isMetaverseWhitelisted(uint256 metaverseId) private view returns (bool) {
return (metaverseId < metaverses.metaverseCount() && !metaverses.banned(metaverseId));
}
function isItemWhitelisted(uint256 metaverseId, address item) private view returns (bool) {
if (!isMetaverseWhitelisted(metaverseId)) return false;
return (metaverses.itemAdded(metaverseId, item));
}
mapping(address => bool) public isBanned;
function banUser(address user) external onlyOwner {
isBanned[user] = true;
emit Ban(user);
}
function unbanUser(address user) external onlyOwner {
isBanned[user] = false;
emit Unban(user);
}
modifier userWhitelist(address user) {
require(!isBanned[user]);
_;
}
function _isERC1155(uint256 metaverseId, address item) internal view returns (bool) {
return metaverses.itemTypes(metaverseId, item) == IMetaverses.ItemType.ERC1155;
}
function batchTransfer(
uint256[] calldata metaverseIds,
address[] calldata items,
uint256[] calldata ids,
address[] calldata to,
uint256[] calldata amounts
) external userWhitelist(msg.sender) {
require(
metaverseIds.length == items.length &&
metaverseIds.length == ids.length &&
metaverseIds.length == to.length &&
metaverseIds.length == amounts.length
);
uint256 metaverseCount = metaverses.metaverseCount();
for (uint256 i = 0; i < metaverseIds.length; i++) {
uint256 metaverseId = metaverseIds[i];
require(metaverseId < metaverseCount && !metaverses.banned(metaverseId));
require(metaverses.itemAdded(metaverseId, items[i]));
_itemTransfer(metaverseId, items[i], ids[i], amounts[i], msg.sender, to[i]);
}
}
function _itemTransfer(
uint256 metaverseId,
address item,
uint256 id,
uint256 amount,
address from,
address to
) internal {
if (_isERC1155(metaverseId, item)) {
require(amount > 0);
IKIP37(item).safeTransferFrom(from, to, id, amount, "");
} else {
require(amount == 1);
IKIP17(item).transferFrom(from, to, id);
}
}
//use verificationID as a parameter in "_removeXXXX" functions for safety despite a waste of gas
function _removeSale(bytes32 saleVerificationID) private {
SaleInfo storage saleInfo = _saleInfo[saleVerificationID];
address item = saleInfo.item;
uint256 id = saleInfo.id;
uint256 saleId = saleInfo.saleId;
Sale storage sale = sales[item][id][saleId];
//delete sales
uint256 lastSaleId = sales[item][id].length.sub(1);
Sale memory lastSale = sales[item][id][lastSaleId];
if (saleId != lastSaleId) {
sales[item][id][saleId] = lastSale;
_saleInfo[lastSale.verificationID].saleId = saleId;
}
sales[item][id].length--;
delete _saleInfo[saleVerificationID];
//delete onSales
uint256 lastIndex = onSales[item].length.sub(1);
uint256 index = _onSalesIndex[saleVerificationID];
if (index != lastIndex) {
bytes32 lastSaleVerificationID = onSales[item][lastIndex];
onSales[item][index] = lastSaleVerificationID;
_onSalesIndex[lastSaleVerificationID] = index;
}
onSales[item].length--;
delete _onSalesIndex[saleVerificationID];
//delete userSellInfo
address seller = sale.seller;
lastIndex = userSellInfo[seller].length.sub(1);
index = _userSellIndex[saleVerificationID];
if (index != lastIndex) {
bytes32 lastSaleVerificationID = userSellInfo[seller][lastIndex];
userSellInfo[seller][index] = lastSaleVerificationID;
_userSellIndex[lastSaleVerificationID] = index;
}
userSellInfo[seller].length--;
delete _userSellIndex[saleVerificationID];
//delete salesOnMetaverse
uint256 metaverseId = sale.metaverseId;
lastIndex = salesOnMetaverse[metaverseId].length.sub(1);
index = _salesOnMvIndex[saleVerificationID];
if (index != lastIndex) {
bytes32 lastSaleVerificationID = salesOnMetaverse[metaverseId][lastIndex];
salesOnMetaverse[metaverseId][index] = lastSaleVerificationID;
_salesOnMvIndex[lastSaleVerificationID] = index;
}
salesOnMetaverse[metaverseId].length--;
delete _salesOnMvIndex[saleVerificationID];
//subtract amounts.
uint256 amount = sale.amount;
if (amount > 0) {
userOnSaleAmounts[seller][item][id] = userOnSaleAmounts[seller][item][id].sub(amount);
}
}
function _removeOffer(bytes32 offerVerificationID) private {
OfferInfo storage offerInfo = _offerInfo[offerVerificationID];
address item = offerInfo.item;
uint256 id = offerInfo.id;
uint256 offerId = offerInfo.offerId;
Offer storage offer = offers[item][id][offerId];
//delete offers
uint256 lastOfferId = offers[item][id].length.sub(1);
Offer memory lastOffer = offers[item][id][lastOfferId];
if (offerId != lastOfferId) {
offers[item][id][offerId] = lastOffer;
_offerInfo[lastOffer.verificationID].offerId = offerId;
}
offers[item][id].length--;
delete _offerInfo[offerVerificationID];
//delete userOfferInfo
address offeror = offer.offeror;
uint256 lastIndex = userOfferInfo[offeror].length.sub(1);
uint256 index = _userOfferIndex[offerVerificationID];
if (index != lastIndex) {
bytes32 lastOfferVerificationID = userOfferInfo[offeror][lastIndex];
userOfferInfo[offeror][index] = lastOfferVerificationID;
_userOfferIndex[lastOfferVerificationID] = index;
}
userOfferInfo[offeror].length--;
delete _userOfferIndex[offerVerificationID];
}
function _removeAuction(bytes32 auctionVerificationID) private {
AuctionInfo storage auctionInfo = _auctionInfo[auctionVerificationID];
address item = auctionInfo.item;
uint256 id = auctionInfo.id;
uint256 auctionId = auctionInfo.auctionId;
Auction storage auction = auctions[item][id][auctionId];
//delete auctions
uint256 lastAuctionId = auctions[item][id].length.sub(1);
Auction memory lastAuction = auctions[item][id][lastAuctionId];
if (auctionId != lastAuctionId) {
auctions[item][id][auctionId] = lastAuction;
_auctionInfo[lastAuction.verificationID].auctionId = auctionId;
}
auctions[item][id].length--;
delete _auctionInfo[auctionVerificationID];
//delete onAuctions
uint256 lastIndex = onAuctions[item].length.sub(1);
uint256 index = _onAuctionsIndex[auctionVerificationID];
if (index != lastIndex) {
bytes32 lastAuctionVerificationID = onAuctions[item][lastIndex];
onAuctions[item][index] = lastAuctionVerificationID;
_onAuctionsIndex[lastAuctionVerificationID] = index;
}
onAuctions[item].length--;
delete _onAuctionsIndex[auctionVerificationID];
//delete userAuctionInfo
address seller = auction.seller;
lastIndex = userAuctionInfo[seller].length.sub(1);
index = _userAuctionIndex[auctionVerificationID];
if (index != lastIndex) {
bytes32 lastAuctionVerificationID = userAuctionInfo[seller][lastIndex];
userAuctionInfo[seller][index] = lastAuctionVerificationID;
_userAuctionIndex[lastAuctionVerificationID] = index;
}
userAuctionInfo[seller].length--;
delete _userAuctionIndex[auctionVerificationID];
//delete auctionsOnMetaverse
uint256 metaverseId = auction.metaverseId;
lastIndex = auctionsOnMetaverse[metaverseId].length.sub(1);
index = _auctionsOnMvIndex[auctionVerificationID];
if (index != lastIndex) {
bytes32 lastAuctionVerificationID = auctionsOnMetaverse[metaverseId][lastIndex];
auctionsOnMetaverse[metaverseId][index] = lastAuctionVerificationID;
_auctionsOnMvIndex[lastAuctionVerificationID] = index;
}
auctionsOnMetaverse[metaverseId].length--;
delete _auctionsOnMvIndex[auctionVerificationID];
}
function _distributeReward(
uint256 metaverseId,
address buyer,
address seller,
uint256 price
) private {
(address receiver, uint256 royalty) = metaverses.royalties(metaverseId);
uint256 _fee;
uint256 _royalty;
uint256 _mileage;
if (metaverses.mileageMode(metaverseId)) {
if (metaverses.onlyKlubsMembership(metaverseId)) {
uint256 mileageFromFee = price.mul(mileage.onlyKlubsPercent()).div(1e4);
_fee = price.mul(fee).div(1e4);
if (_fee > mileageFromFee) {
_mileage = mileageFromFee;
_fee = _fee.sub(mileageFromFee);
} else {
_mileage = _fee;
_fee = 0;
}
uint256 mileageFromRoyalty = price.mul(mileage.mileagePercent()).div(1e4).sub(mileageFromFee);
_royalty = price.mul(royalty).div(1e4);
if (_royalty > mileageFromRoyalty) {
_mileage = _mileage.add(mileageFromRoyalty);
_royalty = _royalty.sub(mileageFromRoyalty);
} else {
_mileage = _mileage.add(_royalty);
_royalty = 0;
}
} else {
_fee = price.mul(fee).div(1e4);
_mileage = price.mul(mileage.mileagePercent()).div(1e4);
_royalty = price.mul(royalty).div(1e4);
if (_royalty > _mileage) {
_royalty = _royalty.sub(_mileage);
} else {
_mileage = _royalty;
_royalty = 0;
}
}
} else {
_fee = price.mul(fee).div(1e4);
_royalty = price.mul(royalty).div(1e4);
}
if (_fee > 0) mix.transfer(feeReceiver, _fee);
if (_royalty > 0) mix.transfer(receiver, _royalty);
if (_mileage > 0) {
mix.approve(address(mileage), _mileage);
mileage.charge(buyer, _mileage);
}
mix.transfer(seller, price.sub(_fee).sub(_royalty).sub(_mileage));
}
mapping(address => uint256) public nonce;
//Sale
struct Sale {
address seller;
uint256 metaverseId;
address item;
uint256 id;
uint256 amount;
uint256 unitPrice;
bool partialBuying;
bytes32 verificationID;
}
struct SaleInfo {
address item;
uint256 id;
uint256 saleId;
}
mapping(address => mapping(uint256 => Sale[])) public sales; //sales[item][id].
mapping(bytes32 => SaleInfo) internal _saleInfo; //_saleInfo[saleVerificationID].
mapping(address => bytes32[]) public onSales; //onSales[item]. 아이템 계약 중 onSale 중인 정보들. "return saleVerificationID."
mapping(bytes32 => uint256) private _onSalesIndex; //_onSalesIndex[saleVerificationID]. 특정 세일의 onSales index.
mapping(address => bytes32[]) public userSellInfo; //userSellInfo[seller] 셀러가 팔고있는 세일의 정보. "return saleVerificationID."
mapping(bytes32 => uint256) private _userSellIndex; //_userSellIndex[saleVerificationID]. 특정 세일의 userSellInfo index.
mapping(uint256 => bytes32[]) public salesOnMetaverse; //salesOnMetaverse[metaverseId]. 특정 메타버스에서 판매되고있는 모든 세일들. "return saleVerificationID."
mapping(bytes32 => uint256) private _salesOnMvIndex; //_salesOnMvIndex[saleVerificationID]. 특정 세일의 salesOnMetaverse index.
mapping(address => mapping(address => mapping(uint256 => uint256))) public userOnSaleAmounts; //userOnSaleAmounts[seller][item][id]. 셀러가 판매중인 특정 id의 아이템의 총 합.
function getSaleInfo(bytes32 saleVerificationID)
external
view
returns (
address item,
uint256 id,
uint256 saleId
)
{
SaleInfo memory saleInfo = _saleInfo[saleVerificationID];
require(saleInfo.item != address(0));
return (saleInfo.item, saleInfo.id, saleInfo.saleId);
}
function salesCount(address item, uint256 id) external view returns (uint256) {
return sales[item][id].length;
}
function onSalesCount(address item) external view returns (uint256) {
return onSales[item].length;
}
function userSellInfoLength(address seller) external view returns (uint256) {
return userSellInfo[seller].length;
}
function salesOnMetaverseLength(uint256 metaverseId) external view returns (uint256) {
return salesOnMetaverse[metaverseId].length;
}
function canSell(
address seller,
uint256 metaverseId,
address item,
uint256 id,
uint256 amount
) public view returns (bool) {
if (!isItemWhitelisted(metaverseId, item)) return false;
if (_isERC1155(metaverseId, item)) {
if (amount == 0) return false;
if (userOnSaleAmounts[seller][item][id].add(amount) > IKIP37(item).balanceOf(seller, id)) return false;
return true;
} else {
if (amount != 1) return false;
if (IKIP17(item).ownerOf(id) != seller) return false;
if (userOnSaleAmounts[seller][item][id] != 0) return false;
return true;
}
}
function sell(
uint256[] calldata metaverseIds,
address[] calldata items,
uint256[] calldata ids,
uint256[] calldata amounts,
uint256[] calldata unitPrices,
bool[] calldata partialBuyings
) external userWhitelist(msg.sender) {
require(
metaverseIds.length == items.length &&
metaverseIds.length == ids.length &&
metaverseIds.length == amounts.length &&
metaverseIds.length == unitPrices.length &&
metaverseIds.length == partialBuyings.length
);
for (uint256 i = 0; i < metaverseIds.length; i++) {
uint256 metaverseId = metaverseIds[i];
address item = items[i];
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 unitPrice = unitPrices[i];
bool partialBuying = partialBuyings[i];
require(unitPrice > 0);
require(canSell(msg.sender, metaverseId, item, id, amount));
bytes32 verificationID = keccak256(
abi.encodePacked(msg.sender, metaverseId, item, id, amount, unitPrice, partialBuying, nonce[msg.sender]++)
);
require(_saleInfo[verificationID].item == address(0));
uint256 saleId = sales[item][id].length;
sales[item][id].push(
Sale({
seller: msg.sender,
metaverseId: metaverseId,
item: item,
id: id,
amount: amount,
unitPrice: unitPrice,
partialBuying: partialBuying,
verificationID: verificationID
})
);
_saleInfo[verificationID] = SaleInfo({item: item, id: id, saleId: saleId});
_onSalesIndex[verificationID] = onSales[item].length;
onSales[item].push(verificationID);
_userSellIndex[verificationID] = userSellInfo[msg.sender].length;
userSellInfo[msg.sender].push(verificationID);
_salesOnMvIndex[verificationID] = salesOnMetaverse[metaverseId].length;
salesOnMetaverse[metaverseId].push(verificationID);
userOnSaleAmounts[msg.sender][item][id] = userOnSaleAmounts[msg.sender][item][id].add(amount);
emit Sell(metaverseId, item, id, msg.sender, amount, unitPrice, partialBuying, verificationID);
}
}
function changeSellPrice(bytes32[] calldata saleVerificationIDs, uint256[] calldata unitPrices) external userWhitelist(msg.sender) {
require(saleVerificationIDs.length == unitPrices.length);
for (uint256 i = 0; i < saleVerificationIDs.length; i++) {
SaleInfo storage saleInfo = _saleInfo[saleVerificationIDs[i]];
address item = saleInfo.item;
uint256 id = saleInfo.id;
Sale storage sale = sales[item][id][saleInfo.saleId];
require(sale.seller == msg.sender);
require(sale.unitPrice != unitPrices[i]);
sale.unitPrice = unitPrices[i];
emit ChangeSellPrice(sale.metaverseId, item, id, unitPrices[i], saleVerificationIDs[i]);
}
}
function cancelSale(bytes32[] calldata saleVerificationIDs) external {
for (uint256 i = 0; i < saleVerificationIDs.length; i++) {
SaleInfo storage saleInfo = _saleInfo[saleVerificationIDs[i]];
address item = saleInfo.item;
uint256 id = saleInfo.id;
Sale storage sale = sales[item][id][saleInfo.saleId];
require(sale.seller == msg.sender);
emit CancelSale(sale.metaverseId, item, id, sale.amount, saleVerificationIDs[i]);
_removeSale(saleVerificationIDs[i]);
}
}
function buy(
bytes32[] calldata saleVerificationIDs,
uint256[] calldata amounts,
uint256[] calldata unitPrices,
uint256[] calldata mileages
) external userWhitelist(msg.sender) {
require(amounts.length == saleVerificationIDs.length && amounts.length == unitPrices.length && amounts.length == mileages.length);
for (uint256 i = 0; i < amounts.length; i++) {
bytes32 saleVerificationID = saleVerificationIDs[i];
SaleInfo memory saleInfo = _saleInfo[saleVerificationID];
Sale storage sale = sales[saleInfo.item][saleInfo.id][saleInfo.saleId];
address seller = sale.seller;
uint256 metaverseId = sale.metaverseId;
require(isItemWhitelisted(metaverseId, saleInfo.item));
require(seller != address(0) && seller != msg.sender);
require(sale.unitPrice == unitPrices[i]);
uint256 amount = amounts[i];
uint256 saleAmount = sale.amount;
if (!sale.partialBuying) {
require(saleAmount == amount);
} else {
require(saleAmount >= amount);
}
uint256 amountLeft = saleAmount.sub(amount);
sale.amount = amountLeft;
_itemTransfer(metaverseId, saleInfo.item, saleInfo.id, amount, seller, msg.sender);
uint256 price = amount.mul(unitPrices[i]);
uint256 _mileage = mileages[i];
mix.transferFrom(msg.sender, address(this), price.sub(_mileage));
if (_mileage > 0) mileage.use(msg.sender, _mileage);
_distributeReward(metaverseId, msg.sender, seller, price);
userOnSaleAmounts[msg.sender][saleInfo.item][saleInfo.id] = userOnSaleAmounts[msg.sender][saleInfo.item][saleInfo.id].sub(amount);
bool isFulfilled = false;
if (amountLeft == 0) {
_removeSale(saleVerificationID);
isFulfilled = true;
}
emit Buy(metaverseId, saleInfo.item, saleInfo.id, msg.sender, amount, isFulfilled, saleVerificationID);
}
}
//Offer
struct Offer {
address offeror;
uint256 metaverseId;
address item;
uint256 id;
uint256 amount;
uint256 unitPrice;
bool partialBuying;
uint256 mileage;
bytes32 verificationID;
}
struct OfferInfo {
address item;
uint256 id;
uint256 offerId;
}
mapping(address => mapping(uint256 => Offer[])) public offers; //offers[item][id].
mapping(bytes32 => OfferInfo) internal _offerInfo; //_offerInfo[offerVerificationID].
mapping(address => bytes32[]) public userOfferInfo; //userOfferInfo[offeror] 오퍼러의 오퍼들 정보. "return offerVerificationID."
mapping(bytes32 => uint256) private _userOfferIndex; //_userOfferIndex[offerVerificationID]. 특정 오퍼의 userOfferInfo index.
function getOfferInfo(bytes32 offerVerificationID)
external
view
returns (
address item,
uint256 id,
uint256 offerId
)
{
OfferInfo memory offerInfo = _offerInfo[offerVerificationID];
require(offerInfo.item != address(0));
return (offerInfo.item, offerInfo.id, offerInfo.offerId);
}
function userOfferInfoLength(address offeror) external view returns (uint256) {
return userOfferInfo[offeror].length;
}
function offersCount(address item, uint256 id) external view returns (uint256) {
return offers[item][id].length;
}
function canOffer(
address offeror,
uint256 metaverseId,
address item,
uint256 id,
uint256 amount
) public view returns (bool) {
if (!isItemWhitelisted(metaverseId, item)) return false;
if (_isERC1155(metaverseId, item)) {
if (amount == 0) return false;
return true;
} else {
if (amount != 1) return false;
if (IKIP17(item).ownerOf(id) == offeror) return false;
return true;
}
}
function makeOffer(
uint256 metaverseId,
address item,
uint256 id,
uint256 amount,
uint256 unitPrice,
bool partialBuying,
uint256 _mileage
) external userWhitelist(msg.sender) returns (uint256 offerId) {
require(unitPrice > 0);
require(canOffer(msg.sender, metaverseId, item, id, amount));
bytes32 verificationID = keccak256(
abi.encodePacked(msg.sender, metaverseId, item, id, amount, unitPrice, partialBuying, _mileage, nonce[msg.sender]++)
);
require(_offerInfo[verificationID].item == address(0));
offerId = offers[item][id].length;
offers[item][id].push(
Offer({
offeror: msg.sender,
metaverseId: metaverseId,
item: item,
id: id,
amount: amount,
unitPrice: unitPrice,
partialBuying: partialBuying,
mileage: _mileage,
verificationID: verificationID
})
);
_userOfferIndex[verificationID] = userOfferInfo[msg.sender].length;
userOfferInfo[msg.sender].push(verificationID);
mix.transferFrom(msg.sender, address(this), amount.mul(unitPrice).sub(_mileage));
if (_mileage > 0) mileage.use(msg.sender, _mileage);
emit MakeOffer(metaverseId, item, id, msg.sender, amount, unitPrice, partialBuying, verificationID);
}
function cancelOffer(bytes32 offerVerificationID) external {
OfferInfo storage offerInfo = _offerInfo[offerVerificationID];
address item = offerInfo.item;
uint256 id = offerInfo.id;
Offer storage offer = offers[item][id][offerInfo.offerId];
require(offer.offeror == msg.sender);
uint256 amount = offer.amount;
uint256 _mileage = offer.mileage;
mix.transfer(msg.sender, amount.mul(offer.unitPrice).sub(_mileage));
if (_mileage > 0) {
mix.approve(address(mileage), _mileage);
mileage.charge(msg.sender, _mileage);
}
emit CancelOffer(offer.metaverseId, item, id, amount, offerVerificationID);
_removeOffer(offerVerificationID);
}
function acceptOffer(bytes32 offerVerificationID, uint256 amount) external userWhitelist(msg.sender) {
OfferInfo storage offerInfo = _offerInfo[offerVerificationID];
address item = offerInfo.item;
uint256 id = offerInfo.id;
Offer storage offer = offers[item][id][offerInfo.offerId];
address offeror = offer.offeror;
uint256 metaverseId = offer.metaverseId;
uint256 offerAmount = offer.amount;
require(isItemWhitelisted(metaverseId, item));
require(offeror != address(0) && offeror != msg.sender);
if (!offer.partialBuying) {
require(offerAmount == amount);
} else {
require(offerAmount >= amount);
}
uint256 amountLeft = offerAmount.sub(amount);
offer.amount = amountLeft;
_itemTransfer(metaverseId, item, id, amount, msg.sender, offeror);
uint256 price = amount.mul(offer.unitPrice);
_distributeReward(metaverseId, offeror, msg.sender, price);
bool isFulfilled = false;
if (amountLeft == 0) {
_removeOffer(offerVerificationID);
isFulfilled = true;
}
emit AcceptOffer(metaverseId, item, id, msg.sender, offerAmount, isFulfilled, offerVerificationID);
}
//Auction
struct Auction {
address seller;
uint256 metaverseId;
address item;
uint256 id;
uint256 amount;
uint256 startTotalPrice;
uint256 endBlock;
bytes32 verificationID;
}
struct AuctionInfo {
address item;
uint256 id;
uint256 auctionId;
}
mapping(address => mapping(uint256 => Auction[])) public auctions; //auctions[item][id].
mapping(bytes32 => AuctionInfo) internal _auctionInfo; //_auctionInfo[auctionVerificationID].
mapping(address => bytes32[]) public onAuctions; //onAuctions[item]. 아이템 계약 중 onAuction 중인 정보들. "return auctionsVerificationID."
mapping(bytes32 => uint256) private _onAuctionsIndex; //_onAuctionsIndex[auctionVerificationID]. 특정 옥션의 onAuctions index.
mapping(address => bytes32[]) public userAuctionInfo; //userAuctionInfo[seller] 셀러의 옥션들 정보. "return auctionsVerificationID."
mapping(bytes32 => uint256) private _userAuctionIndex; //_userAuctionIndex[auctionVerificationID]. 특정 옥션의 userAuctionInfo index.
mapping(uint256 => bytes32[]) public auctionsOnMetaverse; //auctionsOnMetaverse[metaverseId]. 특정 메타버스의 모든 옥션들. "return auctionsVerificationID."
mapping(bytes32 => uint256) private _auctionsOnMvIndex; //_auctionsOnMvIndex[auctionVerificationID]. 특정 옥션의 auctionsOnMetaverse index.
function getAuctionInfo(bytes32 auctionVerificationID)
external
view
returns (
address item,
uint256 id,
uint256 auctionId
)
{
AuctionInfo memory auctionInfo = _auctionInfo[auctionVerificationID];
require(auctionInfo.item != address(0));
return (auctionInfo.item, auctionInfo.id, auctionInfo.auctionId);
}
function auctionsCount(address item, uint256 id) external view returns (uint256) {
return auctions[item][id].length;
}
function onAuctionsCount(address item) external view returns (uint256) {
return onAuctions[item].length;
}
function userAuctionInfoLength(address seller) external view returns (uint256) {
return userAuctionInfo[seller].length;
}
function auctionsOnMetaverseLength(uint256 metaverseId) external view returns (uint256) {
return auctionsOnMetaverse[metaverseId].length;
}
function canCreateAuction(
address seller,
uint256 metaverseId,
address item,
uint256 id,
uint256 amount
) public view returns (bool) {
if (!isItemWhitelisted(metaverseId, item)) return false;
if (_isERC1155(metaverseId, item)) {
if (amount == 0) return false;
if (IKIP37(item).balanceOf(seller, id) < amount) return false;
return true;
} else {
if (amount != 1) return false;
if (IKIP17(item).ownerOf(id) != seller) return false;
return true;
}
}
function createAuction(
uint256 metaverseId,
address item,
uint256 id,
uint256 amount,
uint256 startTotalPrice,
uint256 endBlock
) external userWhitelist(msg.sender) returns (uint256 auctionId) {
require(startTotalPrice > 0);
require(endBlock > block.number);
require(canCreateAuction(msg.sender, metaverseId, item, id, amount));
bytes32 verificationID = keccak256(
abi.encodePacked(msg.sender, metaverseId, item, id, amount, startTotalPrice, endBlock, nonce[msg.sender]++)
);
require(_auctionInfo[verificationID].item == address(0));
auctionId = auctions[item][id].length;
auctions[item][id].push(
Auction({
seller: msg.sender,
metaverseId: metaverseId,
item: item,
id: id,
amount: amount,
startTotalPrice: startTotalPrice,
endBlock: endBlock,
verificationID: verificationID
})
);
_auctionInfo[verificationID] = AuctionInfo({item: item, id: id, auctionId: auctionId});
_onAuctionsIndex[verificationID] = onAuctions[item].length;
onAuctions[item].push(verificationID);
_userAuctionIndex[verificationID] = userAuctionInfo[msg.sender].length;
userAuctionInfo[msg.sender].push(verificationID);
_auctionsOnMvIndex[verificationID] = auctionsOnMetaverse[metaverseId].length;
auctionsOnMetaverse[metaverseId].push(verificationID);
_itemTransfer(metaverseId, item, id, amount, msg.sender, address(this));
emit CreateAuction(metaverseId, item, id, msg.sender, amount, startTotalPrice, endBlock, verificationID);
}
function cancelAuction(bytes32 auctionVerificationID) external {
require(biddings[auctionVerificationID].length == 0);
AuctionInfo storage auctionInfo = _auctionInfo[auctionVerificationID];
address item = auctionInfo.item;
uint256 id = auctionInfo.id;
Auction storage auction = auctions[item][id][auctionInfo.auctionId];
require(auction.seller == msg.sender);
uint256 metaverseId = auction.metaverseId;
_itemTransfer(metaverseId, item, id, auction.amount, address(this), msg.sender);
emit CancelAuction(metaverseId, item, id, auctionVerificationID);
_removeAuction(auctionVerificationID);
}
//Bidding
struct Bidding {
address bidder;
uint256 metaverseId;
address item;
uint256 id;
uint256 amount;
uint256 price;
uint256 mileage;
}
struct BiddingInfo {
bytes32 auctionVerificationID;
uint256 biddingId;
}
mapping(bytes32 => Bidding[]) public biddings; //biddings[auctionVerificationID].
mapping(address => BiddingInfo[]) public userBiddingInfo; //userBiddingInfo[bidder] 비더의 비딩들 정보. "return BiddingInfo"
mapping(address => mapping(bytes32 => uint256)) private _userBiddingIndex;
//_userBiddingIndex[bidder][auctionVerificationID]. 특정 유저가 특정 옥션에 최종 입찰 중인 비딩의 userBiddingInfo index.
function userBiddingInfoLength(address bidder) external view returns (uint256) {
return userBiddingInfo[bidder].length;
}
function biddingsCount(bytes32 auctionVerificationID) external view returns (uint256) {
return biddings[auctionVerificationID].length;
}
function canBid(
address bidder,
uint256 price,
bytes32 auctionVerificationID
) public view returns (bool) {
AuctionInfo storage auctionInfo = _auctionInfo[auctionVerificationID];
address item = auctionInfo.item;
if (item == address(0)) return false;
Auction storage auction = auctions[item][auctionInfo.id][auctionInfo.auctionId];
if (!isItemWhitelisted(auction.metaverseId, item)) return false;
address seller = auction.seller;
if (seller == address(0) || seller == bidder) return false;
if (auction.endBlock <= block.number) return false;
Bidding[] storage bs = biddings[auctionVerificationID];
uint256 biddingLength = bs.length;
if (biddingLength == 0) {
if (auction.startTotalPrice > price) return false;
return true;
} else {
if (bs[biddingLength - 1].price >= price) return false;
return true;
}
}
function bid(
bytes32 auctionVerificationID,
uint256 price,
uint256 _mileage
) external userWhitelist(msg.sender) returns (uint256 biddingId) {
require(canBid(msg.sender, price, auctionVerificationID));
AuctionInfo memory auctionInfo = _auctionInfo[auctionVerificationID];
Auction storage auction = auctions[auctionInfo.item][auctionInfo.id][auctionInfo.auctionId];
uint256 metaverseId = auction.metaverseId;
uint256 amount = auction.amount;
Bidding[] storage bs = biddings[auctionVerificationID];
biddingId = bs.length;
if (biddingId > 0) {
Bidding storage lastBidding = bs[biddingId - 1];
address lastBidder = lastBidding.bidder;
uint256 lastMileage = lastBidding.mileage;
mix.transfer(lastBidder, lastBidding.price.sub(lastMileage));
if (lastMileage > 0) {
mix.approve(address(mileage), lastMileage);
mileage.charge(lastBidder, lastMileage);
}
_removeUserBiddingInfo(lastBidder, auctionVerificationID);
}
bs.push(
Bidding({
bidder: msg.sender,
metaverseId: metaverseId,
item: auctionInfo.item,
id: auctionInfo.id,
amount: amount,
price: price,
mileage: _mileage
})
);
_userBiddingIndex[msg.sender][auctionVerificationID] = userBiddingInfo[msg.sender].length;
userBiddingInfo[msg.sender].push(BiddingInfo({auctionVerificationID: auctionVerificationID, biddingId: biddingId}));
mix.transferFrom(msg.sender, address(this), price.sub(_mileage));
if (_mileage > 0) mileage.use(msg.sender, _mileage);
{
//to avoid stack too deep error
uint256 endBlock = auction.endBlock;
if (block.number >= endBlock.sub(auctionExtensionInterval)) {
auction.endBlock = endBlock.add(auctionExtensionInterval);
}
}
emit Bid(metaverseId, auctionInfo.item, auctionInfo.id, msg.sender, amount, price, auctionVerificationID, biddingId);
}
function _removeUserBiddingInfo(address bidder, bytes32 auctionVerificationID) private {
uint256 lastIndex = userBiddingInfo[bidder].length.sub(1);
uint256 index = _userBiddingIndex[bidder][auctionVerificationID];
if (index != lastIndex) {
BiddingInfo memory lastBiddingInfo = userBiddingInfo[bidder][lastIndex];
userBiddingInfo[bidder][index] = lastBiddingInfo;
_userBiddingIndex[bidder][lastBiddingInfo.auctionVerificationID] = index;
}
delete _userBiddingIndex[bidder][auctionVerificationID];
userBiddingInfo[bidder].length--;
}
function claim(bytes32 auctionVerificationID) external {
AuctionInfo storage auctionInfo = _auctionInfo[auctionVerificationID];
address item = auctionInfo.item;
uint256 id = auctionInfo.id;
Auction storage auction = auctions[item][id][auctionInfo.auctionId];
uint256 metaverseId = auction.metaverseId;
uint256 amount = auction.amount;
Bidding[] storage bs = biddings[auctionVerificationID];
uint256 bestBiddingId = bs.length.sub(1);
Bidding storage bestBidding = bs[bestBiddingId];
address bestBidder = bestBidding.bidder;
uint256 bestBiddingPrice = bestBidding.price;
require(block.number >= auction.endBlock);
_itemTransfer(metaverseId, item, id, amount, address(this), bestBidder);
_distributeReward(metaverseId, bestBidder, auction.seller, bestBiddingPrice);
_removeUserBiddingInfo(bestBidder, auctionVerificationID);
delete biddings[auctionVerificationID];
_removeAuction(auctionVerificationID);
emit Claim(metaverseId, item, id, bestBidder, amount, bestBiddingPrice, auctionVerificationID, bestBiddingId);
}
//"cancel" functions with ownership
function cancelSaleByOwner(bytes32[] calldata saleVerificationIDs) external onlyOwner {
for (uint256 i = 0; i < saleVerificationIDs.length; i++) {
SaleInfo storage saleInfo = _saleInfo[saleVerificationIDs[i]];
address item = saleInfo.item;
uint256 id = saleInfo.id;
Sale storage sale = sales[item][id][saleInfo.saleId];
address seller = sale.seller;
require(seller != address(0));
uint256 metaverseId = sale.metaverseId;
emit CancelSale(metaverseId, item, id, sale.amount, saleVerificationIDs[i]);
emit CancelSaleByOwner(metaverseId, item, id, saleVerificationIDs[i]);
_removeSale(saleVerificationIDs[i]);
}
}
function cancelOfferByOwner(bytes32[] calldata offerVerificationIDs) external onlyOwner {
for (uint256 i = 0; i < offerVerificationIDs.length; i++) {
OfferInfo storage offerInfo = _offerInfo[offerVerificationIDs[i]];
address item = offerInfo.item;
uint256 id = offerInfo.id;
Offer storage offer = offers[item][id][offerInfo.offerId];
address offeror = offer.offeror;
require(offeror != address(0));
uint256 amount = offer.amount;
uint256 _mileage = offer.mileage;
mix.transfer(offeror, amount.mul(offer.unitPrice).sub(_mileage));
if (_mileage > 0) {
mix.approve(address(mileage), _mileage);
mileage.charge(offeror, _mileage);
}
uint256 metaverseId = offer.metaverseId;
emit CancelOffer(metaverseId, item, id, amount, offerVerificationIDs[i]);
emit CancelOfferByOwner(metaverseId, item, id, offerVerificationIDs[i]);
_removeOffer(offerVerificationIDs[i]);
}
}
function cancelAuctionByOwner(bytes32[] calldata auctionVerificationIDs) external onlyOwner {
for (uint256 i = 0; i < auctionVerificationIDs.length; i++) {
AuctionInfo storage auctionInfo = _auctionInfo[auctionVerificationIDs[i]];
address item = auctionInfo.item;
uint256 id = auctionInfo.id;
Auction storage auction = auctions[item][id][auctionInfo.auctionId];
Bidding[] storage bs = biddings[auctionVerificationIDs[i]];
uint256 biddingLength = bs.length;
if (biddingLength > 0) {
Bidding storage lastBidding = bs[biddingLength - 1];
address lastBidder = lastBidding.bidder;
uint256 lastMileage = lastBidding.mileage;
mix.transfer(lastBidder, lastBidding.price.sub(lastMileage));
if (lastMileage > 0) {
mix.approve(address(mileage), lastMileage);
mileage.charge(lastBidder, lastMileage);
}
_removeUserBiddingInfo(lastBidder, auctionVerificationIDs[i]);
delete biddings[auctionVerificationIDs[i]];
}
uint256 metaverseId = auction.metaverseId;
_itemTransfer(metaverseId, item, id, auction.amount, address(this), auction.seller);
_removeAuction(auctionVerificationIDs[i]);
emit CancelAuction(metaverseId, item, id, auctionVerificationIDs[i]);
emit CancelAuctionByOwner(metaverseId, item, id, auctionVerificationIDs[i]);
}
}
} | delete userAuctionInfo | address seller = auction.seller;
| 935,131 | [
1,
3733,
729,
37,
4062,
966,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
1758,
29804,
273,
279,
4062,
18,
1786,
749,
31,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.23;
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender)
public view returns (uint256);
function transferFrom(address from, address to, uint256 value)
public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
contract DefaultToken is BasicToken {
string public name;
string public symbol;
uint8 public decimals;
constructor(string _name, string _symbol, uint8 _decimals) public {
name = _name;
symbol = _symbol;
decimals = _decimals;
}
}
// Wings Controller Interface
contract IWingsController {
uint256 public ethRewardPart;
uint256 public tokenRewardPart;
function fitCollectedValueIntoRange(uint256 _totalCollected) public view returns (uint256);
}
contract HasManager {
address public manager;
modifier onlyManager {
require(msg.sender == manager);
_;
}
function transferManager(address _newManager) public onlyManager() {
require(_newManager != address(0));
manager = _newManager;
}
}
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
// Crowdsale contracts interface
contract ICrowdsaleProcessor is Ownable, HasManager {
modifier whenCrowdsaleAlive() {
require(isActive());
_;
}
modifier whenCrowdsaleFailed() {
require(isFailed());
_;
}
modifier whenCrowdsaleSuccessful() {
require(isSuccessful());
_;
}
modifier hasntStopped() {
require(!stopped);
_;
}
modifier hasBeenStopped() {
require(stopped);
_;
}
modifier hasntStarted() {
require(!started);
_;
}
modifier hasBeenStarted() {
require(started);
_;
}
// Minimal acceptable hard cap
uint256 constant public MIN_HARD_CAP = 1 ether;
// Minimal acceptable duration of crowdsale
uint256 constant public MIN_CROWDSALE_TIME = 3 days;
// Maximal acceptable duration of crowdsale
uint256 constant public MAX_CROWDSALE_TIME = 50 days;
// Becomes true when timeframe is assigned
bool public started;
// Becomes true if cancelled by owner
bool public stopped;
// Total collected forecast question currency
uint256 public totalCollected;
// Total collected Ether
uint256 public totalCollectedETH;
// Total amount of project's token sold: must be updated every time tokens has been sold
uint256 public totalSold;
// Crowdsale minimal goal, must be greater or equal to Forecasting min amount
uint256 public minimalGoal;
// Crowdsale hard cap, must be less or equal to Forecasting max amount
uint256 public hardCap;
// Crowdsale duration in seconds.
// Accepted range is MIN_CROWDSALE_TIME..MAX_CROWDSALE_TIME.
uint256 public duration;
// Start timestamp of crowdsale, absolute UTC time
uint256 public startTimestamp;
// End timestamp of crowdsale, absolute UTC time
uint256 public endTimestamp;
// Allows to transfer some ETH into the contract without selling tokens
function deposit() public payable {}
// Returns address of crowdsale token, must be ERC20 compilant
function getToken() public returns(address);
// Transfers ETH rewards amount (if ETH rewards is configured) to Forecasting contract
function mintETHRewards(address _contract, uint256 _amount) public onlyManager();
// Mints token Rewards to Forecasting contract
function mintTokenRewards(address _contract, uint256 _amount) public onlyManager();
// Releases tokens (transfers crowdsale token from mintable to transferrable state)
function releaseTokens() public onlyManager() hasntStopped() whenCrowdsaleSuccessful();
// Stops crowdsale. Called by CrowdsaleController, the latter is called by owner.
// Crowdsale may be stopped any time before it finishes.
function stop() public onlyManager() hasntStopped();
// Validates parameters and starts crowdsale
function start(uint256 _startTimestamp, uint256 _endTimestamp, address _fundingAddress)
public onlyManager() hasntStarted() hasntStopped();
// Is crowdsale failed (completed, but minimal goal wasn't reached)
function isFailed() public constant returns (bool);
// Is crowdsale active (i.e. the token can be sold)
function isActive() public constant returns (bool);
// Is crowdsale completed successfully
function isSuccessful() public constant returns (bool);
}
// Basic crowdsale implementation both for regualt and 3rdparty Crowdsale contracts
contract BasicCrowdsale is ICrowdsaleProcessor {
event CROWDSALE_START(uint256 startTimestamp, uint256 endTimestamp, address fundingAddress);
// Where to transfer collected ETH
address public fundingAddress;
// Ctor.
function BasicCrowdsale(
address _owner,
address _manager
)
public
{
owner = _owner;
manager = _manager;
}
// called by CrowdsaleController to transfer reward part of ETH
// collected by successful crowdsale to Forecasting contract.
// This call is made upon closing successful crowdfunding process
// iff agreed ETH reward part is not zero
function mintETHRewards(
address _contract, // Forecasting contract
uint256 _amount // agreed part of totalCollected which is intended for rewards
)
public
onlyManager() // manager is CrowdsaleController instance
{
require(_contract.call.value(_amount)());
}
// cancels crowdsale
function stop() public onlyManager() hasntStopped() {
// we can stop only not started and not completed crowdsale
if (started) {
require(!isFailed());
require(!isSuccessful());
}
stopped = true;
}
// called by CrowdsaleController to setup start and end time of crowdfunding process
// as well as funding address (where to transfer ETH upon successful crowdsale)
function start(
uint256 _startTimestamp,
uint256 _endTimestamp,
address _fundingAddress
)
public
onlyManager() // manager is CrowdsaleController instance
hasntStarted() // not yet started
hasntStopped() // crowdsale wasn't cancelled
{
require(_fundingAddress != address(0));
// start time must not be earlier than current time
require(_startTimestamp >= block.timestamp);
// range must be sane
require(_endTimestamp > _startTimestamp);
duration = _endTimestamp - _startTimestamp;
// duration must fit constraints
require(duration >= MIN_CROWDSALE_TIME && duration <= MAX_CROWDSALE_TIME);
startTimestamp = _startTimestamp;
endTimestamp = _endTimestamp;
fundingAddress = _fundingAddress;
// now crowdsale is considered started, even if the current time is before startTimestamp
started = true;
CROWDSALE_START(_startTimestamp, _endTimestamp, _fundingAddress);
}
// must return true if crowdsale is over, but it failed
function isFailed()
public
constant
returns(bool)
{
return (
// it was started
started &&
// crowdsale period has finished
block.timestamp >= endTimestamp &&
// but collected ETH is below the required minimum
totalCollected < minimalGoal
);
}
// must return true if crowdsale is active (i.e. the token can be bought)
function isActive()
public
constant
returns(bool)
{
return (
// it was started
started &&
// hard cap wasn't reached yet
totalCollected < hardCap &&
// and current time is within the crowdfunding period
block.timestamp >= startTimestamp &&
block.timestamp < endTimestamp
);
}
// must return true if crowdsale completed successfully
function isSuccessful()
public
constant
returns(bool)
{
return (
// either the hard cap is collected
totalCollected >= hardCap ||
// ...or the crowdfunding period is over, but the minimum has been reached
(block.timestamp >= endTimestamp && totalCollected >= minimalGoal)
);
}
}
/*
Standalone Bridge
*/
contract Bridge is BasicCrowdsale {
using SafeMath for uint256;
event CUSTOM_CROWDSALE_TOKEN_ADDED(address token, uint8 decimals);
event CUSTOM_CROWDSALE_FINISH();
// Crowdsale token must be ERC20-compliant
DefaultToken token;
// Crowdsale state
bool completed;
// Constructor
constructor(
//uint256 _minimalGoal,
//uint256 _hardCap,
//address _token
) public
BasicCrowdsale(msg.sender, msg.sender) // owner, manager
{
minimalGoal = 1;
hardCap = 1;
token = DefaultToken(0x9998Db897783603c9344ED2678AB1B5D73d0f7C3);
}
/*
Here goes ICrowdsaleProcessor methods implementation
*/
// Returns address of crowdsale token
function getToken()
public
returns (address)
{
return address(token);
}
// Mints token Rewards to Forecasting contract
// called by CrowdsaleController
function mintTokenRewards(
address _contract,
uint256 _amount // agreed part of totalSold which is intended for rewards
)
public
onlyManager()
{
// in our example we are transferring tokens instead of minting them
token.transfer(_contract, _amount);
}
function releaseTokens() public onlyManager() hasntStopped() whenCrowdsaleSuccessful() {
}
/*
Crowdsale methods implementation
*/
// Fallback payable function
function() public payable {
}
// Update information about collected ETH and sold tokens amount
function notifySale(uint256 _amount, uint256 _ethAmount, uint256 _tokensAmount)
public
hasBeenStarted()
hasntStopped()
whenCrowdsaleAlive()
onlyOwner()
{
totalCollected = totalCollected.add(_amount);
totalCollectedETH = totalCollectedETH.add(_ethAmount);
totalSold = totalSold.add(_tokensAmount);
}
// Validates parameters and starts crowdsale
// called by CrowdsaleController
function start(
uint256 _startTimestamp,
uint256 _endTimestamp,
address _fundingAddress
)
public
hasntStarted()
hasntStopped()
onlyManager()
{
started = true;
emit CROWDSALE_START(_startTimestamp, _endTimestamp, _fundingAddress);
}
// Finish crowdsale
function finish()
public
hasntStopped()
hasBeenStarted()
whenCrowdsaleAlive()
onlyOwner()
{
completed = true;
emit CUSTOM_CROWDSALE_FINISH();
}
function isFailed()
public
view
returns (bool)
{
return (false);
}
function isActive()
public
view
returns (bool)
{
return (started && !completed);
}
function isSuccessful()
public
view
returns (bool)
{
return (completed);
}
// Find out the amount of rewards in ETH and tokens
function calculateRewards() public view returns (uint256, uint256) {
uint256 tokenRewardPart = IWingsController(manager).tokenRewardPart();
uint256 ethRewardPart = IWingsController(manager).ethRewardPart();
uint256 ethReward;
bool hasEthReward = (ethRewardPart != 0);
uint256 tokenReward = totalSold.mul(tokenRewardPart) / 1000000;
if (totalCollectedETH != 0) {
totalCollected = totalCollectedETH;
}
totalCollected = IWingsController(manager).fitCollectedValueIntoRange(totalCollected);
if (hasEthReward) {
ethReward = totalCollected.mul(ethRewardPart) / 1000000;
}
return (ethReward, tokenReward);
}
// Change token address (in case you've used the dafault token address during bridge deployment)
function changeToken(address _newToken) public onlyOwner() {
token = DefaultToken(_newToken);
emit CUSTOM_CROWDSALE_TOKEN_ADDED(address(token), uint8(token.decimals()));
}
// Gives owner ability to withdraw eth and wings from Bridge contract balance in case if some error during reward calculation occured
function withdraw() public onlyOwner() {
uint256 ethBalance = address(this).balance;
uint256 tokenBalance = token.balanceOf(address(this));
if (ethBalance > 0) {
require(msg.sender.send(ethBalance));
}
if (tokenBalance > 0) {
require(token.transfer(msg.sender, tokenBalance));
}
}
} | Crowdsale minimal goal, must be greater or equal to Forecasting min amount | uint256 public minimalGoal;
| 6,201,688 | [
1,
39,
492,
2377,
5349,
16745,
17683,
16,
1297,
506,
6802,
578,
3959,
358,
17605,
4155,
310,
1131,
3844,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
2254,
5034,
1071,
16745,
27716,
31,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0x7e1e077b289c0153b5ceAD9F264d66215341c9Ab/sources/contracts/plugins/assets/compoundv3/WrappedERC20.sol | * @dev See {IERC20-allowance}./ | function allowance(address owner, address spender)
public
view
virtual
override
returns (uint256)
{
return hasPermission(owner, spender) ? type(uint256).max : 0;
}
| 3,138,301 | [
1,
9704,
288,
45,
654,
39,
3462,
17,
5965,
1359,
5496,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
1699,
1359,
12,
2867,
3410,
16,
1758,
17571,
264,
13,
203,
3639,
1071,
203,
3639,
1476,
203,
3639,
5024,
203,
3639,
3849,
203,
3639,
1135,
261,
11890,
5034,
13,
203,
565,
288,
203,
3639,
327,
26097,
12,
8443,
16,
17571,
264,
13,
692,
618,
12,
11890,
5034,
2934,
1896,
294,
374,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/3/0x7d516621e4b2cb3c0f106db9656D4E832A131454/sources/ShockLinkTest.sol | ------------------------------------------------------------------------ ------------------------------------------------------------------------these addresses won't be affected by burn,ie liquidity pools ------------------------------------------------------------------------ | {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
string constant tokenName = "Shock Link Test";
string constant tokenSymbol = "SLT";
uint8 constant tokenDecimals = 18;
uint256 _totalSupply = 100000 * 18;
address public contractOwner;
uint256 public fullUnitsVested_total = 0;
mapping (address => bool) public isVesting;
uint256 _totalVestRewardsPerUnit = 0;
mapping (address => uint256) private _totalVestRewardsPerUnit_positions;
mapping (address => uint256) private _savedVestRewards;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
bool public migrationActive = true;
mapping(address => bool) public whitelistFrom;
mapping(address => bool) public whitelistTo;
event WhitelistFrom(address _addr, bool _whitelisted);
event WhitelistTo(address _addr, bool _whitelisted);
constructor() public ERC20Detailed(tokenName, tokenSymbol, tokenDecimals)
{
contractOwner = msg.sender;
_mint(msg.sender, 100000 * (10**uint256(tokenDecimals)));
}
modifier onlyOwner() {
require(msg.sender == contractOwner, "only owner");
_;
}
function transferOwnership(address newOwner) public
{
require(msg.sender == contractOwner);
require(newOwner != address(0));
emit OwnershipTransferred(contractOwner, newOwner);
contractOwner = newOwner;
}
function totalSupply() public view returns (uint256)
{
return _totalSupply;
}
function balanceOf(address owner) public view returns (uint256)
{
return _balances[owner];
}
function fullUnitsVested(address owner) external view returns (uint256)
{
return isVesting[owner] ? toFullUnits(_balances[owner]) : 0;
}
function toFullUnits(uint256 valueWithDecimals) public pure returns (uint256)
{
return valueWithDecimals.div(10**uint256(tokenDecimals));
}
function allowance(address owner, address spender) public view returns (uint256)
{
return _allowed[owner][spender];
}
function transfer(address to, uint256 value) public returns (bool)
{
_executeTransfer(msg.sender, to, value);
return true;
}
function transferAndCall(address to, uint value, bytes memory data) public returns (bool)
{
require(transfer(to, value));
require(TransferAndCallFallBack(to).receiveToken(msg.sender, value, address(this), data));
return true;
}
function multiTransfer(address[] memory receivers, uint256[] memory values) public
{
require(receivers.length == values.length);
for(uint256 i = 0; i < receivers.length; i++)
_executeTransfer(msg.sender, receivers[i], values[i]);
}
function transferFrom(address from, address to, uint256 value) public returns (bool)
{
require(value <= _allowed[from][msg.sender]);
_allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value);
_executeTransfer(from, to, value);
return true;
}
function transferFromAndCall(address from, address to, uint value, bytes memory data) public returns (bool)
{
require(transferFrom(from, to, value));
require(TransferAndCallFallBack(to).receiveToken(from, value, address(this), data));
return true;
}
function approve(address spender, uint256 value) public returns (bool)
{
require(spender != address(0));
_allowed[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
function approveAndCall(address spender, uint tokens, bytes memory data) public returns (bool success)
{
require(approve(spender, tokens));
require(ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, address(this), data));
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public returns (bool)
{
require(spender != address(0));
_allowed[msg.sender][spender] = (_allowed[msg.sender][spender].add(addedValue));
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool)
{
require(spender != address(0));
_allowed[msg.sender][spender] = (_allowed[msg.sender][spender].sub(subtractedValue));
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
function _mint(address account, uint256 value) internal
{
require(value != 0);
uint256 initalBalance = _balances[account];
uint256 newBalance = initalBalance.add(value);
_balances[account] = newBalance;
_totalSupply = _totalSupply.add(value);
if(isVesting[account])
{
uint256 fus_total = fullUnitsVested_total;
fus_total = fus_total.sub(toFullUnits(initalBalance));
fus_total = fus_total.add(toFullUnits(newBalance));
fullUnitsVested_total = fus_total;
}
emit Transfer(address(0), account, value);
}
function _mint(address account, uint256 value) internal
{
require(value != 0);
uint256 initalBalance = _balances[account];
uint256 newBalance = initalBalance.add(value);
_balances[account] = newBalance;
_totalSupply = _totalSupply.add(value);
if(isVesting[account])
{
uint256 fus_total = fullUnitsVested_total;
fus_total = fus_total.sub(toFullUnits(initalBalance));
fus_total = fus_total.add(toFullUnits(newBalance));
fullUnitsVested_total = fus_total;
}
emit Transfer(address(0), account, value);
}
function burn(uint256 value) external
{
_burn(msg.sender, value);
}
function burnFrom(address account, uint256 value) external
{
require(value <= _allowed[account][msg.sender]);
_allowed[account][msg.sender] = _allowed[account][msg.sender].sub(value);
_burn(account, value);
}
function _burn(address account, uint256 value) internal
{
require(value != 0);
require(value <= _balances[account]);
uint256 initalBalance = _balances[account];
uint256 newBalance = initalBalance.sub(value);
_balances[account] = newBalance;
_totalSupply = _totalSupply.sub(value);
if(isVesting[account])
{
uint256 fus_total = fullUnitsVested_total;
fus_total = fus_total.sub(toFullUnits(initalBalance));
fus_total = fus_total.add(toFullUnits(newBalance));
fullUnitsVested_total = fus_total;
}
emit Transfer(account, address(0), value);
}
function _burn(address account, uint256 value) internal
{
require(value != 0);
require(value <= _balances[account]);
uint256 initalBalance = _balances[account];
uint256 newBalance = initalBalance.sub(value);
_balances[account] = newBalance;
_totalSupply = _totalSupply.sub(value);
if(isVesting[account])
{
uint256 fus_total = fullUnitsVested_total;
fus_total = fus_total.sub(toFullUnits(initalBalance));
fus_total = fus_total.add(toFullUnits(newBalance));
fullUnitsVested_total = fus_total;
}
emit Transfer(account, address(0), value);
}
function _executeTransfer(address from, address to, uint256 value) private
{
require(value <= _balances[from]);
require(to != address(0) && to != address(this));
updateVestRewardsFor(from);
updateVestRewardsFor(to);
uint256 fourPercent = 0;
if(!whitelistFrom[from] && !whitelistTo[to])
{
fourPercent = value.mul(4).div(100);
if(fourPercent == 0 && value > 0)
fourPercent = 1;
}
uint256 initalBalance_from = _balances[from];
uint256 newBalance_from = initalBalance_from.sub(value);
value = value.sub(fourPercent);
uint256 initalBalance_to = from != to ? _balances[to] : newBalance_from;
uint256 newBalance_to = initalBalance_to.add(value);
_balances[to] = newBalance_to;
emit Transfer(from, to, value);
if(isVesting[from])
{
fus_total = fus_total.sub(toFullUnits(initalBalance_from));
fus_total = fus_total.add(toFullUnits(newBalance_from));
}
if(isVesting[to])
{
fus_total = fus_total.sub(toFullUnits(initalBalance_to));
fus_total = fus_total.add(toFullUnits(newBalance_to));
}
fullUnitsVested_total = fus_total;
uint256 amountToBurn = fourPercent;
if(fus_total > 0)
{
uint256 vestingRewards = fourPercent.div(2);
uint256 vestRewardsPerUnit = vestingRewards.div(fus_total);
_totalVestRewardsPerUnit = _totalVestRewardsPerUnit.add(vestRewardsPerUnit);
_balances[address(this)] = _balances[address(this)].add(vestingRewards);
if(vestingRewards > 0)
emit Transfer(msg.sender, address(this), vestingRewards);
amountToBurn = amountToBurn.sub(vestingRewards);
}
if(amountToBurn > 0)
emit Transfer(msg.sender, address(0), amountToBurn);
}
function _executeTransfer(address from, address to, uint256 value) private
{
require(value <= _balances[from]);
require(to != address(0) && to != address(this));
updateVestRewardsFor(from);
updateVestRewardsFor(to);
uint256 fourPercent = 0;
if(!whitelistFrom[from] && !whitelistTo[to])
{
fourPercent = value.mul(4).div(100);
if(fourPercent == 0 && value > 0)
fourPercent = 1;
}
uint256 initalBalance_from = _balances[from];
uint256 newBalance_from = initalBalance_from.sub(value);
value = value.sub(fourPercent);
uint256 initalBalance_to = from != to ? _balances[to] : newBalance_from;
uint256 newBalance_to = initalBalance_to.add(value);
_balances[to] = newBalance_to;
emit Transfer(from, to, value);
if(isVesting[from])
{
fus_total = fus_total.sub(toFullUnits(initalBalance_from));
fus_total = fus_total.add(toFullUnits(newBalance_from));
}
if(isVesting[to])
{
fus_total = fus_total.sub(toFullUnits(initalBalance_to));
fus_total = fus_total.add(toFullUnits(newBalance_to));
}
fullUnitsVested_total = fus_total;
uint256 amountToBurn = fourPercent;
if(fus_total > 0)
{
uint256 vestingRewards = fourPercent.div(2);
uint256 vestRewardsPerUnit = vestingRewards.div(fus_total);
_totalVestRewardsPerUnit = _totalVestRewardsPerUnit.add(vestRewardsPerUnit);
_balances[address(this)] = _balances[address(this)].add(vestingRewards);
if(vestingRewards > 0)
emit Transfer(msg.sender, address(this), vestingRewards);
amountToBurn = amountToBurn.sub(vestingRewards);
}
if(amountToBurn > 0)
emit Transfer(msg.sender, address(0), amountToBurn);
}
_balances[from] = newBalance_from;
uint256 fus_total = fullUnitsVested_total;
function _executeTransfer(address from, address to, uint256 value) private
{
require(value <= _balances[from]);
require(to != address(0) && to != address(this));
updateVestRewardsFor(from);
updateVestRewardsFor(to);
uint256 fourPercent = 0;
if(!whitelistFrom[from] && !whitelistTo[to])
{
fourPercent = value.mul(4).div(100);
if(fourPercent == 0 && value > 0)
fourPercent = 1;
}
uint256 initalBalance_from = _balances[from];
uint256 newBalance_from = initalBalance_from.sub(value);
value = value.sub(fourPercent);
uint256 initalBalance_to = from != to ? _balances[to] : newBalance_from;
uint256 newBalance_to = initalBalance_to.add(value);
_balances[to] = newBalance_to;
emit Transfer(from, to, value);
if(isVesting[from])
{
fus_total = fus_total.sub(toFullUnits(initalBalance_from));
fus_total = fus_total.add(toFullUnits(newBalance_from));
}
if(isVesting[to])
{
fus_total = fus_total.sub(toFullUnits(initalBalance_to));
fus_total = fus_total.add(toFullUnits(newBalance_to));
}
fullUnitsVested_total = fus_total;
uint256 amountToBurn = fourPercent;
if(fus_total > 0)
{
uint256 vestingRewards = fourPercent.div(2);
uint256 vestRewardsPerUnit = vestingRewards.div(fus_total);
_totalVestRewardsPerUnit = _totalVestRewardsPerUnit.add(vestRewardsPerUnit);
_balances[address(this)] = _balances[address(this)].add(vestingRewards);
if(vestingRewards > 0)
emit Transfer(msg.sender, address(this), vestingRewards);
amountToBurn = amountToBurn.sub(vestingRewards);
}
if(amountToBurn > 0)
emit Transfer(msg.sender, address(0), amountToBurn);
}
function _executeTransfer(address from, address to, uint256 value) private
{
require(value <= _balances[from]);
require(to != address(0) && to != address(this));
updateVestRewardsFor(from);
updateVestRewardsFor(to);
uint256 fourPercent = 0;
if(!whitelistFrom[from] && !whitelistTo[to])
{
fourPercent = value.mul(4).div(100);
if(fourPercent == 0 && value > 0)
fourPercent = 1;
}
uint256 initalBalance_from = _balances[from];
uint256 newBalance_from = initalBalance_from.sub(value);
value = value.sub(fourPercent);
uint256 initalBalance_to = from != to ? _balances[to] : newBalance_from;
uint256 newBalance_to = initalBalance_to.add(value);
_balances[to] = newBalance_to;
emit Transfer(from, to, value);
if(isVesting[from])
{
fus_total = fus_total.sub(toFullUnits(initalBalance_from));
fus_total = fus_total.add(toFullUnits(newBalance_from));
}
if(isVesting[to])
{
fus_total = fus_total.sub(toFullUnits(initalBalance_to));
fus_total = fus_total.add(toFullUnits(newBalance_to));
}
fullUnitsVested_total = fus_total;
uint256 amountToBurn = fourPercent;
if(fus_total > 0)
{
uint256 vestingRewards = fourPercent.div(2);
uint256 vestRewardsPerUnit = vestingRewards.div(fus_total);
_totalVestRewardsPerUnit = _totalVestRewardsPerUnit.add(vestRewardsPerUnit);
_balances[address(this)] = _balances[address(this)].add(vestingRewards);
if(vestingRewards > 0)
emit Transfer(msg.sender, address(this), vestingRewards);
amountToBurn = amountToBurn.sub(vestingRewards);
}
if(amountToBurn > 0)
emit Transfer(msg.sender, address(0), amountToBurn);
}
function _executeTransfer(address from, address to, uint256 value) private
{
require(value <= _balances[from]);
require(to != address(0) && to != address(this));
updateVestRewardsFor(from);
updateVestRewardsFor(to);
uint256 fourPercent = 0;
if(!whitelistFrom[from] && !whitelistTo[to])
{
fourPercent = value.mul(4).div(100);
if(fourPercent == 0 && value > 0)
fourPercent = 1;
}
uint256 initalBalance_from = _balances[from];
uint256 newBalance_from = initalBalance_from.sub(value);
value = value.sub(fourPercent);
uint256 initalBalance_to = from != to ? _balances[to] : newBalance_from;
uint256 newBalance_to = initalBalance_to.add(value);
_balances[to] = newBalance_to;
emit Transfer(from, to, value);
if(isVesting[from])
{
fus_total = fus_total.sub(toFullUnits(initalBalance_from));
fus_total = fus_total.add(toFullUnits(newBalance_from));
}
if(isVesting[to])
{
fus_total = fus_total.sub(toFullUnits(initalBalance_to));
fus_total = fus_total.add(toFullUnits(newBalance_to));
}
fullUnitsVested_total = fus_total;
uint256 amountToBurn = fourPercent;
if(fus_total > 0)
{
uint256 vestingRewards = fourPercent.div(2);
uint256 vestRewardsPerUnit = vestingRewards.div(fus_total);
_totalVestRewardsPerUnit = _totalVestRewardsPerUnit.add(vestRewardsPerUnit);
_balances[address(this)] = _balances[address(this)].add(vestingRewards);
if(vestingRewards > 0)
emit Transfer(msg.sender, address(this), vestingRewards);
amountToBurn = amountToBurn.sub(vestingRewards);
}
if(amountToBurn > 0)
emit Transfer(msg.sender, address(0), amountToBurn);
}
_totalSupply = _totalSupply.sub(amountToBurn);
function updateVestRewardsFor(address vester) private
{
_savedVestRewards[vester] = viewUnpaidVestRewards(vester);
_totalVestRewardsPerUnit_positions[vester] = _totalVestRewardsPerUnit;
}
function viewUnpaidVestRewards(address vester) public view returns (uint256)
{
if(!isVesting[vester])
return _savedVestRewards[vester];
uint256 newVestRewardsPerUnit = _totalVestRewardsPerUnit.sub(_totalVestRewardsPerUnit_positions[vester]);
uint256 newVestRewards = newVestRewardsPerUnit.mul(toFullUnits(_balances[vester]));
return _savedVestRewards[vester].add(newVestRewards);
}
function payoutVestRewards() public
{
updateVestRewardsFor(msg.sender);
uint256 rewardsVest = _savedVestRewards[msg.sender];
require(rewardsVest > 0 && rewardsVest <= _balances[address(this)]);
_savedVestRewards[msg.sender] = 0;
uint256 initalBalance_vester = _balances[msg.sender];
uint256 newBalance_vester = initalBalance_vester.add(rewardsVest);
if(isVesting[msg.sender])
{
uint256 fus_total = fullUnitsVested_total;
fus_total = fus_total.sub(toFullUnits(initalBalance_vester));
fus_total = fus_total.add(toFullUnits(newBalance_vester));
fullUnitsVested_total = fus_total;
}
_balances[msg.sender] = newBalance_vester;
emit Transfer(address(this), msg.sender, rewardsVest);
}
function payoutVestRewards() public
{
updateVestRewardsFor(msg.sender);
uint256 rewardsVest = _savedVestRewards[msg.sender];
require(rewardsVest > 0 && rewardsVest <= _balances[address(this)]);
_savedVestRewards[msg.sender] = 0;
uint256 initalBalance_vester = _balances[msg.sender];
uint256 newBalance_vester = initalBalance_vester.add(rewardsVest);
if(isVesting[msg.sender])
{
uint256 fus_total = fullUnitsVested_total;
fus_total = fus_total.sub(toFullUnits(initalBalance_vester));
fus_total = fus_total.add(toFullUnits(newBalance_vester));
fullUnitsVested_total = fus_total;
}
_balances[msg.sender] = newBalance_vester;
emit Transfer(address(this), msg.sender, rewardsVest);
}
_balances[address(this)] = _balances[address(this)].sub(rewardsVest);
function enableVesting() public { _enableVesting(msg.sender); }
function disableVesting() public { _disableVesting(msg.sender); }
function enableVestingFor(address vester) public onlyOwner { _enableVesting(vester); }
function disableVestingFor(address vester) public onlyOwner { _disableVesting(vester); }
function _enableVesting(address vester) private
{
require(!isVesting[vester]);
updateVestRewardsFor(vester);
isVesting[vester] = true;
fullUnitsVested_total = fullUnitsVested_total.add(toFullUnits(_balances[vester]));
}
function _disableVesting(address vester) private
{
require(isVesting[vester]);
updateVestRewardsFor(vester);
isVesting[vester] = false;
fullUnitsVested_total = fullUnitsVested_total.sub(toFullUnits(_balances[vester]));
}
function withdrawERC20Tokens(address tokenAddress, uint256 amount) public onlyOwner
{
require(tokenAddress != address(this));
IERC20(tokenAddress).transfer(msg.sender, amount);
}
function setWhitelistedTo(address _addr, bool _whitelisted) external onlyOwner {
emit WhitelistTo(_addr, _whitelisted);
whitelistTo[_addr] = _whitelisted;
}
function setWhitelistedFrom(address _addr, bool _whitelisted) external onlyOwner {
emit WhitelistFrom(_addr, _whitelisted);
whitelistFrom[_addr] = _whitelisted;
}
function multiMigrateBalance(address[] memory receivers, uint256[] memory values) public
{
require(receivers.length == values.length);
for(uint256 i = 0; i < receivers.length; i++)
migrateBalance(receivers[i], values[i]);
}
function migrateBalance(address account, uint256 amount) public onlyOwner
{
require(migrationActive);
_mint(account, amount);
}
function endMigration() public onlyOwner
{
migrationActive = false;
}
} | 5,075,004 | [
1,
29461,
8879,
17082,
451,
3392,
6138,
8462,
1404,
506,
9844,
635,
18305,
16,
1385,
4501,
372,
24237,
16000,
8879,
17082,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
95,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
377,
203,
565,
2874,
261,
2867,
516,
2254,
5034,
13,
3238,
389,
70,
26488,
31,
203,
565,
2874,
261,
2867,
516,
2874,
261,
2867,
516,
2254,
5034,
3719,
3238,
389,
8151,
31,
203,
377,
203,
565,
533,
5381,
1147,
461,
273,
315,
1555,
975,
4048,
7766,
14432,
203,
565,
533,
5381,
1147,
5335,
273,
315,
4559,
56,
14432,
7010,
565,
2254,
28,
225,
5381,
1147,
31809,
273,
6549,
31,
203,
565,
2254,
5034,
389,
4963,
3088,
1283,
273,
25259,
380,
6549,
31,
203,
377,
203,
21281,
565,
1758,
1071,
6835,
5541,
31,
203,
203,
565,
2254,
5034,
1071,
1983,
7537,
58,
3149,
67,
4963,
273,
374,
31,
203,
565,
2874,
261,
2867,
516,
1426,
13,
1071,
353,
58,
10100,
31,
203,
203,
565,
2254,
5034,
389,
4963,
58,
395,
17631,
14727,
2173,
2802,
273,
374,
31,
203,
565,
2874,
261,
2867,
516,
2254,
5034,
13,
3238,
389,
4963,
58,
395,
17631,
14727,
2173,
2802,
67,
12388,
31,
203,
565,
2874,
261,
2867,
516,
2254,
5034,
13,
3238,
389,
14077,
58,
395,
17631,
14727,
31,
203,
377,
203,
565,
871,
14223,
9646,
5310,
1429,
4193,
12,
2867,
8808,
2416,
5541,
16,
1758,
8808,
394,
5541,
1769,
203,
377,
203,
377,
203,
565,
1426,
1071,
6333,
3896,
273,
638,
31,
203,
377,
203,
565,
2874,
12,
2867,
516,
1426,
13,
1071,
10734,
1265,
31,
203,
565,
2874,
12,
2867,
516,
1426,
13,
1071,
10734,
774,
31,
203,
565,
871,
3497,
7523,
1265,
12,
2867,
389,
2
] |
/*
Copyright 2017 Loopring Project Ltd (Loopring Foundation).
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.4.24;
pragma experimental "v0.5.0";
pragma experimental "ABIEncoderV2";
import "./AddressUtil.sol";
import "./ERC20.sol";
import "./MathUint.sol";
/// @title ERC20 Token Implementation
/// @dev see https://github.com/ethereum/EIPs/issues/20
/// @author Daniel Wang - <[email protected]>
contract ERC20Token is ERC20 {
using MathUint for uint;
string public name;
string public symbol;
uint8 public decimals;
uint public totalSupply_;
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) internal allowed;
event Transfer(
address indexed from,
address indexed to,
uint256 value
);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
constructor(
string _name,
string _symbol,
uint8 _decimals,
uint _totalSupply,
address _firstHolder
)
public
{
require(_totalSupply > 0);
require(_firstHolder != 0x0);
checkSymbolAndName(_symbol,_name);
name = _name;
symbol = _symbol;
decimals = _decimals;
totalSupply_ = _totalSupply;
balances[_firstHolder] = totalSupply_;
}
function ()
payable
external
{
revert();
}
/**
* @dev total number of tokens in existence
*/
function totalSupply()
public
view
returns (uint256)
{
return totalSupply_;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(
address _to,
uint256 _value
)
public
returns (bool)
{
require(_to != address(0));
require(_value <= balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(
address _owner
)
public
view
returns (uint256 balance)
{
return balances[_owner];
}
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool)
{
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(
address _spender,
uint256 _value
)
public
returns (bool)
{
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(
address _spender,
uint _addedValue
)
public
returns (bool)
{
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(
address _spender,
uint _subtractedValue
)
public
returns (bool)
{
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
// Make sure symbol has 3-8 chars in [A-Za-z._] and name has up to 128 chars.
function checkSymbolAndName(
string memory _symbol,
string memory _name
)
internal
pure
{
bytes memory s = bytes(_symbol);
require(s.length >= 3 && s.length <= 8);
for (uint i = 0; i < s.length; i++) {
// make sure symbol contains only [A-Za-z._]
require(
s[i] == 0x2E || (
s[i] == 0x5F) || (
s[i] >= 0x41 && s[i] <= 0x5A) || (
s[i] >= 0x61 && s[i] <= 0x7A)
);
}
bytes memory n = bytes(_name);
require(n.length >= s.length && n.length <= 128);
for (uint i = 0; i < n.length; i++) {
require(n[i] >= 0x20 && n[i] <= 0x7E);
}
}
}
| * @dev Increase the amount of tokens that an owner allowed to a spender. approve should be called when allowed[_spender] == 0. To increment allowed value is better to use this function to avoid 2 calls (and wait until the first transaction is mined) From MonolithDAO Token.sol @param _spender The address which will spend the funds. @param _addedValue The amount of tokens to increase the allowance by./ | function increaseApproval(
address _spender,
uint _addedValue
)
public
returns (bool)
{
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
| 7,271,776 | [
1,
382,
11908,
326,
3844,
434,
2430,
716,
392,
3410,
2935,
358,
279,
17571,
264,
18,
6617,
537,
1410,
506,
2566,
1347,
2935,
63,
67,
87,
1302,
264,
65,
422,
374,
18,
2974,
5504,
2935,
460,
353,
7844,
358,
999,
333,
445,
358,
4543,
576,
4097,
261,
464,
2529,
3180,
326,
1122,
2492,
353,
1131,
329,
13,
6338,
9041,
355,
483,
18485,
3155,
18,
18281,
225,
389,
87,
1302,
264,
1021,
1758,
1492,
903,
17571,
326,
284,
19156,
18,
225,
389,
9665,
620,
1021,
3844,
434,
2430,
358,
10929,
326,
1699,
1359,
635,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
10929,
23461,
12,
203,
3639,
1758,
389,
87,
1302,
264,
16,
203,
3639,
2254,
389,
9665,
620,
203,
3639,
262,
203,
3639,
1071,
203,
3639,
1135,
261,
6430,
13,
203,
565,
288,
203,
3639,
2935,
63,
3576,
18,
15330,
6362,
67,
87,
1302,
264,
65,
273,
2935,
63,
3576,
18,
15330,
6362,
67,
87,
1302,
264,
8009,
1289,
24899,
9665,
620,
1769,
203,
3639,
3626,
1716,
685,
1125,
12,
3576,
18,
15330,
16,
389,
87,
1302,
264,
16,
2935,
63,
3576,
18,
15330,
6362,
67,
87,
1302,
264,
19226,
203,
3639,
327,
638,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0x5BeC63131bDb80a17F94E29926Eef09353C5D03a/sources/Crowdsale.sol | add contribution to the purchaser | contributions[purchaser] = contributions[purchaser].add(value);
| 9,231,839 | [
1,
1289,
24880,
358,
326,
5405,
343,
14558,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
13608,
6170,
63,
12688,
343,
14558,
65,
273,
13608,
6170,
63,
12688,
343,
14558,
8009,
1289,
12,
1132,
1769,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity 0.4.18;
/// @title Ownable
/// @dev The Ownable contract has an owner address, and provides basic authorization control functions,
/// this simplifies the implementation of "user permissions".
/// @dev Based on OpenZeppelin's Ownable.
contract Ownable {
address public owner;
address public newOwnerCandidate;
event OwnershipRequested(address indexed _by, address indexed _to);
event OwnershipTransferred(address indexed _from, address indexed _to);
/// @dev Constructor sets the original `owner` of the contract to the sender account.
function Ownable() public {
owner = msg.sender;
}
/// @dev Reverts if called by any account other than the owner.
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
modifier onlyOwnerCandidate() {
require(msg.sender == newOwnerCandidate);
_;
}
/// @dev Proposes to transfer control of the contract to a newOwnerCandidate.
/// @param _newOwnerCandidate address The address to transfer ownership to.
function requestOwnershipTransfer(address _newOwnerCandidate) external onlyOwner {
require(_newOwnerCandidate != address(0));
newOwnerCandidate = _newOwnerCandidate;
OwnershipRequested(msg.sender, newOwnerCandidate);
}
/// @dev Accept ownership transfer. This method needs to be called by the perviously proposed owner.
function acceptOwnership() external onlyOwnerCandidate {
address previousOwner = owner;
owner = newOwnerCandidate;
newOwnerCandidate = address(0);
OwnershipTransferred(previousOwner, owner);
}
}
/// @title Math operations with safety checks
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
require(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// require(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// require(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
function max64(uint64 a, uint64 b) internal pure returns (uint64) {
return a >= b ? a : b;
}
function min64(uint64 a, uint64 b) internal pure returns (uint64) {
return a < b ? a : b;
}
function max256(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
function min256(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
function toPower2(uint256 a) internal pure returns (uint256) {
return mul(a, a);
}
function sqrt(uint256 a) internal pure returns (uint256) {
uint256 c = (a + 1) / 2;
uint256 b = a;
while (c < b) {
b = c;
c = (a / c + c) / 2;
}
return b;
}
}
/// @title ERC Token Standard #20 Interface (https://github.com/ethereum/EIPs/issues/20)
contract ERC20 {
uint public totalSupply;
function balanceOf(address _owner) constant public returns (uint balance);
function transfer(address _to, uint _value) public returns (bool success);
function transferFrom(address _from, address _to, uint _value) public returns (bool success);
function approve(address _spender, uint _value) public returns (bool success);
function allowance(address _owner, address _spender) public constant returns (uint remaining);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
/// @title ERC Token Standard #677 Interface (https://github.com/ethereum/EIPs/issues/677)
contract ERC677 is ERC20 {
function transferAndCall(address to, uint value, bytes data) public returns (bool ok);
event TransferAndCall(address indexed from, address indexed to, uint value, bytes data);
}
/// @title ERC223Receiver Interface
/// @dev Based on the specs form: https://github.com/ethereum/EIPs/issues/223
contract ERC223Receiver {
function tokenFallback(address _sender, uint _value, bytes _data) external returns (bool ok);
}
/// @title Basic ERC20 token contract implementation.
/// @dev Based on OpenZeppelin's StandardToken.
contract BasicToken is ERC20 {
using SafeMath for uint256;
uint256 public totalSupply;
mapping (address => mapping (address => uint256)) allowed;
mapping (address => uint256) balances;
event Approval(address indexed owner, address indexed spender, uint256 value);
event Transfer(address indexed from, address indexed to, uint256 value);
/// @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
/// @param _spender address The address which will spend the funds.
/// @param _value uint256 The amount of tokens to be spent.
function approve(address _spender, uint256 _value) public returns (bool) {
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#approve (see NOTE)
if ((_value != 0) && (allowed[msg.sender][_spender] != 0)) {
revert();
}
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/// @dev Function to check the amount of tokens that an owner allowed to a spender.
/// @param _owner address The address which owns the funds.
/// @param _spender address The address which will spend the funds.
/// @return uint256 specifying the amount of tokens still available for the spender.
function allowance(address _owner, address _spender) constant public returns (uint256 remaining) {
return allowed[_owner][_spender];
}
/// @dev Gets the balance of the specified address.
/// @param _owner address The address to query the the balance of.
/// @return uint256 representing the amount owned by the passed address.
function balanceOf(address _owner) constant public returns (uint256 balance) {
return balances[_owner];
}
/// @dev Transfer token to a specified address.
/// @param _to address The address to transfer to.
/// @param _value uint256 The amount to be transferred.
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/// @dev Transfer tokens from one address to another.
/// @param _from address The address which you want to send tokens from.
/// @param _to address The address which you want to transfer to.
/// @param _value uint256 the amount of tokens to be transferred.
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
var _allowance = allowed[_from][msg.sender];
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
Transfer(_from, _to, _value);
return true;
}
}
/// @title Standard677Token implentation, base on https://github.com/ethereum/EIPs/issues/677
contract Standard677Token is ERC677, BasicToken {
/// @dev ERC223 safe token transfer from one address to another
/// @param _to address the address which you want to transfer to.
/// @param _value uint256 the amount of tokens to be transferred.
/// @param _data bytes data that can be attached to the token transation
function transferAndCall(address _to, uint _value, bytes _data) public returns (bool) {
require(super.transfer(_to, _value)); // do a normal token transfer
TransferAndCall(msg.sender, _to, _value, _data);
//filtering if the target is a contract with bytecode inside it
if (isContract(_to)) return contractFallback(_to, _value, _data);
return true;
}
/// @dev called when transaction target is a contract
/// @param _to address the address which you want to transfer to.
/// @param _value uint256 the amount of tokens to be transferred.
/// @param _data bytes data that can be attached to the token transation
function contractFallback(address _to, uint _value, bytes _data) private returns (bool) {
ERC223Receiver receiver = ERC223Receiver(_to);
require(receiver.tokenFallback(msg.sender, _value, _data));
return true;
}
/// @dev check if the address is contract
/// assemble the given address bytecode. If bytecode exists then the _addr is a contract.
/// @param _addr address the address to check
function isContract(address _addr) private constant returns (bool is_contract) {
// retrieve the size of the code on target address, this needs assembly
uint length;
assembly { length := extcodesize(_addr) }
return length > 0;
}
}
/// @title Token holder contract.
contract TokenHolder is Ownable {
/// @dev Allow the owner to transfer out any accidentally sent ERC20 tokens.
/// @param _tokenAddress address The address of the ERC20 contract.
/// @param _amount uint256 The amount of tokens to be transferred.
function transferAnyERC20Token(address _tokenAddress, uint256 _amount) public onlyOwner returns (bool success) {
return ERC20(_tokenAddress).transfer(owner, _amount);
}
}
/// @title Colu Local Network contract.
/// @author Tal Beja.
contract ColuLocalNetwork is Ownable, Standard677Token, TokenHolder {
using SafeMath for uint256;
string public constant name = "Colu Local Network";
string public constant symbol = "CLN";
// Using same decimals value as ETH (makes ETH-CLN conversion much easier).
uint8 public constant decimals = 18;
// States whether token transfers is allowed or not.
// Used during token sale.
bool public isTransferable = false;
event TokensTransferable();
modifier transferable() {
require(msg.sender == owner || isTransferable);
_;
}
/// @dev Creates all tokens and gives them to the owner.
function ColuLocalNetwork(uint256 _totalSupply) public {
totalSupply = _totalSupply;
balances[msg.sender] = totalSupply;
}
/// @dev start transferable mode.
function makeTokensTransferable() external onlyOwner {
if (isTransferable) {
return;
}
isTransferable = true;
TokensTransferable();
}
/// @dev Same ERC20 behavior, but reverts if not transferable.
/// @param _spender address The address which will spend the funds.
/// @param _value uint256 The amount of tokens to be spent.
function approve(address _spender, uint256 _value) public transferable returns (bool) {
return super.approve(_spender, _value);
}
/// @dev Same ERC20 behavior, but reverts if not transferable.
/// @param _to address The address to transfer to.
/// @param _value uint256 The amount to be transferred.
function transfer(address _to, uint256 _value) public transferable returns (bool) {
return super.transfer(_to, _value);
}
/// @dev Same ERC20 behavior, but reverts if not transferable.
/// @param _from address The address to send tokens from.
/// @param _to address The address to transfer to.
/// @param _value uint256 the amount of tokens to be transferred.
function transferFrom(address _from, address _to, uint256 _value) public transferable returns (bool) {
return super.transferFrom(_from, _to, _value);
}
/// @dev Same ERC677 behavior, but reverts if not transferable.
/// @param _to address The address to transfer to.
/// @param _value uint256 The amount to be transferred.
/// @param _data bytes data to send to receiver if it is a contract.
function transferAndCall(address _to, uint _value, bytes _data) public transferable returns (bool success) {
return super.transferAndCall(_to, _value, _data);
}
}
/// @title Standard ERC223 Token Receiver implementing tokenFallback function and tokenPayable modifier
contract Standard223Receiver is ERC223Receiver {
Tkn tkn;
struct Tkn {
address addr;
address sender; // the transaction caller
uint256 value;
}
bool __isTokenFallback;
modifier tokenPayable {
require(__isTokenFallback);
_;
}
/// @dev Called when the receiver of transfer is contract
/// @param _sender address the address of tokens sender
/// @param _value uint256 the amount of tokens to be transferred.
/// @param _data bytes data that can be attached to the token transation
function tokenFallback(address _sender, uint _value, bytes _data) external returns (bool ok) {
if (!supportsToken(msg.sender)) {
return false;
}
// Problem: This will do a sstore which is expensive gas wise. Find a way to keep it in memory.
// Solution: Remove the the data
tkn = Tkn(msg.sender, _sender, _value);
__isTokenFallback = true;
if (!address(this).delegatecall(_data)) {
__isTokenFallback = false;
return false;
}
// avoid doing an overwrite to .token, which would be more expensive
// makes accessing .tkn values outside tokenPayable functions unsafe
__isTokenFallback = false;
return true;
}
function supportsToken(address token) public constant returns (bool);
}
/// @title TokenOwnable
/// @dev The TokenOwnable contract adds a onlyTokenOwner modifier as a tokenReceiver with ownable addaptation
contract TokenOwnable is Standard223Receiver, Ownable {
/// @dev Reverts if called by any account other than the owner for token sending.
modifier onlyTokenOwner() {
require(tkn.sender == owner);
_;
}
}
/// @title Vesting trustee contract for Colu Local Network.
/// @dev This Contract can't be TokenHolder, since it will allow its owner to drain its vested tokens.
/// @dev This means that any token sent to it different than ColuLocalNetwork is basicly stucked here forever.
/// @dev ColuLocalNetwork that sent here (by mistake) can withdrawn using the grant method.
contract VestingTrustee is TokenOwnable {
using SafeMath for uint256;
// Colu Local Network contract.
ColuLocalNetwork public cln;
// Vesting grant for a speicifc holder.
struct Grant {
uint256 value;
uint256 start;
uint256 cliff;
uint256 end;
uint256 installmentLength; // In seconds.
uint256 transferred;
bool revokable;
}
// Holder to grant information mapping.
mapping (address => Grant) public grants;
// Total tokens vested.
uint256 public totalVesting;
event NewGrant(address indexed _from, address indexed _to, uint256 _value);
event TokensUnlocked(address indexed _to, uint256 _value);
event GrantRevoked(address indexed _holder, uint256 _refund);
uint constant OK = 1;
uint constant ERR_INVALID_VALUE = 10001;
uint constant ERR_INVALID_VESTED = 10002;
uint constant ERR_INVALID_TRANSFERABLE = 10003;
event Error(address indexed sender, uint error);
/// @dev Constructor that initializes the address of the Colu Local Network contract.
/// @param _cln ColuLocalNetwork The address of the previously deployed Colu Local Network contract.
function VestingTrustee(ColuLocalNetwork _cln) public {
require(_cln != address(0));
cln = _cln;
}
/// @dev Allow only cln token to be tokenPayable
/// @param token the token to check
function supportsToken(address token) public constant returns (bool) {
return (cln == token);
}
/// @dev Grant tokens to a specified address.
/// @param _to address The holder address.
/// @param _start uint256 The beginning of the vesting period (timestamp).
/// @param _cliff uint256 When the first installment is made (timestamp).
/// @param _end uint256 The end of the vesting period (timestamp).
/// @param _installmentLength uint256 The length of each vesting installment (in seconds).
/// @param _revokable bool Whether the grant is revokable or not.
function grant(address _to, uint256 _start, uint256 _cliff, uint256 _end,
uint256 _installmentLength, bool _revokable)
external onlyTokenOwner tokenPayable {
require(_to != address(0));
require(_to != address(this)); // Protect this contract from receiving a grant.
uint256 value = tkn.value;
require(value > 0);
// Require that every holder can be granted tokens only once.
require(grants[_to].value == 0);
// Require for time ranges to be consistent and valid.
require(_start <= _cliff && _cliff <= _end);
// Require installment length to be valid and no longer than (end - start).
require(_installmentLength > 0 && _installmentLength <= _end.sub(_start));
// Grant must not exceed the total amount of tokens currently available for vesting.
require(totalVesting.add(value) <= cln.balanceOf(address(this)));
// Assign a new grant.
grants[_to] = Grant({
value: value,
start: _start,
cliff: _cliff,
end: _end,
installmentLength: _installmentLength,
transferred: 0,
revokable: _revokable
});
// Since tokens have been granted, increase the total amount vested.
totalVesting = totalVesting.add(value);
NewGrant(msg.sender, _to, value);
}
/// @dev Grant tokens to a specified address.
/// @param _to address The holder address.
/// @param _value uint256 The amount of tokens to be granted.
/// @param _start uint256 The beginning of the vesting period (timestamp).
/// @param _cliff uint256 When the first installment is made (timestamp).
/// @param _end uint256 The end of the vesting period (timestamp).
/// @param _installmentLength uint256 The length of each vesting installment (in seconds).
/// @param _revokable bool Whether the grant is revokable or not.
function grant(address _to, uint256 _value, uint256 _start, uint256 _cliff, uint256 _end,
uint256 _installmentLength, bool _revokable)
external onlyOwner {
require(_to != address(0));
require(_to != address(this)); // Protect this contract from receiving a grant.
require(_value > 0);
// Require that every holder can be granted tokens only once.
require(grants[_to].value == 0);
// Require for time ranges to be consistent and valid.
require(_start <= _cliff && _cliff <= _end);
// Require installment length to be valid and no longer than (end - start).
require(_installmentLength > 0 && _installmentLength <= _end.sub(_start));
// Grant must not exceed the total amount of tokens currently available for vesting.
require(totalVesting.add(_value) <= cln.balanceOf(address(this)));
// Assign a new grant.
grants[_to] = Grant({
value: _value,
start: _start,
cliff: _cliff,
end: _end,
installmentLength: _installmentLength,
transferred: 0,
revokable: _revokable
});
// Since tokens have been granted, increase the total amount vested.
totalVesting = totalVesting.add(_value);
NewGrant(msg.sender, _to, _value);
}
/// @dev Revoke the grant of tokens of a specifed address.
/// @dev Unlocked tokens will be sent to the grantee, the rest is transferred to the trustee's owner.
/// @param _holder The address which will have its tokens revoked.
function revoke(address _holder) public onlyOwner {
Grant memory grant = grants[_holder];
// Grant must be revokable.
require(grant.revokable);
// Get the total amount of vested tokens, acccording to grant.
uint256 vested = calculateVestedTokens(grant, now);
// Calculate the untransferred vested tokens.
uint256 transferable = vested.sub(grant.transferred);
if (transferable > 0) {
// Update transferred and total vesting amount, then transfer remaining vested funds to holder.
grant.transferred = grant.transferred.add(transferable);
totalVesting = totalVesting.sub(transferable);
require(cln.transfer(_holder, transferable));
TokensUnlocked(_holder, transferable);
}
// Calculate amount of remaining tokens that can still be returned.
uint256 refund = grant.value.sub(grant.transferred);
// Remove the grant.
delete grants[_holder];
// Update total vesting amount and transfer previously calculated tokens to owner.
totalVesting = totalVesting.sub(refund);
require(cln.transfer(msg.sender, refund));
GrantRevoked(_holder, refund);
}
/// @dev Calculate the amount of ready tokens of a holder.
/// @param _holder address The address of the holder.
/// @return a uint256 Representing a holder's total amount of vested tokens.
function readyTokens(address _holder) public constant returns (uint256) {
Grant memory grant = grants[_holder];
if (grant.value == 0) {
return 0;
}
uint256 vested = calculateVestedTokens(grant, now);
if (vested == 0) {
return 0;
}
return vested.sub(grant.transferred);
}
/// @dev Calculate the total amount of vested tokens of a holder at a given time.
/// @param _holder address The address of the holder.
/// @param _time uint256 The specific time to calculate against.
/// @return a uint256 Representing a holder's total amount of vested tokens.
function vestedTokens(address _holder, uint256 _time) public constant returns (uint256) {
Grant memory grant = grants[_holder];
if (grant.value == 0) {
return 0;
}
return calculateVestedTokens(grant, _time);
}
/// @dev Calculate amount of vested tokens at a specifc time.
/// @param _grant Grant The vesting grant.
/// @param _time uint256 The time to be checked
/// @return An uint256 Representing the amount of vested tokens of a specific grant.
function calculateVestedTokens(Grant _grant, uint256 _time) private pure returns (uint256) {
// If we're before the cliff, then nothing is vested.
if (_time < _grant.cliff) {
return 0;
}
// If we're after the end of the vesting period - everything is vested.
if (_time >= _grant.end) {
return _grant.value;
}
// Calculate amount of installments past until now.
//
// NOTE: result gets floored because of integer division.
uint256 installmentsPast = _time.sub(_grant.start).div(_grant.installmentLength);
// Calculate amount of days in entire vesting period.
uint256 vestingDays = _grant.end.sub(_grant.start);
// Calculate and return the number of tokens according to vesting days that have passed.
return _grant.value.mul(installmentsPast.mul(_grant.installmentLength)).div(vestingDays);
}
/// @dev Unlock vested tokens and transfer them to the grantee.
/// @return a uint The success or error code.
function unlockVestedTokens() external returns (uint) {
return unlockVestedTokens(msg.sender);
}
/// @dev Unlock vested tokens and transfer them to the grantee (helper function).
/// @param _grantee address The address of the grantee.
/// @return a uint The success or error code.
function unlockVestedTokens(address _grantee) private returns (uint) {
Grant storage grant = grants[_grantee];
// Make sure the grant has tokens available.
if (grant.value == 0) {
Error(_grantee, ERR_INVALID_VALUE);
return ERR_INVALID_VALUE;
}
// Get the total amount of vested tokens, acccording to grant.
uint256 vested = calculateVestedTokens(grant, now);
if (vested == 0) {
Error(_grantee, ERR_INVALID_VESTED);
return ERR_INVALID_VESTED;
}
// Make sure the holder doesn't transfer more than what he already has.
uint256 transferable = vested.sub(grant.transferred);
if (transferable == 0) {
Error(_grantee, ERR_INVALID_TRANSFERABLE);
return ERR_INVALID_TRANSFERABLE;
}
// Update transferred and total vesting amount, then transfer remaining vested funds to holder.
grant.transferred = grant.transferred.add(transferable);
totalVesting = totalVesting.sub(transferable);
require(cln.transfer(_grantee, transferable));
TokensUnlocked(_grantee, transferable);
return OK;
}
/// @dev batchUnlockVestedTokens vested tokens and transfer them to the grantees.
/// @param _grantees address[] The addresses of the grantees.
/// @return a boo if success.
function batchUnlockVestedTokens(address[] _grantees) external onlyOwner returns (bool success) {
for (uint i = 0; i<_grantees.length; i++) {
unlockVestedTokens(_grantees[i]);
}
return true;
}
/// @dev Allow the owner to transfer out any accidentally sent ERC20 tokens.
/// @param _tokenAddress address The address of the ERC20 contract.
/// @param _amount uint256 The amount of tokens to be transferred.
function withdrawERC20(address _tokenAddress, uint256 _amount) public onlyOwner returns (bool success) {
if (_tokenAddress == address(cln)) {
// If the token is cln, allow to withdraw only non vested tokens.
uint256 availableCLN = cln.balanceOf(this).sub(totalVesting);
require(_amount <= availableCLN);
}
return ERC20(_tokenAddress).transfer(owner, _amount);
}
}
/// @title Colu Local Network sale contract.
/// @author Tal Beja.
contract ColuLocalNetworkSale is Ownable, TokenHolder {
using SafeMath for uint256;
// External parties:
// Colu Local Network contract.
ColuLocalNetwork public cln;
// Vesting contract for presale participants.
VestingTrustee public trustee;
// Received funds are forwarded to this address.
address public fundingRecipient;
// Post-TDE multisig addresses.
address public communityPoolAddress;
address public futureDevelopmentPoolAddress;
address public stakeholdersPoolAddress;
// Colu Local Network decimals.
// Using same decimals value as ETH (makes ETH-CLN conversion much easier).
// This is the same as in Colu Local Network contract.
uint256 public constant TOKEN_DECIMALS = 10 ** 18;
// Additional Lockup Allocation Pool
uint256 public constant ALAP = 40701333592592592592614116;
// Maximum number of tokens in circulation: 1.5 trillion.
uint256 public constant MAX_TOKENS = 15 * 10 ** 8 * TOKEN_DECIMALS + ALAP;
// Maximum tokens offered in the sale (35%) + ALAP.
uint256 public constant MAX_TOKENS_SOLD = 525 * 10 ** 6 * TOKEN_DECIMALS + ALAP;
// Maximum tokens offered in the presale (from the initial 35% offered tokens) + ALAP.
uint256 public constant MAX_PRESALE_TOKENS_SOLD = 2625 * 10 ** 5 * TOKEN_DECIMALS + ALAP;
// Tokens allocated for Community pool (30%).
uint256 public constant COMMUNITY_POOL = 45 * 10 ** 7 * TOKEN_DECIMALS;
// Tokens allocated for Future development pool (29%).
uint256 public constant FUTURE_DEVELOPMENT_POOL = 435 * 10 ** 6 * TOKEN_DECIMALS;
// Tokens allocated for Stakeholdes pool (6%).
uint256 public constant STAKEHOLDERS_POOL = 9 * 10 ** 7 * TOKEN_DECIMALS;
// CLN to ETH ratio.
uint256 public constant CLN_PER_ETH = 8600;
// Sale start, end blocks (time ranges)
uint256 public constant SALE_DURATION = 4 days;
uint256 public startTime;
uint256 public endTime;
// Amount of tokens sold until now in the sale.
uint256 public tokensSold = 0;
// Amount of tokens sold until now in the presale.
uint256 public presaleTokensSold = 0;
// Accumulated amount each participant has contributed so far in the sale (in WEI).
mapping (address => uint256) public participationHistory;
// Accumulated amount each participant have contributed so far in the presale.
mapping (address => uint256) public participationPresaleHistory;
// Maximum amount that each particular is allowed to contribute (in ETH-WEI).
// Defaults to zero. Serving as a functional whitelist.
mapping (address => uint256) public participationCaps;
// Maximum amount ANYONE is currently allowed to contribute. Set to max uint256 so no limitation other than personal participationCaps.
uint256 public hardParticipationCap = uint256(-1);
// initialization of the contract, splitted from the constructor to avoid gas block limit.
bool public initialized = false;
// Vesting plan structure for presale
struct VestingPlan {
uint256 startOffset;
uint256 cliffOffset;
uint256 endOffset;
uint256 installmentLength;
uint8 alapPercent;
}
// Vesting plans for presale
VestingPlan[] public vestingPlans;
// Each token that is sent from the ColuLocalNetworkSale is considered as issued.
event TokensIssued(address indexed to, uint256 tokens);
/// @dev Reverts if called not before the sale.
modifier onlyBeforeSale() {
if (now >= startTime) {
revert();
}
_;
}
/// @dev Reverts if called not during the sale.
modifier onlyDuringSale() {
if (tokensSold >= MAX_TOKENS_SOLD || now < startTime || now >= endTime) {
revert();
}
_;
}
/// @dev Reverts if called before the sale ends.
modifier onlyAfterSale() {
if (!(tokensSold >= MAX_TOKENS_SOLD || now >= endTime)) {
revert();
}
_;
}
/// @dev Reverts if called before the sale is initialized.
modifier notInitialized() {
if (initialized) {
revert();
}
_;
}
/// @dev Reverts if called after the sale is initialized.
modifier isInitialized() {
if (!initialized) {
revert();
}
_;
}
/// @dev Constructor sets the sale addresses and start time.
/// @param _owner address The address of this contract owner.
/// @param _fundingRecipient address The address of the funding recipient.
/// @param _communityPoolAddress address The address of the community pool.
/// @param _futureDevelopmentPoolAddress address The address of the future development pool.
/// @param _stakeholdersPoolAddress address The address of the team pool.
/// @param _startTime uint256 The start time of the token sale.
function ColuLocalNetworkSale(address _owner,
address _fundingRecipient,
address _communityPoolAddress,
address _futureDevelopmentPoolAddress,
address _stakeholdersPoolAddress,
uint256 _startTime) public {
require(_owner != address(0));
require(_fundingRecipient != address(0));
require(_communityPoolAddress != address(0));
require(_futureDevelopmentPoolAddress != address(0));
require(_stakeholdersPoolAddress != address(0));
require(_startTime > now);
owner = _owner;
fundingRecipient = _fundingRecipient;
communityPoolAddress = _communityPoolAddress;
futureDevelopmentPoolAddress = _futureDevelopmentPoolAddress;
stakeholdersPoolAddress = _stakeholdersPoolAddress;
startTime = _startTime;
endTime = startTime + SALE_DURATION;
}
/// @dev Initialize the sale conditions.
function initialize() public onlyOwner notInitialized {
initialized = true;
uint256 months = 1 years / 12;
vestingPlans.push(VestingPlan(0, 0, 1, 1, 0));
vestingPlans.push(VestingPlan(0, 0, 6 * months, 1 * months, 4));
vestingPlans.push(VestingPlan(0, 0, 1 years, 1 * months, 12));
vestingPlans.push(VestingPlan(0, 0, 2 years, 1 * months, 26));
vestingPlans.push(VestingPlan(0, 0, 3 years, 1 * months, 35));
// Deploy new ColuLocalNetwork contract.
cln = new ColuLocalNetwork(MAX_TOKENS);
// Deploy new VestingTrustee contract.
trustee = new VestingTrustee(cln);
// allocate pool tokens:
// Issue the remaining tokens to designated pools.
require(transferTokens(communityPoolAddress, COMMUNITY_POOL));
// stakeholdersPoolAddress will create its own vesting trusts.
require(transferTokens(stakeholdersPoolAddress, STAKEHOLDERS_POOL));
}
/// @dev Allocate tokens to presale participant according to its vesting plan and invesment value.
/// @param _recipient address The presale participant address to recieve the tokens.
/// @param _etherValue uint256 The invesment value (in ETH).
/// @param _vestingPlanIndex uint8 The vesting plan index.
function presaleAllocation(address _recipient, uint256 _etherValue, uint8 _vestingPlanIndex) external onlyOwner onlyBeforeSale isInitialized {
require(_recipient != address(0));
require(_vestingPlanIndex < vestingPlans.length);
// Calculate plan and token amount.
VestingPlan memory plan = vestingPlans[_vestingPlanIndex];
uint256 tokensAndALAPPerEth = CLN_PER_ETH.mul(SafeMath.add(100, plan.alapPercent)).div(100);
uint256 tokensLeftInPreSale = MAX_PRESALE_TOKENS_SOLD.sub(presaleTokensSold);
uint256 weiLeftInSale = tokensLeftInPreSale.div(tokensAndALAPPerEth);
uint256 weiToParticipate = SafeMath.min256(_etherValue, weiLeftInSale);
require(weiToParticipate > 0);
participationPresaleHistory[msg.sender] = participationPresaleHistory[msg.sender].add(weiToParticipate);
uint256 tokensToTransfer = weiToParticipate.mul(tokensAndALAPPerEth);
presaleTokensSold = presaleTokensSold.add(tokensToTransfer);
tokensSold = tokensSold.add(tokensToTransfer);
// Transfer tokens to trustee and create grant.
grant(_recipient, tokensToTransfer, startTime.add(plan.startOffset), startTime.add(plan.cliffOffset),
startTime.add(plan.endOffset), plan.installmentLength, false);
}
/// @dev Add a list of participants to a capped participation tier.
/// @param _participants address[] The list of participant addresses.
/// @param _cap uint256 The cap amount (in ETH-WEI).
function setParticipationCap(address[] _participants, uint256 _cap) external onlyOwner isInitialized {
for (uint i = 0; i < _participants.length; i++) {
participationCaps[_participants[i]] = _cap;
}
}
/// @dev Set hard participation cap for all participants.
/// @param _cap uint256 The hard cap amount.
function setHardParticipationCap(uint256 _cap) external onlyOwner isInitialized {
require(_cap > 0);
hardParticipationCap = _cap;
}
/// @dev Fallback function that will delegate the request to participate().
function () external payable onlyDuringSale isInitialized {
participate(msg.sender);
}
/// @dev Create and sell tokens to the caller.
/// @param _recipient address The address of the recipient receiving the tokens.
function participate(address _recipient) public payable onlyDuringSale isInitialized {
require(_recipient != address(0));
// Enforce participation cap (in WEI received).
uint256 weiAlreadyParticipated = participationHistory[_recipient];
uint256 participationCap = SafeMath.min256(participationCaps[_recipient], hardParticipationCap);
uint256 cappedWeiReceived = SafeMath.min256(msg.value, participationCap.sub(weiAlreadyParticipated));
require(cappedWeiReceived > 0);
// Accept funds and transfer to funding recipient.
uint256 tokensLeftInSale = MAX_TOKENS_SOLD.sub(tokensSold);
uint256 weiLeftInSale = tokensLeftInSale.div(CLN_PER_ETH);
uint256 weiToParticipate = SafeMath.min256(cappedWeiReceived, weiLeftInSale);
participationHistory[_recipient] = weiAlreadyParticipated.add(weiToParticipate);
fundingRecipient.transfer(weiToParticipate);
// Transfer tokens to recipient.
uint256 tokensToTransfer = weiToParticipate.mul(CLN_PER_ETH);
if (tokensLeftInSale.sub(tokensToTransfer) < CLN_PER_ETH) {
// If purchase would cause less than CLN_PER_ETH tokens to be left then nobody could ever buy them.
// So, gift them to the last buyer.
tokensToTransfer = tokensLeftInSale;
}
tokensSold = tokensSold.add(tokensToTransfer);
require(transferTokens(_recipient, tokensToTransfer));
// Partial refund if full participation not possible
// e.g. due to cap being reached.
uint256 refund = msg.value.sub(weiToParticipate);
if (refund > 0) {
msg.sender.transfer(refund);
}
}
/// @dev Finalizes the token sale event: make future development pool grant (lockup) and make token transfarable.
function finalize() external onlyAfterSale onlyOwner isInitialized {
if (cln.isTransferable()) {
revert();
}
// Add unsold token to the future development pool grant (lockup).
uint256 tokensLeftInSale = MAX_TOKENS_SOLD.sub(tokensSold);
uint256 futureDevelopmentPool = FUTURE_DEVELOPMENT_POOL.add(tokensLeftInSale);
// Future Development Pool is locked for 3 years.
grant(futureDevelopmentPoolAddress, futureDevelopmentPool, startTime, startTime.add(3 years),
startTime.add(3 years), 1 days, false);
// Make tokens Transferable, end the sale!.
cln.makeTokensTransferable();
}
function grant(address _grantee, uint256 _amount, uint256 _start, uint256 _cliff, uint256 _end,
uint256 _installmentLength, bool _revokable) private {
// bytes4 grantSig = bytes4(keccak256("grant(address,uint256,uint256,uint256,uint256,bool)"));
bytes4 grantSig = 0x5ee7e96d;
// 6 arguments of size 32
uint256 argsSize = 6 * 32;
// sig + arguments size
uint256 dataSize = 4 + argsSize;
bytes memory m_data = new bytes(dataSize);
assembly {
// Add the signature first to memory
mstore(add(m_data, 0x20), grantSig)
// Add the parameters
mstore(add(m_data, 0x24), _grantee)
mstore(add(m_data, 0x44), _start)
mstore(add(m_data, 0x64), _cliff)
mstore(add(m_data, 0x84), _end)
mstore(add(m_data, 0xa4), _installmentLength)
mstore(add(m_data, 0xc4), _revokable)
}
require(transferTokens(trustee, _amount, m_data));
}
/// @dev Transfer tokens from the sale contract to a recipient.
/// @param _recipient address The address of the recipient.
/// @param _tokens uint256 The amount of tokens to transfer.
function transferTokens(address _recipient, uint256 _tokens) private returns (bool ans) {
ans = cln.transfer(_recipient, _tokens);
if (ans) {
TokensIssued(_recipient, _tokens);
}
}
/// @dev Transfer tokens from the sale contract to a recipient.
/// @param _recipient address The address of the recipient.
/// @param _tokens uint256 The amount of tokens to transfer.
/// @param _data bytes data to send to receiver if it is a contract.
function transferTokens(address _recipient, uint256 _tokens, bytes _data) private returns (bool ans) {
// Request Colu Local Network contract to transfer the requested tokens for the buyer.
ans = cln.transferAndCall(_recipient, _tokens, _data);
if (ans) {
TokensIssued(_recipient, _tokens);
}
}
/// @dev Requests to transfer control of the Colu Local Network contract to a new owner.
/// @param _newOwnerCandidate address The address to transfer ownership to.
///
/// NOTE:
/// 1. The new owner will need to call Colu Local Network contract's acceptOwnership directly in order to accept the ownership.
/// 2. Calling this method during the token sale will prevent the token sale to continue, since only the owner of
/// the Colu Local Network contract can transfer tokens during the sale.
function requestColuLocalNetworkOwnershipTransfer(address _newOwnerCandidate) external onlyOwner {
cln.requestOwnershipTransfer(_newOwnerCandidate);
}
/// @dev Accepts new ownership on behalf of the Colu Local Network contract.
// This can be used by the sale contract itself to claim back ownership of the Colu Local Network contract.
function acceptColuLocalNetworkOwnership() external onlyOwner {
cln.acceptOwnership();
}
/// @dev Requests to transfer control of the VestingTrustee contract to a new owner.
/// @param _newOwnerCandidate address The address to transfer ownership to.
///
/// NOTE:
/// 1. The new owner will need to call trustee contract's acceptOwnership directly in order to accept the ownership.
/// 2. Calling this method during the token sale will prevent the token sale from alocation presale grunts add finalize, since only the owner of
/// the trustee contract can create grunts needed in the presaleAlocation add finalize methods.
function requestVestingTrusteeOwnershipTransfer(address _newOwnerCandidate) external onlyOwner {
trustee.requestOwnershipTransfer(_newOwnerCandidate);
}
/// @dev Accepts new ownership on behalf of the VestingTrustee contract.
/// This can be used by the token sale contract itself to claim back ownership of the VestingTrustee contract.
function acceptVestingTrusteeOwnership() external onlyOwner {
trustee.acceptOwnership();
}
} | @dev check if the address is contract assemble the given address bytecode. If bytecode exists then the _addr is a contract. @param _addr address the address to check retrieve the size of the code on target address, this needs assembly | function isContract(address _addr) private constant returns (bool is_contract) {
uint length;
return length > 0;
}
| 1,083,081 | [
1,
1893,
309,
326,
1758,
353,
6835,
19540,
326,
864,
1758,
22801,
18,
971,
22801,
1704,
1508,
326,
389,
4793,
353,
279,
6835,
18,
225,
389,
4793,
1758,
326,
1758,
358,
866,
4614,
326,
963,
434,
326,
981,
603,
1018,
1758,
16,
333,
4260,
19931,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
353,
8924,
12,
2867,
389,
4793,
13,
3238,
5381,
1135,
261,
6430,
353,
67,
16351,
13,
288,
203,
565,
2254,
769,
31,
203,
565,
327,
769,
405,
374,
31,
203,
225,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/*
Copyright 2019 Swap Holdings Ltd.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.5.10;
pragma experimental ABIEncoderV2;
// File: @airswap/types/contracts/Types.sol
/**
* @title Types: Library of Swap Protocol Types and Hashes
*/
library Types {
bytes constant internal EIP191_HEADER = "\x19\x01";
struct Party {
address wallet; // Wallet address of the party
address token; // Contract address of the token
uint256 param; // Value (ERC-20) or ID (ERC-721)
bytes4 kind; // Interface ID of the token
}
struct Order {
uint256 nonce; // Unique per order and should be sequential
uint256 expiry; // Expiry in seconds since 1 January 1970
Party maker; // Party to the trade that sets terms
Party taker; // Party to the trade that accepts terms
Party affiliate; // Party compensated for facilitating (optional)
}
struct Signature {
address signer; // Address of the wallet used to sign
uint8 v; // `v` value of an ECDSA signature
bytes32 r; // `r` value of an ECDSA signature
bytes32 s; // `s` value of an ECDSA signature
bytes1 version; // EIP-191 signature version
}
bytes32 constant DOMAIN_TYPEHASH = keccak256(abi.encodePacked(
"EIP712Domain(",
"string name,",
"string version,",
"address verifyingContract",
")"
));
bytes32 constant ORDER_TYPEHASH = keccak256(abi.encodePacked(
"Order(",
"uint256 nonce,",
"uint256 expiry,",
"Party maker,",
"Party taker,",
"Party affiliate",
")",
"Party(",
"address wallet,",
"address token,",
"uint256 param,",
"bytes4 kind",
")"
));
bytes32 constant PARTY_TYPEHASH = keccak256(abi.encodePacked(
"Party(",
"address wallet,",
"address token,",
"uint256 param,",
"bytes4 kind",
")"
));
/**
* @notice Hash an order into bytes32
* @dev EIP-191 header and domain separator included
* @param _order Order
* @param _domainSeparator bytes32
* @return bytes32 returns a keccak256 abi.encodePacked value
*/
function hashOrder(
Order calldata _order,
bytes32 _domainSeparator
) external pure returns (bytes32) {
return keccak256(abi.encodePacked(
EIP191_HEADER,
_domainSeparator,
keccak256(abi.encode(
ORDER_TYPEHASH,
_order.nonce,
_order.expiry,
keccak256(abi.encode(
PARTY_TYPEHASH,
_order.maker.wallet,
_order.maker.token,
_order.maker.param,
_order.maker.kind
)),
keccak256(abi.encode(
PARTY_TYPEHASH,
_order.taker.wallet,
_order.taker.token,
_order.taker.param,
_order.taker.kind
)),
keccak256(abi.encode(
PARTY_TYPEHASH,
_order.affiliate.wallet,
_order.affiliate.token,
_order.affiliate.param,
_order.affiliate.kind
))
))
));
}
/**
* @notice Hash domain parameters into bytes32
* @dev Used for signature validation (EIP-712)
* @param _name bytes
* @param _version bytes
* @param _verifyingContract address
* @return bytes32 returns a keccak256 abi.encodePacked value
*/
function hashDomain(
bytes calldata _name,
bytes calldata _version,
address _verifyingContract
) external pure returns (bytes32) {
return keccak256(abi.encode(
DOMAIN_TYPEHASH,
keccak256(_name),
keccak256(_version),
_verifyingContract
));
}
}
// File: @airswap/swap/interfaces/ISwap.sol
interface ISwap {
event Swap(
uint256 indexed nonce,
uint256 timestamp,
address indexed makerWallet,
uint256 makerParam,
address makerToken,
address indexed takerWallet,
uint256 takerParam,
address takerToken,
address affiliateWallet,
uint256 affiliateParam,
address affiliateToken
);
event Cancel(
uint256 indexed nonce,
address indexed makerWallet
);
event Invalidate(
uint256 indexed nonce,
address indexed makerWallet
);
event Authorize(
address indexed approverAddress,
address indexed delegateAddress,
uint256 expiry
);
event Revoke(
address indexed approverAddress,
address indexed delegateAddress
);
function delegateApprovals(address, address) external returns (uint256);
function makerOrderStatus(address, uint256) external returns (byte);
function makerMinimumNonce(address) external returns (uint256);
/**
* @notice Atomic Token Swap
* @param order Types.Order
* @param signature Types.Signature
*/
function swap(
Types.Order calldata order,
Types.Signature calldata signature
) external;
/**
* @notice Atomic Token Swap (Simple)
* @param _nonce uint256
* @param _expiry uint256
* @param _makerWallet address
* @param _makerParam uint256
* @param _makerToken address
* @param _takerWallet address
* @param _takerParam uint256
* @param _takerToken address
* @param _v uint8
* @param _r bytes32
* @param _s bytes32
*/
function swapSimple(
uint256 _nonce,
uint256 _expiry,
address _makerWallet,
uint256 _makerParam,
address _makerToken,
address _takerWallet,
uint256 _takerParam,
address _takerToken,
uint8 _v,
bytes32 _r,
bytes32 _s
) external;
/**
* @notice Cancel one or more open orders by nonce
* @param _nonces uint256[]
*/
function cancel(
uint256[] calldata _nonces
) external;
/**
* @notice Invalidate all orders below a nonce value
* @param _minimumNonce uint256
*/
function invalidate(
uint256 _minimumNonce
) external;
/**
* @notice Authorize a delegate
* @param _delegate address
* @param _expiry uint256
*/
function authorize(
address _delegate,
uint256 _expiry
) external;
/**
* @notice Revoke an authorization
* @param _delegate address
*/
function revoke(
address _delegate
) external;
}
// File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see `ERC20Detailed`.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a `Transfer` event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through `transferFrom`. This is
* zero by default.
*
* This value changes when `approve` or `transferFrom` are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* > Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an `Approval` event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a `Transfer` event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to `approve`. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: openzeppelin-solidity/contracts/introspection/IERC165.sol
/**
* @dev Interface of the ERC165 standard, as defined in the
* [EIP](https://eips.ethereum.org/EIPS/eip-165).
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others (`ERC165Checker`).
*
* For an implementation, see `ERC165`.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* [EIP section](https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified)
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File: openzeppelin-solidity/contracts/token/ERC721/IERC721.sol
/**
* @dev Required interface of an ERC721 compliant contract.
*/
contract IERC721 is IERC165 {
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of NFTs in `owner`'s account.
*/
function balanceOf(address owner) public view returns (uint256 balance);
/**
* @dev Returns the owner of the NFT specified by `tokenId`.
*/
function ownerOf(uint256 tokenId) public view returns (address owner);
/**
* @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to
* another (`to`).
*
*
*
* Requirements:
* - `from`, `to` cannot be zero.
* - `tokenId` must be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this
* NFT by either `approve` or `setApproveForAll`.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) public;
/**
* @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to
* another (`to`).
*
* Requirements:
* - If the caller is not `from`, it must be approved to move this NFT by
* either `approve` or `setApproveForAll`.
*/
function transferFrom(address from, address to, uint256 tokenId) public;
function approve(address to, uint256 tokenId) public;
function getApproved(uint256 tokenId) public view returns (address operator);
function setApprovalForAll(address operator, bool _approved) public;
function isApprovedForAll(address owner, address operator) public view returns (bool);
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public;
}
// File: contracts/Swap.sol
/**
* @title Swap: The Atomic Swap used by the Swap Protocol
*/
contract Swap is ISwap {
// Domain and version for use in signatures (EIP-712)
bytes constant internal DOMAIN_NAME = "SWAP";
bytes constant internal DOMAIN_VERSION = "2";
// Unique domain identifier for use in signatures (EIP-712)
bytes32 private domainSeparator;
// Possible order statuses
byte constant private OPEN = 0x00;
byte constant private TAKEN = 0x01;
byte constant private CANCELED = 0x02;
// ERC-20 (fungible token) interface identifier (ERC-165)
bytes4 constant internal ERC20_INTERFACE_ID = 0x277f8169;
/*
bytes4(keccak256('transfer(address,uint256)')) ^
bytes4(keccak256('transferFrom(address,address,uint256)')) ^
bytes4(keccak256('balanceOf(address)')) ^
bytes4(keccak256('allowance(address,address)'));
*/
// ERC-721 (non-fungible token) interface identifier (ERC-165)
bytes4 constant internal ERC721_INTERFACE_ID = 0x80ac58cd;
/*
bytes4(keccak256('balanceOf(address)')) ^
bytes4(keccak256('ownerOf(uint256)')) ^
bytes4(keccak256('approve(address,uint256)')) ^
bytes4(keccak256('getApproved(uint256)')) ^
bytes4(keccak256('setApprovalForAll(address,bool)')) ^
bytes4(keccak256('isApprovedForAll(address,address)')) ^
bytes4(keccak256('transferFrom(address,address,uint256)')) ^
bytes4(keccak256('safeTransferFrom(address,address,uint256)')) ^
bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)'));
*/
// Mapping of peer address to delegate address and expiry.
mapping (address => mapping (address => uint256)) public delegateApprovals;
// Mapping of makers to orders by nonce as TAKEN (0x01) or CANCELED (0x02)
mapping (address => mapping (uint256 => byte)) public makerOrderStatus;
// Mapping of makers to an optionally set minimum valid nonce
mapping (address => uint256) public makerMinimumNonce;
/**
* @notice Contract Constructor
* @dev Sets domain for signature validation (EIP-712)
*/
constructor() public {
domainSeparator = Types.hashDomain(
DOMAIN_NAME,
DOMAIN_VERSION,
address(this)
);
}
/**
* @notice Atomic Token Swap
* @param _order Types.Order
* @param _signature Types.Signature
*/
function swap(
Types.Order calldata _order,
Types.Signature calldata _signature
)
external
{
// Ensure the order is not expired.
require(_order.expiry > block.timestamp,
"ORDER_EXPIRED");
// Ensure the order is not already taken.
require(makerOrderStatus[_order.maker.wallet][_order.nonce] != TAKEN,
"ORDER_ALREADY_TAKEN");
// Ensure the order is not already canceled.
require(makerOrderStatus[_order.maker.wallet][_order.nonce] != CANCELED,
"ORDER_ALREADY_CANCELED");
// Ensure the order nonce is above the minimum.
require(_order.nonce >= makerMinimumNonce[_order.maker.wallet],
"NONCE_TOO_LOW");
// Mark the order TAKEN (0x01).
makerOrderStatus[_order.maker.wallet][_order.nonce] = TAKEN;
// Validate the taker side of the trade.
address finalTakerWallet;
if (_order.taker.wallet == address(0)) {
/**
* Taker is not specified. The sender of the transaction becomes
* the taker of the _order.
*/
finalTakerWallet = msg.sender;
} else {
/**
* Taker is specified. If the sender is not the specified taker,
* determine whether the sender has been authorized by the taker.
*/
if (msg.sender != _order.taker.wallet) {
require(isAuthorized(_order.taker.wallet, msg.sender),
"SENDER_UNAUTHORIZED");
}
// The specified taker is all clear.
finalTakerWallet = _order.taker.wallet;
}
// Validate the maker side of the trade.
if (_signature.v == 0) {
/**
* Signature is not provided. The maker may have authorized the sender
* to swap on its behalf, which does not require a _signature.
*/
require(isAuthorized(_order.maker.wallet, msg.sender),
"SIGNER_UNAUTHORIZED");
} else {
/**
* The signature is provided. Determine whether the signer is
* authorized by the maker and if so validate the signature itself.
*/
require(isAuthorized(_order.maker.wallet, _signature.signer),
"SIGNER_UNAUTHORIZED");
// Ensure the signature is valid.
require(isValid(_order, _signature, domainSeparator),
"SIGNATURE_INVALID");
}
// Transfer token from taker to maker.
transferToken(
finalTakerWallet,
_order.maker.wallet,
_order.taker.param,
_order.taker.token,
_order.taker.kind
);
// Transfer token from maker to taker.
transferToken(
_order.maker.wallet,
finalTakerWallet,
_order.maker.param,
_order.maker.token,
_order.maker.kind
);
// Transfer token from maker to affiliate if specified.
if (_order.affiliate.wallet != address(0)) {
transferToken(
_order.maker.wallet,
_order.affiliate.wallet,
_order.affiliate.param,
_order.affiliate.token,
_order.affiliate.kind
);
}
emit Swap(_order.nonce, block.timestamp,
_order.maker.wallet, _order.maker.param, _order.maker.token,
finalTakerWallet, _order.taker.param, _order.taker.token,
_order.affiliate.wallet, _order.affiliate.param, _order.affiliate.token
);
}
/**
* @notice Atomic Token Swap (Simple)
* @dev Supports fungible token transfers (ERC-20)
* @param _nonce uint256
* @param _expiry uint256
* @param _makerWallet address
* @param _makerParam uint256
* @param _makerToken address
* @param _takerWallet address
* @param _takerParam uint256
* @param _takerToken address
* @param _v uint8
* @param _r bytes32
* @param _s bytes32
*/
function swapSimple(
uint256 _nonce,
uint256 _expiry,
address _makerWallet,
uint256 _makerParam,
address _makerToken,
address _takerWallet,
uint256 _takerParam,
address _takerToken,
uint8 _v,
bytes32 _r,
bytes32 _s
)
external
{
// Ensure the order has not already been taken or canceled.
require(makerOrderStatus[_makerWallet][_nonce] == OPEN,
"ORDER_UNAVAILABLE");
// Ensure the order is not expired.
require(_expiry > block.timestamp,
"ORDER_EXPIRED");
require(_nonce >= makerMinimumNonce[_makerWallet],
"NONCE_TOO_LOW");
// Validate the taker side of the trade.
address finalTakerWallet;
if (_takerWallet == address(0)) {
// Set a null taker to be the order sender.
finalTakerWallet = msg.sender;
} else {
// Ensure the order sender is authorized.
if (msg.sender != _takerWallet) {
require(isAuthorized(_takerWallet, msg.sender),
"SENDER_UNAUTHORIZED");
}
finalTakerWallet = _takerWallet;
}
// Validate the maker side of the trade.
if (_v == 0) {
/**
* Signature is not provided. The maker may have authorized the sender
* to swap on its behalf, which does not require a signature.
*/
require(isAuthorized(_makerWallet, msg.sender),
"SIGNER_UNAUTHORIZED");
} else {
// Signature is provided. Ensure that it is valid.
require(_makerWallet == ecrecover(
keccak256(abi.encodePacked(
"\x19Ethereum Signed Message:\n32",
keccak256(abi.encodePacked(
byte(0),
address(this),
_nonce,
_expiry,
_makerWallet,
_makerParam,
_makerToken,
_takerWallet,
_takerParam,
_takerToken
))
)), _v, _r, _s), "SIGNATURE_INVALID");
}
// Mark the order TAKEN (0x01).
makerOrderStatus[_makerWallet][_nonce] = TAKEN;
// Transfer token from taker to maker.
transferToken(
finalTakerWallet,
_makerWallet,
_takerParam,
_takerToken,
ERC20_INTERFACE_ID
);
// Transfer token from maker to taker.
transferToken(
_makerWallet,
finalTakerWallet,
_makerParam,
_makerToken,
ERC20_INTERFACE_ID
);
emit Swap(_nonce, block.timestamp,
_makerWallet, _makerParam, _makerToken,
finalTakerWallet, _takerParam, _takerToken,
address(0), 0, address(0)
);
}
/**
* @notice Cancel one or more open orders by nonce
* @dev Canceled orders are marked CANCELED (0x02)
* @dev Emits a Cancel event
* @param _nonces uint256[]
*/
function cancel(
uint256[] calldata _nonces
) external {
for (uint256 i = 0; i < _nonces.length; i++) {
if (makerOrderStatus[msg.sender][_nonces[i]] == OPEN) {
makerOrderStatus[msg.sender][_nonces[i]] = CANCELED;
emit Cancel(_nonces[i], msg.sender);
}
}
}
/**
* @notice Invalidate all orders below a nonce value
* @dev Emits an Invalidate event
* @param _minimumNonce uint256
*/
function invalidate(
uint256 _minimumNonce
) external {
makerMinimumNonce[msg.sender] = _minimumNonce;
emit Invalidate(_minimumNonce, msg.sender);
}
/**
* @notice Authorize a delegate
* @dev Emits an Authorize event
* @param _delegate address
* @param _expiry uint256
*/
function authorize(
address _delegate,
uint256 _expiry
) external {
require(msg.sender != _delegate, "INVALID_AUTH_DELEGATE");
require(_expiry > block.timestamp, "INVALID_AUTH_EXPIRY");
delegateApprovals[msg.sender][_delegate] = _expiry;
emit Authorize(msg.sender, _delegate, _expiry);
}
/**
* @notice Revoke an authorization
* @dev Emits a Revoke event
* @param _delegate address
*/
function revoke(
address _delegate
) external {
delete delegateApprovals[msg.sender][_delegate];
emit Revoke(msg.sender, _delegate);
}
/**
* @notice Determine whether a delegate is authorized
* @param _approver address
* @param _delegate address
* @return bool returns whether a delegate is authorized
*/
function isAuthorized(
address _approver,
address _delegate
) internal view returns (bool) {
if (_approver == _delegate) return true;
return (delegateApprovals[_approver][_delegate] > block.timestamp);
}
/**
* @notice Validate signature using an EIP-712 typed data hash
* @param _order Order
* @param _signature Signature
* @return bool returns whether the signature + order is valid
*/
function isValid(
Types.Order memory _order,
Types.Signature memory _signature,
bytes32 _domainSeparator
) internal pure returns (bool) {
if (_signature.version == byte(0x01)) {
return _signature.signer == ecrecover(
Types.hashOrder(
_order,
_domainSeparator),
_signature.v,
_signature.r,
_signature.s
);
}
if (_signature.version == byte(0x45)) {
return _signature.signer == ecrecover(
keccak256(
abi.encodePacked(
"\x19Ethereum Signed Message:\n32",
Types.hashOrder(_order, _domainSeparator)
)
),
_signature.v,
_signature.r,
_signature.s
);
}
return false;
}
/**
* @notice Perform an ERC-20 or ERC-721 token transfer
* @dev Transfer type specified by the bytes4 _kind param
* @param _from address wallet address to send from
* @param _to address wallet address to send to
* @param _param uint256 amount for ERC-20 or token ID for ERC-721
* @param _token address contract address of token
* @param _kind bytes4 EIP-165 interface ID of the token
*/
function transferToken(
address _from,
address _to,
uint256 _param,
address _token,
bytes4 _kind
) internal {
if (_kind == ERC721_INTERFACE_ID) {
// Attempt to transfer an ERC-721 token.
IERC721(_token).safeTransferFrom(_from, _to, _param);
} else {
// Attempt to transfer an ERC-20 token.
require(IERC20(_token).transferFrom(_from, _to, _param));
}
}
} | * @notice Invalidate all orders below a nonce value @dev Emits an Invalidate event @param _minimumNonce uint256/ | function invalidate(
uint256 _minimumNonce
) external {
makerMinimumNonce[msg.sender] = _minimumNonce;
emit Invalidate(_minimumNonce, msg.sender);
}
| 13,037,590 | [
1,
26970,
777,
11077,
5712,
279,
7448,
460,
225,
7377,
1282,
392,
1962,
340,
871,
225,
389,
15903,
13611,
2254,
5034,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
11587,
12,
203,
565,
2254,
5034,
389,
15903,
13611,
203,
225,
262,
3903,
288,
203,
565,
312,
6388,
13042,
13611,
63,
3576,
18,
15330,
65,
273,
389,
15903,
13611,
31,
203,
565,
3626,
1962,
340,
24899,
15903,
13611,
16,
1234,
18,
15330,
1769,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/8453/0xE4AD80eD0c7d12A8B687c6C987d07f1D486fEd85/sources/src/royalty/ABRoyalty.sol | Superfluid Contracts */ | import {ISuperToken} from "@superfluid-finance/ethereum-contracts/contracts/interfaces/superfluid/ISuperToken.sol";
| 11,535,328 | [
1,
8051,
2242,
1911,
30131,
342,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
5666,
288,
45,
8051,
1345,
97,
628,
8787,
9565,
2242,
1911,
17,
926,
1359,
19,
546,
822,
379,
17,
16351,
87,
19,
16351,
87,
19,
15898,
19,
9565,
2242,
1911,
19,
45,
8051,
1345,
18,
18281,
14432,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2021-07-20
*/
// File: contracts/IERC20.sol
pragma solidity >=0.5.0 <0.7.0;
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
function decimals() external view returns (uint8);
function transfer(address recipient, uint256 amount) external returns (bool);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
function burn(uint256 _value) external returns (bool success);
function burnFrom(address _from, uint256 _value) external returns (bool success);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
event Burn(address indexed from, uint256 value);
}
// File: contracts/SafeMath.sol
pragma solidity >=0.5.0 <0.7.0;
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
/**
* @dev gives square root of given x.
*/
function sqrt(uint256 x)
internal
pure
returns(uint256 y) {
uint256 z = ((add(x, 1)) / 2);
y = x;
while (z < y) {
y = z;
z = ((add((x / z), z)) / 2);
}
}
/**
* @dev gives square. multiplies x by x
*/
function sq(uint256 x)
internal
pure
returns(uint256) {
return (mul(x, x));
}
/**
* @dev x to the power of y
*/
function pwr(uint256 x, uint256 y)
internal
pure
returns(uint256) {
if (x == 0)
return (0);
else if (y == 0)
return (1);
else {
uint256 z = x;
for (uint256 i = 1; i < y; i++)
z = mul(z, x);
return (z);
}
}
}
// File: contracts/owned.sol
pragma solidity ^0.5.10;
contract owned {
address public owner;
constructor() public {
owner = msg.sender;
}
modifier onlyOwner {
require (msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
if (newOwner != address(0)) {
owner = newOwner;
}
}
}
// File: contracts/ECOPLocker.sol
pragma solidity ^0.5.10;
contract ECOPLocker is owned{
using SafeMath for uint256;
uint256[] public MONTH_TIER = [79435,66196,66196,66196,4413,4413,4413,4413,4413,4413,4413,4413,4414];
uint256 constant public TOTAL_AMOUNT = 317741*10**18;
event CoinWithdrawn(address indexed addr, uint256 amount);
address payable user_addr;
IERC20 ecop;
uint256 public withdraw_tokens;
uint40 public online_time;
constructor(address payable ecopContractAddress, address payable userAddress) public {
ecop = IERC20(ecopContractAddress);
user_addr = userAddress;
withdraw_tokens = 0;
//init online time for 1 year later
online_time = uint40(block.timestamp+365*86400);
}
function setOnlineTime(uint40 ts) onlyOwner public {
online_time = ts;
}
function withdraw() public {
require(msg.sender == user_addr, "only authorized user.");
uint256 amount = this.getAvailableAmount();
require(amount > 0, "No available coins.");
uint256 ecop_balance = ecop.balanceOf(address(this));
require(ecop_balance >= amount, "No ECOP left for withdrawing");
ecop.transfer(msg.sender, amount);
withdraw_tokens = withdraw_tokens.add(amount);
emit CoinWithdrawn(msg.sender, amount);
}
/*
Only external call
*/
function getAvailableAmount() view external returns(uint256) {
uint256 ts = block.timestamp;
if(ts < online_time)
return 0;
uint256 time_span = ts.sub(online_time);
uint256 index = time_span.div(30*86400);
uint256 amount = 0;
for(uint256 i=0; i <= index; i++)
{
amount = amount.add(MONTH_TIER[i].mul(10**18));
}
if(amount > TOTAL_AMOUNT)
amount = TOTAL_AMOUNT;
if(amount < withdraw_tokens)
amount = 0;
else
amount = amount.sub(withdraw_tokens);
return amount;
}
function getContractInfo() view external returns(uint256 _total_amount, uint256 _withdraw_tokens, uint256 _available_tokens, uint40 _online_time, address _user_addr) {
_total_amount = TOTAL_AMOUNT;
_withdraw_tokens = withdraw_tokens;
_available_tokens = this.getAvailableAmount();
_online_time = online_time;
_user_addr = user_addr;
}
} | * @dev gives square root of given x./ | function sqrt(uint256 x)
internal
pure
returns(uint256 y) {
uint256 z = ((add(x, 1)) / 2);
y = x;
while (z < y) {
y = z;
z = ((add((x / z), z)) / 2);
}
}
| 6,554,618 | [
1,
75,
3606,
8576,
1365,
434,
864,
619,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
5700,
12,
11890,
5034,
619,
13,
203,
225,
2713,
203,
225,
16618,
203,
225,
1135,
12,
11890,
5034,
677,
13,
288,
203,
565,
2254,
5034,
998,
273,
14015,
1289,
12,
92,
16,
404,
3719,
342,
576,
1769,
203,
565,
677,
273,
619,
31,
203,
565,
1323,
261,
94,
411,
677,
13,
288,
203,
1377,
677,
273,
998,
31,
203,
1377,
998,
273,
14015,
1289,
12443,
92,
342,
998,
3631,
998,
3719,
342,
576,
1769,
203,
565,
289,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/5/0x8e5F7382Ec9DC8ECC58A99c510fB7eAcC8562599/sources/contracts/poolv2-implementation/interfaces/IAssetRouter.sol | kbp = Known Bandwidth Proof dst bandwidth
| uint256 actualKbp; | 1,950,251 | [
1,
8899,
84,
273,
30036,
27601,
2819,
1186,
792,
3046,
20508,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
2254,
5034,
3214,
47,
17152,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0xF8e465C2Db4794A87B345414F47F00acCADDaCAB/sources/contracts/IceNFT.sol | check if user's upline is already set check if cycle referral find upline's upline(referrer's referrer) set relationship | function setReferralRelationship(address user, address referredBy) internal {
require(user != address(0), "Referral: user is zero address");
require(referredBy != address(0), "Referral: referredBy is zero address");
require(usersUpline[user] == address(0), "Referral: user's upline is already set");
require(usersUpline[referredBy] != user, "Referral: cycle referral");
address upUpline = usersUpline[referredBy];
usersUpline[user] = referredBy;
usersDownlines[referredBy].push(user);
emit SetRelationship(user, referredBy, upUpline);
}
| 2,919,690 | [
1,
1893,
309,
729,
1807,
582,
412,
558,
353,
1818,
444,
866,
309,
8589,
1278,
29084,
1104,
582,
412,
558,
1807,
582,
412,
558,
12,
1734,
11110,
1807,
14502,
13,
444,
5232,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
444,
1957,
29084,
8180,
12,
2867,
729,
16,
1758,
29230,
858,
13,
2713,
288,
203,
565,
2583,
12,
1355,
480,
1758,
12,
20,
3631,
315,
1957,
29084,
30,
729,
353,
3634,
1758,
8863,
203,
565,
2583,
12,
266,
4193,
858,
480,
1758,
12,
20,
3631,
315,
1957,
29084,
30,
29230,
858,
353,
3634,
1758,
8863,
203,
203,
565,
2583,
12,
5577,
57,
412,
558,
63,
1355,
65,
422,
1758,
12,
20,
3631,
315,
1957,
29084,
30,
729,
1807,
582,
412,
558,
353,
1818,
444,
8863,
203,
203,
565,
2583,
12,
5577,
57,
412,
558,
63,
266,
4193,
858,
65,
480,
729,
16,
315,
1957,
29084,
30,
8589,
1278,
29084,
8863,
203,
203,
565,
1758,
731,
57,
412,
558,
273,
3677,
57,
412,
558,
63,
266,
4193,
858,
15533,
203,
203,
565,
3677,
57,
412,
558,
63,
1355,
65,
273,
29230,
858,
31,
203,
565,
3677,
4164,
3548,
63,
266,
4193,
858,
8009,
6206,
12,
1355,
1769,
203,
203,
565,
3626,
1000,
8180,
12,
1355,
16,
29230,
858,
16,
731,
57,
412,
558,
1769,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// to test issue with nodes breaking with large clients over WS
// fixed in web3 with fragmentationThreshold: 8192
pragma solidity ^0.4.17;
contract BigFreakingContract {
event Transfer(address indexed from, address indexed to, uint value);
event Approval( address indexed owner, address indexed spender, uint value);
mapping( address => uint ) _balances;
mapping( address => mapping( address => uint ) ) _approvals;
uint public _supply;
constructor( uint initial_balance ) public {
_balances[msg.sender] = initial_balance;
_supply = initial_balance;
}
function totalSupply() public constant returns (uint supply) {
return _supply;
}
function balanceOf( address who ) public constant returns (uint value) {
return _balances[who];
}
function transfer( address to, uint value) public returns (bool ok) {
if( _balances[msg.sender] < value ) {
revert();
}
if( !safeToAdd(_balances[to], value) ) {
revert();
}
_balances[msg.sender] -= value;
_balances[to] += value;
emit Transfer( msg.sender, to, value );
return true;
}
function transferFrom( address from, address to, uint value) public returns (bool ok) {
// if you don't have enough balance, throw
if( _balances[from] < value ) {
revert();
}
// if you don't have approval, throw
if( _approvals[from][msg.sender] < value ) {
revert();
}
if( !safeToAdd(_balances[to], value) ) {
revert();
}
// transfer and return true
_approvals[from][msg.sender] -= value;
_balances[from] -= value;
_balances[to] += value;
emit Transfer( from, to, value );
return true;
}
function approve(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function allowance(address owner, address spender) public constant returns (uint _allowance) {
return _approvals[owner][spender];
}
function safeToAdd(uint a, uint b) internal pure returns (bool) {
return (a + b >= a);
}
function isAvailable() public pure returns (bool) {
return false;
}
function approve_1(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_2(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_3(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_4(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_5(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_6(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_7(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_8(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_9(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_10(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_11(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_12(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_13(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_14(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_15(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_16(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_17(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_18(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_19(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_20(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_21(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_22(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_23(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_24(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_25(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_26(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_27(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_28(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_29(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_30(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_31(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_32(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_33(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_34(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_35(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_36(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_37(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_38(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_39(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_40(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_41(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_42(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_43(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_44(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_45(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_46(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_47(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_48(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_49(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_50(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_51(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_52(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_53(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_54(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_55(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_56(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_57(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_58(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_59(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_60(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_61(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_62(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_63(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_64(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_65(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_66(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_67(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_68(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_69(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_70(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_71(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_72(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_73(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_74(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_75(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_76(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_77(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_78(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_79(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_80(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_81(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_82(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_83(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_84(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_85(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_86(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_87(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_88(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_89(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_90(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_91(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_92(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_93(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_94(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_95(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_96(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_97(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_98(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_99(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_100(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_101(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_102(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_103(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_104(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_105(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_106(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_107(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_108(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_109(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_110(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_111(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_112(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_113(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_114(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_115(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_116(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_117(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_118(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_119(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_120(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_121(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_122(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_123(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_124(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_125(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_126(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_127(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_128(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_129(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_130(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_131(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_132(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_133(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_134(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_135(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_136(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_137(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_138(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_139(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_140(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_141(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_142(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_143(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_144(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_145(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_146(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_147(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_148(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_149(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_150(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_151(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_152(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_153(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_154(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_155(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_156(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_157(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_158(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_159(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_160(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_161(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_162(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_163(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_164(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_165(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_166(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_167(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_168(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_169(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_170(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_171(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_172(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_173(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_174(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_175(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_176(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_177(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_178(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_179(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_180(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_181(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_182(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_183(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_184(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_185(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_186(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_187(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_188(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_189(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_190(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_191(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_192(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_193(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_194(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_195(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_196(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_197(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_198(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_199(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_200(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_201(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_202(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_203(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_204(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_205(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_206(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_207(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_208(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_209(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_210(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_211(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_212(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_213(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_214(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_215(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_216(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_217(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_218(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_219(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_220(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_221(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_222(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_223(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_224(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_225(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_226(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_227(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_228(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_229(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_230(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_231(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_232(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_233(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_234(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_235(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_236(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_237(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_238(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_239(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_240(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_241(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_242(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_243(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_244(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_245(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_246(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_247(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_248(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_249(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_250(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_251(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_252(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_253(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_254(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_255(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_256(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_257(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_258(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_259(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_260(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_261(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_262(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_263(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_264(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_265(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_266(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_267(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_268(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_269(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_270(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_271(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_272(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_273(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_274(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_275(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_276(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_277(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_278(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_279(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_280(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_281(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_282(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_283(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_284(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_285(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_286(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_287(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_288(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_289(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_290(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_291(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_292(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_293(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_294(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_295(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_296(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_297(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_298(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_299(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_300(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_301(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_302(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_303(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_304(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_305(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_306(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_307(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_308(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_309(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_310(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_311(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_312(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_313(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_314(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_315(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_316(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_317(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_318(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_319(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_320(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_321(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_322(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_323(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_324(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_325(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_326(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_327(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_328(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_329(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_330(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_331(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_332(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_333(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_334(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_335(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_336(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_337(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_338(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_339(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_340(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_341(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_342(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_343(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_344(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_345(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_346(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_347(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_348(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_349(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_350(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_351(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_352(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_353(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_354(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_355(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_356(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_357(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_358(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_359(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_360(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_361(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_362(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_363(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_364(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_365(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_366(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_367(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_368(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_369(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_370(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_371(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_372(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_373(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_374(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_375(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_376(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_377(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_378(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_379(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_380(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_381(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_382(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_383(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_384(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_385(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_386(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_387(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_388(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_389(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_390(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_391(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_392(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_393(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_394(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_395(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_396(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_397(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_398(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_399(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_400(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_401(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_402(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_403(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_404(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_405(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_406(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_407(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_408(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_409(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_410(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_411(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_412(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_413(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_414(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_415(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_416(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_417(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_418(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_419(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_420(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_421(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_422(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_423(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_424(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_425(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_426(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_427(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_428(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_429(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_430(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_431(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_432(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_433(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_434(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_435(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_436(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_437(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_438(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_439(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_440(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_441(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_442(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_443(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_444(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_445(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_446(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_447(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_448(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_449(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_450(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_451(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_452(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_453(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_454(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_455(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_456(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_457(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_458(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_459(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_460(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_461(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_462(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_463(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_464(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_465(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_466(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_467(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_468(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_469(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_470(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_471(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_472(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_473(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_474(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_475(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_476(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_477(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_478(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_479(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_480(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_481(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_482(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_483(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_484(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_485(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_486(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_487(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_488(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_489(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_490(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_491(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_492(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_493(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_494(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_495(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_496(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_497(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_498(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_499(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_500(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_501(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_502(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_503(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_504(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_505(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_506(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_507(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_508(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_509(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_510(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_511(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_512(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_513(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_514(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_515(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_516(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_517(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_518(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_519(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_520(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_521(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_522(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_523(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_524(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_525(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_526(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_527(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_528(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_529(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_530(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_531(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_532(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_533(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_534(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_535(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_536(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_537(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_538(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_539(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_540(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_541(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_542(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_543(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_544(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_545(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_546(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_547(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_548(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_549(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_550(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_551(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_552(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_553(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_554(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_555(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_556(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_557(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_558(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_559(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_560(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_561(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_562(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_563(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_564(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_565(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_566(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_567(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_568(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_569(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_570(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_571(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_572(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_573(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_574(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_575(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_576(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_577(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_578(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_579(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_580(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_581(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_582(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_583(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_584(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_585(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_586(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_587(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_588(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_589(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_590(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_591(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_592(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_593(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_594(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_595(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_596(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_597(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_598(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_599(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_600(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_601(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_602(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_603(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_604(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_605(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_606(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_607(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_608(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_609(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_610(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_611(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_612(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_613(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_614(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_615(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_616(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_617(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_618(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_619(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_620(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_621(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_622(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_623(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_624(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_625(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_626(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_627(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_628(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_629(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_630(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_631(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_632(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_633(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_634(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_635(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_636(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_637(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_638(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_639(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_640(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_641(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_642(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_643(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_644(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_645(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_646(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_647(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_648(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_649(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_650(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_651(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_652(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_653(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_654(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_655(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_656(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_657(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_658(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_659(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_660(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_661(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_662(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_663(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_664(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_665(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_666(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_667(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_668(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_669(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_670(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_671(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_672(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_673(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_674(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_675(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_676(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_677(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_678(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_679(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_680(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_681(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_682(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_683(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_684(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_685(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_686(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_687(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_688(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_689(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_690(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_691(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_692(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_693(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_694(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_695(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_696(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_697(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_698(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_699(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_700(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_701(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_702(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_703(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_704(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_705(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_706(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_707(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_708(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_709(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_710(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_711(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_712(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_713(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_714(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_715(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_716(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_717(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_718(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_719(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_720(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_721(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_722(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_723(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_724(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_725(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_726(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_727(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_728(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_729(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_730(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_731(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_732(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_733(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_734(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_735(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_736(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_737(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_738(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_739(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_740(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_741(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_742(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_743(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_744(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_745(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_746(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_747(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_748(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_749(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_750(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_751(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_752(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_753(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_754(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_755(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_756(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_757(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_758(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_759(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_760(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_761(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_762(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_763(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_764(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_765(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_766(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_767(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_768(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_769(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_770(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_771(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_772(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_773(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_774(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_775(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_776(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_777(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_778(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_779(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_780(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_781(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_782(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_783(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_784(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_785(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_786(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_787(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_788(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_789(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_790(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_791(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_792(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_793(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_794(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_795(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_796(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_797(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_798(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_799(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_800(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_801(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_802(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_803(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_804(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_805(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_806(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_807(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_808(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_809(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_810(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_811(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_812(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_813(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_814(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_815(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_816(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_817(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_818(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_819(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_820(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_821(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_822(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_823(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_824(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_825(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_826(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_827(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_828(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_829(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_830(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_831(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_832(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_833(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_834(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_835(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_836(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_837(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_838(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_839(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_840(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_841(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_842(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_843(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_844(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_845(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_846(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_847(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_848(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_849(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_850(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_851(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_852(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_853(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_854(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_855(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_856(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_857(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_858(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_859(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_860(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_861(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_862(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_863(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_864(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_865(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_866(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_867(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_868(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_869(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_870(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_871(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_872(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_873(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_874(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_875(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_876(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_877(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_878(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_879(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_880(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_881(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_882(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_883(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_884(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_885(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_886(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_887(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_888(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_889(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_890(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_891(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_892(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_893(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_894(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_895(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_896(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_897(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_898(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_899(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_900(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_901(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
}
| TODO: should increase instead | function approve_127(address spender, uint value) public returns (bool ok) {
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
| 6,453,840 | [
1,
6241,
30,
1410,
10929,
3560,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
6617,
537,
67,
14260,
12,
2867,
17571,
264,
16,
2254,
460,
13,
1071,
1135,
261,
6430,
1529,
13,
288,
203,
565,
389,
12908,
4524,
63,
3576,
18,
15330,
6362,
87,
1302,
264,
65,
273,
460,
31,
203,
565,
3626,
1716,
685,
1125,
12,
1234,
18,
15330,
16,
17571,
264,
16,
460,
11272,
203,
565,
327,
638,
31,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts
// Tokenfy Contracts
// _____ _ _____ _ _ _____ _ _ ______ _ _____ _ _ _ _ _ _____ _ _ _ _ _____
// / __ \ | | / __ \ | | (_) / __ \| | | | | ___ \ | | / __ \ | || | | | | | | | | ___| | |(_)| | (_) |____ |
// | / \/ _ __ _ _ _ __ | |_ ___ | / \/ __ _ _ __ _ __ __ _ | |__ _ ___ | / \/| | _ _ | |__ | |_/ / _ __ __ _ _ __ __| | | / \/ ___ | || | ___ ___ | |_ __ _ | |__ | | ___ | |__ __| | _ | |_ _ ___ _ __ / /
// | | | '__|| | | || '_ \ | __|/ _ \ | | / _` || '_ \ | '_ \ / _` || '_ \ | |/ __| | | | || | | || '_ \ | ___ \| '__|/ _` || '_ \ / _` | | | / _ \ | || | / _ \ / __|| __|/ _` || '_ \ | | / _ \ | __| / _` || || __|| | / _ \ | '_ \ \ \
// | \__/\| | | |_| || |_) || |_| (_) | | \__/\| (_| || | | || | | || (_| || |_) || |\__ \ | \__/\| || |_| || |_) | | |_/ /| | | (_| || | | || (_| | | \__/\| (_) || || || __/| (__ | |_| (_| || |_) || || __/ | |___| (_| || || |_ | || (_) || | | | .___/ /
// \____/|_| \__, || .__/ \__|\___/ \____/ \__,_||_| |_||_| |_| \__,_||_.__/ |_||___/ \____/|_| \__,_||_.__/ \____/ |_| \__,_||_| |_| \__,_| \____/ \___/ |_||_| \___| \___| \__|\__,_||_.__/ |_| \___| \____/ \__,_||_| \__||_| \___/ |_| |_| \____/
// __/ || |
// |___/ |_|
pragma solidity 0.8.11;
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
interface IERC1155 is IERC165 {
/**
* @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
*/
event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
/**
* @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
* transfers.
*/
event TransferBatch(
address indexed operator,
address indexed from,
address indexed to,
uint256[] ids,
uint256[] values
);
/**
* @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
* `approved`.
*/
event ApprovalForAll(address indexed account, address indexed operator, bool approved);
/**
* @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
*
* If an {URI} event was emitted for `id`, the standard
* https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
* returned by {IERC1155MetadataURI-uri}.
*/
event URI(string value, uint256 indexed id);
/**
* @dev Returns the amount of tokens of token type `id` owned by `account`.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) external view returns (uint256);
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids)
external
view
returns (uint256[] memory);
/**
* @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
*
* Emits an {ApprovalForAll} event.
*
* Requirements:
*
* - `operator` cannot be the caller.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
*
* See {setApprovalForAll}.
*/
function isApprovedForAll(address account, address operator) external view returns (bool);
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes calldata data
) external;
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] calldata ids,
uint256[] calldata amounts,
bytes calldata data
) external;
}
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
} else if (error == RecoverError.InvalidSignatureV) {
revert("ECDSA: invalid signature 'v' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else if (signature.length == 64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address, RecoverError) {
bytes32 s;
uint8 v;
assembly {
s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
v := add(shr(255, vs), 27)
}
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
if (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
}
library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract GanjiBrandCollectable is ERC721, Ownable, ReentrancyGuard {
using ECDSA for bytes32;
using Strings for uint256;
using SafeERC20 for IERC20;
uint256 private _currentIndex = 0;
uint256 private _totalBurned = 0;
string private _baseTokenURI = "https://metadata.api.tokenfy.com/19/metadata/";
string private _contractURI = "https://tokenfy-production-public.s3.us-east-2.amazonaws.com/19/contract-uri";
address public tokenfyAddress = 0xa6dD98031551C23bb4A2fBE2C4d524e8f737c6f7;
// sale currency settings
bool public ethEnabled = true;
bool public tokenfyEnabled = false;
// mint settings
uint256 public maxSupply = 2000;
uint256 public maxPerMint = 10;
uint256 public pricePerToken = 20000000000000000;
uint256 public tokenfyPrice = 0;
// presale settings
address private signerAddress;
mapping(address => uint256) public presaleMinted;
uint256 public presaleMaxSupply = 250;
uint256 public presaleMaxPerMint = 1;
uint256 public presalePricePerToken = 0;
uint256 public tokenfyPresalePrice = 0;
// activation flags
bool public instantRevealActive = false;
bool public presaleLive = false;
bool public saleLive = false;
bool public burnLive = false;
modifier presaleValid(bytes32 hash, bytes memory sig, uint256 qty, uint256 max, uint256 expiresAt) {
require(presaleLive, "Presale not live");
require(matchAddresSigner(hash, sig), "Invalid signer");
require(hashTransaction(msg.sender, qty, max, expiresAt) == hash, "Hash check failed");
require(expiresAt >= block.timestamp, "Signature is expired");
require(qty <= presaleMaxPerMint, "Max per mint exceeded");
require(presaleMinted[msg.sender] + qty <= max, "Max per wallet exceeded");
require(_currentIndex + qty <= presaleMaxSupply, "Exceeds max supply");
_;
}
modifier saleValid(uint256 qty) {
require(saleLive, "Sale not live");
require(qty <= maxPerMint, "Max per mint exceeded");
require(_currentIndex + qty <= maxSupply, "Exceeds max supply");
_;
}
constructor(address _signerAddress) ERC721("Crypto Cannabis Club Brand Collectable Edition 3", "Ganj") {
signerAddress = _signerAddress;
}
function presaleMint(
bytes32 hash,
bytes memory sig,
uint256 qty,
uint256 max,
uint256 expiresAt
) external payable nonReentrant presaleValid(hash, sig, qty, max, expiresAt) {
require(ethEnabled, "ETH not enabled");
require(presalePricePerToken * qty == msg.value, "Incorrect price");
presaleMinted[msg.sender] += qty;
for (uint256 i = 0; i < qty; i++) {
mintToken(msg.sender);
}
}
function presaleMintTokenfy(
bytes32 hash,
bytes memory sig,
uint256 qty,
uint256 max,
uint256 expiresAt,
uint256 value
) external nonReentrant presaleValid(hash, sig, qty, max, expiresAt) {
require(tokenfyEnabled, "TKNFY not enabled");
require(tokenfyPresalePrice * qty == value, "Incorrect price");
IERC20(tokenfyAddress).safeTransferFrom(msg.sender, address(this), value);
presaleMinted[msg.sender] += qty;
for (uint256 i = 0; i < qty; i++) {
mintToken(msg.sender);
}
}
function mint(uint256 qty) external payable nonReentrant saleValid(qty) {
require(ethEnabled, "ETH not enabled");
require(pricePerToken * qty == msg.value, "Incorrect price");
for (uint256 i = 0; i < qty; i++) {
mintToken(msg.sender);
}
}
function mintTokenfy(uint256 qty, uint256 value) external nonReentrant saleValid(qty) {
require(tokenfyEnabled, "TKNFY not enabled");
require(tokenfyPrice * qty == value, "Incorrect price");
IERC20(tokenfyAddress).safeTransferFrom(msg.sender, address(this), value);
for (uint256 i = 0; i < qty; i++) {
mintToken(msg.sender);
}
}
function adminMint(uint256 qty, address to) public onlyOwner {
require(qty > 0, "Must mint at least 1 token");
require(_currentIndex + qty <= maxSupply, "Exceeds max supply");
for (uint256 i = 0; i < qty; i++) {
mintToken(to);
}
}
function mintToken(address receiver) private {
_currentIndex += 1;
_safeMint(receiver, _currentIndex);
}
function hashTransaction(address sender, uint256 qty, uint256 max, uint256 expiresAt) private pure returns (bytes32) {
bytes32 hash = keccak256(
abi.encodePacked("\x19Ethereum Signed Message:\n32", keccak256(abi.encodePacked(sender, qty, max, expiresAt)))
);
return hash;
}
function matchAddresSigner(bytes32 hash, bytes memory signature) private view returns (bool) {
return signerAddress == hash.recover(signature);
}
function burn(uint256 tokenId) public nonReentrant {
require(burnLive, "Burn not live");
require(_isApprovedOrOwner(_msgSender(), tokenId), "Caller is not owner nor approved");
_totalBurned += 1;
_burn(tokenId);
}
function totalSupply() public view virtual returns (uint256) {
return _currentIndex - _totalBurned;
}
function exists(uint256 _tokenId) external view returns (bool) {
return _exists(_tokenId);
}
function _baseURI() internal view virtual override returns (string memory) {
return _baseTokenURI;
}
function setBaseURI(string memory newBaseURI) public onlyOwner {
_baseTokenURI = newBaseURI;
}
function setContractURI(string memory newuri) public onlyOwner {
_contractURI = newuri;
}
function contractURI() public view returns (string memory) {
return _contractURI;
}
// withdrawing earnings
function withdrawEarnings() public onlyOwner {
uint256 balance = address(this).balance;
payable(msg.sender).transfer(balance);
}
// reclaiming tokens
function reclaimERC20(IERC20 erc20Token, address to) public onlyOwner {
erc20Token.safeTransfer(to, erc20Token.balanceOf(address(this)));
}
function reclaimERC1155(IERC1155 erc1155Token, uint256 id, address to) public onlyOwner {
erc1155Token.safeTransferFrom(address(this), to, id, 1, "");
}
function reclaimERC721(IERC721 erc721Token, uint256 id, address to) public onlyOwner {
erc721Token.safeTransferFrom(address(this), to, id);
}
// activating contact events
function setPresaleLive(bool live) external onlyOwner {
presaleLive = live;
}
function setSaleLive(bool live) external onlyOwner {
saleLive = live;
}
function setBurnLive(bool live) external onlyOwner {
burnLive = live;
}
function setInstantReveal(bool reveal) external onlyOwner {
instantRevealActive = reveal;
}
// mint-related settings
function changePrice(uint256 newPrice) external onlyOwner {
pricePerToken = newPrice;
}
function changeTokenfyPrice(uint256 newPrice) external onlyOwner {
tokenfyPrice = newPrice;
}
function changeMaxSupply(uint256 _maxSupply) external onlyOwner {
require(_maxSupply >= _currentIndex, "Must be larger than minted count");
maxSupply = _maxSupply;
}
function setMaxPerMint(uint256 _maxPerMint) external onlyOwner {
require(_maxPerMint > 0, "Invalid max per mint");
maxPerMint = _maxPerMint;
}
// presale-related settings
function changePresalePrice(uint256 newPrice) external onlyOwner {
presalePricePerToken = newPrice;
}
function changeTokenfyPresalePrice(uint256 newPrice) external onlyOwner {
tokenfyPresalePrice = newPrice;
}
function changePresaleMaxSupply(uint256 _maxSupply) external onlyOwner {
require(_maxSupply >= _currentIndex, "Must be larger than minted count");
require(_maxSupply <= maxSupply, "Must be less than max supply");
presaleMaxSupply = _maxSupply;
}
function setPresaleMaxPerMint(uint256 _maxPerMint) external onlyOwner {
require(_maxPerMint > 0, "Must be > 0");
presaleMaxPerMint = _maxPerMint;
}
function setSignerAddress(address _signer) external onlyOwner {
signerAddress = _signer;
}
function setETHEnabled(bool enabled) external onlyOwner {
ethEnabled = enabled;
}
function setTokenfyEnabled(bool enabled) external onlyOwner {
tokenfyEnabled = enabled;
}
} | sale currency settings mint settings presale settings activation flags | contract GanjiBrandCollectable is ERC721, Ownable, ReentrancyGuard {
using ECDSA for bytes32;
using Strings for uint256;
using SafeERC20 for IERC20;
uint256 private _currentIndex = 0;
uint256 private _totalBurned = 0;
address public tokenfyAddress = 0xa6dD98031551C23bb4A2fBE2C4d524e8f737c6f7;
bool public ethEnabled = true;
bool public tokenfyEnabled = false;
uint256 public maxSupply = 2000;
uint256 public maxPerMint = 10;
uint256 public pricePerToken = 20000000000000000;
uint256 public tokenfyPrice = 0;
address private signerAddress;
mapping(address => uint256) public presaleMinted;
uint256 public presaleMaxSupply = 250;
uint256 public presaleMaxPerMint = 1;
uint256 public presalePricePerToken = 0;
uint256 public tokenfyPresalePrice = 0;
bool public instantRevealActive = false;
bool public presaleLive = false;
bool public saleLive = false;
bool public burnLive = false;
modifier presaleValid(bytes32 hash, bytes memory sig, uint256 qty, uint256 max, uint256 expiresAt) {
require(presaleLive, "Presale not live");
require(matchAddresSigner(hash, sig), "Invalid signer");
require(hashTransaction(msg.sender, qty, max, expiresAt) == hash, "Hash check failed");
require(expiresAt >= block.timestamp, "Signature is expired");
require(qty <= presaleMaxPerMint, "Max per mint exceeded");
require(presaleMinted[msg.sender] + qty <= max, "Max per wallet exceeded");
require(_currentIndex + qty <= presaleMaxSupply, "Exceeds max supply");
_;
}
modifier saleValid(uint256 qty) {
require(saleLive, "Sale not live");
require(qty <= maxPerMint, "Max per mint exceeded");
require(_currentIndex + qty <= maxSupply, "Exceeds max supply");
_;
}
constructor(address _signerAddress) ERC721("Crypto Cannabis Club Brand Collectable Edition 3", "Ganj") {
signerAddress = _signerAddress;
}
function presaleMint(
bytes32 hash,
bytes memory sig,
uint256 qty,
uint256 max,
uint256 expiresAt
) external payable nonReentrant presaleValid(hash, sig, qty, max, expiresAt) {
require(ethEnabled, "ETH not enabled");
require(presalePricePerToken * qty == msg.value, "Incorrect price");
presaleMinted[msg.sender] += qty;
for (uint256 i = 0; i < qty; i++) {
mintToken(msg.sender);
}
}
function presaleMint(
bytes32 hash,
bytes memory sig,
uint256 qty,
uint256 max,
uint256 expiresAt
) external payable nonReentrant presaleValid(hash, sig, qty, max, expiresAt) {
require(ethEnabled, "ETH not enabled");
require(presalePricePerToken * qty == msg.value, "Incorrect price");
presaleMinted[msg.sender] += qty;
for (uint256 i = 0; i < qty; i++) {
mintToken(msg.sender);
}
}
function presaleMintTokenfy(
bytes32 hash,
bytes memory sig,
uint256 qty,
uint256 max,
uint256 expiresAt,
uint256 value
) external nonReentrant presaleValid(hash, sig, qty, max, expiresAt) {
require(tokenfyEnabled, "TKNFY not enabled");
require(tokenfyPresalePrice * qty == value, "Incorrect price");
IERC20(tokenfyAddress).safeTransferFrom(msg.sender, address(this), value);
presaleMinted[msg.sender] += qty;
for (uint256 i = 0; i < qty; i++) {
mintToken(msg.sender);
}
}
function presaleMintTokenfy(
bytes32 hash,
bytes memory sig,
uint256 qty,
uint256 max,
uint256 expiresAt,
uint256 value
) external nonReentrant presaleValid(hash, sig, qty, max, expiresAt) {
require(tokenfyEnabled, "TKNFY not enabled");
require(tokenfyPresalePrice * qty == value, "Incorrect price");
IERC20(tokenfyAddress).safeTransferFrom(msg.sender, address(this), value);
presaleMinted[msg.sender] += qty;
for (uint256 i = 0; i < qty; i++) {
mintToken(msg.sender);
}
}
function mint(uint256 qty) external payable nonReentrant saleValid(qty) {
require(ethEnabled, "ETH not enabled");
require(pricePerToken * qty == msg.value, "Incorrect price");
for (uint256 i = 0; i < qty; i++) {
mintToken(msg.sender);
}
}
function mint(uint256 qty) external payable nonReentrant saleValid(qty) {
require(ethEnabled, "ETH not enabled");
require(pricePerToken * qty == msg.value, "Incorrect price");
for (uint256 i = 0; i < qty; i++) {
mintToken(msg.sender);
}
}
function mintTokenfy(uint256 qty, uint256 value) external nonReentrant saleValid(qty) {
require(tokenfyEnabled, "TKNFY not enabled");
require(tokenfyPrice * qty == value, "Incorrect price");
IERC20(tokenfyAddress).safeTransferFrom(msg.sender, address(this), value);
for (uint256 i = 0; i < qty; i++) {
mintToken(msg.sender);
}
}
function mintTokenfy(uint256 qty, uint256 value) external nonReentrant saleValid(qty) {
require(tokenfyEnabled, "TKNFY not enabled");
require(tokenfyPrice * qty == value, "Incorrect price");
IERC20(tokenfyAddress).safeTransferFrom(msg.sender, address(this), value);
for (uint256 i = 0; i < qty; i++) {
mintToken(msg.sender);
}
}
function adminMint(uint256 qty, address to) public onlyOwner {
require(qty > 0, "Must mint at least 1 token");
require(_currentIndex + qty <= maxSupply, "Exceeds max supply");
for (uint256 i = 0; i < qty; i++) {
mintToken(to);
}
}
function adminMint(uint256 qty, address to) public onlyOwner {
require(qty > 0, "Must mint at least 1 token");
require(_currentIndex + qty <= maxSupply, "Exceeds max supply");
for (uint256 i = 0; i < qty; i++) {
mintToken(to);
}
}
function mintToken(address receiver) private {
_currentIndex += 1;
_safeMint(receiver, _currentIndex);
}
function hashTransaction(address sender, uint256 qty, uint256 max, uint256 expiresAt) private pure returns (bytes32) {
bytes32 hash = keccak256(
abi.encodePacked("\x19Ethereum Signed Message:\n32", keccak256(abi.encodePacked(sender, qty, max, expiresAt)))
);
return hash;
}
function matchAddresSigner(bytes32 hash, bytes memory signature) private view returns (bool) {
return signerAddress == hash.recover(signature);
}
function burn(uint256 tokenId) public nonReentrant {
require(burnLive, "Burn not live");
require(_isApprovedOrOwner(_msgSender(), tokenId), "Caller is not owner nor approved");
_totalBurned += 1;
_burn(tokenId);
}
function totalSupply() public view virtual returns (uint256) {
return _currentIndex - _totalBurned;
}
function exists(uint256 _tokenId) external view returns (bool) {
return _exists(_tokenId);
}
function _baseURI() internal view virtual override returns (string memory) {
return _baseTokenURI;
}
function setBaseURI(string memory newBaseURI) public onlyOwner {
_baseTokenURI = newBaseURI;
}
function setContractURI(string memory newuri) public onlyOwner {
_contractURI = newuri;
}
function contractURI() public view returns (string memory) {
return _contractURI;
}
function withdrawEarnings() public onlyOwner {
uint256 balance = address(this).balance;
payable(msg.sender).transfer(balance);
}
function reclaimERC20(IERC20 erc20Token, address to) public onlyOwner {
erc20Token.safeTransfer(to, erc20Token.balanceOf(address(this)));
}
function reclaimERC1155(IERC1155 erc1155Token, uint256 id, address to) public onlyOwner {
erc1155Token.safeTransferFrom(address(this), to, id, 1, "");
}
function reclaimERC721(IERC721 erc721Token, uint256 id, address to) public onlyOwner {
erc721Token.safeTransferFrom(address(this), to, id);
}
function setPresaleLive(bool live) external onlyOwner {
presaleLive = live;
}
function setSaleLive(bool live) external onlyOwner {
saleLive = live;
}
function setBurnLive(bool live) external onlyOwner {
burnLive = live;
}
function setInstantReveal(bool reveal) external onlyOwner {
instantRevealActive = reveal;
}
function changePrice(uint256 newPrice) external onlyOwner {
pricePerToken = newPrice;
}
function changeTokenfyPrice(uint256 newPrice) external onlyOwner {
tokenfyPrice = newPrice;
}
function changeMaxSupply(uint256 _maxSupply) external onlyOwner {
require(_maxSupply >= _currentIndex, "Must be larger than minted count");
maxSupply = _maxSupply;
}
function setMaxPerMint(uint256 _maxPerMint) external onlyOwner {
require(_maxPerMint > 0, "Invalid max per mint");
maxPerMint = _maxPerMint;
}
function changePresalePrice(uint256 newPrice) external onlyOwner {
presalePricePerToken = newPrice;
}
function changeTokenfyPresalePrice(uint256 newPrice) external onlyOwner {
tokenfyPresalePrice = newPrice;
}
function changePresaleMaxSupply(uint256 _maxSupply) external onlyOwner {
require(_maxSupply >= _currentIndex, "Must be larger than minted count");
require(_maxSupply <= maxSupply, "Must be less than max supply");
presaleMaxSupply = _maxSupply;
}
function setPresaleMaxPerMint(uint256 _maxPerMint) external onlyOwner {
require(_maxPerMint > 0, "Must be > 0");
presaleMaxPerMint = _maxPerMint;
}
function setSignerAddress(address _signer) external onlyOwner {
signerAddress = _signer;
}
function setETHEnabled(bool enabled) external onlyOwner {
ethEnabled = enabled;
}
function setTokenfyEnabled(bool enabled) external onlyOwner {
tokenfyEnabled = enabled;
}
} | 1,172,259 | [
1,
87,
5349,
5462,
1947,
312,
474,
1947,
4075,
5349,
1947,
10027,
2943,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
611,
304,
78,
17632,
7884,
10808,
429,
353,
4232,
39,
27,
5340,
16,
14223,
6914,
16,
868,
8230,
12514,
16709,
288,
203,
565,
1450,
7773,
19748,
364,
1731,
1578,
31,
203,
202,
9940,
8139,
364,
2254,
5034,
31,
203,
565,
1450,
14060,
654,
39,
3462,
364,
467,
654,
39,
3462,
31,
203,
203,
565,
2254,
5034,
3238,
389,
2972,
1016,
273,
374,
31,
203,
565,
2254,
5034,
3238,
389,
4963,
38,
321,
329,
273,
374,
31,
203,
203,
203,
565,
1758,
1071,
1147,
74,
93,
1887,
273,
374,
6995,
26,
72,
40,
29,
3672,
6938,
2539,
21,
39,
4366,
9897,
24,
37,
22,
74,
5948,
22,
39,
24,
72,
25,
3247,
73,
28,
74,
27,
6418,
71,
26,
74,
27,
31,
203,
203,
565,
1426,
1071,
13750,
1526,
273,
638,
31,
203,
565,
1426,
1071,
1147,
74,
93,
1526,
273,
629,
31,
203,
377,
203,
202,
11890,
5034,
1071,
943,
3088,
1283,
273,
16291,
31,
203,
202,
11890,
5034,
1071,
943,
2173,
49,
474,
273,
1728,
31,
203,
202,
11890,
5034,
1071,
6205,
2173,
1345,
273,
576,
12648,
12648,
31,
203,
565,
2254,
5034,
1071,
1147,
74,
93,
5147,
273,
374,
31,
203,
203,
565,
1758,
3238,
10363,
1887,
31,
203,
565,
2874,
12,
2867,
516,
2254,
5034,
13,
1071,
4075,
5349,
49,
474,
329,
31,
203,
202,
11890,
5034,
1071,
4075,
5349,
2747,
3088,
1283,
273,
16927,
31,
203,
202,
11890,
5034,
1071,
4075,
5349,
2747,
2173,
49,
474,
273,
404,
31,
203,
202,
11890,
5034,
1071,
4075,
5349,
5147,
2173,
1345,
2
] |
./partial_match/4/0xE5b4Cda4dCC0bE5BEA97dDbEE9B584CB7f1ab1ae/sources/coffer_Factory.sol | those methods are called by the legacy contract and they must ensure msg.sender to be the contract address | contract UpgradedStandardToken_CT is StandardToken_CT{
function transferByLegacy(address from, address to, uint value) public;
function transferFromByLegacy(address sender, address from, address spender, uint value) public;
function approveByLegacy(address from, address spender, uint value) public;
}
| 8,523,032 | [
1,
451,
2584,
2590,
854,
2566,
635,
326,
8866,
6835,
471,
2898,
1297,
3387,
1234,
18,
15330,
358,
506,
326,
6835,
1758,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
1948,
19305,
8336,
1345,
67,
1268,
353,
8263,
1345,
67,
1268,
95,
203,
565,
445,
7412,
858,
12235,
12,
2867,
628,
16,
1758,
358,
16,
2254,
460,
13,
1071,
31,
203,
565,
445,
7412,
1265,
858,
12235,
12,
2867,
5793,
16,
1758,
628,
16,
1758,
17571,
264,
16,
2254,
460,
13,
1071,
31,
203,
565,
445,
6617,
537,
858,
12235,
12,
2867,
628,
16,
1758,
17571,
264,
16,
2254,
460,
13,
1071,
31,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@chainlink/contracts/src/v0.6/vendor/SafeMathChainlink.sol";
import "@chainlink/contracts/src/v0.6/interfaces/LinkTokenInterface.sol";
import "./LuckyMachineCoordinator.sol";
contract LuckyMachine is Ownable {
LinkTokenInterface internal LINK;
using SafeMathChainlink for uint256;
address payable public machineCoordinator;
struct Game {
uint id;
address payable player;
uint bet;
uint pick;
uint winner;
bool played;
}
uint internal gas1;
uint internal gas2;
uint internal gas3;
uint internal gas4;
uint internal gas5;
uint internal gas6;
uint internal gas7;
uint internal gas8;
uint internal gas9;
uint internal gas10;
uint internal gas11;
uint public maxPick;
uint public maxBet;
uint public minBet;
uint internal _unplayedBets;
uint internal _currentGame;
address payable public payoutAddress;
uint public payout; // Payout Ratio (payout : 1), e.g. 10 : 1 = payout (10) * bet (X)
mapping(address => bool) public authorizedAddress;
mapping(address => bool) public gasFreeBetAllowed;
mapping(uint => Game) public games;
mapping(bytes32 => uint) internal _gameRequests;
mapping(address => uint) public lastGameCreated;
event GamePlayed(address _player, uint256 _bet, uint256 _pick, uint256 _winner, uint256 _payout);
constructor(address payable _machineCoordinator, address payable _payoutAddress, address _linkToken, uint _maxBet, uint _minBet, uint _maxPick, uint _payout) public {
machineCoordinator = _machineCoordinator;
_currentGame = 1;
_unplayedBets = 0;
payoutAddress = _payoutAddress;
minBet = _minBet;
maxBet = _maxBet;
maxPick = _maxPick;
payout = _payout;
gas1 = 1;
gas2 = 1;
gas3 = 1;
gas4 = 1;
gas5 = 1;
gas6 = 1;
gas7 = 1;
gas8 = 1;
gas9 = 1;
gas10 = 1;
gas11 = 1;
LINK = LinkTokenInterface(_linkToken);
uint256 approvalAmount = 115792089237316195423570985008687907853269984665640564039457584007913129639935;
LINK.approve(machineCoordinator, approvalAmount);
}
receive() external payable {
}
modifier onlyAuthorized() {
require(owner() == msg.sender || authorizedAddress[msg.sender], "caller is not authorized");
_;
}
function getLinkBalance() public view returns(uint){
return LINK.balanceOf(address(this));
}
/**
* @dev Returns whether bet is within range of minimum and maximum
* allowable bets
*/
function betInRange(uint bet) internal view returns(bool){
if (bet >= minBet && bet <= maxBet) {
return true;
} else {
return false;
}
}
/**
* @dev Returns whether a winning bet can by paid out by machine. Balance of
* machine must be at least (value of bet * payout).
*/
function betPayable(uint bet) virtual public view returns(bool){
return (address(this).balance.sub(_unplayedBets) >= bet.mul(payout));
}
function canPayFee(uint _fee) public view returns(bool){
LuckyMachineCoordinator coord = LuckyMachineCoordinator(machineCoordinator);
uint256 coordBalance = coord.getLinkBalance();
uint256 thisBalance = LINK.balanceOf(address(this));
return (thisBalance >= _fee || coordBalance >= _fee);
}
/**
* @dev Returns Game ID, which can be queried for status of game using games('gameID').
* This will fail if machine conditions are not met.
* Use safeBetFor() if all conditions have not been pre-verified.
*/
function placeBetFor(address payable player, uint pick) virtual public payable{
require(msg.value >= minBet, "minimum bet not met");
if(gas1 == 1) {
delete gas1;
delete gas2;
delete gas3;
delete gas4;
delete gas5;
delete gas6;
delete gas7;
delete gas8;
delete gas9;
delete gas10;
delete gas11;
}
_unplayedBets = _unplayedBets.add(msg.value);
createGame(player, msg.value, pick);
playGame(_currentGame);
lastGameCreated[player] = _currentGame;
}
/**
* @dev Returns Game ID, which can be queried for status of game using games('gameID').
* Places bet after ensuring all conditions are met (bet within minimum - maximum
* range, maximum pick not exceeded, winning bet is payable).
*/
function safeBetFor(address payable player, uint pick) virtual public payable{
require(betPayable(msg.value), "Contract has insufficint funds to payout possible win.");
require(pick <= maxPick && pick > 0, "Outside of pickable bounds");
require(betInRange(msg.value),"Outisde of bet range.");
if(gas1 == 1) {
delete gas1;
delete gas2;
delete gas3;
delete gas4;
delete gas5;
delete gas6;
delete gas7;
delete gas8;
delete gas9;
delete gas10;
delete gas11;
}
_unplayedBets = _unplayedBets.add(msg.value);
createGame(player, msg.value, pick);
playGame(_currentGame);
lastGameCreated[player] = _currentGame;
}
/**
* @dev Creates a Game record, which is updated as game is played.
*/
function createGame(address payable _player, uint _bet, uint _pick) virtual internal {
_currentGame = _currentGame.add(1);
Game memory newGame = Game ({
id: _currentGame,
player: _player,
bet: _bet,
pick: _pick,
winner: 0,
played: false
});
games[newGame.id] = newGame;
}
/**
* @dev If game is ready to be played, but random number not yet generated,
* this function may be called. Limited to only when bet is placed to avoid
* over-calling / over-spending Link since random number is generated with
* each call of this. replayGame() may be called by owner in cases of "stuck"
* or unplayed games.
*/
function playGame(uint gameID) virtual internal {
require(games[gameID].played == false, "game already played");
bytes32 reqID = getRandomNumber();
_gameRequests[reqID] = gameID;
}
/**
* @dev Requests a random number, which will be returned through the
* fulfillRandomness() function.
*/
function getRandomNumber() internal returns (bytes32 requestId) {
LuckyMachineCoordinator mc = LuckyMachineCoordinator(machineCoordinator);
return mc.getRandomNumbers(1);
}
/**
* @dev Called by Machine Coordinator only once number is generated. Gas reserves are
* refilled here so they can be cleared for gas savings when next bet is placed.
*/
function fulfillRandomness(bytes32 requestId, uint256[] memory randomness) virtual external {
// ONLY CALLABLE BY MACHINE COORDINATOR
require(msg.sender == machineCoordinator);
Game storage g = games[_gameRequests[requestId]];
if(g.id > 0 && g.played == false){
if(g.bet > maxBet) {
g.bet = maxBet;
}
uint totalPayout = g.bet.mul(payout).add(g.bet);
require(address(this).balance >= totalPayout, "Contract balance too low to play");
g.winner = randomness[0].mod(maxPick).add(1);
g.played = true;
if(_unplayedBets >= g.bet) {
_unplayedBets -= g.bet;
} else {
_unplayedBets = 0;
}
if (g.pick == g.winner) {
g.player.transfer(totalPayout);
} else {
totalPayout = 0;
}
emit GamePlayed(g.player, g.bet, g.pick, g.winner, totalPayout);
}
gas1 = 1;
gas2 = 1;
gas3 = 1;
gas4 = 1;
gas5 = 1;
gas6 = 1;
gas7 = 1;
gas8 = 1;
gas9 = 1;
gas10 = 1;
gas11 = 1;
}
/**
* @dev Returns summary of machine requirements for play and payout multiplier.
*/
function getSummary() public view returns(uint, uint, uint, uint) {
//minBet, maxBet, payout, maxPick
return(minBet, maxBet, payout, maxPick);
}
// Authorized Functions
/**
* @dev Request a refund for an unplayed game. If game is created, but
* machine conditions are not appropriate to allow play, no number will
* be generated and player or authorized address can request refund.
* Regardless of who requests refund, payout will always be to player
* listed in game.
*/
function requestRefund(uint gameID) virtual public{
Game storage g = games[gameID];
require(authorizedAddress[msg.sender] || owner() == msg.sender || g.player == msg.sender, "Not authorized to request refund");
require(g.played == false, "Game already complete. No refund possible.");
require(address(this).balance >= g.bet, "Contract balance too low. Please try again later.");
g.played = true;
if(_unplayedBets >= g.bet) {
_unplayedBets -= g.bet;
} else {
_unplayedBets = 0;
}
g.player.transfer(g.bet);
}
/**
* @dev Withdraw specified amount of ETH from machine. Amount must be less than
* any unplayed bets in machine to allow for refunds.
*/
function withdrawEth(uint amount) public onlyAuthorized {
require ((address(this).balance - amount) >= _unplayedBets, "Can't withdraw unplayed bets");
payoutAddress.transfer(amount);
}
/**
* @dev Withdraw specified amount of LINK from machine.
*/
function withdrawLink(uint amount) public onlyAuthorized {
LINK.transfer(payoutAddress, amount);
}
// Owner Functions
/**
* @dev Add any address as authorized user. Can be used to whitelist other contracts
* that may want to interact with authorized functions.
*/
function setAuthorizedUser(address userAddress, bool authorized) public onlyOwner {
authorizedAddress[userAddress] = authorized;
}
/**
* @dev Updates the address to which all withdrawals of ETH & LINK will be sent. If
* machine is closed (all funds withdrawn), this address receives all available funds.
*/
function setPayoutAddress(address payable _payoutAddress) public onlyOwner {
payoutAddress = _payoutAddress;
}
/**
* @dev Withdraws all available funds from the machine, leaving behind only
* _unplayedBets, which must remain for any refund requests. This does not
* do anything to halt operations other than removing funding, which
* automatically disallows play. If machine is re-funded, play may continue.
*/
function closeMachine() public onlyOwner {
uint availableContractBalance = address(this).balance.sub(_unplayedBets);
payoutAddress.transfer(availableContractBalance);
if (LINK.balanceOf(address(this)) > 0) {
LINK.transfer(payoutAddress, LINK.balanceOf(address(this)));
}
}
/**
* @dev Can update LINK address if necessary. Should not have to call this,
* but herein case token address is updated for any reason. Can also be set to any
* ERC-20 token in case of other tokens inadvertently sent to contract.
*/
function setLINK(address _linkAddress) public onlyOwner {
LINK = LinkTokenInterface(_linkAddress);
}
/**
* @dev Option to replay any games that may have been created, but unable to complete initial
* play for some reason. Unplayed games may be refunded or replayed until the number has been
* generated and game is marked as played.
*/
function replayGame(uint gameID) virtual public onlyOwner {
playGame(gameID);
}
}
contract LuckyMachineFactory{
address[] public machines;
mapping(address => address[]) internal ownedMachines;
/**
* @dev Used to create a LuckyMachine that can be verified and included in the
* factory list.
*/
function createMachine(address payable machineCoordinator, address linkToken, uint maxBet, uint minBet, uint maxPick, uint payout) public returns(address){
LuckyMachine newMachine = new LuckyMachine(machineCoordinator, msg.sender, linkToken, maxBet, minBet, maxPick, payout);
newMachine.transferOwnership(msg.sender);
address newMachineAddress = address(newMachine);
machines.push(newMachineAddress);
ownedMachines[msg.sender].push(newMachineAddress);
return newMachineAddress;
}
/**
* @dev Returns a list of all machines created from this factory. Useful to verify
* a machine was setup appropriately and is a "legitimate" LuckyMachine.
*/
function getMachines() public view returns (address[] memory) {
return machines;
}
/**
* @dev Returns a list of all machines created by the sender.
*/
function getOwnedMachines() public view returns (address[] memory) {
return ownedMachines[msg.sender];
}
}
| * @dev Returns whether a winning bet can by paid out by machine. Balance of machine must be at least (value of bet payout)./ | function betPayable(uint bet) virtual public view returns(bool){
return (address(this).balance.sub(_unplayedBets) >= bet.mul(payout));
}
| 2,500,325 | [
1,
1356,
2856,
279,
5657,
2093,
2701,
848,
635,
30591,
596,
635,
5228,
18,
30918,
434,
5228,
1297,
506,
622,
4520,
261,
1132,
434,
2701,
225,
293,
2012,
2934,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
2701,
9148,
429,
12,
11890,
2701,
13,
5024,
1071,
1476,
1135,
12,
6430,
15329,
203,
3639,
327,
261,
2867,
12,
2211,
2934,
12296,
18,
1717,
24899,
318,
1601,
329,
38,
2413,
13,
1545,
2701,
18,
16411,
12,
84,
2012,
10019,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.18;
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title ERC20 interface
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
/**
* @dev total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @param _spender address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @title SimpleToken
* @dev Very simple ERC20 Token example, where all tokens are pre-assigned to the creator.
* Note they can later distribute these tokens as they wish using `transfer` and other
*/
contract XXXToken is StandardToken , Ownable {
string public constant name = "XXXToken"; // solium-disable-line uppercase
string public constant symbol = "XXX"; // solium-disable-line uppercase
uint8 public constant decimals = 18; // solium-disable-line uppercase
uint256 public constant INITIAL_SUPPLY = 30000000 * (10 ** uint256(decimals));
uint256 public MINTING_SUPPLY = 9000000 * (10 ** uint256(decimals));
/**
* @dev Constructor that gives msg.sender all of existing tokens.
*/
function XXXToken() public {
totalSupply_ = INITIAL_SUPPLY;
balances[msg.sender] = INITIAL_SUPPLY;
Transfer(0x0, msg.sender, INITIAL_SUPPLY);
}
}
/**
* @dev lock coin
*/
contract XXXTokenVault is Ownable {
using SafeMath for uint256;
address private owner;
uint256 private teamTimeLock = 1 * 365 days;
// uint256 private mintingTimeLock = 90 days;
uint256 private mintingTimeLock = 90 seconds;
/** Reserve allocations */
mapping (address=>mapping(uint256 => mapping (uint8 => uint256))) public allocations;
/** When timeLocks are over (UNIX Timestamp) */
mapping (address=>mapping(uint256 => mapping (uint8 => uint256))) public timeLocks;
/** When this vault was locked (UNIX Timestamp)*/
uint256 private lockedAt = 0;
XXXToken public token;
/** Distributed reserved tokens */
event Distributed(uint256 lockId,uint8 batch, uint256 value);
/** Tokens have been locked */
event Locked(uint256 lockId,uint256 lockTime, uint256 value);
function XXXTokenVault(ERC20 _token) public {
owner = msg.sender;
token = XXXToken(_token);
}
/** lock team coin */
function lockTeam(uint256 lockId,uint256 _amount) public onlyOwner returns (bool){
lockedAt = block.timestamp;
timeLocks[msg.sender][lockId][0] = lockedAt.add(teamTimeLock);
timeLocks[msg.sender][lockId][1] = lockedAt.add(teamTimeLock.mul(2));
allocations[msg.sender][lockId][0] = _amount;
allocations[msg.sender][lockId][1] = 0;
Locked(lockId,lockedAt,_amount);
}
/** lock minting coin */
function lockMinting(address _owner, uint256 lockId,uint256 _amount) public returns (bool){
lockedAt = block.timestamp;
timeLocks[_owner][lockId][0] = lockedAt.add(mintingTimeLock);
timeLocks[_owner][lockId][1] = lockedAt.add(mintingTimeLock.mul(2));
allocations[_owner][lockId][0] = _amount.div(2);
allocations[_owner][lockId][1] = _amount.div(2);
Locked(lockId,lockedAt,_amount);
return true;
}
// Total number of tokens currently in the vault
function getTotalBalance() public view returns (uint256 tokensCurrentlyInVault) {
return token.balanceOf(address(this));
}
// Number of tokens that are still locked
function getLockedBalance(address parter,uint256 lockId) public view returns (uint256 tokensLocked) {
return allocations[parter][lockId][0].add(allocations[parter][lockId][1]);
}
//Claim tokens for reserve wallets
function claimTokenReserve(address parter,uint256 lockId,uint8 batch) public returns (bool){
require( batch==0 || batch==1);
require(allocations[parter][lockId][batch] !=0 &&timeLocks[parter][lockId][batch] !=0);
require(block.timestamp > timeLocks[parter][lockId][batch]);
uint256 amount = allocations[parter][lockId][batch];
require(token.transfer(msg.sender, amount));
allocations[parter][lockId][batch]=0;
timeLocks[parter][lockId][batch]=0;
Distributed(lockId,batch, amount);
return true;
}
}
contract TetherToken {
modifier onlyPayloadSize(uint size) {
require(!(msg.data.length < size + 4));
_;
}
function transfer(address _to, uint _value) public onlyPayloadSize(2 * 32);
function transferFrom(address _from, address _to, uint _value) public onlyPayloadSize(3 * 32);
function allowance(address _owner, address _spender) public constant returns (uint remaining);
function balanceOf(address who) public constant returns (uint);
}
contract Minting is Ownable {
using SafeMath for uint256;
address public admin;
mapping (address => uint256) public minters;
TetherToken public tokenUsdt;
XXXToken public tokenXXX;
XXXTokenVault public tokenVault;
address public beneficiary;
uint256 public price;
// Transfer all tokens on this contract back to the owner
function getUsdt(address _Account,uint256 _mount) external onlyOwner returns (bool){
tokenUsdt.transfer(_Account, _mount);
}
function Minting(address _adminAccount, ERC20 _tokenUsdt, ERC20 _tokenXXX, ERC20 _tokenVault, uint256 _price) public {
admin = _adminAccount;
transferOwnership(admin);
tokenXXX = XXXToken(_tokenXXX);
tokenUsdt = TetherToken(_tokenUsdt);
tokenVault = XXXTokenVault(_tokenVault);
price = _price;
}
function setPrice(uint256 _price) public onlyOwner returns (bool){
price = _price;
}
function setMinter(address minter, uint256 _usdtAmount) public onlyOwner returns (bool){
minters[minter]=_usdtAmount;
}
function mintingXXX(uint256 Appid, uint256 _usdtAmount) public returns (bool){
beneficiary = msg.sender;
require(minters[beneficiary]>0);
_preValidatePurchaseMinting(beneficiary, _usdtAmount);
uint256 _usdtToXXXAmount = _usdtAmount.mul(price).div(10000);
require(tokenXXX.balanceOf(address(this)) >= _usdtToXXXAmount);
tokenUsdt.transferFrom(msg.sender, address(this), _usdtAmount);
require(tokenXXX.transfer(tokenVault, _usdtToXXXAmount));
require(tokenVault.lockMinting(msg.sender,Appid,_usdtToXXXAmount));
minters[beneficiary]=0;
return true;
}
function refundXXX(uint256 _XXXAmount) public returns (bool){
beneficiary = msg.sender;
_preValidatePurchaseRefund(beneficiary, _XXXAmount);
uint256 _XXXToUsdtAmount = _XXXAmount.div(price).mul(10000);
require(tokenUsdt.balanceOf(address(this)) >= _XXXToUsdtAmount);
require(tokenXXX.transferFrom(msg.sender, address(this), _XXXAmount));
tokenUsdt.transfer(beneficiary, _XXXToUsdtAmount);
return true;
}
function _preValidatePurchaseRefund(address _beneficiary, uint256 _amount) internal view {
require(_amount > 0);
require(tokenXXX.allowance(_beneficiary, address(this)) >= _amount);
require(tokenXXX.balanceOf(_beneficiary) >= _amount);
this;
}
function _preValidatePurchaseMinting(address _beneficiary, uint256 _amount) internal view {
require(_amount > 0);
require(tokenUsdt.allowance(_beneficiary, address(this)) >= _amount);
require(tokenUsdt.balanceOf(_beneficiary) >= _amount);
this;
}
} | * lock minting coin */ | function lockMinting(address _owner, uint256 lockId,uint256 _amount) public returns (bool){
lockedAt = block.timestamp;
timeLocks[_owner][lockId][0] = lockedAt.add(mintingTimeLock);
timeLocks[_owner][lockId][1] = lockedAt.add(mintingTimeLock.mul(2));
allocations[_owner][lockId][0] = _amount.div(2);
allocations[_owner][lockId][1] = _amount.div(2);
Locked(lockId,lockedAt,_amount);
return true;
}
| 7,850,960 | [
1,
739,
312,
474,
310,
13170,
342,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
2176,
49,
474,
310,
12,
2867,
389,
8443,
16,
2254,
5034,
2176,
548,
16,
11890,
5034,
389,
8949,
13,
1071,
225,
1135,
261,
6430,
15329,
203,
203,
565,
8586,
861,
273,
1203,
18,
5508,
31,
7010,
565,
813,
19159,
63,
67,
8443,
6362,
739,
548,
6362,
20,
65,
273,
8586,
861,
18,
1289,
12,
81,
474,
310,
950,
2531,
1769,
203,
565,
813,
19159,
63,
67,
8443,
6362,
739,
548,
6362,
21,
65,
273,
8586,
861,
18,
1289,
12,
81,
474,
310,
950,
2531,
18,
16411,
12,
22,
10019,
203,
565,
23804,
63,
67,
8443,
6362,
739,
548,
6362,
20,
65,
273,
389,
8949,
18,
2892,
12,
22,
1769,
203,
565,
23804,
63,
67,
8443,
6362,
739,
548,
6362,
21,
65,
273,
389,
8949,
18,
2892,
12,
22,
1769,
203,
203,
565,
3488,
329,
12,
739,
548,
16,
15091,
861,
16,
67,
8949,
1769,
203,
377,
203,
565,
327,
638,
31,
203,
203,
225,
289,
203,
21281,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.24;
import "zeppelin/token/ERC20/SafeERC20.sol";
import "contracts/Issuer.sol";
/**
* @notice PolicyManager interface
**/
contract PolicyManagerInterface {
function register(address _node, uint16 _period) external;
function updateReward(address _node, uint16 _period) external;
function escrow() public view returns (address);
}
/**
* @notice Contract holds and locks miners tokens.
* Each miner that locks their tokens will receive some compensation
**/
contract MinersEscrow is Issuer {
using SafeERC20 for NuCypherToken;
using AdditionalMath for uint256;
using AdditionalMath for uint16;
event Deposited(address indexed miner, uint256 value, uint16 periods);
event Locked(address indexed miner, uint256 value, uint16 firstPeriod, uint16 periods);
event Divided(
address indexed miner,
uint256 oldValue,
uint16 lastPeriod,
uint256 newValue,
uint16 periods
);
event Withdrawn(address indexed miner, uint256 value);
event ActivityConfirmed(address indexed miner, uint16 indexed period, uint256 value);
event Mined(address indexed miner, uint16 indexed period, uint256 value);
struct StakeInfo {
uint16 firstPeriod;
uint16 lastPeriod;
uint16 periods;
uint256 lockedValue;
}
struct Downtime {
uint16 startPeriod;
uint16 endPeriod;
}
struct MinerInfo {
uint256 value;
/*
* Stores periods that are confirmed but not yet mined.
* In order to optimize storage, only two values are used instead of an array.
* lock() and confirmActivity() methods invoke the mint() method so there can only be two confirmed
* periods that are not yet mined: the current and the next periods.
* Periods are not stored in order due to storage savings;
* So, each time values of both variables need to be checked.
* The EMPTY_CONFIRMED_PERIOD constant is used as a placeholder for removed values
*/
uint16 confirmedPeriod1;
uint16 confirmedPeriod2;
// downtime
uint16 lastActivePeriod;
Downtime[] pastDowntime;
StakeInfo[] stakes;
}
/*
* Used as removed value for confirmedPeriod1(2).
* Non zero value decreases gas usage in some executions of confirmActivity() method
* but increases gas usage in mint() method. In both cases confirmActivity()
* with one execution of mint() method consume the same amount of gas
*/
uint16 constant EMPTY_CONFIRMED_PERIOD = 0;
uint16 constant RESERVED_PERIOD = 0;
uint16 constant MAX_CHECKED_VALUES = 5;
mapping (address => MinerInfo) public minerInfo;
address[] public miners;
mapping (uint16 => uint256) public lockedPerPeriod;
uint16 public minLockedPeriods;
uint256 public minAllowableLockedTokens;
uint256 public maxAllowableLockedTokens;
PolicyManagerInterface public policyManager;
/**
* @notice Constructor sets address of token contract and coefficients for mining
* @param _token Token contract
* @param _hoursPerPeriod Size of period in hours
* @param _miningCoefficient Mining coefficient
* @param _minLockedPeriods Min amount of periods during which tokens can be locked
* @param _lockedPeriodsCoefficient Locked blocks coefficient
* @param _rewardedPeriods Max periods that will be additionally rewarded
* @param _minAllowableLockedTokens Min amount of tokens that can be locked
* @param _maxAllowableLockedTokens Max amount of tokens that can be locked
**/
constructor(
NuCypherToken _token,
uint32 _hoursPerPeriod,
uint256 _miningCoefficient,
uint256 _lockedPeriodsCoefficient,
uint16 _rewardedPeriods,
uint16 _minLockedPeriods,
uint256 _minAllowableLockedTokens,
uint256 _maxAllowableLockedTokens
)
public
Issuer(
_token,
_hoursPerPeriod,
_miningCoefficient,
_lockedPeriodsCoefficient,
_rewardedPeriods
)
{
// constant `1` in the expression `_minLockedPeriods > 1` uses to simplify the `lock` method
require(_minLockedPeriods > 1 && _maxAllowableLockedTokens != 0);
minLockedPeriods = _minLockedPeriods;
minAllowableLockedTokens = _minAllowableLockedTokens;
maxAllowableLockedTokens = _maxAllowableLockedTokens;
}
/**
* @dev Checks the existence of a miner in the contract
**/
modifier onlyMiner()
{
require(minerInfo[msg.sender].value > 0);
_;
}
/**
* @notice Get the start period. Use in the calculation of the last period of the stake
**/
function getStartPeriod(MinerInfo storage _info, uint16 _currentPeriod)
internal view returns (uint16)
{
// if the next period (after current) is confirmed
if (_info.confirmedPeriod1 > _currentPeriod || _info.confirmedPeriod2 > _currentPeriod) {
return _currentPeriod.add16(1);
}
return _currentPeriod;
}
/**
* @notice Get the last period of the stake
**/
function getLastPeriodOfStake(StakeInfo storage _stake, uint16 _startPeriod)
internal view returns (uint16)
{
return _stake.lastPeriod != 0 ? _stake.lastPeriod : _startPeriod.add16(_stake.periods);
}
/**
* @notice Get the last period of the stake
* @param _miner Miner
* @param _index Stake index
**/
function getLastPeriodOfStake(address _miner, uint256 _index)
public view returns (uint16)
{
MinerInfo storage info = minerInfo[_miner];
require(_index < info.stakes.length);
StakeInfo storage stake = info.stakes[_index];
uint16 startPeriod = getStartPeriod(info, getCurrentPeriod());
return getLastPeriodOfStake(stake, startPeriod);
}
/**
* @notice Get the value of locked tokens for a miner in a future period
* @param _miner Miner
* @param _periods Amount of periods to calculate locked tokens
**/
function getLockedTokens(address _miner, uint16 _periods)
public view returns (uint256 lockedValue)
{
uint16 startPeriod = getCurrentPeriod();
uint16 nextPeriod = startPeriod.add16(_periods);
MinerInfo storage info = minerInfo[_miner];
startPeriod = getStartPeriod(info, startPeriod);
for (uint256 i = 0; i < info.stakes.length; i++) {
StakeInfo storage stake = info.stakes[i];
if (stake.firstPeriod <= nextPeriod &&
getLastPeriodOfStake(stake, startPeriod) >= nextPeriod) {
lockedValue = lockedValue.add(stake.lockedValue);
}
}
}
/**
* @notice Get the value of locked tokens for a miner in the current period
* @param _miner Miner
**/
function getLockedTokens(address _miner)
public view returns (uint256)
{
return getLockedTokens(_miner, 0);
}
/**
* @notice Pre-deposit tokens
* @param _miners Miners
* @param _values Amount of tokens to deposit for each miner
* @param _periods Amount of periods during which tokens will be locked for each miner
**/
function preDeposit(address[] _miners, uint256[] _values, uint16[] _periods)
public isInitialized
{
require(_miners.length != 0 &&
_miners.length == _values.length &&
_miners.length == _periods.length);
uint16 currentPeriod = getCurrentPeriod();
uint256 allValue = 0;
for (uint256 i = 0; i < _miners.length; i++) {
address miner = _miners[i];
uint256 value = _values[i];
uint16 periods = _periods[i];
MinerInfo storage info = minerInfo[miner];
require(info.stakes.length == 0 &&
value >= minAllowableLockedTokens &&
value <= maxAllowableLockedTokens &&
periods >= minLockedPeriods);
miners.push(miner);
policyManager.register(miner, currentPeriod);
info.value = value;
info.stakes.push(StakeInfo(currentPeriod.add16(1), 0, periods, value));
allValue = allValue.add(value);
emit Deposited(miner, value, periods);
}
token.safeTransferFrom(msg.sender, address(this), allValue);
}
/**
* @notice Get the last active miner's period
* @param _miner Miner
**/
function getLastActivePeriod(address _miner) public view returns (uint16) {
MinerInfo storage info = minerInfo[_miner];
if (info.confirmedPeriod1 != EMPTY_CONFIRMED_PERIOD ||
info.confirmedPeriod2 != EMPTY_CONFIRMED_PERIOD) {
return AdditionalMath.max16(info.confirmedPeriod1, info.confirmedPeriod2);
}
return info.lastActivePeriod;
}
/**
* @notice Implementation of the receiveApproval(address,uint256,address,bytes) method
* (see NuCypherToken contract). Deposit all tokens that were approved to transfer
* @param _from Miner
* @param _value Amount of tokens to deposit
* @param _tokenContract Token contract address
* @notice (param _extraData) Amount of periods during which tokens will be locked
**/
function receiveApproval(
address _from,
uint256 _value,
address _tokenContract,
bytes /* _extraData */
)
external
{
require(_tokenContract == address(token) && msg.sender == address(token));
// copy first 32 bytes from _extraData. Position is calculated as
// 4 bytes method signature plus 32 * 3 bytes for previous params and
// addition 32 bytes to skip _extraData pointer
uint256 payloadSize;
uint256 payload;
assembly {
payloadSize := calldataload(0x84)
payload := calldataload(0xA4)
}
payload = payload >> 8*(32 - payloadSize);
deposit(_from, _value, uint16(payload));
}
/**
* @notice Deposit tokens
* @param _value Amount of tokens to deposit
* @param _periods Amount of periods during which tokens will be locked
**/
function deposit(uint256 _value, uint16 _periods) public {
deposit(msg.sender, _value, _periods);
}
/**
* @notice Deposit tokens
* @param _miner Miner
* @param _value Amount of tokens to deposit
* @param _periods Amount of periods during which tokens will be locked
**/
function deposit(address _miner, uint256 _value, uint16 _periods) internal isInitialized {
require(_value != 0);
MinerInfo storage info = minerInfo[_miner];
// initial stake of the miner
if (info.stakes.length == 0) {
miners.push(_miner);
policyManager.register(_miner, getCurrentPeriod());
}
info.value = info.value.add(_value);
token.safeTransferFrom(_miner, address(this), _value);
lock(_miner, _value, _periods);
emit Deposited(_miner, _value, _periods);
}
/**
* @notice Lock some tokens as a stake
* @param _value Amount of tokens which will be locked
* @param _periods Amount of periods during which tokens will be locked
**/
function lock(uint256 _value, uint16 _periods) public onlyMiner {
lock(msg.sender, _value, _periods);
}
/**
* @notice Lock some tokens as a stake
* @param _miner Miner
* @param _value Amount of tokens which will be locked
* @param _periods Amount of periods during which tokens will be locked
**/
function lock(address _miner, uint256 _value, uint16 _periods) internal {
require(_value <= token.balanceOf(address(this)) &&
_value >= minAllowableLockedTokens &&
_periods >= minLockedPeriods);
uint16 lastActivePeriod = getLastActivePeriod(_miner);
mint(_miner);
uint256 lockedTokens = getLockedTokens(_miner, 1);
MinerInfo storage info = minerInfo[_miner];
require(_value.add(lockedTokens) <= info.value &&
_value.add(lockedTokens) <= maxAllowableLockedTokens);
uint16 nextPeriod = getCurrentPeriod().add16(1);
if (info.confirmedPeriod1 != nextPeriod && info.confirmedPeriod2 != nextPeriod) {
info.stakes.push(StakeInfo(nextPeriod, 0, _periods, _value));
} else {
info.stakes.push(StakeInfo(nextPeriod, 0, _periods - 1, _value));
}
confirmActivity(_miner, _value + lockedTokens, _value, lastActivePeriod);
emit Locked(_miner, _value, nextPeriod, _periods);
}
/**
* @notice Divide stake into two parts
* @param _index Index of the stake
* @param _newValue New stake value
* @param _periods Amount of periods for extending stake
**/
function divideStake(
uint256 _index,
uint256 _newValue,
uint16 _periods
)
public onlyMiner
{
MinerInfo storage info = minerInfo[msg.sender];
require(_newValue >= minAllowableLockedTokens &&
_periods > 0 &&
_index < info.stakes.length);
StakeInfo storage stake = info.stakes[_index];
uint16 currentPeriod = getCurrentPeriod();
uint16 startPeriod = getStartPeriod(info, currentPeriod);
uint16 lastPeriod = getLastPeriodOfStake(stake, startPeriod);
require(lastPeriod >= currentPeriod);
uint256 oldValue = stake.lockedValue;
stake.lockedValue = oldValue.sub(_newValue);
require(stake.lockedValue >= minAllowableLockedTokens);
info.stakes.push(StakeInfo(stake.firstPeriod, 0, stake.periods.add16(_periods), _newValue));
// if the next period is confirmed and old stake is finishing in the current period then rerun confirmActivity
if (lastPeriod == currentPeriod && startPeriod > currentPeriod) {
confirmActivity(msg.sender, _newValue, _newValue, 0);
}
emit Divided(msg.sender, oldValue, lastPeriod, _newValue, _periods);
emit Locked(msg.sender, _newValue, stake.firstPeriod, stake.periods + _periods);
}
/**
* @notice Withdraw available amount of tokens to miner
* @param _value Amount of tokens to withdraw
**/
function withdraw(uint256 _value) public onlyMiner {
MinerInfo storage info = minerInfo[msg.sender];
// the max locked tokens in most cases will be in the current period
// but when the miner stakes more then we should use the next period
uint256 lockedTokens = Math.max256(getLockedTokens(msg.sender, 1),
getLockedTokens(msg.sender, 0));
require(_value <= token.balanceOf(address(this)) &&
_value <= info.value.sub(lockedTokens));
info.value -= _value;
token.safeTransfer(msg.sender, _value);
emit Withdrawn(msg.sender, _value);
}
/**
* @notice Confirm activity for the next period
* @param _miner Miner
* @param _lockedValue Locked tokens in the next period
* @param _additional Additional locked tokens in the next period.
* Used only if the period has already been confirmed
* @param _lastActivePeriod Last active period
**/
function confirmActivity(
address _miner,
uint256 _lockedValue,
uint256 _additional,
uint16 _lastActivePeriod
) internal {
require(_lockedValue > 0);
MinerInfo storage info = minerInfo[_miner];
uint16 currentPeriod = getCurrentPeriod();
uint16 nextPeriod = currentPeriod.add16(1);
// update lockedValue if the period has already been confirmed
if (info.confirmedPeriod1 == nextPeriod) {
lockedPerPeriod[nextPeriod] = lockedPerPeriod[nextPeriod].add(_additional);
emit ActivityConfirmed(_miner, nextPeriod, _additional);
return;
} else if (info.confirmedPeriod2 == nextPeriod) {
lockedPerPeriod[nextPeriod] = lockedPerPeriod[nextPeriod].add(_additional);
emit ActivityConfirmed(_miner, nextPeriod, _additional);
return;
}
lockedPerPeriod[nextPeriod] = lockedPerPeriod[nextPeriod].add(_lockedValue);
if (info.confirmedPeriod1 == EMPTY_CONFIRMED_PERIOD) {
info.confirmedPeriod1 = nextPeriod;
} else {
info.confirmedPeriod2 = nextPeriod;
}
for (uint256 index = 0; index < info.stakes.length; index++) {
StakeInfo storage stake = info.stakes[index];
if (stake.periods > 1) {
stake.periods--;
} else if (stake.periods == 1) {
stake.periods = 0;
stake.lastPeriod = nextPeriod;
}
}
// miner was inactive for several periods
if (_lastActivePeriod < currentPeriod) {
info.pastDowntime.push(Downtime(_lastActivePeriod + 1, currentPeriod));
}
emit ActivityConfirmed(_miner, nextPeriod, _lockedValue);
}
/**
* @notice Confirm activity for the next period and mine for the previous period
**/
function confirmActivity() external onlyMiner {
uint16 lastActivePeriod = getLastActivePeriod(msg.sender);
mint(msg.sender);
MinerInfo storage info = minerInfo[msg.sender];
uint16 currentPeriod = getCurrentPeriod();
uint16 nextPeriod = currentPeriod + 1;
// the period has already been confirmed
if (info.confirmedPeriod1 == nextPeriod ||
info.confirmedPeriod2 == nextPeriod) {
return;
}
uint256 lockedTokens = getLockedTokens(msg.sender, 1);
confirmActivity(msg.sender, lockedTokens, 0, lastActivePeriod);
}
/**
* @notice Mint tokens for previous periods if miner locked their tokens and confirmed activity
**/
function mint() external onlyMiner {
// save last active period to the storage if only one period is confirmed
// because after this minting confirmed periods can be empty and can't calculate period from them
// see getLastActivePeriod(address)
MinerInfo storage info = minerInfo[msg.sender];
if (info.confirmedPeriod1 != EMPTY_CONFIRMED_PERIOD ||
info.confirmedPeriod2 != EMPTY_CONFIRMED_PERIOD) {
info.lastActivePeriod = AdditionalMath.max16(info.confirmedPeriod1, info.confirmedPeriod2);
}
mint(msg.sender);
}
/**
* @notice Mint tokens for previous periods if miner locked their tokens and confirmed activity
* @param _miner Miner
**/
function mint(address _miner) internal {
uint16 startPeriod = getCurrentPeriod();
uint16 previousPeriod = startPeriod.sub16(1);
MinerInfo storage info = minerInfo[_miner];
if (info.confirmedPeriod1 > previousPeriod &&
info.confirmedPeriod2 > previousPeriod ||
info.confirmedPeriod1 > previousPeriod &&
info.confirmedPeriod2 == EMPTY_CONFIRMED_PERIOD ||
info.confirmedPeriod2 > previousPeriod &&
info.confirmedPeriod1 == EMPTY_CONFIRMED_PERIOD ||
info.confirmedPeriod1 == EMPTY_CONFIRMED_PERIOD &&
info.confirmedPeriod2 == EMPTY_CONFIRMED_PERIOD) {
return;
}
uint16 first;
uint16 last;
if (info.confirmedPeriod1 > info.confirmedPeriod2) {
last = info.confirmedPeriod1;
first = info.confirmedPeriod2;
} else {
first = info.confirmedPeriod1;
last = info.confirmedPeriod2;
}
startPeriod = getStartPeriod(info, startPeriod);
uint256 reward = 0;
if (info.confirmedPeriod1 != EMPTY_CONFIRMED_PERIOD &&
info.confirmedPeriod1 < info.confirmedPeriod2) {
reward = reward.add(mint(_miner, info, info.confirmedPeriod1, previousPeriod, startPeriod));
info.confirmedPeriod1 = EMPTY_CONFIRMED_PERIOD;
} else if (info.confirmedPeriod2 != EMPTY_CONFIRMED_PERIOD &&
info.confirmedPeriod2 < info.confirmedPeriod1) {
reward = reward.add(mint(_miner, info, info.confirmedPeriod2, previousPeriod, startPeriod));
info.confirmedPeriod2 = EMPTY_CONFIRMED_PERIOD;
}
if (info.confirmedPeriod2 <= previousPeriod &&
info.confirmedPeriod2 > info.confirmedPeriod1) {
reward = reward.add(mint(_miner, info, info.confirmedPeriod2, previousPeriod, startPeriod));
info.confirmedPeriod2 = EMPTY_CONFIRMED_PERIOD;
} else if (info.confirmedPeriod1 <= previousPeriod &&
info.confirmedPeriod1 > info.confirmedPeriod2) {
reward = reward.add(mint(_miner, info, info.confirmedPeriod1, previousPeriod, startPeriod));
info.confirmedPeriod1 = EMPTY_CONFIRMED_PERIOD;
}
info.value = info.value.add(reward);
emit Mined(_miner, previousPeriod, reward);
}
/**
* @notice Calculate reward for one period
**/
function mint(
address _miner,
MinerInfo storage _info,
uint16 _period,
uint16 _previousPeriod,
uint16 _startPeriod
)
internal returns (uint256 reward)
{
for (uint256 i = 0; i < _info.stakes.length; i++) {
StakeInfo storage stake = _info.stakes[i];
uint16 lastPeriod = getLastPeriodOfStake(stake, _startPeriod);
if (stake.firstPeriod <= _period && lastPeriod >= _period) {
reward = reward.add(mint(
_previousPeriod,
stake.lockedValue,
lockedPerPeriod[_period],
lastPeriod.sub16(_period)));
}
}
policyManager.updateReward(_miner, _period);
}
/**
* @notice Get the value of locked tokens for active miners in (getCurrentPeriod() + _periods) period
* @param _periods Amount of periods for locked tokens calculation
**/
function getAllLockedTokens(uint16 _periods)
external view returns (uint256 lockedTokens)
{
require(_periods > 0);
uint16 currentPeriod = getCurrentPeriod();
for (uint256 i = 0; i < miners.length; i++) {
address miner = miners[i];
MinerInfo storage info = minerInfo[miner];
if (info.confirmedPeriod1 != currentPeriod &&
info.confirmedPeriod2 != currentPeriod) {
continue;
}
lockedTokens = lockedTokens.add(getLockedTokens(miner, _periods));
}
}
/**
* @notice Get active miners based on input points
* @param _points Array of absolute values
* @param _periods Amount of periods for locked tokens calculation
*
* @dev Sampling iterates over an array of miners and input points.
* Each iteration checks if the current point is contained within the current miner stake.
* If the point is greater than or equal to the current sum of stakes,
* this miner is skipped and the sum is increased by the value of next miner's stake.
* If a point is less than the current sum of stakes, then the current miner is appended to the resulting array.
* Secondly, the sum of stakes is decreased by a point;
* The next iteration will check the next point for the difference.
* Only miners which confirmed the current period (in the previous period) are used.
* If the number of points is more than the number of active miners with suitable stakes,
* the last values in the resulting array will be zeros addresses.
* The length of this array is always equal to the number of points.
**/
function sample(uint256[] _points, uint16 _periods)
external view returns (address[] result)
{
require(_periods > 0 && _points.length > 0);
uint16 currentPeriod = getCurrentPeriod();
result = new address[](_points.length);
uint256 pointIndex = 0;
uint256 sumOfLockedTokens = 0;
uint256 minerIndex = 0;
bool addMoreTokens = true;
while (minerIndex < miners.length && pointIndex < _points.length) {
address currentMiner = miners[minerIndex];
MinerInfo storage info = minerInfo[currentMiner];
uint256 point = _points[pointIndex];
if (info.confirmedPeriod1 != currentPeriod &&
info.confirmedPeriod2 != currentPeriod) {
minerIndex += 1;
addMoreTokens = true;
continue;
}
if (addMoreTokens) {
sumOfLockedTokens = sumOfLockedTokens.add(getLockedTokens(currentMiner, _periods));
}
if (sumOfLockedTokens > point) {
result[pointIndex] = currentMiner;
sumOfLockedTokens -= point;
pointIndex += 1;
addMoreTokens = false;
} else {
minerIndex += 1;
addMoreTokens = true;
}
}
}
/**
* @notice Set policy manager address
**/
function setPolicyManager(PolicyManagerInterface _policyManager) external onlyOwner {
require(address(policyManager) == 0x0 &&
_policyManager.escrow() == address(this));
policyManager = _policyManager;
}
/**
* @notice Return the length of the array of miners
**/
function getMinersLength() public view returns (uint256) {
return miners.length;
}
/**
* @notice Return the length of the array of stakes
**/
function getStakesLength(address _miner) public view returns (uint256) {
return minerInfo[_miner].stakes.length;
}
/**
* @notice Return the information about stake
**/
function getStakeInfo(address _miner, uint256 _index)
// TODO change to structure when ABIEncoderV2 is released
// public view returns (StakeInfo)
public view returns (uint16 firstPeriod, uint16 lastPeriod, uint16 periods, uint256 lockedValue)
{
StakeInfo storage info = minerInfo[_miner].stakes[_index];
firstPeriod = info.firstPeriod;
lastPeriod = info.lastPeriod;
periods = info.periods;
lockedValue = info.lockedValue;
}
/**
* @notice Return the length of the array of past downtime
**/
function getPastDowntimeLength(address _miner) public view returns (uint256) {
return minerInfo[_miner].pastDowntime.length;
}
/**
* @notice Return the information about past downtime
**/
function getPastDowntime(address _miner, uint256 _index)
// TODO change to structure when ABIEncoderV2 is released
// public view returns (Downtime)
public view returns (uint16 startPeriod, uint16 endPeriod)
{
Downtime storage downtime = minerInfo[_miner].pastDowntime[_index];
startPeriod = downtime.startPeriod;
endPeriod = downtime.endPeriod;
}
/**
* @dev Get MinerInfo structure by delegatecall
**/
function delegateGetMinerInfo(address _target, address _miner)
internal returns (MinerInfo memory result)
{
bytes32 memoryAddress = delegateGetData(_target, "minerInfo(address)", 1, bytes32(_miner), 0);
assembly {
result := memoryAddress
}
}
/**
* @dev Get StakeInfo structure by delegatecall
**/
function delegateGetStakeInfo(address _target, address _miner, uint256 _index)
internal returns (StakeInfo memory result)
{
bytes32 memoryAddress = delegateGetData(
_target, "getStakeInfo(address,uint256)", 2, bytes32(_miner), bytes32(_index));
assembly {
result := memoryAddress
}
}
/**
* @dev Get Downtime structure by delegatecall
**/
function delegateGetPastDowntime(address _target, address _miner, uint256 _index)
internal returns (Downtime memory result)
{
bytes32 memoryAddress = delegateGetData(
_target, "getPastDowntime(address,uint256)", 2, bytes32(_miner), bytes32(_index));
assembly {
result := memoryAddress
}
}
function verifyState(address _testTarget) public onlyOwner {
super.verifyState(_testTarget);
require(uint16(delegateGet(_testTarget, "minLockedPeriods()")) ==
minLockedPeriods);
require(uint256(delegateGet(_testTarget, "minAllowableLockedTokens()")) ==
minAllowableLockedTokens);
require(uint256(delegateGet(_testTarget, "maxAllowableLockedTokens()")) ==
maxAllowableLockedTokens);
require(address(delegateGet(_testTarget, "policyManager()")) == address(policyManager));
require(uint256(delegateGet(_testTarget, "lockedPerPeriod(uint16)",
bytes32(RESERVED_PERIOD))) == lockedPerPeriod[RESERVED_PERIOD]);
require(uint256(delegateGet(_testTarget, "getMinersLength()")) == miners.length);
if (miners.length == 0) {
return;
}
address minerAddress = miners[0];
bytes32 miner = bytes32(minerAddress);
require(address(delegateGet(_testTarget, "miners(uint256)", 0)) == minerAddress);
MinerInfo storage info = minerInfo[minerAddress];
MinerInfo memory infoToCheck = delegateGetMinerInfo(_testTarget, minerAddress);
require(infoToCheck.value == info.value &&
infoToCheck.confirmedPeriod1 == info.confirmedPeriod1 &&
infoToCheck.confirmedPeriod2 == info.confirmedPeriod2 &&
infoToCheck.lastActivePeriod == info.lastActivePeriod);
require(uint256(delegateGet(_testTarget, "getPastDowntimeLength(address)", miner)) ==
info.pastDowntime.length);
for (i = 0; i < info.pastDowntime.length && i < MAX_CHECKED_VALUES; i++) {
Downtime storage downtime = info.pastDowntime[i];
Downtime memory downtimeToCheck = delegateGetPastDowntime(_testTarget, minerAddress, i);
require(downtimeToCheck.startPeriod == downtime.startPeriod &&
downtimeToCheck.endPeriod == downtime.endPeriod);
}
require(uint256(delegateGet(_testTarget, "getStakesLength(address)", miner)) == info.stakes.length);
for (uint256 i = 0; i < info.stakes.length && i < MAX_CHECKED_VALUES; i++) {
StakeInfo storage stakeInfo = info.stakes[i];
StakeInfo memory stakeInfoToCheck = delegateGetStakeInfo(_testTarget, minerAddress, i);
require(stakeInfoToCheck.firstPeriod == stakeInfo.firstPeriod &&
stakeInfoToCheck.lastPeriod == stakeInfo.lastPeriod &&
stakeInfoToCheck.periods == stakeInfo.periods &&
stakeInfoToCheck.lockedValue == stakeInfo.lockedValue);
}
}
function finishUpgrade(address _target) public onlyOwner {
super.finishUpgrade(_target);
MinersEscrow escrow = MinersEscrow(_target);
minLockedPeriods = escrow.minLockedPeriods();
minAllowableLockedTokens = escrow.minAllowableLockedTokens();
maxAllowableLockedTokens = escrow.maxAllowableLockedTokens();
// Create fake period
lockedPerPeriod[RESERVED_PERIOD] = 111;
}
}
| * @notice Return the information about past downtime/ TODO change to structure when ABIEncoderV2 is released public view returns (Downtime) | function getPastDowntime(address _miner, uint256 _index)
public view returns (uint16 startPeriod, uint16 endPeriod)
{
Downtime storage downtime = minerInfo[_miner].pastDowntime[_index];
startPeriod = downtime.startPeriod;
endPeriod = downtime.endPeriod;
}
| 1,068,909 | [
1,
990,
326,
1779,
2973,
8854,
22095,
29367,
19,
2660,
2549,
358,
3695,
1347,
10336,
45,
7204,
58,
22,
353,
15976,
3639,
1071,
1476,
1135,
261,
40,
543,
29367,
13,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
225,
1689,
689,
40,
543,
29367,
12,
2867,
389,
1154,
264,
16,
2254,
5034,
389,
1615,
13,
203,
3639,
1071,
1476,
1135,
261,
11890,
2313,
787,
5027,
16,
2254,
2313,
679,
5027,
13,
203,
565,
288,
203,
3639,
463,
543,
29367,
2502,
22095,
29367,
273,
1131,
264,
966,
63,
67,
1154,
264,
8009,
84,
689,
40,
543,
29367,
63,
67,
1615,
15533,
203,
3639,
787,
5027,
273,
22095,
29367,
18,
1937,
5027,
31,
203,
3639,
679,
5027,
273,
22095,
29367,
18,
409,
5027,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
//This file was auto-generated on Sun Nov 03 2019 18:59:53 GMT+0200 (Israel Standard Time)
//Source file: build/contracts/MyContract.json
pragma solidity ^0.5.8;
//manually modified, to access this source code rather than our NPM package...
import "./Factory2.sol";
//import "@tabookey/create2-helper/contracts/Factory2.sol";
import "./MyContract.sol";
/*
Helper Factory to create class "MyContract" using create2
For a given list of constructor param, getAddress will always return the same address.
The create method will create the object at that same address, exactly once
(and revert if called again)
For more information, https://github.com/tabookey/create2-helper
USAGE:
IMyContractFactory factory = MyContractFactory.createFactory();
address toBeCreated = factory.getAddress(_name, _age);
MyContract newObj = factory.create(_name, _age);
require( address(newObj) == toBeCreated );
*/
interface IMyContractFactory {
function create(string calldata _name, uint256 _age) external returns (MyContract);
function getAddress(string calldata _name, uint256 _age) view external returns (address);
function setSalt(uint salt) external returns (IMyContractFactory);
}
library MyContractFactory {
function createFactory() internal returns (IMyContractFactory) {
return IMyContractFactory(address(new Factory2( type(MyContract).creationCode, IMyContractFactory(0).create.selector)));
}
}
| import "@tabookey/create2-helper/contracts/Factory2.sol"; | import "./MyContract.sol";
| 5,480,544 | [
1,
5666,
8787,
7032,
1184,
402,
19,
2640,
22,
17,
4759,
19,
16351,
87,
19,
1733,
22,
18,
18281,
14432,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
5666,
25165,
12062,
8924,
18,
18281,
14432,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/*
* source https://github.com/lukso-network/rICO-smart-contracts
* @name rICO
* @package rICO-smart-contracts
* @author Micky Socaci <[email protected]>, Fabian Vogelsteller <@frozeman>, Marjorie Hernandez <[email protected]>
* @license MIT
*/
pragma solidity ^0.5.0;
import "./zeppelin/math/SafeMath.sol";
import "./zeppelin/token/ERC777/IERC777.sol";
import "./zeppelin/token/ERC777/IERC777Recipient.sol";
import "./zeppelin/introspection/IERC1820Registry.sol";
contract ReversibleICO is IERC777Recipient {
/*
* Instances
*/
using SafeMath for uint256;
/// @dev The address of the introspection registry contract deployed.
IERC1820Registry private ERC1820 = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24);
bytes32 constant private TOKENS_RECIPIENT_INTERFACE_HASH = keccak256("ERC777TokensRecipient");
/*
* Contract States
*/
/// @dev It is set to TRUE after the deployer initializes the contract.
bool public initialized;
/// @dev Security guard. The freezer address can the freeze the contract and move its funds in case of emergency.
bool public frozen;
uint256 public frozenPeriod;
uint256 public freezeStart;
/*
* Addresses
*/
/// @dev Only the deploying address is allowed to initialize the contract.
address public deployingAddress;
/// @dev The rICO token contract address.
address public tokenAddress;
/// @dev The address of wallet of the project running the rICO.
address public projectAddress;
/// @dev Only the whitelist controller can whitelist addresses.
address public whitelistingAddress;
/// @dev Only the freezer address can call the freeze functions.
address public freezerAddress;
/// @dev Only the rescuer address can move funds if the rICO is frozen.
address public rescuerAddress;
/*
* Public Variables
*/
/// @dev Total amount tokens initially available to be bought, increases if the project adds more.
uint256 public initialTokenSupply;
/// @dev Total amount tokens currently available to be bought.
uint256 public tokenSupply;
/// @dev Total amount of ETH currently accepted as a commitment to buy tokens (excluding pendingETH).
uint256 public committedETH;
/// @dev Total amount of ETH currently pending to be whitelisted.
uint256 public pendingETH;
/// @dev Accumulated amount of all ETH returned from canceled pending ETH.
uint256 public canceledETH;
/// @dev Accumulated amount of all ETH withdrawn by participants.
uint256 public withdrawnETH;
/// @dev Count of the number the project has withdrawn from the funds raised.
uint256 public projectWithdrawCount;
/// @dev Total amount of ETH withdrawn by the project
uint256 public projectWithdrawnETH;
/// @dev Minimum amount of ETH accepted for a contribution. Everything lower than that will trigger a canceling of pending ETH.
uint256 public minContribution = 0.001 ether;
uint256 public maxContribution = 4000 ether;
mapping(uint8 => Stage) public stages;
uint8 public stageCount;
/// @dev Maps participants stats by their address.
mapping(address => Participant) public participants;
/// @dev Maps participants address to a unique participant ID (incremental IDs, based on "participantCount").
mapping(uint256 => address) public participantsById;
/// @dev Total number of rICO participants.
uint256 public participantCount;
/*
* Commit phase (Stage 0)
*/
/// @dev Initial token price in the commit phase (Stage 0).
uint256 public commitPhasePrice;
/// @dev Block number that indicates the start of the commit phase.
uint256 public commitPhaseStartBlock;
/// @dev Block number that indicates the end of the commit phase.
uint256 public commitPhaseEndBlock;
/// @dev The duration of the commit phase in blocks.
uint256 public commitPhaseBlockCount;
/*
* Buy phases (Stages 1-n)
*/
/// @dev Block number that indicates the start of the buy phase (Stages 1-n).
uint256 public buyPhaseStartBlock;
/// @dev Block number that indicates the end of the buy phase.
uint256 public buyPhaseEndBlock;
/// @dev The duration of the buy phase in blocks.
uint256 public buyPhaseBlockCount;
/*
* Internal Variables
*/
/// @dev Total amount of the current reserved ETH for the project by the participants contributions.
uint256 internal _projectCurrentlyReservedETH;
/// @dev Accumulated amount allocated to the project by participants.
uint256 internal _projectUnlockedETH;
/// @dev Last block since the project has calculated the _projectUnlockedETH.
uint256 internal _projectLastBlock;
/*
* Structs
*/
/*
* Stages
* Stage 0 = commit phase
* Stage 1-n = buy phase
*/
struct Stage {
uint256 tokenLimit; // 500k > 9.5M >
uint256 tokenPrice;
}
/*
* Participants
*/
struct Participant {
bool whitelisted;
uint32 contributions;
uint32 withdraws;
uint256 firstContributionBlock;
uint256 reservedTokens;
uint256 committedETH;
uint256 pendingETH;
uint256 _currentReservedTokens;
uint256 _unlockedTokens;
uint256 _lastBlock;
mapping(uint8 => ParticipantStageDetails) stages;
}
struct ParticipantStageDetails {
uint256 pendingETH;
}
/*
* Events
*/
event PendingContributionAdded(address indexed participantAddress, uint256 indexed amount, uint32 indexed contributionId, uint8 stageId);
event PendingContributionsCanceled(address indexed participantAddress, uint256 indexed amount, uint32 indexed contributionId);
event WhitelistApproved(address indexed participantAddress, uint256 indexed pendingETH, uint32 indexed contributions);
event WhitelistRejected(address indexed participantAddress, uint256 indexed pendingETH, uint32 indexed contributions);
event ContributionsAccepted(address indexed participantAddress, uint256 indexed ethAmount, uint256 indexed tokenAmount, uint8 stageId);
event ProjectWithdraw(address indexed projectAddress, uint256 indexed amount, uint32 indexed withdrawCount);
event ParticipantWithdraw(address indexed participantAddress, uint256 indexed ethAmount, uint256 indexed tokenAmount, uint32 withdrawCount);
event StageChanged(uint8 indexed stageId, uint256 indexed tokenLimit, uint256 indexed tokenPrice, uint256 effectiveBlockNumber);
event WhitelistingAddressChanged(address indexed whitelistingAddress, uint8 indexed stageId, uint256 indexed effectiveBlockNumber);
event FreezerAddressChanged(address indexed freezerAddress, uint8 indexed stageId, uint256 indexed effectiveBlockNumber);
event SecurityFreeze(address indexed freezerAddress, uint8 indexed stageId, uint256 indexed effectiveBlockNumber);
event SecurityUnfreeze(address indexed freezerAddress, uint8 indexed stageId, uint256 indexed effectiveBlockNumber);
event SecurityDisableEscapeHatch(address indexed freezerAddress, uint8 indexed stageId, uint256 indexed effectiveBlockNumber);
event SecurityEscapeHatch(address indexed rescuerAddress, address indexed to, uint8 indexed stageId, uint256 effectiveBlockNumber);
event TransferEvent (
uint8 indexed typeId,
address indexed relatedAddress,
uint256 indexed value
);
enum TransferTypes {
NOT_SET, // 0
WHITELIST_REJECTED, // 1
CONTRIBUTION_CANCELED, // 2
CONTRIBUTION_ACCEPTED_OVERFLOW, // 3 not accepted ETH
PARTICIPANT_WITHDRAW, // 4
PARTICIPANT_WITHDRAW_OVERFLOW, // 5 not returnable tokens
PROJECT_WITHDRAWN, // 6
FROZEN_ESCAPEHATCH_TOKEN, // 7
FROZEN_ESCAPEHATCH_ETH // 8
}
// ------------------------------------------------------------------------------------------------
/// @notice Constructor sets the deployer and defines ERC777TokensRecipient interface support.
constructor() public {
deployingAddress = msg.sender;
ERC1820.setInterfaceImplementer(address(this), TOKENS_RECIPIENT_INTERFACE_HASH, address(this));
}
/**
* @notice Initializes the contract. Only the deployer (set in the constructor) can call this method.
* @param _tokenAddress The address of the ERC777 rICO token contract.
* @param _whitelistingAddress The address handling whitelisting.
* @param _projectAddress The project wallet that can withdraw ETH contributions.
* @param _commitPhaseStartBlock The block at which the commit phase starts.
* @param _buyPhaseStartBlock The duration of the commit phase in blocks.
* @param _initialPrice The initial token price (in WEI per token) during the commit phase.
* @param _stageCount The number of the rICO stages, excluding the commit phase (Stage 0).
* @param _stageTokenLimitIncrease The duration of each stage in blocks.
* @param _stagePriceIncrease A factor used to increase the token price from the _initialPrice at each subsequent stage.
*/
function init(
address _tokenAddress,
address _whitelistingAddress,
address _freezerAddress,
address _rescuerAddress,
address _projectAddress,
uint256 _commitPhaseStartBlock,
uint256 _buyPhaseStartBlock,
uint256 _buyPhaseEndBlock,
uint256 _initialPrice,
uint8 _stageCount, // Its not recommended to choose more than 50 stages! (9 stages require ~650k GAS when whitelisting contributions, the whitelisting function could run out of gas with a high number of stages, preventing accepting contributions)
uint256 _stageTokenLimitIncrease,
uint256 _stagePriceIncrease
)
public
onlyDeployingAddress
isNotInitialized
{
require(_tokenAddress != address(0), "_tokenAddress cannot be 0x");
require(_whitelistingAddress != address(0), "_whitelistingAddress cannot be 0x");
require(_freezerAddress != address(0), "_freezerAddress cannot be 0x");
require(_rescuerAddress != address(0), "_rescuerAddress cannot be 0x");
require(_projectAddress != address(0), "_projectAddress cannot be 0x");
// require(_commitPhaseStartBlock > getCurrentBlockNumber(), "Start block cannot be set in the past.");
// Assign address variables
tokenAddress = _tokenAddress;
whitelistingAddress = _whitelistingAddress;
freezerAddress = _freezerAddress;
rescuerAddress = _rescuerAddress;
projectAddress = _projectAddress;
// UPDATE global STATS
commitPhaseStartBlock = _commitPhaseStartBlock;
commitPhaseEndBlock = _buyPhaseStartBlock.sub(1);
commitPhaseBlockCount = commitPhaseEndBlock.sub(commitPhaseStartBlock).add(1);
commitPhasePrice = _initialPrice;
stageCount = _stageCount;
// Setup stage 0: The commit phase.
Stage storage commitPhase = stages[0];
commitPhase.tokenLimit = _stageTokenLimitIncrease;
commitPhase.tokenPrice = _initialPrice;
// Setup stage 1 to n: The buy phase stages
uint256 previousStageTokenLimit = _stageTokenLimitIncrease;
// Update stages: start, end, price
for (uint8 i = 1; i <= _stageCount; i++) {
// Get i-th stage
Stage storage byStage = stages[i];
// set the stage limit amount
byStage.tokenLimit = previousStageTokenLimit.add(_stageTokenLimitIncrease);
// Store the current stage endBlock in order to update the next one
previousStageTokenLimit = byStage.tokenLimit;
// At each stage the token price increases by _stagePriceIncrease * stageCount
byStage.tokenPrice = _initialPrice.add(_stagePriceIncrease.mul(i));
}
// UPDATE global STATS
// The buy phase starts on the subsequent block of the commitPhase's (stage0) endBlock
buyPhaseStartBlock = _buyPhaseStartBlock;
// The buy phase ends when the lat stage ends
buyPhaseEndBlock = _buyPhaseEndBlock;
// The duration of buyPhase in blocks
buyPhaseBlockCount = buyPhaseEndBlock.sub(buyPhaseStartBlock).add(1);
// The contract is now initialized
initialized = true;
}
/*
* Public functions
* ------------------------------------------------------------------------------------------------
*/
/*
* Public functions
* The main way to interact with the rICO.
*/
/**
* @notice FALLBACK function: If the amount sent is smaller than `minContribution` it cancels all pending contributions.
* IF you are a known contributor with at least 1 contribution and you are whitelisted, you can send ETH without calling "commit()" to contribute more.
*/
function()
external
payable
isInitialized
isNotFrozen
{
Participant storage participantStats = participants[msg.sender];
// allow to commit directly if its a known user with at least 1 contribution
if (participantStats.whitelisted == true && participantStats.contributions > 0) {
commit();
// otherwise try to cancel
} else {
require(msg.value < minContribution, 'To contribute call commit() [0x3c7a3aff] and send ETH along.');
// Participant cancels pending contributions.
cancelPendingContributions(msg.sender, msg.value);
}
}
/**
* @notice ERC777TokensRecipient implementation for receiving ERC777 tokens.
* @param _from Token sender.
* @param _amount Token amount.
*/
function tokensReceived(
address,
address _from,
address,
uint256 _amount,
bytes calldata,
bytes calldata
)
external
isInitialized
isNotFrozen
{
// rICO should only receive tokens from the rICO token contract.
// Transactions from any other token contract revert
require(msg.sender == tokenAddress, "Unknown token contract sent tokens.");
// Project wallet adds tokens to the sale
if (_from == projectAddress) {
// increase the supply
tokenSupply = tokenSupply.add(_amount);
initialTokenSupply = initialTokenSupply.add(_amount);
// rICO participant sends tokens back
} else {
withdraw(_from, _amount);
}
}
/**
* @notice Allows a participant to reserve tokens by committing ETH as contributions.
*
* Function signature: 0x3c7a3aff
*/
function commit()
public
payable
isInitialized
isNotFrozen
isRunning
{
// Reject contributions lower than the minimum amount, and max than maxContribution
require(msg.value >= minContribution, "Value sent is less than the minimum contribution.");
// Participant initial state record
uint8 currentStage = getCurrentStage();
Participant storage participantStats = participants[msg.sender];
ParticipantStageDetails storage byStage = participantStats.stages[currentStage];
require(participantStats.committedETH.add(msg.value) <= maxContribution, "Value sent is larger than the maximum contribution.");
// Check if participant already exists
if (participantStats.contributions == 0) {
// Identify the participants by their Id
participantsById[participantCount] = msg.sender;
// Increase participant count
participantCount++;
}
// UPDATE PARTICIPANT STATS
participantStats.contributions++;
participantStats.pendingETH = participantStats.pendingETH.add(msg.value);
byStage.pendingETH = byStage.pendingETH.add(msg.value);
// UPDATE GLOBAL STATS
pendingETH = pendingETH.add(msg.value);
emit PendingContributionAdded(
msg.sender,
msg.value,
uint32(participantStats.contributions),
currentStage
);
// If whitelisted, process the contribution automatically
if (participantStats.whitelisted == true) {
acceptContributions(msg.sender);
}
}
/**
* @notice Allows a participant to cancel pending contributions
*
* Function signature: 0xea8a1af0
*/
function cancel()
external
payable
isInitialized
isNotFrozen
{
cancelPendingContributions(msg.sender, msg.value);
}
/**
* @notice Approves or rejects participants.
* @param _addresses The list of participant address.
* @param _approve Indicates if the provided participants are approved (true) or rejected (false).
*/
function whitelist(address[] calldata _addresses, bool _approve)
external
onlyWhitelistingAddress
isInitialized
isNotFrozen
isRunning
{
// Revert if the provided list is empty
require(_addresses.length > 0, "No addresses given to whitelist.");
for (uint256 i = 0; i < _addresses.length; i++) {
address participantAddress = _addresses[i];
Participant storage participantStats = participants[participantAddress];
if (_approve) {
if (participantStats.whitelisted == false) {
// If participants are approved: whitelist them and accept their contributions
participantStats.whitelisted = true;
emit WhitelistApproved(participantAddress, participantStats.pendingETH, uint32(participantStats.contributions));
}
// accept any pending ETH
acceptContributions(participantAddress);
} else {
participantStats.whitelisted = false;
emit WhitelistRejected(participantAddress, participantStats.pendingETH, uint32(participantStats.contributions));
// Cancel participants pending contributions.
cancelPendingContributions(participantAddress, 0);
}
}
}
/**
* @notice Allows the project to withdraw tokens.
* @param _tokenAmount The token amount.
*/
function projectTokenWithdraw(uint256 _tokenAmount)
external
onlyProjectAddress
isInitialized
{
require(_tokenAmount <= tokenSupply, "Requested amount too high, not enough tokens available.");
// decrease the supply
tokenSupply = tokenSupply.sub(_tokenAmount);
initialTokenSupply = initialTokenSupply.sub(_tokenAmount);
// sent all tokens from the contract to the _to address
// solium-disable-next-line security/no-send
IERC777(tokenAddress).send(projectAddress, _tokenAmount, "");
}
/**
* @notice Allows for the project to withdraw ETH.
* @param _ethAmount The ETH amount in wei.
*/
function projectWithdraw(uint256 _ethAmount)
external
onlyProjectAddress
isInitialized
isNotFrozen
{
// UPDATE the locked/unlocked ratio for the project
calcProjectAllocation();
// Get current allocated ETH to the project
uint256 availableForWithdraw = _projectUnlockedETH.sub(projectWithdrawnETH);
require(_ethAmount <= availableForWithdraw, "Requested amount too high, not enough ETH unlocked.");
// UPDATE global STATS
projectWithdrawCount++;
projectWithdrawnETH = projectWithdrawnETH.add(_ethAmount);
// Event emission
emit ProjectWithdraw(
projectAddress,
_ethAmount,
uint32(projectWithdrawCount)
);
emit TransferEvent(
uint8(TransferTypes.PROJECT_WITHDRAWN),
projectAddress,
_ethAmount
);
// Transfer ETH to project wallet
address(uint160(projectAddress)).transfer(_ethAmount);
}
function changeStage(uint8 _stageId, uint256 _tokenLimit, uint256 _tokenPrice)
external
onlyProjectAddress
isInitialized
{
stages[_stageId].tokenLimit = _tokenLimit;
stages[_stageId].tokenPrice = _tokenPrice;
if(_stageId > stageCount) {
stageCount = _stageId;
}
emit StageChanged(_stageId, _tokenLimit, _tokenPrice, getCurrentEffectiveBlockNumber());
}
function changeWhitelistingAddress(address _newAddress)
external
onlyProjectAddress
isInitialized
{
whitelistingAddress = _newAddress;
emit WhitelistingAddressChanged(whitelistingAddress, getCurrentStage(), getCurrentEffectiveBlockNumber());
}
function changeFreezerAddress(address _newAddress)
external
onlyProjectAddress
isInitialized
{
freezerAddress = _newAddress;
emit FreezerAddressChanged(freezerAddress, getCurrentStage(), getCurrentEffectiveBlockNumber());
}
/*
* Security functions.
* If the rICO runs fine the freezer address can be set to 0x0, for the beginning its good to have a safe guard.
*/
/**
* @notice Freezes the rICO in case of emergency.
*
* Function signature: 0x62a5af3b
*/
function freeze()
external
onlyFreezerAddress
isNotFrozen
{
frozen = true;
freezeStart = getCurrentEffectiveBlockNumber();
// Emit event
emit SecurityFreeze(freezerAddress, getCurrentStage(), freezeStart);
}
/**
* @notice Un-freezes the rICO.
*
* Function signature: 0x6a28f000
*/
function unfreeze()
external
onlyFreezerAddress
isFrozen
{
uint256 currentBlock = getCurrentEffectiveBlockNumber();
frozen = false;
frozenPeriod = frozenPeriod.add(
currentBlock.sub(freezeStart)
);
// Emit event
emit SecurityUnfreeze(freezerAddress, getCurrentStage(), currentBlock);
}
/**
* @notice Sets the freeze address to 0x0
*
* Function signature: 0xeb10dec7
*/
function disableEscapeHatch()
external
onlyFreezerAddress
isNotFrozen
{
freezerAddress = address(0);
rescuerAddress = address(0);
// Emit event
emit SecurityDisableEscapeHatch(freezerAddress, getCurrentStage(), getCurrentEffectiveBlockNumber());
}
/**
* @notice Moves the funds to a safe place, in case of emergency. Only possible, when the the rICO is frozen.
*/
function escapeHatch(address _to)
external
onlyRescuerAddress
isFrozen
{
require(getCurrentEffectiveBlockNumber() >= freezeStart.add(18000), 'Let it cool.. Wait at least ~3 days (18000 blk) before moving anything.');
uint256 tokenBalance = IERC777(tokenAddress).balanceOf(address(this));
uint256 ethBalance = address(this).balance;
// sent all tokens from the contract to the _to address
// solium-disable-next-line security/no-send
IERC777(tokenAddress).send(_to, tokenBalance, "");
// sent all ETH from the contract to the _to address
address(uint160(_to)).transfer(ethBalance);
// Emit events
emit SecurityEscapeHatch(rescuerAddress, _to, getCurrentStage(), getCurrentEffectiveBlockNumber());
emit TransferEvent(uint8(TransferTypes.FROZEN_ESCAPEHATCH_TOKEN), _to, tokenBalance);
emit TransferEvent(uint8(TransferTypes.FROZEN_ESCAPEHATCH_ETH), _to, ethBalance);
}
/*
* Public view functions
* ------------------------------------------------------------------------------------------------
*/
/**
* @notice Returns project's total unlocked ETH.
* @return uint256 The amount of ETH unlocked over the whole rICO.
*/
function getUnlockedProjectETH() public view returns (uint256) {
// calc from the last known point on
uint256 newlyUnlockedEth = calcUnlockedAmount(_projectCurrentlyReservedETH, _projectLastBlock);
return _projectUnlockedETH
.add(newlyUnlockedEth);
}
/**
* @notice Returns project's current available unlocked ETH reduced by what was already withdrawn.
* @return uint256 The amount of ETH available to the project for withdraw.
*/
function getAvailableProjectETH() public view returns (uint256) {
return getUnlockedProjectETH()
.sub(projectWithdrawnETH);
}
/**
* @notice Returns the participant's amount of locked tokens at the current block.
* @param _participantAddress The participant's address.
*/
function getParticipantReservedTokens(address _participantAddress) public view returns (uint256) {
Participant storage participantStats = participants[_participantAddress];
if(participantStats._currentReservedTokens == 0) {
return 0;
}
return participantStats._currentReservedTokens.sub(
calcUnlockedAmount(participantStats._currentReservedTokens, participantStats._lastBlock)
);
}
/**
* @notice Returns the participant's amount of unlocked tokens at the current block.
* This function is used for internal sanity checks.
* Note: this value can differ from the actual unlocked token balance of the participant, if he received tokens from other sources than the rICO.
* @param _participantAddress The participant's address.
*/
function getParticipantUnlockedTokens(address _participantAddress) public view returns (uint256) {
Participant storage participantStats = participants[_participantAddress];
return participantStats._unlockedTokens.add(
calcUnlockedAmount(participantStats._currentReservedTokens, participantStats._lastBlock)
);
}
/**
* @notice Returns the token amount that are still available at the current stage
* @return The amount of tokens
*/
function getAvailableTokenAtCurrentStage() public view returns (uint256) {
return stages[getCurrentStage()].tokenLimit.sub(
initialTokenSupply.sub(tokenSupply)
);
}
/**
* @notice Returns the current stage at current sold token amount
* @return The current stage ID
*/
function getCurrentStage() public view returns (uint8) {
return getStageByTokenLimit(
initialTokenSupply.sub(tokenSupply)
);
}
/**
* @notice Returns the current token price at the current stage.
* @return The current ETH price in wei.
*/
function getCurrentPrice() public view returns (uint256) {
return getPriceAtStage(getCurrentStage());
}
/**
* @notice Returns the token price at the specified stage ID.
* @param _stageId the stage ID at which we want to retrieve the token price.
*/
function getPriceAtStage(uint8 _stageId) public view returns (uint256) {
if (_stageId <= stageCount) {
return stages[_stageId].tokenPrice;
}
return stages[stageCount].tokenPrice;
}
/**
* @notice Returns the token price for when a specific amount of tokens is sold
* @param _tokenLimit The amount of tokens for which we want to know the respective token price
* @return The ETH price in wei
*/
function getPriceForTokenLimit(uint256 _tokenLimit) public view returns (uint256) {
return getPriceAtStage(getStageByTokenLimit(_tokenLimit));
}
/**
* @notice Returns the stage at a point where a certain amount of tokens is sold
* @param _tokenLimit The amount of tokens for which we want to know the stage ID
*/
function getStageByTokenLimit(uint256 _tokenLimit) public view returns (uint8) {
// Go through all stages, until we find the one that matches the supply
for (uint8 stageId = 0; stageId <= stageCount; stageId++) {
if(_tokenLimit <= stages[stageId].tokenLimit) {
return stageId;
}
}
// if amount is more than available stages return last stage with the highest price
return stageCount;
}
/**
* @notice Returns the rICOs available ETH to reserve tokens at a given stage.
* @param _stageId the stage ID.
*/
function committableEthAtStage(uint8 _stageId, uint8 _currentStage) public view returns (uint256) {
uint256 supply;
// past stages
if(_stageId < _currentStage) {
return 0;
// last stage
} else if(_stageId >= stageCount) {
supply = tokenSupply;
// current stage
} else if(_stageId == _currentStage) {
supply = stages[_currentStage].tokenLimit.sub(
initialTokenSupply.sub(tokenSupply)
);
// later stages
} else if(_stageId > _currentStage) {
supply = stages[_stageId].tokenLimit.sub(stages[_stageId - 1].tokenLimit); // calc difference to last stage
}
return getEthAmountForTokensAtStage(
supply
, _stageId);
}
/**
* @notice Returns the amount of ETH (in wei) for a given token amount at a given stage.
* @param _tokenAmount The amount of token.
* @param _stageId the stage ID.
* @return The ETH amount in wei
*/
function getEthAmountForTokensAtStage(uint256 _tokenAmount, uint8 _stageId) public view returns (uint256) {
return _tokenAmount
.mul(stages[_stageId].tokenPrice)
.div(10 ** 18);
}
/**
* @notice Returns the amount of tokens that given ETH would buy at a given stage.
* @param _ethAmount The ETH amount in wei.
* @param _stageId the stage ID.
* @return The token amount in its smallest unit (token "wei")
*/
function getTokenAmountForEthAtStage(uint256 _ethAmount, uint8 _stageId) public view returns (uint256) {
return _ethAmount
.mul(10 ** 18)
.div(stages[_stageId].tokenPrice);
}
/**
* @notice Returns the current block number: required in order to override when running tests.
*/
function getCurrentBlockNumber() public view returns (uint256) {
return uint256(block.number);
}
/**
* @notice Returns the current block number - the frozen period: required in order to override when running tests.
*/
function getCurrentEffectiveBlockNumber() public view returns (uint256) {
return uint256(block.number)
.sub(frozenPeriod); // make sure we deduct any frozenPeriod from calculations
}
/**
* @notice rICO HEART: Calculates the unlocked amount tokens/ETH beginning from the buy phase start or last block to the current block.
* This function is used by the participants as well as the project, to calculate the current unlocked amount.
*
* @return the unlocked amount of tokens or ETH.
*/
function calcUnlockedAmount(uint256 _amount, uint256 _lastBlock) public view returns (uint256) {
uint256 currentBlock = getCurrentEffectiveBlockNumber();
if(_amount == 0) {
return 0;
}
// Calculate WITHIN the buy phase
if (currentBlock >= buyPhaseStartBlock && currentBlock < buyPhaseEndBlock) {
// security/no-assign-params: "calcUnlockedAmount": Avoid assigning to function parameters.
uint256 lastBlock = _lastBlock;
if(lastBlock < buyPhaseStartBlock) {
lastBlock = buyPhaseStartBlock.sub(1); // We need to reduce it by 1, as the startBlock is always already IN the period.
}
// get the number of blocks that have "elapsed" since the last block
uint256 passedBlocks = currentBlock.sub(lastBlock);
// number of blocks ( ie: start=4/end=10 => 10 - 4 => 6 )
uint256 totalBlockCount = buyPhaseEndBlock.sub(lastBlock);
return _amount.mul(
passedBlocks.mul(10 ** 20)
.div(totalBlockCount)
).div(10 ** 20);
// Return everything AFTER the buy phase
} else if (currentBlock >= buyPhaseEndBlock) {
return _amount;
}
// Return nothing BEFORE the buy phase
return 0;
}
/*
* Internal functions
* ------------------------------------------------------------------------------------------------
*/
/**
* @notice Checks the projects core variables and ETH amounts in the contract for correctness.
*/
function sanityCheckProject() internal view {
// PROJECT: The sum of reserved + unlocked has to be equal the committedETH.
require(
committedETH == _projectCurrentlyReservedETH.add(_projectUnlockedETH),
'Project Sanity check failed! Reserved + Unlock must equal committedETH'
);
// PROJECT: The ETH in the rICO has to be the total of unlocked + reserved - withdraw
require(
address(this).balance == _projectUnlockedETH.add(_projectCurrentlyReservedETH).add(pendingETH).sub(projectWithdrawnETH),
'Project sanity check failed! balance = Unlock + Reserved - Withdrawn'
);
}
/**
* @notice Checks the projects core variables and ETH amounts in the contract for correctness.
*/
function sanityCheckParticipant(address _participantAddress) internal view {
Participant storage participantStats = participants[_participantAddress];
// PARTICIPANT: The sum of reserved + unlocked has to be equal the totalReserved.
require(
participantStats.reservedTokens == participantStats._currentReservedTokens.add(participantStats._unlockedTokens),
'Participant Sanity check failed! Reser. + Unlock must equal totalReser'
);
}
/**
* @notice Calculates the projects allocation since the last calculation.
*/
function calcProjectAllocation() internal {
uint256 newlyUnlockedEth = calcUnlockedAmount(_projectCurrentlyReservedETH, _projectLastBlock);
// UPDATE GLOBAL STATS
_projectCurrentlyReservedETH = _projectCurrentlyReservedETH.sub(newlyUnlockedEth);
_projectUnlockedETH = _projectUnlockedETH.add(newlyUnlockedEth);
_projectLastBlock = getCurrentEffectiveBlockNumber();
sanityCheckProject();
}
/**
* @notice Calculates the participants allocation since the last calculation.
*/
function calcParticipantAllocation(address _participantAddress) internal {
Participant storage participantStats = participants[_participantAddress];
// UPDATE the locked/unlocked ratio for this participant
participantStats._unlockedTokens = getParticipantUnlockedTokens(_participantAddress);
participantStats._currentReservedTokens = getParticipantReservedTokens(_participantAddress);
// RESET BLOCK NUMBER: Force the unlock calculations to start from this point in time.
participantStats._lastBlock = getCurrentEffectiveBlockNumber();
// UPDATE the locked/unlocked ratio for the project as well
calcProjectAllocation();
}
/**
* @notice Cancels any participant's pending ETH contributions.
* Pending is any ETH from participants that are not whitelisted yet.
*/
function cancelPendingContributions(address _participantAddress, uint256 _sentValue)
internal
isInitialized
isNotFrozen
{
Participant storage participantStats = participants[_participantAddress];
uint256 participantPendingEth = participantStats.pendingETH;
// Fail silently if no ETH are pending
if(participantPendingEth == 0) {
// sent at least back what he contributed
if(_sentValue > 0) {
address(uint160(_participantAddress)).transfer(_sentValue);
}
return;
}
// UPDATE PARTICIPANT STAGES
for (uint8 stageId = 0; stageId <= stageCount; stageId++) {
participantStats.stages[stageId].pendingETH = 0;
}
// UPDATE PARTICIPANT STATS
participantStats.pendingETH = 0;
// UPDATE GLOBAL STATS
canceledETH = canceledETH.add(participantPendingEth);
pendingETH = pendingETH.sub(participantPendingEth);
// Emit events
emit PendingContributionsCanceled(_participantAddress, participantPendingEth, uint32(participantStats.contributions));
emit TransferEvent(
uint8(TransferTypes.CONTRIBUTION_CANCELED),
_participantAddress,
participantPendingEth
);
// transfer ETH back to participant including received value
address(uint160(_participantAddress)).transfer(participantPendingEth.add(_sentValue));
// SANITY check
sanityCheckParticipant(_participantAddress);
sanityCheckProject();
}
/**
* @notice Accept a participant's contribution.
* @param _participantAddress Participant's address.
*/
function acceptContributions(address _participantAddress)
internal
isInitialized
isNotFrozen
isRunning
{
Participant storage participantStats = participants[_participantAddress];
// Fail silently if no ETH are pending
if (participantStats.pendingETH == 0) {
return;
}
uint8 currentStage = getCurrentStage();
uint256 totalRefundedETH;
uint256 totalNewReservedTokens;
calcParticipantAllocation(_participantAddress);
// set the first contribution block
if(participantStats.committedETH == 0) {
participantStats.firstContributionBlock = participantStats._lastBlock; // `_lastBlock` was set in calcParticipantAllocation()
}
// Iterate over all stages and their pending contributions
for (uint8 stageId = 0; stageId <= stageCount; stageId++) {
ParticipantStageDetails storage byStage = participantStats.stages[stageId];
// skip if not ETH is pending
if (byStage.pendingETH == 0) {
continue;
}
// skip if stage is below "currentStage" (as they have no available tokens)
if(stageId < currentStage) {
// add this stage pendingETH to the "currentStage"
participantStats.stages[currentStage].pendingETH = participantStats.stages[currentStage].pendingETH.add(byStage.pendingETH);
// and reset this stage
byStage.pendingETH = 0;
continue;
}
// --> We continue only if in "currentStage" or later stages
uint256 maxCommittableEth = committableEthAtStage(stageId, currentStage);
uint256 newlyCommittableEth = byStage.pendingETH;
uint256 returnEth = 0;
uint256 overflowEth = 0;
// If incoming value is higher than what we can accept,
// just accept the difference and return the rest
if (newlyCommittableEth > maxCommittableEth) {
overflowEth = newlyCommittableEth.sub(maxCommittableEth);
newlyCommittableEth = maxCommittableEth;
// if in the last stage, return ETH
if (stageId == stageCount) {
returnEth = overflowEth;
totalRefundedETH = totalRefundedETH.add(returnEth);
// if below the last stage, move pending ETH to the next stage
} else {
participantStats.stages[stageId + 1].pendingETH = participantStats.stages[stageId + 1].pendingETH.add(overflowEth);
byStage.pendingETH = byStage.pendingETH.sub(overflowEth);
}
}
// convert ETH to TOKENS
uint256 newTokenAmount = getTokenAmountForEthAtStage(
newlyCommittableEth, stageId
);
totalNewReservedTokens = totalNewReservedTokens.add(newTokenAmount);
// UPDATE PARTICIPANT STATS
participantStats._currentReservedTokens = participantStats._currentReservedTokens.add(newTokenAmount);
participantStats.reservedTokens = participantStats.reservedTokens.add(newTokenAmount);
participantStats.committedETH = participantStats.committedETH.add(newlyCommittableEth);
participantStats.pendingETH = participantStats.pendingETH.sub(newlyCommittableEth).sub(returnEth);
byStage.pendingETH = byStage.pendingETH.sub(newlyCommittableEth).sub(returnEth);
// UPDATE GLOBAL STATS
tokenSupply = tokenSupply.sub(newTokenAmount);
pendingETH = pendingETH.sub(newlyCommittableEth).sub(returnEth);
committedETH = committedETH.add(newlyCommittableEth);
_projectCurrentlyReservedETH = _projectCurrentlyReservedETH.add(newlyCommittableEth);
// Emit event
emit ContributionsAccepted(_participantAddress, newlyCommittableEth, newTokenAmount, stageId);
}
// Refund what couldn't be accepted
if (totalRefundedETH > 0) {
emit TransferEvent(uint8(TransferTypes.CONTRIBUTION_ACCEPTED_OVERFLOW), _participantAddress, totalRefundedETH);
address(uint160(_participantAddress)).transfer(totalRefundedETH);
}
// Transfer tokens to the participant
// solium-disable-next-line security/no-send
IERC777(tokenAddress).send(_participantAddress, totalNewReservedTokens, "");
// SANITY CHECK
sanityCheckParticipant(_participantAddress);
sanityCheckProject();
}
/**
* @notice Allow a participant to withdraw by sending tokens back to rICO contract.
* @param _participantAddress participant address.
* @param _returnedTokenAmount The amount of tokens returned.
*/
function withdraw(address _participantAddress, uint256 _returnedTokenAmount)
internal
isInitialized
isNotFrozen
isRunning
{
Participant storage participantStats = participants[_participantAddress];
calcParticipantAllocation(_participantAddress);
require(_returnedTokenAmount > 0, 'You can not withdraw without sending tokens.');
require(participantStats._currentReservedTokens > 0 && participantStats.reservedTokens > 0, 'You can not withdraw, you have no locked tokens.');
uint256 returnedTokenAmount = _returnedTokenAmount;
uint256 overflowingTokenAmount;
uint256 returnEthAmount;
// Only allow reserved tokens be returned, return the overflow.
if (returnedTokenAmount > participantStats._currentReservedTokens) {
overflowingTokenAmount = returnedTokenAmount.sub(participantStats._currentReservedTokens);
returnedTokenAmount = participantStats._currentReservedTokens;
}
// Calculate the return amount
returnEthAmount = participantStats.committedETH.mul(
returnedTokenAmount.sub(1).mul(10 ** 20) // deduct 1 token-wei to minimize rounding issues
.div(participantStats.reservedTokens)
).div(10 ** 20);
// UPDATE PARTICIPANT STATS
participantStats.withdraws++;
participantStats._currentReservedTokens = participantStats._currentReservedTokens.sub(returnedTokenAmount);
participantStats.reservedTokens = participantStats.reservedTokens.sub(returnedTokenAmount);
participantStats.committedETH = participantStats.committedETH.sub(returnEthAmount);
// UPDATE global STATS
tokenSupply = tokenSupply.add(returnedTokenAmount);
withdrawnETH = withdrawnETH.add(returnEthAmount);
committedETH = committedETH.sub(returnEthAmount);
_projectCurrentlyReservedETH = _projectCurrentlyReservedETH.sub(returnEthAmount);
// Return overflowing tokens received
if (overflowingTokenAmount > 0) {
// send tokens back to participant
bytes memory data;
// Emit event
emit TransferEvent(uint8(TransferTypes.PARTICIPANT_WITHDRAW_OVERFLOW), _participantAddress, overflowingTokenAmount);
// solium-disable-next-line security/no-send
IERC777(tokenAddress).send(_participantAddress, overflowingTokenAmount, data);
}
// Emit events
emit ParticipantWithdraw(_participantAddress, returnEthAmount, returnedTokenAmount, uint32(participantStats.withdraws));
emit TransferEvent(uint8(TransferTypes.PARTICIPANT_WITHDRAW), _participantAddress, returnEthAmount);
// Return ETH back to participant
address(uint160(_participantAddress)).transfer(returnEthAmount);
// SANITY CHECK
sanityCheckParticipant(_participantAddress);
sanityCheckProject();
}
/*
* Modifiers
*/
/**
* @notice Checks if the sender is the project.
*/
modifier onlyProjectAddress() {
require(msg.sender == projectAddress, "Only the project can call this method.");
_;
}
/**
* @notice Checks if the sender is the deployer.
*/
modifier onlyDeployingAddress() {
require(msg.sender == deployingAddress, "Only the deployer can call this method.");
_;
}
/**
* @notice Checks if the sender is the whitelist controller.
*/
modifier onlyWhitelistingAddress() {
require(msg.sender == whitelistingAddress, "Only the whitelist controller can call this method.");
_;
}
/**
* @notice Checks if the sender is the freezer controller address.
*/
modifier onlyFreezerAddress() {
require(msg.sender == freezerAddress, "Only the freezer address can call this method.");
_;
}
/**
* @notice Checks if the sender is the freezer controller address.
*/
modifier onlyRescuerAddress() {
require(msg.sender == rescuerAddress, "Only the rescuer address can call this method.");
_;
}
/**
* @notice Requires the contract to have been initialized.
*/
modifier isInitialized() {
require(initialized == true, "Contract must be initialized.");
_;
}
/**
* @notice Requires the contract to NOT have been initialized,
*/
modifier isNotInitialized() {
require(initialized == false, "Contract can not be initialized.");
_;
}
/**
* @notice @dev Requires the contract to be frozen.
*/
modifier isFrozen() {
require(frozen == true, "rICO has to be frozen!");
_;
}
/**
* @notice @dev Requires the contract not to be frozen.
*/
modifier isNotFrozen() {
require(frozen == false, "rICO is frozen!");
_;
}
/**
* @notice Checks if the rICO is running.
*/
modifier isRunning() {
uint256 blockNumber = getCurrentEffectiveBlockNumber();
require(blockNumber >= commitPhaseStartBlock && blockNumber <= buyPhaseEndBlock, "Current block is outside the rICO period.");
_;
}
} | * @notice rICO HEART: Calculates the unlocked amount tokens/ETH beginning from the buy phase start or last block to the current block. This function is used by the participants as well as the project, to calculate the current unlocked amount. @return the unlocked amount of tokens or ETH./ Calculate WITHIN the buy phase security/no-assign-params: "calcUnlockedAmount": Avoid assigning to function parameters. | function calcUnlockedAmount(uint256 _amount, uint256 _lastBlock) public view returns (uint256) {
uint256 currentBlock = getCurrentEffectiveBlockNumber();
if(_amount == 0) {
return 0;
}
if (currentBlock >= buyPhaseStartBlock && currentBlock < buyPhaseEndBlock) {
uint256 lastBlock = _lastBlock;
if(lastBlock < buyPhaseStartBlock) {
}
return _amount.mul(
passedBlocks.mul(10 ** 20)
.div(totalBlockCount)
).div(10 ** 20);
return _amount;
}
}
| 6,399,484 | [
1,
86,
2871,
51,
4194,
4928,
30,
26128,
326,
25966,
3844,
2430,
19,
1584,
44,
8435,
628,
326,
30143,
6855,
787,
578,
1142,
1203,
358,
326,
783,
1203,
18,
1220,
445,
353,
1399,
635,
326,
22346,
487,
5492,
487,
326,
1984,
16,
358,
4604,
326,
783,
25966,
3844,
18,
327,
326,
25966,
3844,
434,
2430,
578,
512,
2455,
18,
19,
9029,
13601,
706,
326,
30143,
6855,
4373,
19,
2135,
17,
6145,
17,
2010,
30,
315,
12448,
7087,
329,
6275,
6877,
17843,
28639,
358,
445,
1472,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
7029,
7087,
329,
6275,
12,
11890,
5034,
389,
8949,
16,
2254,
5034,
389,
2722,
1768,
13,
1071,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
203,
3639,
2254,
5034,
30610,
273,
5175,
28531,
1768,
1854,
5621,
203,
203,
3639,
309,
24899,
8949,
422,
374,
13,
288,
203,
5411,
327,
374,
31,
203,
3639,
289,
203,
203,
3639,
309,
261,
2972,
1768,
1545,
30143,
11406,
1685,
1768,
597,
30610,
411,
30143,
11406,
1638,
1768,
13,
288,
203,
203,
5411,
2254,
5034,
1142,
1768,
273,
389,
2722,
1768,
31,
203,
5411,
309,
12,
2722,
1768,
411,
30143,
11406,
1685,
1768,
13,
288,
203,
5411,
289,
203,
203,
203,
203,
5411,
327,
389,
8949,
18,
16411,
12,
203,
7734,
2275,
6450,
18,
16411,
12,
2163,
2826,
4200,
13,
203,
7734,
263,
2892,
12,
4963,
1768,
1380,
13,
203,
5411,
262,
18,
2892,
12,
2163,
2826,
4200,
1769,
203,
203,
5411,
327,
389,
8949,
31,
203,
3639,
289,
203,
565,
289,
203,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.6;
pragma experimental ABIEncoderV2;
import "./Currency.sol";
import "./standard/IERC721Receiver.sol";
/** @title ERC20 Proxy contract.
* @dev Manages ERC20 assets using the chain owner as a signing oracle for validation and cross-chain transfer
*/
contract CurrencyProxy {
address internal signer; // signer oracle address
uint256 internal chainId; // unique chain id
Currency internal parent; // managed ERC20 contract
uint256 internal deposits; // amount deposited in this contract
mapping(bytes32 => bool) internal usedWithdrawHashes; // deposit hashes that have been used up (replay protection)
bytes internal prefix = "\x19Ethereum Signed Message:\n32"; // Signed message prefix
/**
* @dev Construct the proxy with a managed parent and chain ID
* @param parentAddress Address of the managed ERC20 contract
* @param signerAddress Address of an authorized signer
* @param _chainId Chain ID this contract is attached to
* Default parent address: 0xd7523103ba15c1dfcf0f5ea1c553bc18179ac656
* Default signer address: 0xfa80e7480e9c42a9241e16d6c1e7518c1b1757e4
*/
constructor(
address parentAddress,
address signerAddress,
uint256 _chainId
) {
signer = signerAddress;
chainId = _chainId;
parent = Currency(parentAddress);
}
/** @dev Log the fact that we withdrew oracle-signed fungible assets
* @param from Address withdrawn from
* @param amount Amount to withdraw
* @param timestamp Time of the transaction withdrawl
*/
event Withdrew(
address indexed from,
uint256 indexed amount,
uint256 indexed timestamp
);
/** @dev Used by the oracle when signing
* @param from Address deposited from
* @param amount Amount to deposit
*/
event Deposited(address indexed from, uint256 indexed amount);
/** @dev Set the address for the signer oracle
* @param newSigner Address of the new signer
*/
function setSigner(address newSigner) public {
require(
msg.sender == signer,
"new signer can only be set by old signer"
);
signer = newSigner;
}
/** @dev Set the parent contract that this proxy manages
* @param newParent Address of parent contract
*/
function setCoinParent(address newParent) public {
require(msg.sender == signer, "must be signer");
parent = Currency(newParent);
}
/** @dev Withdraw ERC20 assets to an address
* @param to Address to withdraw to
* Example is 0x08E242bB06D85073e69222aF8273af419d19E4f6
* @param amount Amount to withdraw
* @param timestamp Timestamp of the transaction
* @param r ECDSA output
* Example is 0xc336b0bb5cac4584d79e77b1680ab789171ebc95f44f68bb1cc0a7b1174058ad
* @param s ECDSA output
* Example is 0x72b888e952c0c39a8054f2b6dc41df645f5d4dc3d9cc6118535d88aa34945440
* @param v Recovery ID
* Example is 0x1c
* Example args: 0x08E242bB06D85073e69222aF8273af419d19E4f6, 1, 10, 0xc336b0bb5cac4584d79e77b1680ab789171ebc95f44f68bb1cc0a7b1174058ad, 0x72b888e952c0c39a8054f2b6dc41df645f5d4dc3d9cc6118535d88aa34945440, 0x1c
*/
function withdraw(
address to,
uint256 amount,
uint256 timestamp,
bytes32 r,
bytes32 s,
uint8 v
) public {
bytes memory message = abi.encodePacked(to, amount, timestamp, chainId); // Encode message
bytes32 messageHash = keccak256(message); // Hash the message
bytes32 prefixedHash = keccak256(abi.encodePacked(prefix, messageHash)); // Add the signed preview and hash that
require(
ecrecover(prefixedHash, v, r, s) == signer,
"invalid signature"
); // Recover address from sig check if it's the signer
require(!usedWithdrawHashes[prefixedHash], "hash already used"); // Check if this transaction has been used (to prevent replay attacks)
usedWithdrawHashes[prefixedHash] = true; // Mark the transaction hash as used, so it can't be used again
bool needsMint = deposits < amount; // Check if we have enough asset, or if we need to mint more
uint256 balanceNeeded = SafeMath.sub(amount, deposits); // Calculate how much we need
if (needsMint) {
deposits = SafeMath.add(deposits, balanceNeeded); // If we need to mint more, add the balance
}
deposits = SafeMath.sub(deposits, amount); // Set remaining deposits
emit Withdrew(to, amount, timestamp); // Emit Withdraw event
if (needsMint) {
parent.mint(address(this), balanceNeeded); // If we need to mint more, mint it
}
require(parent.transfer(to, amount), "transfer failed"); // Attempt the transfer, back out if it fails
}
/** @dev Deposit ERC20 assets to an address
* @param to Address to deposit to
* Example is 0x08E242bB06D85073e69222aF8273af419d19E4f6
* @param amount Amount to withdraw
*/
function deposit(address to, uint256 amount) public {
deposits = SafeMath.add(deposits, amount); // add the amount to deposits
emit Deposited(to, amount); // emit Deposited event
require(
parent.transferFrom(msg.sender, address(this), amount),
"transfer failed"
); // Attempt transfer and back out if it fails
}
/** @dev Check if the nonce has been used
* @param to Address to deposit to
* Example is 0x08E242bB06D85073e69222aF8273af419d19E4f6
* @param amount Amount to withdraw
* @param timestamp Timestamp of the transaction
* @return true if the nonce has been used
*/
function withdrawNonceUsed(
address to,
uint256 amount,
uint256 timestamp
) public view returns (bool) {
bytes memory message = abi.encodePacked(to, amount, timestamp, chainId);
bytes32 messageHash = keccak256(message);
bytes32 prefixedHash = keccak256(abi.encodePacked(prefix, messageHash));
return usedWithdrawHashes[prefixedHash]; // return true if it exists
}
}
| * @dev Used by the oracle when signing @param from Address deposited from @param amount Amount to deposit/ | event Deposited(address indexed from, uint256 indexed amount);
| 1,754,195 | [
1,
6668,
635,
326,
20865,
1347,
10611,
225,
628,
5267,
443,
1724,
329,
628,
225,
3844,
16811,
358,
443,
1724,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
871,
4019,
538,
16261,
12,
2867,
8808,
628,
16,
2254,
5034,
8808,
3844,
1769,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.5.10;
import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol";
contract FlightSuretyData {
using SafeMath for uint256;
/********************************************************************************************/
/* DATA VARIABLES */
/********************************************************************************************/
address private contractOwner; // Account used to deploy contract
bool private operational = true; // Blocks all state changes throughout the contract if false
struct Airline {
bool isRegistered;
bool isFunded;
uint256 funds;
}
mapping(address => Airline) private airlines;
uint registeredAirlines;
struct Flight {
bool isRegistered;
string from;
string to;
address airline;
uint status;
}
struct Claim {
address passenger;
uint256 purchaseAmt;
uint payout;
bool paidStatus;
}
mapping(bytes32 => Flight) public flights;
bytes32[] public registeredFlights;
mapping(bytes32 => Claim[]) public flightClaims;
mapping(address => uint256) public withdrawals;
/********************************************************************************************/
/* EVENT DEFINITIONS */
/********************************************************************************************/
/**
* @dev Constructor
* The deploying account becomes contractOwner
*/
constructor (address airlineAddr) public
{
contractOwner = msg.sender;
airlines[airlineAddr] = Airline(true, false, 0);
registeredAirlines = 1;
}
/********************************************************************************************/
/* EVENT DEFINITIONS */
/********************************************************************************************/
event AirlineRegistered(address airline);
event AirlineFunded(address airline);
event Paid(address recipient, uint256 amt);
event Credited(bytes32 flight, address passenger, uint256 amt);
event FlightRegistered(bytes32 flight);
event ProcessedFlightStatus(bytes32 flight, uint status);
/********************************************************************************************/
/* FUNCTION MODIFIERS */
/********************************************************************************************/
// Modifiers help avoid duplication of code. They are typically used to validate something
// before a function is allowed to be executed.
/**
* @dev Modifier that requires the "operational" boolean variable to be "true"
* This is used on all state changing functions to pause the contract in
* the event there is an issue that needs to be fixed
*/
modifier requireIsOperational()
{
require(operational, "Contract is currently not operational");
_; // All modifiers require an "_" which indicates where the function body will be added
}
/**
* @dev Modifier that requires the "ContractOwner" account to be the function caller
*/
modifier requireContractOwner()
{
require(msg.sender == contractOwner, "Caller is not contract owner");
_;
}
modifier onlyRegisteredFlight(bytes32 flight) {
require(flights[flight].isRegistered, "Flight is not registered");
_;
}
modifier onlyNonRegisteredFlight(bytes32 flight) {
require(!flights[flight].isRegistered, "Flight is not registered");
_;
}
modifier onlyRegisteredAirline(address airline) {
require(airlines[airline].isRegistered, "Airline is not registered");
_;
}
modifier onlyNonRegisteredAirline(address airline) {
require(!airlines[airline].isRegistered, "Airline is already registered");
_;
}
modifier onlyFundedAirline(address airline) {
require(airlines[airline].isFunded, "Airline is not funded");
_;
}
modifier onlyNonFundedAirline(address airline) {
require(!airlines[airline].isFunded, "Airline is already funded");
_;
}
/********************************************************************************************/
/* UTILITY FUNCTIONS */
/********************************************************************************************/
/**
* @dev Get operating status of contract
*
* @return A bool that is the current operating status
*/
function isOperational()
public
view
returns(bool)
{
return operational;
}
/**
* @dev Sets contract operations on/off
*
* When operational mode is disabled, all write transactions except for this one will fail
*/
function setOperatingStatus
(
bool mode
)
external
requireContractOwner
{
operational = mode;
}
/********************************************************************************************/
/* SMART CONTRACT FUNCTIONS */
/********************************************************************************************/
function getRegisteredAirlineCount() public requireIsOperational view returns(uint256) {
return registeredAirlines;
}
function getRegisteredFlightCount() public requireIsOperational view returns(uint256) {
return registeredFlights.length;
}
function isAirlineRegistered (address airline) public view requireIsOperational returns(bool) {
return airlines[airline].isRegistered;
}
function isAirlineFunded (address airline) public view requireIsOperational returns(bool) {
return airlines[airline].isFunded;
}
function isFlightRegistered (bytes32 flight) public view requireIsOperational returns(bool) {
return flights[flight].isRegistered;
}
function hasFlightLanded (bytes32 flight) public view returns(bool) {
if (flights[flight].status > 0)
return true;
return false;
}
function getAirlineFunds(address airline) public view returns(uint256) {
return airlines[airline].funds;
}
/**
* @dev Add an airline to the registration queue
* Can only be called from FlightSuretyApp contract
*
*/
function registerAirline
(
address airline,
address originalAirline
)
external
requireIsOperational
onlyNonRegisteredAirline(airline)
onlyFundedAirline(originalAirline)
{
airlines[airline] = Airline(true, false, 0);
registeredAirlines++;
emit AirlineRegistered(airline);
}
function fundAirline
(
address airline,
uint256 amt
)
external
requireIsOperational
onlyRegisteredAirline(airline)
onlyNonFundedAirline(airline)
{
airlines[airline].isFunded = true;
airlines[airline].funds = airlines[airline].funds.add(amt);
emit AirlineFunded(airline);
}
function registerFlight
(
bytes32 flightKey,
address airline,
string calldata from,
string calldata to
)
external
requireIsOperational
onlyNonRegisteredFlight(flightKey)
{
// bytes32 flightKey = getFlightKey(airline, flight, landing);
flights[flightKey] = Flight(true, from, to, airline, 0);
registeredFlights.push(flightKey);
emit FlightRegistered(flightKey);
}
function processFlightStatus(address airline, string calldata flight, uint256 timestamp, uint status) external requireIsOperational {
bytes32 flightKey = getFlightKey(airline, flight, timestamp);
require(!hasFlightLanded(flightKey), "Flight has already landed");
if(flights[flightKey].status == 0) {
flights[flightKey].status = status;
}
if(flights[flightKey].status == 20) {
creditInsurees(flightKey);
}
emit ProcessedFlightStatus(flightKey, status);
}
/**
* @dev Buy insurance for a flight
*
*/
function buy
(
bytes32 flight,
address passenger,
uint256 amt,
uint payout
)
external
payable
requireIsOperational
{
require(isFlightRegistered(flight));
flightClaims[flight].push(Claim(passenger, amt, payout, false));
}
/**
* @dev Credits payouts to insurees
*/
function creditInsurees
(
bytes32 flight
)
internal
requireIsOperational
{
for (uint i=0; i <= flightClaims[flight].length; i++) {
flightClaims[flight][i].paidStatus = true;
uint256 creditAmt = flightClaims[flight][i].purchaseAmt.mul(flightClaims[flight][i].payout).div(100);
withdrawals[flightClaims[flight][i].passenger] = withdrawals[flightClaims[flight][i].passenger].add(creditAmt);
emit Credited(flight, flightClaims[flight][i].passenger, creditAmt);
}
}
/**
* @dev Transfers eligible payout funds to insuree
*
*/
function pay
(
address payable passenger
)
external
payable
{
uint256 amt = withdrawals[passenger];
withdrawals[passenger] = 0;
passenger.transfer(amt);
emit Paid(passenger, amt);
}
/**
* @dev Initial funding for the insurance. Unless there are too many delayed flights
* resulting in insurance payouts, the contract should be self-sustaining
*
*/
function fund
(
)
public
payable
{
}
function getFlightKey
(
address airline,
string memory flight,
uint256 timestamp
)
pure
internal
returns(bytes32)
{
return keccak256(abi.encodePacked(airline, flight, timestamp));
}
/**
* @dev Fallback function for funding smart contract.
*
*/
function()
external
payable
{
fund();
}
}
| * @dev Credits payouts to insurees/ | function creditInsurees
(
bytes32 flight
)
internal
requireIsOperational
{
for (uint i=0; i <= flightClaims[flight].length; i++) {
flightClaims[flight][i].paidStatus = true;
uint256 creditAmt = flightClaims[flight][i].purchaseAmt.mul(flightClaims[flight][i].payout).div(100);
withdrawals[flightClaims[flight][i].passenger] = withdrawals[flightClaims[flight][i].passenger].add(creditAmt);
emit Credited(flight, flightClaims[flight][i].passenger, creditAmt);
}
}
| 15,859,815 | [
1,
24201,
1282,
293,
2012,
87,
358,
316,
2055,
281,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
12896,
382,
2055,
281,
203,
27573,
261,
203,
4766,
565,
1731,
1578,
25187,
203,
27573,
262,
203,
27573,
2713,
203,
27573,
2583,
2520,
2988,
287,
203,
565,
288,
203,
3639,
364,
261,
11890,
277,
33,
20,
31,
277,
1648,
25187,
15925,
63,
19131,
8009,
2469,
31,
277,
27245,
288,
203,
5411,
25187,
15925,
63,
19131,
6362,
77,
8009,
29434,
1482,
273,
638,
31,
203,
5411,
2254,
5034,
12896,
31787,
273,
25187,
15925,
63,
19131,
6362,
77,
8009,
12688,
12104,
31787,
18,
16411,
12,
19131,
15925,
63,
19131,
6362,
77,
8009,
84,
2012,
2934,
2892,
12,
6625,
1769,
203,
5411,
598,
9446,
1031,
63,
19131,
15925,
63,
19131,
6362,
77,
8009,
5466,
14348,
65,
273,
598,
9446,
1031,
63,
19131,
15925,
63,
19131,
6362,
77,
8009,
5466,
14348,
8009,
1289,
12,
20688,
31787,
1769,
203,
203,
5411,
3626,
30354,
329,
12,
19131,
16,
25187,
15925,
63,
19131,
6362,
77,
8009,
5466,
14348,
16,
12896,
31787,
1769,
203,
3639,
289,
203,
565,
289,
203,
377,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/utils/EnumerableSet.sol";
import "@openzeppelin/contracts/utils/EnumerableMap.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/math/Math.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "./interfaces/tokens/erc20permit-upgradeable/IERC20PermitUpgradeable.sol";
import "./interfaces/IPolicyBookRegistry.sol";
import "./interfaces/IBMICoverStaking.sol";
import "./interfaces/IContractsRegistry.sol";
import "./interfaces/IRewardsGenerator.sol";
import "./interfaces/ILiquidityMining.sol";
import "./interfaces/IPolicyBook.sol";
import "./interfaces/IBMIStaking.sol";
import "./interfaces/ILiquidityRegistry.sol";
import "./interfaces/IShieldMining.sol";
import "./tokens/ERC1155Upgradeable.sol";
import "./abstract/AbstractDependant.sol";
import "./abstract/AbstractSlasher.sol";
import "./Globals.sol";
contract BMICoverStaking is
IBMICoverStaking,
OwnableUpgradeable,
ERC1155Upgradeable,
AbstractDependant,
AbstractSlasher
{
using EnumerableSet for EnumerableSet.UintSet;
using EnumerableMap for EnumerableMap.UintToAddressMap;
using SafeMath for uint256;
using Math for uint256;
IERC20 public bmiToken;
IPolicyBookRegistry public policyBookRegistry;
IRewardsGenerator public rewardsGenerator;
ILiquidityMining public liquidityMining;
IBMIStaking public bmiStaking;
ILiquidityRegistry public liquidityRegistry;
mapping(uint256 => StakingInfo) public override _stakersPool; // nft index -> info
uint256 internal _nftMintId; // next nft mint id
mapping(address => EnumerableSet.UintSet) internal _nftHolderTokens; // holder -> nfts
EnumerableMap.UintToAddressMap internal _nftTokenOwners; // index nft -> holder
// new state post v2
IShieldMining public shieldMining;
event StakingNFTMinted(uint256 id, address policyBookAddress, address to);
event StakingNFTBurned(uint256 id, address policyBookAddress);
event StakingBMIProfitWithdrawn(
uint256 id,
address policyBookAddress,
address to,
uint256 amount
);
event StakingFundsWithdrawn(uint256 id, address policyBookAddress, address to, uint256 amount);
event TokensRecovered(address to, uint256 amount);
modifier onlyPolicyBooks() {
require(policyBookRegistry.isPolicyBook(_msgSender()), "BDS: No access");
_;
}
function __BMICoverStaking_init() external initializer {
__Ownable_init();
__ERC1155_init("");
_nftMintId = 1;
}
function setDependencies(IContractsRegistry _contractsRegistry)
external
override
onlyInjectorOrZero
{
bmiToken = IERC20(_contractsRegistry.getBMIContract());
rewardsGenerator = IRewardsGenerator(_contractsRegistry.getRewardsGeneratorContract());
policyBookRegistry = IPolicyBookRegistry(
_contractsRegistry.getPolicyBookRegistryContract()
);
liquidityMining = ILiquidityMining(_contractsRegistry.getLiquidityMiningContract());
bmiStaking = IBMIStaking(_contractsRegistry.getBMIStakingContract());
liquidityRegistry = ILiquidityRegistry(_contractsRegistry.getLiquidityRegistryContract());
shieldMining = IShieldMining(_contractsRegistry.getShieldMiningContract());
}
/// @dev the output URI will be: "https://token-cdn-domain/<tokenId>"
function uri(uint256 tokenId)
public
view
override(ERC1155Upgradeable, IBMICoverStaking)
returns (string memory)
{
return string(abi.encodePacked(super.uri(0), Strings.toString(tokenId)));
}
/// @dev this is a correct URI: "https://token-cdn-domain/"
function setBaseURI(string calldata newURI) external onlyOwner {
_setURI(newURI);
}
function recoverTokens() external onlyOwner {
uint256 balance = bmiToken.balanceOf(address(this));
bmiToken.transfer(_msgSender(), balance);
emit TokensRecovered(_msgSender(), balance);
}
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal override {
for (uint256 i = 0; i < ids.length; i++) {
if (amounts[i] != 1) {
// not an NFT
continue;
}
if (from == address(0)) {
// mint happened
_nftHolderTokens[to].add(ids[i]);
_nftTokenOwners.set(ids[i], to);
} else if (to == address(0)) {
// burn happened
_nftHolderTokens[from].remove(ids[i]);
_nftTokenOwners.remove(ids[i]);
} else {
// transfer happened
_nftHolderTokens[from].remove(ids[i]);
_nftHolderTokens[to].add(ids[i]);
_nftTokenOwners.set(ids[i], to);
_updateLiquidityRegistry(to, from, _stakersPool[ids[i]].policyBookAddress);
}
}
}
function _updateLiquidityRegistry(
address to,
address from,
address policyBookAddress
) internal {
liquidityRegistry.tryToAddPolicyBook(to, policyBookAddress);
liquidityRegistry.tryToRemovePolicyBook(from, policyBookAddress);
}
function _mintStake(address staker, uint256 id) internal {
_mint(staker, id, 1, ""); // mint NFT
}
function _burnStake(address staker, uint256 id) internal {
_burn(staker, id, 1); // burn NFT
}
function _mintAggregatedNFT(
address staker,
address policyBookAddress,
uint256[] memory tokenIds
) internal {
require(policyBookRegistry.isPolicyBook(policyBookAddress), "BDS: Not a PB");
uint256 totalBMIXAmount;
for (uint256 i = 0; i < tokenIds.length; i++) {
require(ownerOf(tokenIds[i]) == _msgSender(), "BDS: Not a token owner");
require(
_stakersPool[tokenIds[i]].policyBookAddress == policyBookAddress,
"BDS: NFTs from distinct origins"
);
totalBMIXAmount = totalBMIXAmount.add(_stakersPool[tokenIds[i]].stakedBMIXAmount);
_burnStake(staker, tokenIds[i]);
emit StakingNFTBurned(tokenIds[i], policyBookAddress);
/// @dev should be enough
delete _stakersPool[tokenIds[i]].policyBookAddress;
}
_mintStake(staker, _nftMintId);
_stakersPool[_nftMintId] = StakingInfo(policyBookAddress, totalBMIXAmount);
emit StakingNFTMinted(_nftMintId, policyBookAddress, staker);
_nftMintId++;
}
function _mintNewNFT(
address staker,
uint256 bmiXAmount,
address policyBookAddress
) internal {
_mintStake(staker, _nftMintId);
_stakersPool[_nftMintId] = StakingInfo(policyBookAddress, bmiXAmount);
emit StakingNFTMinted(_nftMintId, policyBookAddress, staker);
_nftMintId++;
}
function aggregateNFTs(address policyBookAddress, uint256[] calldata tokenIds)
external
override
{
require(tokenIds.length > 1, "BDS: Can't aggregate");
_mintAggregatedNFT(_msgSender(), policyBookAddress, tokenIds);
rewardsGenerator.aggregate(policyBookAddress, tokenIds, _nftMintId - 1); // nftMintId is changed, so -1
}
function stakeBMIX(uint256 bmiXAmount, address policyBookAddress) external override {
_stakeBMIX(_msgSender(), bmiXAmount, policyBookAddress);
}
function stakeBMIXWithPermit(
uint256 bmiXAmount,
address policyBookAddress,
uint8 v,
bytes32 r,
bytes32 s
) external override {
_stakeBMIXWithPermit(_msgSender(), bmiXAmount, policyBookAddress, v, r, s);
}
function stakeBMIXFrom(address user, uint256 bmiXAmount) external override onlyPolicyBooks {
_stakeBMIX(user, bmiXAmount, _msgSender());
}
function stakeBMIXFromWithPermit(
address user,
uint256 bmiXAmount,
uint8 v,
bytes32 r,
bytes32 s
) external override onlyPolicyBooks {
_stakeBMIXWithPermit(user, bmiXAmount, _msgSender(), v, r, s);
}
function _stakeBMIXWithPermit(
address staker,
uint256 bmiXAmount,
address policyBookAddress,
uint8 v,
bytes32 r,
bytes32 s
) internal {
IERC20PermitUpgradeable(policyBookAddress).permit(
staker,
address(this),
bmiXAmount,
MAX_INT,
v,
r,
s
);
_stakeBMIX(staker, bmiXAmount, policyBookAddress);
}
function _stakeBMIX(
address user,
uint256 bmiXAmount,
address policyBookAddress
) internal {
require(policyBookRegistry.isPolicyBook(policyBookAddress), "BDS: Not a PB");
require(IPolicyBook(policyBookAddress).whitelisted(), "BDS: PB is not whitelisted");
require(bmiXAmount > 0, "BDS: Zero tokens");
uint256 stblAmount = IPolicyBook(policyBookAddress).convertBMIXToSTBL(bmiXAmount);
IERC20(policyBookAddress).transferFrom(user, address(this), bmiXAmount);
_mintNewNFT(user, bmiXAmount, policyBookAddress);
rewardsGenerator.stake(policyBookAddress, _nftMintId - 1, stblAmount); // nftMintId is changed, so -1
}
function _transferProfit(uint256 tokenId, bool onlyProfit) internal {
address policyBookAddress = _stakersPool[tokenId].policyBookAddress;
uint256 totalProfit;
if (onlyProfit) {
totalProfit = rewardsGenerator.withdrawReward(policyBookAddress, tokenId);
} else {
totalProfit = rewardsGenerator.withdrawFunds(policyBookAddress, tokenId);
}
uint256 bmiStakingProfit =
_getSlashed(totalProfit, liquidityMining.startLiquidityMiningTime());
uint256 profit = totalProfit.sub(bmiStakingProfit);
// transfer slashed bmi to the bmiStaking and add them to the pool
bmiToken.transfer(address(bmiStaking), bmiStakingProfit);
bmiStaking.addToPool(bmiStakingProfit);
// transfer bmi profit to the user
bmiToken.transfer(_msgSender(), profit);
emit StakingBMIProfitWithdrawn(tokenId, policyBookAddress, _msgSender(), profit);
}
/// @param staker address of the staker account
/// @param policyBookAddress addres of the policbook
/// @param offset pagination start up place
/// @param limit size of the listing page
/// @param func callback function that returns a uint256
/// @return total
function _aggregateForEach(
address staker,
address policyBookAddress,
uint256 offset,
uint256 limit,
function(uint256) view returns (uint256) func
) internal view returns (uint256 total) {
bool nullAddr = policyBookAddress == address(0);
require(nullAddr || policyBookRegistry.isPolicyBook(policyBookAddress), "BDS: Not a PB");
uint256 to = (offset.add(limit)).min(balanceOf(staker)).max(offset);
for (uint256 i = offset; i < to; i++) {
uint256 nftIndex = tokenOfOwnerByIndex(staker, i);
if (nullAddr || _stakersPool[nftIndex].policyBookAddress == policyBookAddress) {
total = total.add(func(nftIndex));
}
}
}
function _transferForEach(address policyBookAddress, function(uint256) func) internal {
require(policyBookRegistry.isPolicyBook(policyBookAddress), "BDS: Not a PB");
uint256 stakerBalance = balanceOf(_msgSender());
for (int256 i = int256(stakerBalance) - 1; i >= 0; i--) {
uint256 nftIndex = tokenOfOwnerByIndex(_msgSender(), uint256(i));
if (_stakersPool[nftIndex].policyBookAddress == policyBookAddress) {
func(nftIndex);
}
}
}
function restakeBMIProfit(uint256 tokenId) public override {
require(_stakersPool[tokenId].policyBookAddress != address(0), "BDS: Token doesn't exist");
require(ownerOf(tokenId) == _msgSender(), "BDS: Not a token owner");
uint256 totalProfit =
rewardsGenerator.withdrawReward(_stakersPool[tokenId].policyBookAddress, tokenId);
bmiToken.transfer(address(bmiStaking), totalProfit);
bmiStaking.stakeFor(_msgSender(), totalProfit);
}
function restakeStakerBMIProfit(address policyBookAddress) external override {
_transferForEach(policyBookAddress, restakeBMIProfit);
}
function withdrawBMIProfit(uint256 tokenId) public override {
require(_stakersPool[tokenId].policyBookAddress != address(0), "BDS: Token doesn't exist");
require(ownerOf(tokenId) == _msgSender(), "BDS: Not a token owner");
_transferProfit(tokenId, true);
}
function withdrawStakerBMIProfit(address policyBookAddress) external override {
_transferForEach(policyBookAddress, withdrawBMIProfit);
if (policyBookRegistry.isUserLeveragePool(policyBookAddress)) {
shieldMining.getRewardFor(_msgSender(), policyBookAddress);
} else {
shieldMining.getRewardFor(_msgSender(), policyBookAddress, address(0));
}
}
function withdrawFundsWithProfit(uint256 tokenId) public override {
address policyBookAddress = _stakersPool[tokenId].policyBookAddress;
require(policyBookAddress != address(0), "BDS: Token doesn't exist");
require(ownerOf(tokenId) == _msgSender(), "BDS: Not a token owner");
_transferProfit(tokenId, false);
uint256 stakedFunds = _stakersPool[tokenId].stakedBMIXAmount;
// transfer bmiX from staking to the user
IERC20(policyBookAddress).transfer(_msgSender(), stakedFunds);
emit StakingFundsWithdrawn(tokenId, policyBookAddress, _msgSender(), stakedFunds);
_burnStake(_msgSender(), tokenId);
emit StakingNFTBurned(tokenId, policyBookAddress);
delete _stakersPool[tokenId];
}
function withdrawStakerFundsWithProfit(address policyBookAddress) external override {
_transferForEach(policyBookAddress, withdrawFundsWithProfit);
}
/// @dev returns percentage multiplied by 10**25
function getSlashingPercentage() external view override returns (uint256) {
return getSlashingPercentage(liquidityMining.startLiquidityMiningTime());
}
function getSlashedBMIProfit(uint256 tokenId) public view override returns (uint256) {
return _applySlashing(getBMIProfit(tokenId), liquidityMining.startLiquidityMiningTime());
}
/// @notice retrieves the BMI profit of a tokenId
/// @param tokenId numeric id identifier of the token
/// @return profit amount
function getBMIProfit(uint256 tokenId) public view override returns (uint256) {
return rewardsGenerator.getReward(_stakersPool[tokenId].policyBookAddress, tokenId);
}
function getSlashedStakerBMIProfit(
address staker,
address policyBookAddress,
uint256 offset,
uint256 limit
) external view override returns (uint256 totalProfit) {
uint256 stakerBMIProfit = getStakerBMIProfit(staker, policyBookAddress, offset, limit);
return _applySlashing(stakerBMIProfit, liquidityMining.startLiquidityMiningTime());
}
function getStakerBMIProfit(
address staker,
address policyBookAddress,
uint256 offset,
uint256 limit
) public view override returns (uint256) {
return _aggregateForEach(staker, policyBookAddress, offset, limit, getBMIProfit);
}
function totalStaked(address user) external view override returns (uint256) {
return _aggregateForEach(user, address(0), 0, MAX_INT, stakedByNFT);
}
function totalStakedSTBL(address user) external view override returns (uint256) {
return _aggregateForEach(user, address(0), 0, MAX_INT, stakedSTBLByNFT);
}
function stakedByNFT(uint256 tokenId) public view override returns (uint256) {
return _stakersPool[tokenId].stakedBMIXAmount;
}
function stakedSTBLByNFT(uint256 tokenId) public view override returns (uint256) {
return rewardsGenerator.getStakedNFTSTBL(tokenId);
}
/// @notice returns number of NFTs on user's account
function balanceOf(address user) public view override returns (uint256) {
return _nftHolderTokens[user].length();
}
function ownerOf(uint256 tokenId) public view override returns (address) {
return _nftTokenOwners.get(tokenId);
}
function tokenOfOwnerByIndex(address user, uint256 index)
public
view
override
returns (uint256)
{
return _nftHolderTokens[user].at(index);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
uint256 constant SECONDS_IN_THE_YEAR = 365 * 24 * 60 * 60; // 365 days * 24 hours * 60 minutes * 60 seconds
uint256 constant DAYS_IN_THE_YEAR = 365;
uint256 constant MAX_INT = type(uint256).max;
uint256 constant DECIMALS18 = 10**18;
uint256 constant PRECISION = 10**25;
uint256 constant PERCENTAGE_100 = 100 * PRECISION;
uint256 constant BLOCKS_PER_DAY = 6450;
uint256 constant BLOCKS_PER_YEAR = BLOCKS_PER_DAY * 365;
uint256 constant APY_TOKENS = DECIMALS18;
uint256 constant PROTOCOL_PERCENTAGE = 20 * PRECISION;
uint256 constant DEFAULT_REBALANCING_THRESHOLD = 10**23;
uint256 constant REBALANCE_DURATION = 1 days;
uint256 constant EPOCH_DAYS_AMOUNT = 7;
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
import "../interfaces/IContractsRegistry.sol";
abstract contract AbstractDependant {
/// @dev keccak256(AbstractDependant.setInjector(address)) - 1
bytes32 private constant _INJECTOR_SLOT =
0xd6b8f2e074594ceb05d47c27386969754b6ad0c15e5eb8f691399cd0be980e76;
modifier onlyInjectorOrZero() {
address _injector = injector();
require(_injector == address(0) || _injector == msg.sender, "Dependant: Not an injector");
_;
}
function setInjector(address _injector) external onlyInjectorOrZero {
bytes32 slot = _INJECTOR_SLOT;
assembly {
sstore(slot, _injector)
}
}
/// @dev has to apply onlyInjectorOrZero() modifier
function setDependencies(IContractsRegistry) external virtual;
function injector() public view returns (address _injector) {
bytes32 slot = _INJECTOR_SLOT;
assembly {
_injector := sload(slot)
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/math/Math.sol";
import "../Globals.sol";
abstract contract AbstractSlasher {
using SafeMath for uint256;
using Math for uint256;
uint256 public constant MAX_EXIT_FEE = 90 * PRECISION;
uint256 public constant MIN_EXIT_FEE = 20 * PRECISION;
uint256 public constant EXIT_FEE_DURATION = 100 days;
function getSlashingPercentage(uint256 startTime) public view returns (uint256) {
startTime = startTime == 0 || startTime > block.timestamp ? block.timestamp : startTime;
uint256 feeSpan = MAX_EXIT_FEE.sub(MIN_EXIT_FEE);
uint256 feePerSecond = feeSpan.div(EXIT_FEE_DURATION);
uint256 fee = Math.min(block.timestamp.sub(startTime).mul(feePerSecond), feeSpan);
return MAX_EXIT_FEE.sub(fee);
}
function getSlashingPercentage() external view virtual returns (uint256);
function _applySlashing(uint256 amount, uint256 startTime) internal view returns (uint256) {
return amount.sub(_getSlashed(amount, startTime));
}
function _getSlashed(uint256 amount, uint256 startTime) internal view returns (uint256) {
return amount.mul(getSlashingPercentage(startTime)).div(PERCENTAGE_100);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
interface IBMICoverStaking {
struct StakingInfo {
address policyBookAddress;
uint256 stakedBMIXAmount;
}
struct PolicyBookInfo {
uint256 totalStakedSTBL;
uint256 rewardPerBlock;
uint256 stakingAPY;
uint256 liquidityAPY;
}
struct UserInfo {
uint256 totalStakedBMIX;
uint256 totalStakedSTBL;
uint256 totalBmiReward;
}
struct NFTsInfo {
uint256 nftIndex;
string uri;
uint256 stakedBMIXAmount;
uint256 stakedSTBLAmount;
uint256 reward;
}
function aggregateNFTs(address policyBookAddress, uint256[] calldata tokenIds) external;
function stakeBMIX(uint256 amount, address policyBookAddress) external;
function stakeBMIXWithPermit(
uint256 bmiXAmount,
address policyBookAddress,
uint8 v,
bytes32 r,
bytes32 s
) external;
function stakeBMIXFrom(address user, uint256 amount) external;
function stakeBMIXFromWithPermit(
address user,
uint256 bmiXAmount,
uint8 v,
bytes32 r,
bytes32 s
) external;
// mappings
function _stakersPool(uint256 index)
external
view
returns (address policyBookAddress, uint256 stakedBMIXAmount);
// function getPolicyBookAPY(address policyBookAddress) external view returns (uint256);
function restakeBMIProfit(uint256 tokenId) external;
function restakeStakerBMIProfit(address policyBookAddress) external;
function withdrawBMIProfit(uint256 tokenID) external;
function withdrawStakerBMIProfit(address policyBookAddress) external;
function withdrawFundsWithProfit(uint256 tokenID) external;
function withdrawStakerFundsWithProfit(address policyBookAddress) external;
function getSlashedBMIProfit(uint256 tokenId) external view returns (uint256);
function getBMIProfit(uint256 tokenId) external view returns (uint256);
function getSlashedStakerBMIProfit(
address staker,
address policyBookAddress,
uint256 offset,
uint256 limit
) external view returns (uint256 totalProfit);
function getStakerBMIProfit(
address staker,
address policyBookAddress,
uint256 offset,
uint256 limit
) external view returns (uint256 totalProfit);
function totalStaked(address user) external view returns (uint256);
function totalStakedSTBL(address user) external view returns (uint256);
function stakedByNFT(uint256 tokenId) external view returns (uint256);
function stakedSTBLByNFT(uint256 tokenId) external view returns (uint256);
function balanceOf(address user) external view returns (uint256);
function ownerOf(uint256 tokenId) external view returns (address);
function uri(uint256 tokenId) external view returns (string memory);
function tokenOfOwnerByIndex(address user, uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
import "./tokens/ISTKBMIToken.sol";
interface IBMIStaking {
event StakedBMI(uint256 stakedBMI, uint256 mintedStkBMI, address indexed recipient);
event BMIWithdrawn(uint256 amountBMI, uint256 burnedStkBMI, address indexed recipient);
event UnusedRewardPoolRevoked(address recipient, uint256 amount);
event RewardPoolRevoked(address recipient, uint256 amount);
struct WithdrawalInfo {
uint256 coolDownTimeEnd;
uint256 amountBMIRequested;
}
function stakeWithPermit(
uint256 _amountBMI,
uint8 _v,
bytes32 _r,
bytes32 _s
) external;
function stakeFor(address _user, uint256 _amountBMI) external;
function stake(uint256 _amountBMI) external;
function maturityAt() external view returns (uint256);
function isBMIRewardUnlocked() external view returns (bool);
function whenCanWithdrawBMIReward(address _address) external view returns (uint256);
function unlockTokensToWithdraw(uint256 _amountBMIUnlock) external;
function withdraw() external;
/// @notice Getting withdraw information
/// @return _amountBMIRequested is amount of bmi tokens requested to unlock
/// @return _amountStkBMI is amount of stkBMI that will burn
/// @return _unlockPeriod is its timestamp when user can withdraw
/// returns 0 if it didn't unlocked yet. User has 48hs to withdraw
/// @return _availableFor is the end date if withdraw period has already begun
/// or 0 if it is expired or didn't start
function getWithdrawalInfo(address _userAddr)
external
view
returns (
uint256 _amountBMIRequested,
uint256 _amountStkBMI,
uint256 _unlockPeriod,
uint256 _availableFor
);
function addToPool(uint256 _amount) external;
function stakingReward(uint256 _amount) external view returns (uint256);
function getStakedBMI(address _address) external view returns (uint256);
function getAPY() external view returns (uint256);
function setRewardPerBlock(uint256 _amount) external;
function revokeRewardPool(uint256 _amount) external;
function revokeUnusedRewardPool() external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
import "./IPolicyBookFabric.sol";
interface IClaimingRegistry {
enum ClaimStatus {
CAN_CLAIM,
UNCLAIMABLE,
PENDING,
AWAITING_CALCULATION,
REJECTED_CAN_APPEAL,
REJECTED,
ACCEPTED
}
struct ClaimInfo {
address claimer;
address policyBookAddress;
string evidenceURI;
uint256 dateSubmitted;
uint256 dateEnded;
bool appeal;
ClaimStatus status;
uint256 claimAmount;
}
/// @notice returns anonymous voting duration
function anonymousVotingDuration(uint256 index) external view returns (uint256);
/// @notice returns the whole voting duration
function votingDuration(uint256 index) external view returns (uint256);
/// @notice returns how many time should pass before anyone could calculate a claim result
function anyoneCanCalculateClaimResultAfter(uint256 index) external view returns (uint256);
/// @notice returns true if a user can buy new policy of specified PolicyBook
function canBuyNewPolicy(address buyer, address policyBookAddress)
external
view
returns (bool);
/// @notice submits new PolicyBook claim for the user
function submitClaim(
address user,
address policyBookAddress,
string calldata evidenceURI,
uint256 cover,
bool appeal
) external returns (uint256);
/// @notice returns true if the claim with this index exists
function claimExists(uint256 index) external view returns (bool);
/// @notice returns claim submition time
function claimSubmittedTime(uint256 index) external view returns (uint256);
/// @notice returns claim end time or zero in case it is pending
function claimEndTime(uint256 index) external view returns (uint256);
/// @notice returns true if the claim is anonymously votable
function isClaimAnonymouslyVotable(uint256 index) external view returns (bool);
/// @notice returns true if the claim is exposably votable
function isClaimExposablyVotable(uint256 index) external view returns (bool);
/// @notice returns true if claim is anonymously votable or exposably votable
function isClaimVotable(uint256 index) external view returns (bool);
/// @notice returns true if a claim can be calculated by anyone
function canClaimBeCalculatedByAnyone(uint256 index) external view returns (bool);
/// @notice returns true if this claim is pending or awaiting
function isClaimPending(uint256 index) external view returns (bool);
/// @notice returns how many claims the holder has
function countPolicyClaimerClaims(address user) external view returns (uint256);
/// @notice returns how many pending claims are there
function countPendingClaims() external view returns (uint256);
/// @notice returns how many claims are there
function countClaims() external view returns (uint256);
/// @notice returns a claim index of it's claimer and an ordinal number
function claimOfOwnerIndexAt(address claimer, uint256 orderIndex)
external
view
returns (uint256);
/// @notice returns pending claim index by its ordinal index
function pendingClaimIndexAt(uint256 orderIndex) external view returns (uint256);
/// @notice returns claim index by its ordinal index
function claimIndexAt(uint256 orderIndex) external view returns (uint256);
/// @notice returns current active claim index by policybook and claimer
function claimIndex(address claimer, address policyBookAddress)
external
view
returns (uint256);
/// @notice returns true if the claim is appealed
function isClaimAppeal(uint256 index) external view returns (bool);
/// @notice returns current status of a claim
function policyStatus(address claimer, address policyBookAddress)
external
view
returns (ClaimStatus);
/// @notice returns current status of a claim
function claimStatus(uint256 index) external view returns (ClaimStatus);
/// @notice returns the claim owner (claimer)
function claimOwner(uint256 index) external view returns (address);
/// @notice returns the claim PolicyBook
function claimPolicyBook(uint256 index) external view returns (address);
/// @notice returns claim info by its index
function claimInfo(uint256 index) external view returns (ClaimInfo memory _claimInfo);
function getAllPendingClaimsAmount() external view returns (uint256 _totalClaimsAmount);
function getClaimableAmounts(uint256[] memory _claimIndexes) external view returns (uint256);
/// @notice marks the user's claim as Accepted
function acceptClaim(uint256 index) external;
/// @notice marks the user's claim as Rejected
function rejectClaim(uint256 index) external;
/// @notice Update Image Uri in case it contains material that is ilegal
/// or offensive.
/// @dev Only the owner of the PolicyBookAdmin can erase/update evidenceUri.
/// @param _claimIndex Claim Index that is going to be updated
/// @param _newEvidenceURI New evidence uri. It can be blank.
function updateImageUriOfClaim(uint256 _claimIndex, string calldata _newEvidenceURI) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
interface IContractsRegistry {
function getUniswapRouterContract() external view returns (address);
function getUniswapBMIToETHPairContract() external view returns (address);
function getUniswapBMIToUSDTPairContract() external view returns (address);
function getSushiswapRouterContract() external view returns (address);
function getSushiswapBMIToETHPairContract() external view returns (address);
function getSushiswapBMIToUSDTPairContract() external view returns (address);
function getSushiSwapMasterChefV2Contract() external view returns (address);
function getWETHContract() external view returns (address);
function getUSDTContract() external view returns (address);
function getBMIContract() external view returns (address);
function getPriceFeedContract() external view returns (address);
function getPolicyBookRegistryContract() external view returns (address);
function getPolicyBookFabricContract() external view returns (address);
function getBMICoverStakingContract() external view returns (address);
function getBMICoverStakingViewContract() external view returns (address);
function getLegacyRewardsGeneratorContract() external view returns (address);
function getRewardsGeneratorContract() external view returns (address);
function getBMIUtilityNFTContract() external view returns (address);
function getNFTStakingContract() external view returns (address);
function getLiquidityMiningContract() external view returns (address);
function getClaimingRegistryContract() external view returns (address);
function getPolicyRegistryContract() external view returns (address);
function getLiquidityRegistryContract() external view returns (address);
function getClaimVotingContract() external view returns (address);
function getReinsurancePoolContract() external view returns (address);
function getLeveragePortfolioViewContract() external view returns (address);
function getCapitalPoolContract() external view returns (address);
function getPolicyBookAdminContract() external view returns (address);
function getPolicyQuoteContract() external view returns (address);
function getLegacyBMIStakingContract() external view returns (address);
function getBMIStakingContract() external view returns (address);
function getSTKBMIContract() external view returns (address);
function getVBMIContract() external view returns (address);
function getLegacyLiquidityMiningStakingContract() external view returns (address);
function getLiquidityMiningStakingETHContract() external view returns (address);
function getLiquidityMiningStakingUSDTContract() external view returns (address);
function getReputationSystemContract() external view returns (address);
function getAaveProtocolContract() external view returns (address);
function getAaveLendPoolAddressProvdierContract() external view returns (address);
function getAaveATokenContract() external view returns (address);
function getCompoundProtocolContract() external view returns (address);
function getCompoundCTokenContract() external view returns (address);
function getCompoundComptrollerContract() external view returns (address);
function getYearnProtocolContract() external view returns (address);
function getYearnVaultContract() external view returns (address);
function getYieldGeneratorContract() external view returns (address);
function getShieldMiningContract() external view returns (address);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
interface ILeveragePortfolio {
enum LeveragePortfolio {USERLEVERAGEPOOL, REINSURANCEPOOL}
struct LevFundsFactors {
uint256 netMPL;
uint256 netMPLn;
address policyBookAddr;
// uint256 poolTotalLiquidity;
// uint256 poolUR;
// uint256 minUR;
}
function targetUR() external view returns (uint256);
function d_ProtocolConstant() external view returns (uint256);
function a_ProtocolConstant() external view returns (uint256);
function max_ProtocolConstant() external view returns (uint256);
/// @notice deploy lStable from user leverage pool or reinsurance pool using 2 formulas: access by policybook.
/// @param leveragePoolType LeveragePortfolio is determine the pool which call the function
function deployLeverageStableToCoveragePools(LeveragePortfolio leveragePoolType)
external
returns (uint256);
/// @notice deploy the vStable from RP in v2 and for next versions it will be from RP and LP : access by policybook.
function deployVirtualStableToCoveragePools() external returns (uint256);
/// @notice set the threshold % for re-evaluation of the lStable provided across all Coverage pools : access by owner
/// @param threshold uint256 is the reevaluatation threshold
function setRebalancingThreshold(uint256 threshold) external;
/// @notice set the protocol constant : access by owner
/// @param _targetUR uint256 target utitlization ration
/// @param _d_ProtocolConstant uint256 D protocol constant
/// @param _a_ProtocolConstant uint256 A protocol constant
/// @param _max_ProtocolConstant uint256 the max % included
function setProtocolConstant(
uint256 _targetUR,
uint256 _d_ProtocolConstant,
uint256 _a_ProtocolConstant,
uint256 _max_ProtocolConstant
) external;
/// @notice calc M factor by formual M = min( abs((1/ (Tur-UR))*d) /a, max)
/// @param poolUR uint256 utitilization ratio for a coverage pool
/// @return uint256 M facotr
//function calcM(uint256 poolUR) external returns (uint256);
/// @return uint256 the amount of vStable stored in the pool
function totalLiquidity() external view returns (uint256);
/// @notice add the portion of 80% of premium to user leverage pool where the leverage provide lstable : access policybook
/// add the 20% of premium + portion of 80% of premium where reisnurance pool participate in coverage pools (vStable) : access policybook
/// @param epochsNumber uint256 the number of epochs which the policy holder will pay a premium for
/// @param premiumAmount uint256 the premium amount which is a portion of 80% of the premium
function addPolicyPremium(uint256 epochsNumber, uint256 premiumAmount) external;
/// @notice Used to get a list of coverage pools which get leveraged , use with count()
/// @return _coveragePools a list containing policybook addresses
function listleveragedCoveragePools(uint256 offset, uint256 limit)
external
view
returns (address[] memory _coveragePools);
/// @notice get count of coverage pools which get leveraged
function countleveragedCoveragePools() external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
interface ILiquidityMining {
struct TeamDetails {
string teamName;
address referralLink;
uint256 membersNumber;
uint256 totalStakedAmount;
uint256 totalReward;
}
struct UserInfo {
address userAddr;
string teamName;
uint256 stakedAmount;
uint256 mainNFT; // 0 or NFT index if available
uint256 platinumNFT; // 0 or NFT index if available
}
struct UserRewardsInfo {
string teamName;
uint256 totalBMIReward; // total BMI reward
uint256 availableBMIReward; // current claimable BMI reward
uint256 incomingPeriods; // how many month are incoming
uint256 timeToNextDistribution; // exact time left to next distribution
uint256 claimedBMI; // actual number of claimed BMI
uint256 mainNFTAvailability; // 0 or NFT index if available
uint256 platinumNFTAvailability; // 0 or NFT index if available
bool claimedNFTs; // true if user claimed NFTs
}
struct MyTeamInfo {
TeamDetails teamDetails;
uint256 myStakedAmount;
uint256 teamPlace;
}
struct UserTeamInfo {
address teamAddr;
uint256 stakedAmount;
uint256 countOfRewardedMonth;
bool isNFTDistributed;
}
struct TeamInfo {
string name;
uint256 totalAmount;
address[] teamLeaders;
}
function startLiquidityMiningTime() external view returns (uint256);
function getTopTeams() external view returns (TeamDetails[] memory teams);
function getTopUsers() external view returns (UserInfo[] memory users);
function getAllTeamsLength() external view returns (uint256);
function getAllTeamsDetails(uint256 _offset, uint256 _limit)
external
view
returns (TeamDetails[] memory _teamDetailsArr);
function getMyTeamsLength() external view returns (uint256);
function getMyTeamMembers(uint256 _offset, uint256 _limit)
external
view
returns (address[] memory _teamMembers, uint256[] memory _memberStakedAmount);
function getAllUsersLength() external view returns (uint256);
function getAllUsersInfo(uint256 _offset, uint256 _limit)
external
view
returns (UserInfo[] memory _userInfos);
function getMyTeamInfo() external view returns (MyTeamInfo memory _myTeamInfo);
function getRewardsInfo(address user)
external
view
returns (UserRewardsInfo memory userRewardInfo);
function createTeam(string calldata _teamName) external;
function deleteTeam() external;
function joinTheTeam(address _referralLink) external;
function getSlashingPercentage() external view returns (uint256);
function investSTBL(uint256 _tokensAmount, address _policyBookAddr) external;
function distributeNFT() external;
function checkPlatinumNFTReward(address _userAddr) external view returns (uint256);
function checkMainNFTReward(address _userAddr) external view returns (uint256);
function distributeBMIReward() external;
function getTotalUserBMIReward(address _userAddr) external view returns (uint256);
function checkAvailableBMIReward(address _userAddr) external view returns (uint256);
/// @notice checks if liquidity mining event is lasting (startLiquidityMining() has been called)
/// @return true if LM is started and not ended, false otherwise
function isLMLasting() external view returns (bool);
/// @notice checks if liquidity mining event is finished. In order to be finished, it has to be started
/// @return true if LM is finished, false if event is still going or not started
function isLMEnded() external view returns (bool);
function getEndLMTime() external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
interface ILiquidityRegistry {
struct LiquidityInfo {
address policyBookAddr;
uint256 lockedAmount;
uint256 availableAmount;
uint256 bmiXRatio; // multiply availableAmount by this num to get stable coin
}
struct WithdrawalRequestInfo {
address policyBookAddr;
uint256 requestAmount;
uint256 requestSTBLAmount;
uint256 availableLiquidity;
uint256 readyToWithdrawDate;
uint256 endWithdrawDate;
}
struct WithdrawalSetInfo {
address policyBookAddr;
uint256 requestAmount;
uint256 requestSTBLAmount;
uint256 availableSTBLAmount;
}
function tryToAddPolicyBook(address _userAddr, address _policyBookAddr) external;
function tryToRemovePolicyBook(address _userAddr, address _policyBookAddr) external;
function getPolicyBooksArrLength(address _userAddr) external view returns (uint256);
function getPolicyBooksArr(address _userAddr)
external
view
returns (address[] memory _resultArr);
function getLiquidityInfos(
address _userAddr,
uint256 _offset,
uint256 _limit
) external view returns (LiquidityInfo[] memory _resultArr);
function getWithdrawalRequests(
address _userAddr,
uint256 _offset,
uint256 _limit
) external view returns (uint256 _arrLength, WithdrawalRequestInfo[] memory _resultArr);
function getWithdrawalSet(
address _userAddr,
uint256 _offset,
uint256 _limit
) external view returns (uint256 _arrLength, WithdrawalSetInfo[] memory _resultArr);
function registerWithdrawl(address _policyBook, address _users) external;
function getAllPendingWithdrawalRequestsAmount()
external
returns (uint256 _totalWithdrawlAmount);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
import "./IPolicyBookFabric.sol";
import "./IClaimingRegistry.sol";
import "./IPolicyBookFacade.sol";
interface IPolicyBook {
enum WithdrawalStatus {NONE, PENDING, READY, EXPIRED}
struct PolicyHolder {
uint256 coverTokens;
uint256 startEpochNumber;
uint256 endEpochNumber;
uint256 paid;
uint256 reinsurancePrice;
}
struct WithdrawalInfo {
uint256 withdrawalAmount;
uint256 readyToWithdrawDate;
bool withdrawalAllowed;
}
struct BuyPolicyParameters {
address buyer;
address holder;
uint256 epochsNumber;
uint256 coverTokens;
uint256 distributorFee;
address distributor;
}
function policyHolders(address _holder)
external
view
returns (
uint256,
uint256,
uint256,
uint256,
uint256
);
function policyBookFacade() external view returns (IPolicyBookFacade);
function setPolicyBookFacade(address _policyBookFacade) external;
function EPOCH_DURATION() external view returns (uint256);
function stblDecimals() external view returns (uint256);
function READY_TO_WITHDRAW_PERIOD() external view returns (uint256);
function whitelisted() external view returns (bool);
function epochStartTime() external view returns (uint256);
// @TODO: should we let DAO to change contract address?
/// @notice Returns address of contract this PolicyBook covers, access: ANY
/// @return _contract is address of covered contract
function insuranceContractAddress() external view returns (address _contract);
/// @notice Returns type of contract this PolicyBook covers, access: ANY
/// @return _type is type of contract
function contractType() external view returns (IPolicyBookFabric.ContractType _type);
function totalLiquidity() external view returns (uint256);
function totalCoverTokens() external view returns (uint256);
// /// @notice return MPL for user leverage pool
// function userleveragedMPL() external view returns (uint256);
// /// @notice return MPL for reinsurance pool
// function reinsurancePoolMPL() external view returns (uint256);
// function bmiRewardMultiplier() external view returns (uint256);
function withdrawalsInfo(address _userAddr)
external
view
returns (
uint256 _withdrawalAmount,
uint256 _readyToWithdrawDate,
bool _withdrawalAllowed
);
function __PolicyBook_init(
address _insuranceContract,
IPolicyBookFabric.ContractType _contractType,
string calldata _description,
string calldata _projectSymbol
) external;
function whitelist(bool _whitelisted) external;
function getEpoch(uint256 time) external view returns (uint256);
/// @notice get STBL equivalent
function convertBMIXToSTBL(uint256 _amount) external view returns (uint256);
/// @notice get BMIX equivalent
function convertSTBLToBMIX(uint256 _amount) external view returns (uint256);
/// @notice submits new claim of the policy book
function submitClaimAndInitializeVoting(string calldata evidenceURI) external;
/// @notice submits new appeal claim of the policy book
function submitAppealAndInitializeVoting(string calldata evidenceURI) external;
/// @notice updates info on claim acceptance
function commitClaim(
address claimer,
uint256 claimAmount,
uint256 claimEndTime,
IClaimingRegistry.ClaimStatus status
) external;
/// @notice forces an update of RewardsGenerator multiplier
function forceUpdateBMICoverStakingRewardMultiplier() external;
/// @notice function to get precise current cover and liquidity
function getNewCoverAndLiquidity()
external
view
returns (uint256 newTotalCoverTokens, uint256 newTotalLiquidity);
/// @notice view function to get precise policy price
/// @param _epochsNumber is number of epochs to cover
/// @param _coverTokens is number of tokens to cover
/// @param _buyer address of the user who buy the policy
/// @return totalSeconds is number of seconds to cover
/// @return totalPrice is the policy price which will pay by the buyer
function getPolicyPrice(
uint256 _epochsNumber,
uint256 _coverTokens,
address _buyer
)
external
view
returns (
uint256 totalSeconds,
uint256 totalPrice,
uint256 pricePercentage
);
/// @notice Let user to buy policy by supplying stable coin, access: ANY
/// @param _buyer who is transferring funds
/// @param _holder who owns coverage
/// @param _epochsNumber period policy will cover
/// @param _coverTokens amount paid for the coverage
/// @param _distributorFee distributor fee (commission). It can't be greater than PROTOCOL_PERCENTAGE
/// @param _distributor if it was sold buy a whitelisted distributor, it is distributor address to receive fee (commission)
function buyPolicy(
address _buyer,
address _holder,
uint256 _epochsNumber,
uint256 _coverTokens,
uint256 _distributorFee,
address _distributor
) external returns (uint256, uint256);
function updateEpochsInfo() external;
function secondsToEndCurrentEpoch() external view returns (uint256);
/// @notice Let eligible contracts add liqiudity for another user by supplying stable coin
/// @param _liquidityHolderAddr is address of address to assign cover
/// @param _liqudityAmount is amount of stable coin tokens to secure
function addLiquidityFor(address _liquidityHolderAddr, uint256 _liqudityAmount) external;
/// @notice Let user to add liquidity by supplying stable coin, access: ANY
/// @param _liquidityBuyerAddr address the one that transfer funds
/// @param _liquidityHolderAddr address the one that owns liquidity
/// @param _liquidityAmount uint256 amount to be added on behalf the sender
/// @param _stakeSTBLAmount uint256 the staked amount if add liq and stake
function addLiquidity(
address _liquidityBuyerAddr,
address _liquidityHolderAddr,
uint256 _liquidityAmount,
uint256 _stakeSTBLAmount
) external returns (uint256);
function getAvailableBMIXWithdrawableAmount(address _userAddr) external view returns (uint256);
function getWithdrawalStatus(address _userAddr) external view returns (WithdrawalStatus);
function requestWithdrawal(uint256 _tokensToWithdraw, address _user) external;
// function requestWithdrawalWithPermit(
// uint256 _tokensToWithdraw,
// uint8 _v,
// bytes32 _r,
// bytes32 _s
// ) external;
function unlockTokens() external;
/// @notice Let user to withdraw deposited liqiudity, access: ANY
function withdrawLiquidity(address sender) external returns (uint256);
///@notice for doing defi hard rebalancing, access: policyBookFacade
function updateLiquidity(uint256 _newLiquidity) external;
function getAPY() external view returns (uint256);
/// @notice Getting user stats, access: ANY
function userStats(address _user) external view returns (PolicyHolder memory);
/// @notice Getting number stats, access: ANY
/// @return _maxCapacities is a max token amount that a user can buy
/// @return _totalSTBLLiquidity is PolicyBook's liquidity
/// @return _totalLeveragedLiquidity is PolicyBook's leveraged liquidity
/// @return _stakedSTBL is how much stable coin are staked on this PolicyBook
/// @return _annualProfitYields is its APY
/// @return _annualInsuranceCost is percentage of cover tokens that is required to be paid for 1 year of insurance
function numberStats()
external
view
returns (
uint256 _maxCapacities,
uint256 _totalSTBLLiquidity,
uint256 _totalLeveragedLiquidity,
uint256 _stakedSTBL,
uint256 _annualProfitYields,
uint256 _annualInsuranceCost,
uint256 _bmiXRatio
);
/// @notice Getting info, access: ANY
/// @return _symbol is the symbol of PolicyBook (bmiXCover)
/// @return _insuredContract is an addres of insured contract
/// @return _contractType is a type of insured contract
/// @return _whitelisted is a state of whitelisting
function info()
external
view
returns (
string memory _symbol,
address _insuredContract,
IPolicyBookFabric.ContractType _contractType,
bool _whitelisted
);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
interface IPolicyBookFabric {
enum ContractType {CONTRACT, STABLECOIN, SERVICE, EXCHANGE, VARIOUS}
/// @notice Create new Policy Book contract, access: ANY
/// @param _contract is Contract to create policy book for
/// @param _contractType is Contract to create policy book for
/// @param _description is bmiXCover token desription for this policy book
/// @param _projectSymbol replaces x in bmiXCover token symbol
/// @param _initialDeposit is an amount user deposits on creation (addLiquidity())
/// @return _policyBook is address of created contract
function create(
address _contract,
ContractType _contractType,
string calldata _description,
string calldata _projectSymbol,
uint256 _initialDeposit,
address _shieldMiningToken
) external returns (address);
function createLeveragePools(
ContractType _contractType,
string calldata _description,
string calldata _projectSymbol
) external returns (address);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
import "./IPolicyBook.sol";
import "./ILeveragePortfolio.sol";
interface IPolicyBookFacade {
/// @notice Let user to buy policy by supplying stable coin, access: ANY
/// @param _epochsNumber period policy will cover
/// @param _coverTokens amount paid for the coverage
function buyPolicy(uint256 _epochsNumber, uint256 _coverTokens) external;
/// @param _holder who owns coverage
/// @param _epochsNumber period policy will cover
/// @param _coverTokens amount paid for the coverage
function buyPolicyFor(
address _holder,
uint256 _epochsNumber,
uint256 _coverTokens
) external;
function policyBook() external view returns (IPolicyBook);
function userLiquidity(address account) external view returns (uint256);
/// @notice virtual funds deployed by reinsurance pool
function VUreinsurnacePool() external view returns (uint256);
/// @notice leverage funds deployed by reinsurance pool
function LUreinsurnacePool() external view returns (uint256);
/// @notice leverage funds deployed by user leverage pool
function LUuserLeveragePool(address userLeveragePool) external view returns (uint256);
/// @notice total leverage funds deployed to the pool sum of (VUreinsurnacePool,LUreinsurnacePool,LUuserLeveragePool)
function totalLeveragedLiquidity() external view returns (uint256);
function userleveragedMPL() external view returns (uint256);
function reinsurancePoolMPL() external view returns (uint256);
function rebalancingThreshold() external view returns (uint256);
function safePricingModel() external view returns (bool);
/// @notice policyBookFacade initializer
/// @param pbProxy polciybook address upgreadable cotnract.
function __PolicyBookFacade_init(
address pbProxy,
address liquidityProvider,
uint256 initialDeposit
) external;
/// @param _epochsNumber period policy will cover
/// @param _coverTokens amount paid for the coverage
/// @param _distributor if it was sold buy a whitelisted distributor, it is distributor address to receive fee (commission)
function buyPolicyFromDistributor(
uint256 _epochsNumber,
uint256 _coverTokens,
address _distributor
) external;
/// @param _buyer who is buying the coverage
/// @param _epochsNumber period policy will cover
/// @param _coverTokens amount paid for the coverage
/// @param _distributor if it was sold buy a whitelisted distributor, it is distributor address to receive fee (commission)
function buyPolicyFromDistributorFor(
address _buyer,
uint256 _epochsNumber,
uint256 _coverTokens,
address _distributor
) external;
/// @notice Let user to add liquidity by supplying stable coin, access: ANY
/// @param _liquidityAmount is amount of stable coin tokens to secure
function addLiquidity(uint256 _liquidityAmount) external;
/// @notice Let user to add liquidity by supplying stable coin, access: ANY
/// @param _user the one taht add liquidity
/// @param _liquidityAmount is amount of stable coin tokens to secure
function addLiquidityFromDistributorFor(address _user, uint256 _liquidityAmount) external;
/// @notice Let user to add liquidity by supplying stable coin and stake it,
/// @dev access: ANY
function addLiquidityAndStake(uint256 _liquidityAmount, uint256 _stakeSTBLAmount) external;
/// @notice Let user to withdraw deposited liqiudity, access: ANY
function withdrawLiquidity() external;
/// @notice fetches all the pools data
/// @return uint256 VUreinsurnacePool
/// @return uint256 LUreinsurnacePool
/// @return uint256 LUleveragePool
/// @return uint256 user leverage pool address
function getPoolsData()
external
view
returns (
uint256,
uint256,
uint256,
address
);
/// @notice deploy leverage funds (RP lStable, ULP lStable)
/// @param deployedAmount uint256 the deployed amount to be added or substracted from the total liquidity
/// @param leveragePool whether user leverage or reinsurance leverage
function deployLeverageFundsAfterRebalance(
uint256 deployedAmount,
ILeveragePortfolio.LeveragePortfolio leveragePool
) external;
/// @notice deploy virtual funds (RP vStable)
/// @param deployedAmount uint256 the deployed amount to be added to the liquidity
function deployVirtualFundsAfterRebalance(uint256 deployedAmount) external;
/// @notice set the MPL for the user leverage and the reinsurance leverage
/// @param _userLeverageMPL uint256 value of the user leverage MPL
/// @param _reinsuranceLeverageMPL uint256 value of the reinsurance leverage MPL
function setMPLs(uint256 _userLeverageMPL, uint256 _reinsuranceLeverageMPL) external;
/// @notice sets the rebalancing threshold value
/// @param _newRebalancingThreshold uint256 rebalancing threshhold value
function setRebalancingThreshold(uint256 _newRebalancingThreshold) external;
/// @notice sets the rebalancing threshold value
/// @param _safePricingModel bool is pricing model safe (true) or not (false)
function setSafePricingModel(bool _safePricingModel) external;
/// @notice returns how many BMI tokens needs to approve in order to submit a claim
function getClaimApprovalAmount(address user) external view returns (uint256);
/// @notice upserts a withdraw request
/// @dev prevents adding a request if an already pending or ready request is open.
/// @param _tokensToWithdraw uint256 amount of tokens to withdraw
function requestWithdrawal(uint256 _tokensToWithdraw) external;
function listUserLeveragePools(uint256 offset, uint256 limit)
external
view
returns (address[] memory _userLeveragePools);
function countUserLeveragePools() external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
import "./IPolicyBookFabric.sol";
interface IPolicyBookRegistry {
struct PolicyBookStats {
string symbol;
address insuredContract;
IPolicyBookFabric.ContractType contractType;
uint256 maxCapacity;
uint256 totalSTBLLiquidity;
uint256 totalLeveragedLiquidity;
uint256 stakedSTBL;
uint256 APY;
uint256 annualInsuranceCost;
uint256 bmiXRatio;
bool whitelisted;
}
function policyBooksByInsuredAddress(address insuredContract) external view returns (address);
function policyBookFacades(address facadeAddress) external view returns (address);
/// @notice Adds PolicyBook to registry, access: PolicyFabric
function add(
address insuredContract,
IPolicyBookFabric.ContractType contractType,
address policyBook,
address facadeAddress
) external;
function whitelist(address policyBookAddress, bool whitelisted) external;
/// @notice returns required allowances for the policybooks
function getPoliciesPrices(
address[] calldata policyBooks,
uint256[] calldata epochsNumbers,
uint256[] calldata coversTokens
) external view returns (uint256[] memory _durations, uint256[] memory _allowances);
/// @notice Buys a batch of policies
function buyPolicyBatch(
address[] calldata policyBooks,
uint256[] calldata epochsNumbers,
uint256[] calldata coversTokens
) external;
/// @notice Checks if provided address is a PolicyBook
function isPolicyBook(address policyBook) external view returns (bool);
/// @notice Checks if provided address is a policyBookFacade
function isPolicyBookFacade(address _facadeAddress) external view returns (bool);
/// @notice Checks if provided address is a user leverage pool
function isUserLeveragePool(address policyBookAddress) external view returns (bool);
/// @notice Returns number of registered PolicyBooks with certain contract type
function countByType(IPolicyBookFabric.ContractType contractType)
external
view
returns (uint256);
/// @notice Returns number of registered PolicyBooks, access: ANY
function count() external view returns (uint256);
function countByTypeWhitelisted(IPolicyBookFabric.ContractType contractType)
external
view
returns (uint256);
function countWhitelisted() external view returns (uint256);
/// @notice Listing registered PolicyBooks with certain contract type, access: ANY
/// @return _policyBooksArr is array of registered PolicyBook addresses with certain contract type
function listByType(
IPolicyBookFabric.ContractType contractType,
uint256 offset,
uint256 limit
) external view returns (address[] memory _policyBooksArr);
/// @notice Listing registered PolicyBooks, access: ANY
/// @return _policyBooksArr is array of registered PolicyBook addresses
function list(uint256 offset, uint256 limit)
external
view
returns (address[] memory _policyBooksArr);
function listByTypeWhitelisted(
IPolicyBookFabric.ContractType contractType,
uint256 offset,
uint256 limit
) external view returns (address[] memory _policyBooksArr);
function listWhitelisted(uint256 offset, uint256 limit)
external
view
returns (address[] memory _policyBooksArr);
/// @notice Listing registered PolicyBooks with stats and certain contract type, access: ANY
function listWithStatsByType(
IPolicyBookFabric.ContractType contractType,
uint256 offset,
uint256 limit
) external view returns (address[] memory _policyBooksArr, PolicyBookStats[] memory _stats);
/// @notice Listing registered PolicyBooks with stats, access: ANY
function listWithStats(uint256 offset, uint256 limit)
external
view
returns (address[] memory _policyBooksArr, PolicyBookStats[] memory _stats);
function listWithStatsByTypeWhitelisted(
IPolicyBookFabric.ContractType contractType,
uint256 offset,
uint256 limit
) external view returns (address[] memory _policyBooksArr, PolicyBookStats[] memory _stats);
function listWithStatsWhitelisted(uint256 offset, uint256 limit)
external
view
returns (address[] memory _policyBooksArr, PolicyBookStats[] memory _stats);
/// @notice Getting stats from policy books, access: ANY
/// @param policyBooks is list of PolicyBooks addresses
function stats(address[] calldata policyBooks)
external
view
returns (PolicyBookStats[] memory _stats);
/// @notice Return existing Policy Book contract, access: ANY
/// @param insuredContract is contract address to lookup for created IPolicyBook
function policyBookFor(address insuredContract) external view returns (address);
/// @notice Getting stats from policy books, access: ANY
/// @param insuredContracts is list of insuredContracts in registry
function statsByInsuredContracts(address[] calldata insuredContracts)
external
view
returns (PolicyBookStats[] memory _stats);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
interface IRewardsGenerator {
struct PolicyBookRewardInfo {
uint256 rewardMultiplier; // includes 5 decimal places
uint256 totalStaked;
uint256 lastUpdateBlock;
uint256 lastCumulativeSum; // includes 100 percentage
uint256 cumulativeReward; // includes 100 percentage
}
struct StakeRewardInfo {
uint256 lastCumulativeSum; // includes 100 percentage
uint256 cumulativeReward;
uint256 stakeAmount;
}
/// @notice this function is called every time policybook's STBL to bmiX rate changes
function updatePolicyBookShare(uint256 newRewardMultiplier) external;
/// @notice aggregates specified nfts into a single one
function aggregate(
address policyBookAddress,
uint256[] calldata nftIndexes,
uint256 nftIndexTo
) external;
/// @notice migrates stake from the LegacyRewardsGenerator (will be called once for each user)
/// the rewards multipliers must be set in advance
function migrationStake(
address policyBookAddress,
uint256 nftIndex,
uint256 amount,
uint256 currentReward
) external;
/// @notice informs generator of stake (rewards)
function stake(
address policyBookAddress,
uint256 nftIndex,
uint256 amount
) external;
/// @notice returns policybook's APY multiplied by 10**5
function getPolicyBookAPY(address policyBookAddress) external view returns (uint256);
/// @notice returns policybook's RewardMultiplier multiplied by 10**5
function getPolicyBookRewardMultiplier(address policyBookAddress)
external
view
returns (uint256);
/// @dev returns PolicyBook reward per block multiplied by 10**25
function getPolicyBookRewardPerBlock(address policyBookAddress)
external
view
returns (uint256);
/// @notice returns PolicyBook's staked STBL
function getStakedPolicyBookSTBL(address policyBookAddress) external view returns (uint256);
/// @notice returns NFT's staked STBL
function getStakedNFTSTBL(uint256 nftIndex) external view returns (uint256);
/// @notice returns a reward of NFT
function getReward(address policyBookAddress, uint256 nftIndex)
external
view
returns (uint256);
/// @notice informs generator of withdrawal (all funds)
function withdrawFunds(address policyBookAddress, uint256 nftIndex) external returns (uint256);
/// @notice informs generator of withdrawal (rewards)
function withdrawReward(address policyBookAddress, uint256 nftIndex)
external
returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IShieldMining {
struct ShieldMiningInfo {
IERC20 rewardsToken;
uint8 decimals;
uint256 firstBlockWithReward;
uint256 lastBlockWithReward;
uint256 lastUpdateBlock;
uint256 rewardTokensLocked;
uint256 rewardPerTokenStored;
uint256 totalSupply;
uint256[] endsOfDistribution;
// new state post v2
uint256 nearestLastBlocksWithReward;
// lastBlockWithReward => rewardPerBlock
mapping(uint256 => uint256) rewardPerBlock;
}
struct ShieldMiningDeposit {
address policyBook;
uint256 amount;
uint256 duration;
uint256 depositRewardPerBlock;
uint256 startBlock;
uint256 endBlock;
}
/// TODO document SM functions
function blocksWithRewardsPassed(address _policyBook) external view returns (uint256);
function rewardPerToken(address _policyBook) external view returns (uint256);
function earned(
address _policyBook,
address _userLeveragePool,
address _account
) external view returns (uint256);
function updateTotalSupply(
address _policyBook,
address _userLeveragePool,
address liquidityProvider
) external;
function associateShieldMining(address _policyBook, address _shieldMiningToken) external;
function fillShieldMining(
address _policyBook,
uint256 _amount,
uint256 _duration
) external;
function getRewardFor(
address _userAddress,
address _policyBook,
address _userLeveragePool
) external;
function getRewardFor(address _userAddress, address _userLeveragePoolAddress) external;
function getReward(address _policyBook, address _userLeveragePool) external;
function getReward(address _userLeveragePoolAddress) external;
function getShieldTokenAddress(address _policyBook) external view returns (address);
function getShieldMiningInfo(address _policyBook)
external
view
returns (
address _rewardsToken,
uint256 _decimals,
uint256 _firstBlockWithReward,
uint256 _lastBlockWithReward,
uint256 _lastUpdateBlock,
uint256 _nearestLastBlocksWithReward,
uint256 _rewardTokensLocked,
uint256 _rewardPerTokenStored,
uint256 _rewardPerBlock,
uint256 _tokenPerDay,
uint256 _totalSupply
);
function getDepositList(
address _account,
uint256 _offset,
uint256 _limit
) external view returns (ShieldMiningDeposit[] memory _depositsList);
function countUsersDeposits(address _account) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
interface ISTKBMIToken is IERC20Upgradeable {
function mint(address account, uint256 amount) external;
function burn(address account, uint256 amount) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* COPIED FROM https://github.com/OpenZeppelin/openzeppelin-contracts-upgradeable/tree/release-v3.4/contracts/drafts
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*/
interface IERC20PermitUpgradeable {
/**
* @dev Sets `value` as the allowance of `spender` over `owner`'s tokens,
* given `owner`'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for `permit`, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "@openzeppelin/contracts-upgradeable/token/ERC1155/IERC1155Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC1155/IERC1155MetadataURIUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC1155/IERC1155ReceiverUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/GSN/ContextUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/introspection/ERC165Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
/**
*
* @dev Implementation of the basic standard multi-token.
* See https://eips.ethereum.org/EIPS/eip-1155
* Originally based on code by Enjin: https://github.com/enjin/erc-1155
*
* _Available since v3.1._
*/
contract ERC1155Upgradeable is
Initializable,
ContextUpgradeable,
ERC165Upgradeable,
IERC1155Upgradeable,
IERC1155MetadataURIUpgradeable
{
using SafeMathUpgradeable for uint256;
using AddressUpgradeable for address;
// Mapping from token ID to account balances
mapping(uint256 => mapping(address => uint256)) private _balances;
// Mapping from account to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
// Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json
string private _uri;
/*
* bytes4(keccak256('balanceOf(address,uint256)')) == 0x00fdd58e
* bytes4(keccak256('balanceOfBatch(address[],uint256[])')) == 0x4e1273f4
* bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465
* bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5
* bytes4(keccak256('safeTransferFrom(address,address,uint256,uint256,bytes)')) == 0xf242432a
* bytes4(keccak256('safeBatchTransferFrom(address,address,uint256[],uint256[],bytes)')) == 0x2eb2c2d6
*
* => 0x00fdd58e ^ 0x4e1273f4 ^ 0xa22cb465 ^
* 0xe985e9c5 ^ 0xf242432a ^ 0x2eb2c2d6 == 0xd9b67a26
*/
bytes4 private constant _INTERFACE_ID_ERC1155 = 0xd9b67a26;
/*
* bytes4(keccak256('uri(uint256)')) == 0x0e89341c
*/
bytes4 private constant _INTERFACE_ID_ERC1155_METADATA_URI = 0x0e89341c;
/**
* @dev See {_setURI}.
*/
function __ERC1155_init(string memory uri_) internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__ERC1155_init_unchained(uri_);
}
function __ERC1155_init_unchained(string memory uri_) internal initializer {
_setURI(uri_);
// register the supported interfaces to conform to ERC1155 via ERC165
_registerInterface(_INTERFACE_ID_ERC1155);
// register the supported interfaces to conform to ERC1155MetadataURI via ERC165
_registerInterface(_INTERFACE_ID_ERC1155_METADATA_URI);
}
/**
* @dev See {IERC1155MetadataURI-uri}.
*
* This implementation returns the same URI for *all* token types. It relies
* on the token type ID substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* Clients calling this function must replace the `\{id\}` substring with the
* actual token type ID.
*/
function uri(uint256) public view virtual override returns (string memory) {
return _uri;
}
/**
* @dev See {IERC1155-balanceOf}.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) public view override returns (uint256) {
require(account != address(0), "ERC1155: zero address");
return _balances[id][account];
}
/**
* @dev See {IERC1155-balanceOfBatch}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] memory accounts, uint256[] memory ids)
public
view
override
returns (uint256[] memory)
{
require(accounts.length == ids.length, "ERC1155: length mismatch");
uint256[] memory batchBalances = new uint256[](accounts.length);
for (uint256 i = 0; i < accounts.length; ++i) {
require(accounts[i] != address(0), "ERC1155: zero address");
batchBalances[i] = _balances[ids[i]][accounts[i]];
}
return batchBalances;
}
/**
* @dev See {IERC1155-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(_msgSender() != operator, "ERC1155: self approval");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC1155-isApprovedForAll}.
*/
function isApprovedForAll(address account, address operator)
public
view
override
returns (bool)
{
return _operatorApprovals[account][operator];
}
/**
* @dev See {IERC1155-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) public virtual override {
require(to != address(0), "ERC1155: zero address");
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: transfer failed"
);
address operator = _msgSender();
_beforeTokenTransfer(
operator,
from,
to,
_asSingletonArray(id),
_asSingletonArray(amount),
data
);
_balances[id][from] = _balances[id][from].sub(amount, "ERC1155: insufficient balance");
_balances[id][to] = _balances[id][to].add(amount);
emit TransferSingle(operator, from, to, id, amount);
_doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data);
}
/**
* @dev See {IERC1155-safeBatchTransferFrom}.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) public virtual override {
require(ids.length == amounts.length, "ERC1155: length mismatch");
require(to != address(0), "ERC1155: zero address");
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: transfer failed"
);
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; ++i) {
uint256 id = ids[i];
uint256 amount = amounts[i];
_balances[id][from] = _balances[id][from].sub(amount, "ERC1155: insufficient balance");
_balances[id][to] = _balances[id][to].add(amount);
}
emit TransferBatch(operator, from, to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data);
}
/**
* @dev Sets a new URI for all token types, by relying on the token type ID
* substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* By this mechanism, any occurrence of the `\{id\}` substring in either the
* URI or any of the amounts in the JSON file at said URI will be replaced by
* clients with the token type ID.
*
* For example, the `https://token-cdn-domain/\{id\}.json` URI would be
* interpreted by clients as
* `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json`
* for token type ID 0x4cce0.
*
* See {uri}.
*
* Because these URIs cannot be meaningfully represented by the {URI} event,
* this function emits no events.
*/
function _setURI(string memory newuri) internal virtual {
_uri = newuri;
}
/**
* @dev Creates `amount` tokens of token type `id`, and assigns them to `account`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function _mint(
address account,
uint256 id,
uint256 amount,
bytes memory data
) internal virtual {
require(account != address(0), "ERC1155: zero address");
address operator = _msgSender();
_beforeTokenTransfer(
operator,
address(0),
account,
_asSingletonArray(id),
_asSingletonArray(amount),
data
);
_balances[id][account] = _balances[id][account].add(amount);
emit TransferSingle(operator, address(0), account, id, amount);
_doSafeTransferAcceptanceCheck(operator, address(0), account, id, amount, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function _mintBatch(
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: zero address");
require(ids.length == amounts.length, "ERC1155: length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; i++) {
_balances[ids[i]][to] = amounts[i].add(_balances[ids[i]][to]);
}
emit TransferBatch(operator, address(0), to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data);
}
/**
* @dev Destroys `amount` tokens of token type `id` from `account`
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens of token type `id`.
*/
function _burn(
address account,
uint256 id,
uint256 amount
) internal virtual {
require(account != address(0), "ERC1155: burn from the zero address");
address operator = _msgSender();
_beforeTokenTransfer(
operator,
account,
address(0),
_asSingletonArray(id),
_asSingletonArray(amount),
""
);
_balances[id][account] = _balances[id][account].sub(
amount,
"ERC1155: burn amount exceeds balance"
);
emit TransferSingle(operator, account, address(0), id, amount);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
*/
function _burnBatch(
address account,
uint256[] memory ids,
uint256[] memory amounts
) internal virtual {
require(account != address(0), "ERC1155: burn from the zero address");
require(ids.length == amounts.length, "ERC1155: length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, account, address(0), ids, amounts, "");
for (uint256 i = 0; i < ids.length; i++) {
_balances[ids[i]][account] = _balances[ids[i]][account].sub(
amounts[i],
"ERC1155: burn amount exceeds balance"
);
}
emit TransferBatch(operator, account, address(0), ids, amounts);
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning, as well as batched variants.
*
* The same hook is called on both single and batched variants. For single
* transfers, the length of the `id` and `amount` arrays will be 1.
*
* Calling conditions (for each `id` and `amount` pair):
*
* - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* of token type `id` will be transferred to `to`.
* - When `from` is zero, `amount` tokens of token type `id` will be minted
* for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens of token type `id`
* will be burned.
* - `from` and `to` are never both zero.
* - `ids` and `amounts` have the same, non-zero length.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {}
function _doSafeTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) private {
if (to.isContract()) {
try
IERC1155ReceiverUpgradeable(to).onERC1155Received(operator, from, id, amount, data)
returns (bytes4 response) {
if (response != IERC1155ReceiverUpgradeable(to).onERC1155Received.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: non ERC1155Receiver");
}
}
}
function _doSafeBatchTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) private {
if (to.isContract()) {
try
IERC1155ReceiverUpgradeable(to).onERC1155BatchReceived(
operator,
from,
ids,
amounts,
data
)
returns (bytes4 response) {
if (response != IERC1155ReceiverUpgradeable(to).onERC1155BatchReceived.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: non ERC1155Receiver");
}
}
}
function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) {
uint256[] memory array = new uint256[](1);
array[0] = element;
return array;
}
uint256[47] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../proxy/Initializable.sol";
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../GSN/ContextUpgradeable.sol";
import "../proxy/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./IERC165Upgradeable.sol";
import "../proxy/Initializable.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts may inherit from this and call {_registerInterface} to declare
* their support of an interface.
*/
abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {
/*
* bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
*/
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/**
* @dev Mapping of interface ids to whether or not it's supported.
*/
mapping(bytes4 => bool) private _supportedInterfaces;
function __ERC165_init() internal initializer {
__ERC165_init_unchained();
}
function __ERC165_init_unchained() internal initializer {
// Derived contracts need only register support for their own interfaces,
// we register support for ERC165 itself here
_registerInterface(_INTERFACE_ID_ERC165);
}
/**
* @dev See {IERC165-supportsInterface}.
*
* Time complexity O(1), guaranteed to always use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) public view override returns (bool) {
return _supportedInterfaces[interfaceId];
}
/**
* @dev Registers the contract as an implementer of the interface defined by
* `interfaceId`. Support of the actual ERC165 interface is automatic and
* registering its interface id is not required.
*
* See {IERC165-supportsInterface}.
*
* Requirements:
*
* - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`).
*/
function _registerInterface(bytes4 interfaceId) internal virtual {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165Upgradeable {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMathUpgradeable {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
// solhint-disable-next-line compiler-version
pragma solidity >=0.4.24 <0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function _isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
// solhint-disable-next-line no-inline-assembly
assembly { cs := extcodesize(self) }
return cs == 0;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
import "./IERC1155Upgradeable.sol";
/**
* @dev Interface of the optional ERC1155MetadataExtension interface, as defined
* in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP].
*
* _Available since v3.1._
*/
interface IERC1155MetadataURIUpgradeable is IERC1155Upgradeable {
/**
* @dev Returns the URI for token type `id`.
*
* If the `\{id\}` substring is present in the URI, it must be replaced by
* clients with the actual token type ID.
*/
function uri(uint256 id) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../../introspection/IERC165Upgradeable.sol";
/**
* _Available since v3.1._
*/
interface IERC1155ReceiverUpgradeable is IERC165Upgradeable {
/**
@dev Handles the receipt of a single ERC1155 token type. This function is
called at the end of a `safeTransferFrom` after the balance has been updated.
To accept the transfer, this must return
`bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
(i.e. 0xf23a6e61, or its own function selector).
@param operator The address which initiated the transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param id The ID of the token being transferred
@param value The amount of tokens being transferred
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
*/
function onERC1155Received(
address operator,
address from,
uint256 id,
uint256 value,
bytes calldata data
)
external
returns(bytes4);
/**
@dev Handles the receipt of a multiple ERC1155 token types. This function
is called at the end of a `safeBatchTransferFrom` after the balances have
been updated. To accept the transfer(s), this must return
`bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
(i.e. 0xbc197c81, or its own function selector).
@param operator The address which initiated the batch transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param ids An array containing ids of each token being transferred (order and length must match values array)
@param values An array containing amounts of each token being transferred (order and length must match ids array)
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
*/
function onERC1155BatchReceived(
address operator,
address from,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
)
external
returns(bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
import "../../introspection/IERC165Upgradeable.sol";
/**
* @dev Required interface of an ERC1155 compliant contract, as defined in the
* https://eips.ethereum.org/EIPS/eip-1155[EIP].
*
* _Available since v3.1._
*/
interface IERC1155Upgradeable is IERC165Upgradeable {
/**
* @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
*/
event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
/**
* @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
* transfers.
*/
event TransferBatch(address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values);
/**
* @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
* `approved`.
*/
event ApprovalForAll(address indexed account, address indexed operator, bool approved);
/**
* @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
*
* If an {URI} event was emitted for `id`, the standard
* https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
* returned by {IERC1155MetadataURI-uri}.
*/
event URI(string value, uint256 indexed id);
/**
* @dev Returns the amount of tokens of token type `id` owned by `account`.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) external view returns (uint256);
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory);
/**
* @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
*
* Emits an {ApprovalForAll} event.
*
* Requirements:
*
* - `operator` cannot be the caller.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
*
* See {setApprovalForAll}.
*/
function isApprovedForAll(address account, address operator) external view returns (bool);
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes calldata data) external;
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function safeBatchTransferFrom(address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev Library for managing an enumerable variant of Solidity's
* https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`]
* type.
*
* Maps have the following properties:
*
* - Entries are added, removed, and checked for existence in constant time
* (O(1)).
* - Entries are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableMap for EnumerableMap.UintToAddressMap;
*
* // Declare a set state variable
* EnumerableMap.UintToAddressMap private myMap;
* }
* ```
*
* As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are
* supported.
*/
library EnumerableMap {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Map type with
// bytes32 keys and values.
// The Map implementation uses private functions, and user-facing
// implementations (such as Uint256ToAddressMap) are just wrappers around
// the underlying Map.
// This means that we can only create new EnumerableMaps for types that fit
// in bytes32.
struct MapEntry {
bytes32 _key;
bytes32 _value;
}
struct Map {
// Storage of map keys and values
MapEntry[] _entries;
// Position of the entry defined by a key in the `entries` array, plus 1
// because index 0 means a key is not in the map.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) { // Equivalent to !contains(map, key)
map._entries.push(MapEntry({ _key: key, _value: value }));
// The entry is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
map._indexes[key] = map._entries.length;
return true;
} else {
map._entries[keyIndex - 1]._value = value;
return false;
}
}
/**
* @dev Removes a key-value pair from a map. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function _remove(Map storage map, bytes32 key) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex != 0) { // Equivalent to contains(map, key)
// To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one
// in the array, and then remove the last entry (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = keyIndex - 1;
uint256 lastIndex = map._entries.length - 1;
// When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
MapEntry storage lastEntry = map._entries[lastIndex];
// Move the last entry to the index where the entry to delete is
map._entries[toDeleteIndex] = lastEntry;
// Update the index for the moved entry
map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved entry was stored
map._entries.pop();
// Delete the index for the deleted slot
delete map._indexes[key];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function _contains(Map storage map, bytes32 key) private view returns (bool) {
return map._indexes[key] != 0;
}
/**
* @dev Returns the number of key-value pairs in the map. O(1).
*/
function _length(Map storage map) private view returns (uint256) {
return map._entries.length;
}
/**
* @dev Returns the key-value pair stored at position `index` in the map. O(1).
*
* Note that there are no guarantees on the ordering of entries inside the
* array, and it may change when more entries are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) {
require(map._entries.length > index, "EnumerableMap: index out of bounds");
MapEntry storage entry = map._entries[index];
return (entry._key, entry._value);
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function _get(Map storage map, bytes32 key) private view returns (bytes32) {
return _get(map, key, "EnumerableMap: nonexistent key");
}
/**
* @dev Same as {_get}, with a custom error message when `key` is not in the map.
*/
function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
// UintToAddressMap
struct UintToAddressMap {
Map _inner;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) {
return _set(map._inner, bytes32(key), bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) {
return _remove(map._inner, bytes32(key));
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) {
return _contains(map._inner, bytes32(key));
}
/**
* @dev Returns the number of elements in the map. O(1).
*/
function length(UintToAddressMap storage map) internal view returns (uint256) {
return _length(map._inner);
}
/**
* @dev Returns the element stored at position `index` in the set. O(1).
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) {
(bytes32 key, bytes32 value) = _at(map._inner, index);
return (uint256(key), address(uint256(value)));
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(UintToAddressMap storage map, uint256 key) internal view returns (address) {
return address(uint256(_get(map._inner, bytes32(key))));
}
/**
* @dev Same as {get}, with a custom error message when `key` is not in the map.
*/
function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) {
return address(uint256(_get(map._inner, bytes32(key), errorMessage)));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256`
* (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint256(_at(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev String operations.
*/
library Strings {
/**
* @dev Converts a `uint256` to its ASCII `string` representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
uint256 index = digits - 1;
temp = value;
while (temp != 0) {
buffer[index--] = byte(uint8(48 + temp % 10));
temp /= 10;
}
return string(buffer);
}
} | SPDX-License-Identifier: MIT* @dev Implementation of the basic standard multi-token. _Available since v3.1._/ Mapping from token ID to account balances Mapping from account to operator approvals Used as the URI for all token types by relying on ID substitution, e.g. https:token-cdn-domain/{id}.json | {
using SafeMathUpgradeable for uint256;
using AddressUpgradeable for address;
mapping(uint256 => mapping(address => uint256)) private _balances;
mapping(address => mapping(address => bool)) private _operatorApprovals;
string private _uri;
bytes4 private constant _INTERFACE_ID_ERC1155 = 0xd9b67a26;
bytes4 private constant _INTERFACE_ID_ERC1155_METADATA_URI = 0x0e89341c;
function blocksWithRewardsPassed(address _policyBook) external view returns (uint256);
function rewardPerToken(address _policyBook) external view returns (uint256);
function earned(
address _policyBook,
address _userLeveragePool,
address _account
) external view returns (uint256);
function updateTotalSupply(
address _policyBook,
address _userLeveragePool,
address liquidityProvider
) external;
function associateShieldMining(address _policyBook, address _shieldMiningToken) external;
function fillShieldMining(
address _policyBook,
uint256 _amount,
uint256 _duration
) external;
function getRewardFor(
address _userAddress,
address _policyBook,
address _userLeveragePool
) external;
function getRewardFor(address _userAddress, address _userLeveragePoolAddress) external;
function getReward(address _policyBook, address _userLeveragePool) external;
function getReward(address _userLeveragePoolAddress) external;
function getShieldTokenAddress(address _policyBook) external view returns (address);
function getShieldMiningInfo(address _policyBook)
external
view
returns (
address _rewardsToken,
uint256 _decimals,
uint256 _firstBlockWithReward,
uint256 _lastBlockWithReward,
uint256 _lastUpdateBlock,
uint256 _nearestLastBlocksWithReward,
uint256 _rewardTokensLocked,
uint256 _rewardPerTokenStored,
uint256 _rewardPerBlock,
uint256 _tokenPerDay,
uint256 _totalSupply
);
function getDepositList(
address _account,
uint256 _offset,
uint256 _limit
) external view returns (ShieldMiningDeposit[] memory _depositsList);
function countUsersDeposits(address _account) external view returns (uint256);
}
pragma solidity ^0.7.4;
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
}
pragma solidity >=0.6.0 <0.8.0;
}
pragma solidity >=0.6.0 <0.8.0;
import "@openzeppelin/contracts-upgradeable/token/ERC1155/IERC1155Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC1155/IERC1155MetadataURIUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC1155/IERC1155ReceiverUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/GSN/ContextUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/introspection/ERC165Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
contract ERC1155Upgradeable is
Initializable,
ContextUpgradeable,
ERC165Upgradeable,
IERC1155Upgradeable,
IERC1155MetadataURIUpgradeable
function __ERC1155_init(string memory uri_) internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__ERC1155_init_unchained(uri_);
}
function __ERC1155_init_unchained(string memory uri_) internal initializer {
_setURI(uri_);
_registerInterface(_INTERFACE_ID_ERC1155);
_registerInterface(_INTERFACE_ID_ERC1155_METADATA_URI);
}
function uri(uint256) public view virtual override returns (string memory) {
return _uri;
}
function balanceOf(address account, uint256 id) public view override returns (uint256) {
require(account != address(0), "ERC1155: zero address");
return _balances[id][account];
}
function balanceOfBatch(address[] memory accounts, uint256[] memory ids)
public
view
override
returns (uint256[] memory)
{
require(accounts.length == ids.length, "ERC1155: length mismatch");
uint256[] memory batchBalances = new uint256[](accounts.length);
for (uint256 i = 0; i < accounts.length; ++i) {
require(accounts[i] != address(0), "ERC1155: zero address");
batchBalances[i] = _balances[ids[i]][accounts[i]];
}
return batchBalances;
}
function balanceOfBatch(address[] memory accounts, uint256[] memory ids)
public
view
override
returns (uint256[] memory)
{
require(accounts.length == ids.length, "ERC1155: length mismatch");
uint256[] memory batchBalances = new uint256[](accounts.length);
for (uint256 i = 0; i < accounts.length; ++i) {
require(accounts[i] != address(0), "ERC1155: zero address");
batchBalances[i] = _balances[ids[i]][accounts[i]];
}
return batchBalances;
}
function setApprovalForAll(address operator, bool approved) public virtual override {
require(_msgSender() != operator, "ERC1155: self approval");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
function isApprovedForAll(address account, address operator)
public
view
override
returns (bool)
{
return _operatorApprovals[account][operator];
}
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) public virtual override {
require(to != address(0), "ERC1155: zero address");
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: transfer failed"
);
address operator = _msgSender();
_beforeTokenTransfer(
operator,
from,
to,
_asSingletonArray(id),
_asSingletonArray(amount),
data
);
_balances[id][from] = _balances[id][from].sub(amount, "ERC1155: insufficient balance");
_balances[id][to] = _balances[id][to].add(amount);
emit TransferSingle(operator, from, to, id, amount);
_doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data);
}
function safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) public virtual override {
require(ids.length == amounts.length, "ERC1155: length mismatch");
require(to != address(0), "ERC1155: zero address");
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: transfer failed"
);
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; ++i) {
uint256 id = ids[i];
uint256 amount = amounts[i];
_balances[id][from] = _balances[id][from].sub(amount, "ERC1155: insufficient balance");
_balances[id][to] = _balances[id][to].add(amount);
}
emit TransferBatch(operator, from, to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data);
}
function safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) public virtual override {
require(ids.length == amounts.length, "ERC1155: length mismatch");
require(to != address(0), "ERC1155: zero address");
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: transfer failed"
);
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; ++i) {
uint256 id = ids[i];
uint256 amount = amounts[i];
_balances[id][from] = _balances[id][from].sub(amount, "ERC1155: insufficient balance");
_balances[id][to] = _balances[id][to].add(amount);
}
emit TransferBatch(operator, from, to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data);
}
function _setURI(string memory newuri) internal virtual {
_uri = newuri;
}
function _mint(
address account,
uint256 id,
uint256 amount,
bytes memory data
) internal virtual {
require(account != address(0), "ERC1155: zero address");
address operator = _msgSender();
_beforeTokenTransfer(
operator,
address(0),
account,
_asSingletonArray(id),
_asSingletonArray(amount),
data
);
_balances[id][account] = _balances[id][account].add(amount);
emit TransferSingle(operator, address(0), account, id, amount);
_doSafeTransferAcceptanceCheck(operator, address(0), account, id, amount, data);
}
function _mintBatch(
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: zero address");
require(ids.length == amounts.length, "ERC1155: length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; i++) {
_balances[ids[i]][to] = amounts[i].add(_balances[ids[i]][to]);
}
emit TransferBatch(operator, address(0), to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data);
}
function _mintBatch(
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: zero address");
require(ids.length == amounts.length, "ERC1155: length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; i++) {
_balances[ids[i]][to] = amounts[i].add(_balances[ids[i]][to]);
}
emit TransferBatch(operator, address(0), to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data);
}
function _burn(
address account,
uint256 id,
uint256 amount
) internal virtual {
require(account != address(0), "ERC1155: burn from the zero address");
address operator = _msgSender();
_beforeTokenTransfer(
operator,
account,
address(0),
_asSingletonArray(id),
_asSingletonArray(amount),
""
);
_balances[id][account] = _balances[id][account].sub(
amount,
"ERC1155: burn amount exceeds balance"
);
emit TransferSingle(operator, account, address(0), id, amount);
}
function _burnBatch(
address account,
uint256[] memory ids,
uint256[] memory amounts
) internal virtual {
require(account != address(0), "ERC1155: burn from the zero address");
require(ids.length == amounts.length, "ERC1155: length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, account, address(0), ids, amounts, "");
for (uint256 i = 0; i < ids.length; i++) {
_balances[ids[i]][account] = _balances[ids[i]][account].sub(
amounts[i],
"ERC1155: burn amount exceeds balance"
);
}
emit TransferBatch(operator, account, address(0), ids, amounts);
}
function _burnBatch(
address account,
uint256[] memory ids,
uint256[] memory amounts
) internal virtual {
require(account != address(0), "ERC1155: burn from the zero address");
require(ids.length == amounts.length, "ERC1155: length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, account, address(0), ids, amounts, "");
for (uint256 i = 0; i < ids.length; i++) {
_balances[ids[i]][account] = _balances[ids[i]][account].sub(
amounts[i],
"ERC1155: burn amount exceeds balance"
);
}
emit TransferBatch(operator, account, address(0), ids, amounts);
}
) internal virtual {}
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
function _doSafeTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) private {
if (to.isContract()) {
try
IERC1155ReceiverUpgradeable(to).onERC1155Received(operator, from, id, amount, data)
returns (bytes4 response) {
if (response != IERC1155ReceiverUpgradeable(to).onERC1155Received.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
revert(reason);
revert("ERC1155: non ERC1155Receiver");
}
}
}
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
function _doSafeTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) private {
if (to.isContract()) {
try
IERC1155ReceiverUpgradeable(to).onERC1155Received(operator, from, id, amount, data)
returns (bytes4 response) {
if (response != IERC1155ReceiverUpgradeable(to).onERC1155Received.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
revert(reason);
revert("ERC1155: non ERC1155Receiver");
}
}
}
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
function _doSafeTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) private {
if (to.isContract()) {
try
IERC1155ReceiverUpgradeable(to).onERC1155Received(operator, from, id, amount, data)
returns (bytes4 response) {
if (response != IERC1155ReceiverUpgradeable(to).onERC1155Received.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
revert(reason);
revert("ERC1155: non ERC1155Receiver");
}
}
}
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
function _doSafeTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) private {
if (to.isContract()) {
try
IERC1155ReceiverUpgradeable(to).onERC1155Received(operator, from, id, amount, data)
returns (bytes4 response) {
if (response != IERC1155ReceiverUpgradeable(to).onERC1155Received.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
revert(reason);
revert("ERC1155: non ERC1155Receiver");
}
}
}
} catch Error(string memory reason) {
} catch {
function _doSafeBatchTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) private {
if (to.isContract()) {
try
IERC1155ReceiverUpgradeable(to).onERC1155BatchReceived(
operator,
from,
ids,
amounts,
data
)
returns (bytes4 response) {
if (response != IERC1155ReceiverUpgradeable(to).onERC1155BatchReceived.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
revert(reason);
revert("ERC1155: non ERC1155Receiver");
}
}
}
function _doSafeBatchTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) private {
if (to.isContract()) {
try
IERC1155ReceiverUpgradeable(to).onERC1155BatchReceived(
operator,
from,
ids,
amounts,
data
)
returns (bytes4 response) {
if (response != IERC1155ReceiverUpgradeable(to).onERC1155BatchReceived.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
revert(reason);
revert("ERC1155: non ERC1155Receiver");
}
}
}
function _doSafeBatchTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) private {
if (to.isContract()) {
try
IERC1155ReceiverUpgradeable(to).onERC1155BatchReceived(
operator,
from,
ids,
amounts,
data
)
returns (bytes4 response) {
if (response != IERC1155ReceiverUpgradeable(to).onERC1155BatchReceived.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
revert(reason);
revert("ERC1155: non ERC1155Receiver");
}
}
}
function _doSafeBatchTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) private {
if (to.isContract()) {
try
IERC1155ReceiverUpgradeable(to).onERC1155BatchReceived(
operator,
from,
ids,
amounts,
data
)
returns (bytes4 response) {
if (response != IERC1155ReceiverUpgradeable(to).onERC1155BatchReceived.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
revert(reason);
revert("ERC1155: non ERC1155Receiver");
}
}
}
} catch Error(string memory reason) {
} catch {
function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) {
uint256[] memory array = new uint256[](1);
array[0] = element;
return array;
}
uint256[47] private __gap;
}
| 14,811,791 | [
1,
3118,
28826,
17,
13211,
17,
3004,
30,
490,
1285,
225,
25379,
434,
326,
5337,
4529,
3309,
17,
2316,
18,
389,
5268,
3241,
331,
23,
18,
21,
6315,
19,
9408,
628,
1147,
1599,
358,
2236,
324,
26488,
9408,
628,
2236,
358,
3726,
6617,
4524,
10286,
487,
326,
3699,
364,
777,
1147,
1953,
635,
283,
6291,
603,
1599,
12785,
16,
425,
18,
75,
18,
2333,
30,
2316,
17,
20902,
17,
4308,
4938,
350,
5496,
1977,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
95,
203,
565,
1450,
14060,
10477,
10784,
429,
364,
2254,
5034,
31,
203,
565,
1450,
5267,
10784,
429,
364,
1758,
31,
203,
203,
565,
2874,
12,
11890,
5034,
516,
2874,
12,
2867,
516,
2254,
5034,
3719,
3238,
389,
70,
26488,
31,
203,
203,
565,
2874,
12,
2867,
516,
2874,
12,
2867,
516,
1426,
3719,
3238,
389,
9497,
12053,
4524,
31,
203,
203,
565,
533,
3238,
389,
1650,
31,
203,
203,
565,
1731,
24,
3238,
5381,
389,
18865,
67,
734,
67,
654,
39,
2499,
2539,
273,
374,
7669,
29,
70,
9599,
69,
5558,
31,
203,
203,
565,
1731,
24,
3238,
5381,
389,
18865,
67,
734,
67,
654,
39,
2499,
2539,
67,
22746,
67,
3098,
273,
374,
92,
20,
73,
6675,
5026,
21,
71,
31,
203,
203,
565,
445,
4398,
1190,
17631,
14727,
22530,
12,
2867,
389,
5086,
9084,
13,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
203,
565,
445,
19890,
2173,
1345,
12,
2867,
389,
5086,
9084,
13,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
203,
565,
445,
425,
1303,
329,
12,
203,
3639,
1758,
389,
5086,
9084,
16,
203,
3639,
1758,
389,
1355,
1682,
5682,
2864,
16,
203,
3639,
1758,
389,
4631,
203,
565,
262,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
203,
565,
445,
1089,
5269,
3088,
1283,
12,
203,
3639,
1758,
389,
5086,
9084,
16,
203,
3639,
1758,
389,
1355,
1682,
5682,
2864,
16,
203,
3639,
1758,
4501,
372,
24237,
2249,
203,
565,
262,
3903,
31,
203,
203,
565,
445,
13251,
1555,
491,
2930,
310,
12,
2867,
389,
5086,
2
] |
// File: openzeppelin\contracts\utils\introspection\IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File: openzeppelin\contracts\token\ERC721\IERC721.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File: openzeppelin\contracts\token\ERC721\extensions\IERC721Enumerable.sol
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol)
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// File: openzeppelin\contracts\token\ERC721\IERC721Receiver.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// File: openzeppelin\contracts\security\ReentrancyGuard.sol
// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// File: bapestoken.sol
interface IBEP20 {
function totalSupply() external view returns (uint256);
function decimals() external view returns (uint8);
function symbol() external view returns (string memory);
function name() external view returns (string memory);
function getOwner() external view returns (address);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address _owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
interface IPancakeERC20 {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
}
interface IPancakeFactory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
interface IPancakeRouter01 {
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function factory() external pure returns (address);
function WETH() external pure returns (address);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getamountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getamountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getamountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getamountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
interface IPancakeRouter02 is IPancakeRouter01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () {
address msgSender = msg.sender;
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == msg.sender, "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////
//BallerX Contract ////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////
contract BAPE is IBEP20, Ownable, IERC721Receiver, ReentrancyGuard
{
using Address for address;
using EnumerableSet for EnumerableSet.AddressSet;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
EnumerableSet.AddressSet private _excluded;
//Token Info
string private constant _name = 'BAPE';
string private constant _symbol = 'BAPE';
uint8 private constant _decimals = 9;
uint256 public constant InitialSupply= 1 * 10**9 * 10**_decimals;
uint256 swapLimit = 5 * 10**6 * 10**_decimals; // 0,5%
bool isSwapPegged = false;
//Divider for the buyLimit based on circulating Supply (1%)
uint16 public constant BuyLimitDivider=1;
//Divider for the MaxBalance based on circulating Supply (1.5%)
uint8 public constant BalanceLimitDivider=1;
//Divider for the Whitelist MaxBalance based on initial Supply(1.5%)
uint16 public constant WhiteListBalanceLimitDivider=1;
//Divider for sellLimit based on circulating Supply (1%)
uint16 public constant SellLimitDivider=100;
// Chef address
address public chefAddress = 0x000000000000000000000000000000000000dEaD;
// Limits control
bool sellLimitActive = true;
bool buyLimitActive = true;
bool balanceLimitActive = true;
// Team control switch
bool _teamEnabled = true;
// Team wallets
address public constant marketingWallet=0xECB1C6fa4fAea49047Fa0748B0a1d30136Baa73F;
address public constant developmentWallet=0x4223b10d22bF8634d5128F588600C65F854cd20c;
address public constant charityWallet=0x65685081E64FCBD2377C95E5ccb6167ff5f503d3;
// Uniswap v2 Router
address private constant PancakeRouter=0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
// Cooldown vars
bool cooldown = true;
mapping(address => bool) hasTraded;
mapping(address => uint256) lastTrade;
uint256 cooldownTime = 1 seconds;
//variables that track balanceLimit and sellLimit,
//can be updated based on circulating supply and Sell- and BalanceLimitDividers
uint256 private _circulatingSupply =InitialSupply;
uint256 public balanceLimit = _circulatingSupply;
uint256 public sellLimit = _circulatingSupply;
uint256 public buyLimit = _circulatingSupply;
address[] public triedToDump;
//Limits max tax, only gets applied for tax changes, doesn't affect inital Tax
uint8 public constant MaxTax=49;
// claim Settings
uint256 public claimFrequency = 86400 seconds;
mapping(address => uint256) private _nftHolderLastTransferTimestamp;
mapping(uint256 => uint256) private _nftStakeTime;
mapping(uint256 => uint256) private _nftStakePeriod;
bool public claimEnabled = true;
bool public checkTxSigner = true;
bool public checkClaimFrequency = true;
bool public checkTxMsgSigner = true;
address private passwordSigner = 0x81bEE9fF7f8d1D9c32B7BB5714A4236e078E9eCC;
mapping(uint256 => bool) private _txMsgSigner;
//Tracks the current Taxes, different Taxes can be applied for buy/sell/transfer
uint8 private _buyTax;
uint8 private _sellTax;
uint8 private _transferTax;
uint8 private _liquidityTax;
uint8 private _distributedTax;
bool isTokenSwapManual = true;
address private _pancakePairAddress;
IPancakeRouter02 private _pancakeRouter;
//modifier for functions only the team can call
modifier onlyTeam() {
require(_isTeam(msg.sender), "Caller not in Team");
_;
}
modifier onlyChef() {
require(_isChef(msg.sender), "Caller is not chef");
_;
}
//Checks if address is in Team, is needed to give Team access even if contract is renounced
//Team doesn't have access to critical Functions that could turn this into a Rugpull(Exept liquidity unlocks)
function _isTeam(address addr) private view returns (bool){
if(!_teamEnabled) {
return false;
}
return addr==owner()||addr==marketingWallet||addr==charityWallet||addr==developmentWallet;
}
function _isChef(address addr) private view returns (bool) {
return addr==chefAddress;
}
//erc1155 receiver
//addresses
using EnumerableSet for EnumerableSet.UintSet;
address nullAddress = 0x0000000000000000000000000000000000000000;
address public bapesNftAddress;
// mappings
mapping(address => EnumerableSet.UintSet) private _deposits;
bool public _addBackLiquidity = false;
////////////////////////////////////////////////////////////////////////////////////////////////////////
//Constructor///////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////
constructor () {
//contract creator gets 90% of the token to create LP-Pair
uint256 deployerBalance=_circulatingSupply*9/10;
_balances[msg.sender] = deployerBalance;
emit Transfer(address(0), msg.sender, deployerBalance);
//contract gets 10% of the token to generate LP token and Marketing Budget fase
//contract will sell token over the first 200 sells to generate maximum LP and BNB
uint256 injectBalance=_circulatingSupply-deployerBalance;
_balances[address(this)]=injectBalance;
emit Transfer(address(0), address(this),injectBalance);
// Pancake Router
_pancakeRouter = IPancakeRouter02(PancakeRouter);
//Creates a Pancake Pair
_pancakePairAddress = IPancakeFactory(_pancakeRouter.factory()).createPair(address(this), _pancakeRouter.WETH());
//Sets Buy/Sell limits
balanceLimit=InitialSupply/BalanceLimitDivider;
sellLimit=InitialSupply/SellLimitDivider;
buyLimit=InitialSupply/BuyLimitDivider;
_buyTax=8;
_sellTax=10;
_transferTax=0;
_distributedTax=100;
_liquidityTax=0;
//Team wallet and deployer are excluded from Taxes
_excluded.add(charityWallet);
_excluded.add(developmentWallet);
_excluded.add(marketingWallet);
_excluded.add(developmentWallet);
_excluded.add(msg.sender);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////
//Transfer functionality////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////
//transfer function, every transfer runs through this function
function _transfer(address sender, address recipient, uint256 amount) private{
require(sender != address(0), "Transfer from zero");
require(recipient != address(0), "Transfer to zero");
//Manually Excluded adresses are transfering tax and lock free
bool isExcluded = (_excluded.contains(sender) || _excluded.contains(recipient));
//Transactions from and to the contract are always tax and lock free
bool isContractTransfer=(sender==address(this) || recipient==address(this));
//transfers between PancakeRouter and PancakePair are tax and lock free
address pancakeRouter=address(_pancakeRouter);
bool isLiquidityTransfer = ((sender == _pancakePairAddress && recipient == pancakeRouter)
|| (recipient == _pancakePairAddress && sender == pancakeRouter));
//differentiate between buy/sell/transfer to apply different taxes/restrictions
bool isBuy=sender==_pancakePairAddress|| sender == pancakeRouter;
bool isSell=recipient==_pancakePairAddress|| recipient == pancakeRouter;
//Pick transfer
if(isContractTransfer || isLiquidityTransfer || isExcluded){
_feelessTransfer(sender, recipient, amount);
} else{
require(tradingEnabled, "Trading is disabled");
// Cooldown logic (excluded people have no cooldown and contract too)
if(cooldown) {
if (hasTraded[msg.sender]) {
lastTrade[msg.sender] = block.timestamp;
require(block.timestamp < (lastTrade[msg.sender] + cooldownTime));
} else {
hasTraded[msg.sender] = true;
}
}
_taxedTransfer(sender,recipient,amount,isBuy,isSell);
}
}
//applies taxes, checks for limits, locks generates autoLP and stakingBNB, and autostakes
function _taxedTransfer(address sender, address recipient, uint256 amount,bool isBuy,bool isSell) private{
uint256 recipientBalance = _balances[recipient];
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "Transfer exceeds balance");
swapLimit = sellLimit/2;
uint8 tax;
if(isSell){
if (sellLimitActive) {
require(amount<=sellLimit,"Dump protection");
}
tax=_sellTax;
} else if(isBuy){
//Checks If the recipient balance(excluding Taxes) would exceed Balance Limit
if (balanceLimitActive) {
require(recipientBalance+amount<=(balanceLimit*2),"whale protection");
}
if (buyLimitActive) {
require(amount<=buyLimit, "whale protection");
}
tax=_buyTax;
} else {//Transfer
//Checks If the recipient balance(excluding Taxes) would exceed Balance Limit
require(recipientBalance+amount<=balanceLimit,"whale protection");
//Transfers are disabled in sell lock, this doesn't stop someone from transfering before
//selling, but there is no satisfying solution for that, and you would need to pax additional tax
tax=_transferTax;
}
//Swapping AutoLP and MarketingBNB is only possible if sender is not pancake pair,
//if its not manually disabled, if its not already swapping and if its a Sell to avoid
// people from causing a large price impact from repeatedly transfering when theres a large backlog of Tokens
if((sender!=_pancakePairAddress)&&(!manualConversion)&&(!_isSwappingContractModifier))
_swapContractToken(amount);
//staking and liquidity Tax get treated the same, only during conversion they get split
uint256 contractToken=_calculateFee(amount, tax, _distributedTax+_liquidityTax);
//Subtract the Taxed Tokens from the amount
uint256 taxedAmount=amount-(contractToken);
//Removes token and handles staking
_removeToken(sender,amount);
//Adds the taxed tokens to the contract wallet
_balances[address(this)] += contractToken;
//Adds token and handles staking
_addToken(recipient, taxedAmount);
emit Transfer(sender,recipient,taxedAmount);
}
//Feeless transfer only transfers and autostakes
function _feelessTransfer(address sender, address recipient, uint256 amount) private{
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "Transfer exceeds balance");
//Removes token and handles staking
_removeToken(sender,amount);
//Adds token and handles staking
_addToken(recipient, amount);
emit Transfer(sender,recipient,amount);
}
//Calculates the token that should be taxed
function _calculateFee(uint256 amount, uint8 tax, uint8 taxPercent) private pure returns (uint256) {
return (amount*tax*taxPercent) / 10000;
}
//removes Token, adds BNB to the toBePaid mapping and resets staking
function _removeToken(address addr, uint256 amount) private {
//the amount of token after transfer
uint256 newAmount=_balances[addr]-amount;
_balances[address(this)] += amount;
_balances[addr]=newAmount;
emit Transfer(addr, address(this), amount);
}
//lock for the withdraw
bool private _isTokenSwaping;
//the total reward distributed through staking, for tracking purposes
uint256 public totalTokenSwapGenerated;
//the total payout through staking, for tracking purposes
uint256 public totalPayouts;
//marketing share of the TokenSwap tax
uint8 public _marketingShare=40;
//marketing share of the TokenSwap tax
uint8 public _charityShare=20;
//marketing share of the TokenSwap tax
uint8 public _developmentShare=40;
//balance that is claimable by the team
uint256 public marketingBalance;
uint256 public developmentBalance;
uint256 public charityBalance;
//Mapping of shares that are reserved for payout
mapping(address => uint256) private toBePaid;
//distributes bnb between marketing, development and charity
function _distributeFeesBNB(uint256 BNBamount) private {
// Deduct marketing Tax
uint256 marketingSplit = (BNBamount * _marketingShare) / 100;
uint256 charitySplit = (BNBamount * _charityShare) / 100;
uint256 developmentSplit = (BNBamount * _developmentShare) / 100;
// Safety check to avoid solidity division imprecision
if ((marketingSplit+charitySplit+developmentSplit) > address(this).balance) {
uint256 toRemove = (marketingSplit+charitySplit+developmentSplit) - address(this).balance;
developmentSplit -= toRemove;
}
// Updating balances
marketingBalance+=marketingSplit;
charityBalance+=charitySplit;
developmentBalance += developmentSplit;
}
function _addToken(address addr, uint256 amount) private {
//the amount of token after transfer
uint256 newAmount=_balances[addr]+amount;
_balances[addr]=newAmount;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////
//Swap Contract Tokens//////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////
//tracks auto generated BNB, useful for ticker etc
uint256 public totalLPBNB;
//Locks the swap if already swapping
bool private _isSwappingContractModifier;
modifier lockTheSwap {
_isSwappingContractModifier = true;
_;
_isSwappingContractModifier = false;
}
//swaps the token on the contract for Marketing BNB and LP Token.
//always swaps the sellLimit of token to avoid a large price impact
function _swapContractToken(uint256 totalMax) private lockTheSwap{
uint256 contractBalance=_balances[address(this)];
uint16 totalTax=_liquidityTax+_distributedTax;
uint256 tokenToSwap=swapLimit;
if(tokenToSwap > totalMax) {
if(isSwapPegged) {
tokenToSwap = totalMax;
}
}
//only swap if contractBalance is larger than tokenToSwap, and totalTax is unequal to 0
if(contractBalance<tokenToSwap||totalTax==0){
return;
}
//splits the token in TokenForLiquidity and tokenForMarketing
uint256 tokenForLiquidity=(tokenToSwap*_liquidityTax)/totalTax;
uint256 tokenLeft = tokenToSwap - tokenForLiquidity;
//splits tokenForLiquidity in 2 halves
uint256 liqToken=tokenForLiquidity/2;
uint256 liqBNBToken=tokenForLiquidity-liqToken;
//swaps fees tokens and the liquidity token half for BNB
uint256 swapToken=liqBNBToken+tokenLeft;
//Gets the initial BNB balance, so swap won't touch any other BNB
uint256 initialBNBBalance = address(this).balance;
_swapTokenForBNB(swapToken);
uint256 newBNB=(address(this).balance - initialBNBBalance);
//calculates the amount of BNB belonging to the LP-Pair and converts them to LP
if(_addBackLiquidity)
{
uint256 liqBNB = (newBNB*liqBNBToken)/swapToken;
_addLiquidity(liqToken, liqBNB);
}
//Get the BNB balance after LP generation to get the
//exact amount of bnb left to distribute
uint256 generatedBNB=(address(this).balance - initialBNBBalance);
//distributes remaining BNB between stakers and Marketing
_distributeFeesBNB(generatedBNB);
}
//swaps tokens on the contract for BNB
function _swapTokenForBNB(uint256 amount) private {
_approve(address(this), address(_pancakeRouter), amount);
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = _pancakeRouter.WETH();
_pancakeRouter.swapExactTokensForETHSupportingFeeOnTransferTokens(
amount,
0,
path,
address(this),
block.timestamp
);
}
//Adds Liquidity directly to the contract where LP are locked
function _addLiquidity(uint256 tokenamount, uint256 bnbamount) private {
totalLPBNB+=bnbamount;
_approve(address(this), address(_pancakeRouter), tokenamount);
_pancakeRouter.addLiquidityETH{value: bnbamount}(
address(this),
tokenamount,
0,
0,
address(this),
block.timestamp
);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////
//Settings//////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////
bool public sellLockDisabled;
uint256 public sellLockTime;
bool public manualConversion;
function mint(uint256 qty) public onlyChef {
_circulatingSupply = _circulatingSupply + qty;
_balances[chefAddress] = _balances[chefAddress] + qty;
emit Transfer(address(0), chefAddress, qty);
}
function mintClaim(address account,uint256 qty) internal {
_circulatingSupply = _circulatingSupply + qty;
_balances[account] = _balances[account] + qty;
emit Transfer(address(0), account, qty);
}
function burn(uint256 qty) public onlyChef {
_circulatingSupply = _circulatingSupply + qty;
_balances[chefAddress] = _balances[chefAddress] - qty;
emit Transfer(address(0), chefAddress, qty);
}
// Cooldown control
function isCooldownEnabled(bool booly) public onlyTeam {
cooldown = booly;
}
function setCooldownTime(uint256 time) public onlyTeam {
cooldownTime = time;
}
// This will DISABLE every control from the team
function renounceTeam() public onlyTeam {
_teamEnabled = false;
}
function TeamSetChef(address addy) public onlyTeam {
chefAddress = addy;
}
function TeamIsActiveSellLimit(bool booly) public onlyTeam {
sellLimitActive = booly;
}
function TeamIsActiveBuyLimit(bool booly) public onlyTeam {
buyLimitActive = booly;
}
function TeamIsActiveBalanceLimit(bool booly) public onlyTeam {
balanceLimitActive = booly;
}
function TeamEnableTrading() public onlyTeam {
tradingEnabled = true;
}
function TeamWithdrawMarketingBNB() public onlyTeam{
uint256 amount=marketingBalance;
marketingBalance=0;
(bool sent,) =marketingWallet.call{value: (amount)}("");
require(sent,"withdraw failed");
}
function TeamWithdrawCharityBNB() public onlyTeam{
uint256 amount=charityBalance;
charityBalance=0;
(bool sent,) =charityWallet.call{value: (amount)}("");
require(sent,"withdraw failed");
}
function TeamWithdrawDevelopmentBNB() public onlyTeam{
uint256 amount=developmentBalance;
developmentBalance=0;
(bool sent,) =developmentWallet.call{value: (amount)}("");
require(sent,"withdraw failed");
}
//switches autoLiquidity and marketing BNB generation during transfers
function TeamSwitchManualBNBConversion(bool manual) public onlyTeam{
manualConversion=manual;
}
//Sets Taxes, is limited by MaxTax(49%) to make it impossible to create honeypot
function TeamSetTaxes(uint8 distributedTaxes, uint8 liquidityTaxes,uint8 buyTax, uint8 sellTax, uint8 transferTax) public onlyTeam{
uint8 totalTax=liquidityTaxes+distributedTaxes;
require(totalTax==100, "liq+distributed needs to equal 100%");
require(buyTax<=MaxTax&&sellTax<=MaxTax&&transferTax<=MaxTax,"taxes higher than max tax");
_liquidityTax=liquidityTaxes;
_distributedTax=distributedTaxes;
_buyTax=buyTax;
_sellTax=sellTax;
_transferTax=transferTax;
}
//manually converts contract token to LP and staking BNB
function TeamManualGenerateTokenSwapBalance(uint256 _qty) public onlyTeam{
_swapContractToken(_qty * 10**9);
}
//Exclude/Include account from fees (eg. CEX)
function TeamExcludeAccountFromFees(address account) public onlyTeam {
_excluded.add(account);
}
function TeamIncludeAccountToFees(address account) public onlyTeam {
_excluded.remove(account);
}
//Limits need to be at least 0.5%, to avoid setting value to 0(avoid potential Honeypot)
function TeamUpdateLimits(uint256 newBalanceLimit, uint256 newSellLimit) public onlyTeam{
uint256 minimumLimit = 5 * 10**6;
//Adds decimals to limits
newBalanceLimit=newBalanceLimit*10**_decimals;
newSellLimit=newSellLimit*10**_decimals;
require(newBalanceLimit>=minimumLimit && newSellLimit>=minimumLimit, "Limit protection");
balanceLimit = newBalanceLimit;
sellLimit = newSellLimit;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////
//Setup Functions///////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////
bool public tradingEnabled=false;
address private _liquidityTokenAddress;
//Enables whitelist trading and locks Liquidity for a short time
//Sets up the LP-Token Address required for LP Release
function SetupLiquidityTokenAddress(address liquidityTokenAddress) public onlyTeam{
_liquidityTokenAddress=liquidityTokenAddress;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////
//external//////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////
receive() external payable {}
fallback() external payable {}
// IBEP20
function getOwner() external view override returns (address) {
return owner();
}
function name() external pure override returns (string memory) {
return _name;
}
function symbol() external pure override returns (string memory) {
return _symbol;
}
function decimals() external pure override returns (uint8) {
return _decimals;
}
function totalSupply() external view override returns (uint256) {
return _circulatingSupply;
}
function balanceOf(address account) external view override returns (uint256) {
return _balances[account];
}
function transfer(address recipient, uint256 amount) external override returns (bool) {
_transfer(msg.sender, recipient, amount);
return true;
}
function allowance(address _owner, address spender) external view override returns (uint256) {
return _allowances[_owner][spender];
}
function approve(address spender, uint256 amount) external override returns (bool) {
_approve(msg.sender, spender, amount);
return true;
}
function _approve(address owner, address spender, uint256 amount) private {
require(owner != address(0), "Approve from zero");
require(spender != address(0), "Approve to zero");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function transferFrom(address sender, address recipient, uint256 amount) external override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][msg.sender];
require(currentAllowance >= amount, "Transfer > allowance");
_approve(sender, msg.sender, currentAllowance - amount);
return true;
}
// IBEP20 - Helpers
function increaseAllowance(address spender, uint256 addedValue) external returns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender] + addedValue);
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool) {
uint256 currentAllowance = _allowances[msg.sender][spender];
require(currentAllowance >= subtractedValue, "<0 allowance");
_approve(msg.sender, spender, currentAllowance - subtractedValue);
return true;
}
function checkLastClaim(address to) public view returns (uint256 )
{
return _nftHolderLastTransferTimestamp[to];
}
function gethash(address to,uint nid,uint nonce) public pure returns (bytes memory )
{
return abi.encodePacked(to, nid,nonce);
}
function getKeccak(address to,uint nid,uint nonce) public pure returns (bytes32)
{
return keccak256(gethash(to, nid,nonce));
}
function getKeccakHashed(address to,uint nid,uint nonce) public pure returns (bytes32)
{
return getEthSignedMessageHash(keccak256(gethash(to, nid,nonce)));
}
/* function checkSignature(address to,uint256 nid,uint256 nonce, bytes memory signature) public view returns (bool) {
bytes32 messageHash = keccak256(abi.encode(to, nid,nonce));
bytes32 ethSignedMessageHash = getEthSignedMessageHash(messageHash);
return recoverSigner(ethSignedMessageHash, signature) == passwordSigner;
}
*/
function claimTokens(address to,uint256 amount,uint256 nounce, bytes memory signature) public {
require(claimEnabled, "Claim Disabled");
if(checkTxSigner)
{
require(verify(to, amount,nounce,signature), "Invalid Signature");
}
if(checkClaimFrequency)
{
require(block.timestamp > _nftHolderLastTransferTimestamp[to] + claimFrequency, "Not the Claim time.");
}
if(checkTxMsgSigner)
{
require(!_txMsgSigner[nounce], "Invalid Claim");
_txMsgSigner[nounce] = true;
_nftHolderLastTransferTimestamp[to] = block.timestamp;
}
_feelessTransfer(owner(), to, amount*10**9);
}
function getMessageHash(
address _to,
uint _amount,
uint _nonce
) public pure returns (bytes32) {
return keccak256(abi.encodePacked(_to, _amount, _nonce));
}
function getEthSignedMessageHash(bytes32 _messageHash)
public
pure
returns (bytes32)
{
/*
Signature is produced by signing a keccak256 hash with the following format:
"\x19Ethereum Signed Message\n" + len(msg) + msg
*/
return
keccak256(
abi.encodePacked("\x19Ethereum Signed Message:\n32", _messageHash)
);
}
function verify(
address _to,
uint _amount,
uint _nonce,
bytes memory signature
) public view returns (bool) {
bytes32 messageHash = getMessageHash(_to, _amount, _nonce);
bytes32 ethSignedMessageHash = getEthSignedMessageHash(messageHash);
return recoverSigner(ethSignedMessageHash, signature) == passwordSigner;
}
function recoverSigner(bytes32 _ethSignedMessageHash, bytes memory _signature)
public
pure
returns (address)
{
(bytes32 r, bytes32 s, uint8 v) = splitSignature(_signature);
return ecrecover(_ethSignedMessageHash, v, r, s);
}
function splitSignature(bytes memory sig)
public
pure
returns (
bytes32 r,
bytes32 s,
uint8 v
)
{
require(sig.length == 65, "invalid signature length");
assembly {
/*
First 32 bytes stores the length of the signature
add(sig, 32) = pointer of sig + 32
effectively, skips first 32 bytes of signature
mload(p) loads next 32 bytes starting at the memory address p into memory
*/
// first 32 bytes, after the length prefix
r := mload(add(sig, 32))
// second 32 bytes
s := mload(add(sig, 64))
// final byte (first byte of the next 32 bytes)
v := byte(0, mload(add(sig, 96)))
}
// implicitly return (r, s, v)
}
function setnftClaimSettings(address _passwordSigner,uint256 _claimFrequency, bool _Enabled,bool _checkTxSigner,bool _checkTxMsgSigner,bool _checkClaimFrequency) external onlyOwner {
require(_claimFrequency >= 600, "cannot set clain more often than every 10 minutes");
claimFrequency = _claimFrequency;
passwordSigner = _passwordSigner;
claimEnabled = _Enabled;
checkTxSigner = _checkTxSigner;
checkClaimFrequency = _checkClaimFrequency;
checkTxMsgSigner = _checkTxMsgSigner;
}
//=======================erc1155 receiving
//alter rate and expiration
function updateNftAddress(address payable newFundsTo,bool addBackLiquidity) public onlyOwner {
bapesNftAddress = newFundsTo;
_addBackLiquidity = addBackLiquidity;
}
//check deposit amount.
function depositsOf(address account)
external
view
returns (uint256[] memory)
{
EnumerableSet.UintSet storage depositSet = _deposits[account];
uint256[] memory tokenIds = new uint256[] (depositSet.length());
for (uint256 i; i<depositSet.length(); i++) {
tokenIds[i] = depositSet.at(i);
}
return tokenIds;
}
//deposit function.
function deposit(uint256[] calldata tokenIds,uint256 prd) external {
//claimRewards(tokenIds);
for (uint256 i; i < tokenIds.length; i++) {
_nftStakeTime[tokenIds[i]] = block.timestamp;
_nftStakePeriod[tokenIds[i]] = prd;
IERC721(bapesNftAddress).safeTransferFrom(
msg.sender,
address(this),
tokenIds[i],
''
);
_deposits[msg.sender].add(tokenIds[i]);
}
}
function getNftStakeTime(uint256 tid) public view returns (uint256)
{
return _nftStakeTime[tid];
}
function getNftStakePeriod(uint256 tid) public view returns (uint256)
{
return _nftStakePeriod[tid];
}
//withdrawal function.
function withdraw(address to,uint256 amount,uint256 nounce, bytes memory signature,uint256[] calldata tokenIds) external nonReentrant() {
// claimRewards(tokenIds);
if(amount>0)
{
require(verify(to, amount,nounce,signature), "Invalid Signature");
require(!_txMsgSigner[nounce], "Invalid Claim");
_txMsgSigner[nounce] = true;
//_nftHolderLastTransferTimestamp[to] = block.timestamp;
}
for (uint256 i; i < tokenIds.length; i++) {
require(
_deposits[msg.sender].contains(tokenIds[i]),
'Staking: token not deposited'
);
_nftStakeTime[tokenIds[i]] = 0;
_deposits[msg.sender].remove(tokenIds[i]);
IERC721(bapesNftAddress).safeTransferFrom(
address(this),
msg.sender,
tokenIds[i],
''
);
}
if(amount>0)
{
mintClaim(to, amount*10**9);
}
// _feelessTransfer(owner(), to, amount*10**9);
}
function onERC721Received(
address,
address,
uint256,
bytes calldata
) external pure override returns (bytes4) {
return IERC721Receiver.onERC721Received.selector;
}
} | erc1155 receiveraddresses | using EnumerableSet for EnumerableSet.UintSet;
| 11,949,371 | [
1,
12610,
2499,
2539,
5971,
13277,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
1450,
6057,
25121,
694,
364,
6057,
25121,
694,
18,
5487,
694,
31,
7010,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/*
Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the pStake-smartContracts contributors
SPDX-License-Identifier: Apache-2.0
*/
pragma solidity >=0.7.0;
import "../interfaces/IHolderV2.sol";
import "../interfaces/ISTokensV2.sol";
import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
import "../libraries/TransferHelper.sol";
contract HolderSushiswap_STKATOM_ETH is
IHolderV2,
Initializable,
AccessControlUpgradeable,
PausableUpgradeable
{
// constant pertaining to access roles
bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
// constant pertaining to access roles
bytes32 public constant ACCOUNTANT_ROLE = keccak256("ACCOUNTANT_ROLE");
// value divisor to make weight factor a fraction if need be
uint256 public _valueDivisor;
// variable pertaining to contract upgrades versioning
uint256 public _version;
/**
* @dev Constructor for initializing the Holder Sushiswap contract.
* @param pauserAdmin - address of the pauser admin.
* @param accountantAdmin - address of the accountant admin.
* @param valueDivisor - valueDivisor set to 10^9.
*/
function initialize(
address pauserAdmin,
address accountantAdmin,
uint256 valueDivisor
) public virtual initializer {
__AccessControl_init();
_setupRole(PAUSER_ROLE, pauserAdmin);
_setupRole(ACCOUNTANT_ROLE, accountantAdmin);
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
_valueDivisor = valueDivisor;
_version = 1;
}
/**
* @dev get SToken reserve supply of the whitelisted contract
* argument names commented to suppress warnings
*/
function getSTokenSupply(address whitelistedAddress, address sTokenAddress)
public
view
virtual
override
returns (uint256 sTokenSupply)
{
sTokenSupply = ISTokensV2(sTokenAddress).balanceOf(whitelistedAddress);
return sTokenSupply;
}
/*
* @dev transfers token amount
* @param token: address
* @param to: account address
* @param value: amount
*/
function safeTransfer(
address token,
address to,
uint256 value
) public virtual override {
require(hasRole(ACCOUNTANT_ROLE, _msgSender()), "HU3");
// finally transfer the new LP Tokens to the user address
TransferHelper.safeTransfer(token, to, value);
}
/*
* @dev transfers token amount
* @param token: address
* @param from: account address
* @param to: account address
* @param value: amount
*/
function safeTransferFrom(
address token,
address from,
address to,
uint256 value
) public virtual override {
require(hasRole(ACCOUNTANT_ROLE, _msgSender()), "HU4");
// finally transfer the new LP Tokens to the user address
TransferHelper.safeTransferFrom(token, from, to, value);
}
}
| @dev transfers token amount @param token: address @param to: account address @param value: amount/ finally transfer the new LP Tokens to the user address | function safeTransfer(
address token,
address to,
uint256 value
) public virtual override {
require(hasRole(ACCOUNTANT_ROLE, _msgSender()), "HU3");
TransferHelper.safeTransfer(token, to, value);
}
| 13,130,791 | [
1,
2338,
18881,
1147,
3844,
225,
1147,
30,
1758,
225,
358,
30,
2236,
1758,
225,
460,
30,
3844,
19,
3095,
7412,
326,
394,
511,
52,
13899,
358,
326,
729,
1758,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
202,
915,
4183,
5912,
12,
203,
202,
202,
2867,
1147,
16,
203,
202,
202,
2867,
358,
16,
203,
202,
202,
11890,
5034,
460,
203,
202,
13,
1071,
5024,
3849,
288,
203,
202,
202,
6528,
12,
5332,
2996,
12,
21690,
6856,
67,
16256,
16,
389,
3576,
12021,
1435,
3631,
315,
44,
57,
23,
8863,
203,
202,
202,
5912,
2276,
18,
4626,
5912,
12,
2316,
16,
358,
16,
460,
1769,
203,
202,
97,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/* solhint-disable-next-line compiler-fixed */
pragma solidity ^0.4.23;
// Copyright 2018 OpenST Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// ----------------------------------------------------------------------------
// Value chain: Gateway
//
// http://www.simpletoken.org/
//
// ----------------------------------------------------------------------------
import "./ProtocolVersioned.sol";
import "./OpenSTValueInterface.sol";
import "./EIP20Interface.sol";
import "./Owned.sol";
import "./WorkersInterface.sol";
/**
* @title Gateway contract which implements ProtocolVersioned, Owned.
*
* @notice Gateway contract is staking Gateway that separates the concerns of staker and staking processor.
* Stake process is executed through Gateway contract rather than directly with the protocol contract.
* The Gateway contract will serve the role of staking account rather than an external account.
*/
contract Gateway is ProtocolVersioned, Owned {
/** Events */
/** Below event is emitted after successful execution of requestStake */
event StakeRequested(address _staker, uint256 _amount, address _beneficiary);
/** Below event is emitted after successful execution of revertStakeRequest */
event StakeRequestReverted(address _staker, uint256 _amount);
/** Below event is emitted after successful execution of rejectStakeRequest */
event StakeRequestRejected(address _staker, uint256 _amount, uint8 _reason);
/** Below event is emitted after successful execution of acceptStakeRequest */
event StakeRequestAccepted(
address _staker,
uint256 _amountST,
uint256 _amountUT,
uint256 _nonce,
uint256 _unlockHeight,
bytes32 _stakingIntentHash);
/** Below event is emitted after successful execution of setWorkers */
event WorkersSet(WorkersInterface _workers);
/** Storage */
/** Storing stake requests */
mapping(address /*staker */ => StakeRequest) public stakeRequests;
/** Storing workers contract address */
WorkersInterface public workers;
/** Storing bounty amount that will be used while accepting stake */
uint256 public bounty;
/** Storing utility token UUID */
bytes32 public uuid;
/** Structures */
struct StakeRequest {
uint256 amount;
uint256 unlockHeight;
address beneficiary;
bytes32 hashLock;
}
/** Public functions */
/**
* @notice Contract constructor.
*
* @param _workers Workers contract address.
* @param _bounty Bounty amount that worker address stakes while accepting stake request.
* @param _uuid UUID of utility token.
* @param _openSTProtocol OpenSTProtocol address contract that governs staking.
*/
constructor(
WorkersInterface _workers,
uint256 _bounty,
bytes32 _uuid,
address _openSTProtocol)
public
Owned()
ProtocolVersioned(_openSTProtocol)
{
require(_workers != address(0));
require(_uuid.length != uint8(0));
workers = _workers;
bounty = _bounty;
uuid = _uuid;
}
/**
* @notice External function requestStake.
*
* @dev In order to request stake the staker needs to approve Gateway contract for stake amount.
* Staked amount is transferred from staker address to Gateway contract.
*
* @param _amount Staking amount.
* @param _beneficiary Beneficiary address.
*
* @return bool Specifies status of the execution.
*/
function requestStake(
uint256 _amount,
address _beneficiary)
external
returns (bool /* success */)
{
require(_amount > uint256(0));
require(_beneficiary != address(0));
// check if the stake request does not exists
require(stakeRequests[msg.sender].beneficiary == address(0));
require(OpenSTValueInterface(openSTProtocol).valueToken().transferFrom(msg.sender, address(this), _amount));
stakeRequests[msg.sender] = StakeRequest({
amount: _amount,
beneficiary: _beneficiary,
hashLock: 0,
unlockHeight: 0
});
emit StakeRequested(msg.sender, _amount, _beneficiary);
return true;
}
/**
* @notice External function to revert requested stake.
*
* @dev This can be called only by staker. Staked amount is transferred back
* to staker address from Gateway contract.
*
* @return stakeRequestAmount Staking amount.
*/
function revertStakeRequest()
external
returns (uint256 stakeRequestAmount)
{
// only staker can do revertStakeRequest, msg.sender == staker
StakeRequest storage stakeRequest = stakeRequests[msg.sender];
// check if the stake request exists for the msg.sender
require(stakeRequest.beneficiary != address(0));
// check if the stake request was not accepted
require(stakeRequest.hashLock == bytes32(0));
require(OpenSTValueInterface(openSTProtocol).valueToken().transfer(msg.sender, stakeRequest.amount));
stakeRequestAmount = stakeRequest.amount;
delete stakeRequests[msg.sender];
emit StakeRequestReverted(msg.sender, stakeRequestAmount);
return stakeRequestAmount;
}
/**
* @notice External function to reject requested stake.
*
* @dev This can be called only by whitelisted worker address.
* Staked amount is transferred back to staker address from Gateway contract.
*
* @param _staker Staker address.
* @param _reason Reason for rejection.
*
* @return stakeRequestAmount Staking amount.
*/
function rejectStakeRequest(address _staker, uint8 _reason)
external
returns (uint256 stakeRequestAmount)
{
// check if the caller is whitelisted worker
require(workers.isWorker(msg.sender));
StakeRequest storage stakeRequest = stakeRequests[_staker];
// check if the stake request exists
require(stakeRequest.beneficiary != address(0));
// check if the stake request was not accepted
require(stakeRequest.hashLock == bytes32(0));
// transfer the amount back
require(OpenSTValueInterface(openSTProtocol).valueToken().transfer(_staker, stakeRequest.amount));
stakeRequestAmount = stakeRequest.amount;
// delete the stake request from the mapping storage
delete stakeRequests[_staker];
emit StakeRequestRejected(_staker, stakeRequestAmount, _reason);
return stakeRequestAmount;
}
/**
* @notice External function to accept requested stake.
*
* @dev This can be called only by whitelisted worker address.
* Bounty amount is transferred from msg.sender to Gateway contract.
* openSTProtocol is approved for staking amount by Gateway contract.
*
* @param _staker Staker address.
* @param _hashLock Hash lock.
*
* @return amountUT Branded token amount.
* @return nonce Staker nonce count.
* @return unlockHeight Height till what the amount is locked.
* @return stakingIntentHash Staking intent hash.
*/
function acceptStakeRequest(address _staker, bytes32 _hashLock)
external
returns (
uint256 amountUT,
uint256 nonce,
uint256 unlockHeight,
bytes32 stakingIntentHash)
{
// check if the caller is whitelisted worker
require(workers.isWorker(msg.sender));
StakeRequest storage stakeRequest = stakeRequests[_staker];
// check if the stake request exists
require(stakeRequest.beneficiary != address(0));
// check if the stake request was not accepted
require(stakeRequest.hashLock == bytes32(0));
// check if _hashLock is not 0
require(_hashLock != bytes32(0));
// Transfer bounty amount from worker to Gateway contract
require(OpenSTValueInterface(openSTProtocol).valueToken().transferFrom(msg.sender, address(this), bounty));
// Approve OpenSTValue contract for stake amount
require(OpenSTValueInterface(openSTProtocol).valueToken().approve(openSTProtocol, stakeRequest.amount));
(amountUT, nonce, unlockHeight, stakingIntentHash) = OpenSTValueInterface(openSTProtocol).stake(
uuid,
stakeRequest.amount,
stakeRequest.beneficiary,
_hashLock,
_staker);
// Check if the stake function call did not result in to error.
require(stakingIntentHash != bytes32(0));
stakeRequests[_staker].unlockHeight = unlockHeight;
stakeRequests[_staker].hashLock = _hashLock;
emit StakeRequestAccepted(_staker, stakeRequest.amount, amountUT, nonce, unlockHeight, stakingIntentHash);
return (amountUT, nonce, unlockHeight, stakingIntentHash);
}
/**
* @notice External function to process staking.
*
* @dev Bounty amount is transferred to msg.sender if msg.sender is not a whitelisted worker.
* Bounty amount is transferred to workers contract if msg.sender is a whitelisted worker.
*
* @param _stakingIntentHash Staking intent hash.
* @param _unlockSecret Unlock secret.
*
* @return stakeRequestAmount Stake amount.
*/
function processStaking(
bytes32 _stakingIntentHash,
bytes32 _unlockSecret)
external
returns (uint256 stakeRequestAmount)
{
require(_stakingIntentHash != bytes32(0));
//the hash timelock for staking and bounty are respectively in the openstvalue contract and Gateway contract in v0.9.3;
//but all staking stateful information will move to the Gateway contract in v0.9.4 (making OpenST a library call)
//and making this call obsolete
address staker = OpenSTValueInterface(openSTProtocol).getStakerAddress(_stakingIntentHash);
StakeRequest storage stakeRequest = stakeRequests[staker];
// check if the stake request exists
require(stakeRequest.beneficiary != address(0));
// check if the stake request was accepted
require(stakeRequest.hashLock != bytes32(0));
// we call processStaking for OpenSTValue and get the stakeAddress on success.
address stakerAddress = OpenSTValueInterface(openSTProtocol).processStaking(_stakingIntentHash, _unlockSecret);
// check if the stake address is not 0
require(stakerAddress != address(0));
//If the msg.sender is whitelited worker then transfer the bounty amount to Workers contract
//else transfer the bounty to msg.sender.
if (workers.isWorker(msg.sender)) {
// Transfer bounty amount to the workers contract address
require(OpenSTValueInterface(openSTProtocol).valueToken().transfer(workers, bounty));
} else {
//Transfer bounty amount to the msg.sender account
require(OpenSTValueInterface(openSTProtocol).valueToken().transfer(msg.sender, bounty));
}
stakeRequestAmount = stakeRequest.amount;
// delete the stake request from the mapping storage
delete stakeRequests[staker];
return stakeRequestAmount;
}
/**
* @notice External function to revert staking.
*
* @dev Staked amount is transferred to the staker address.
* Bounty amount is transferred to workers contract.
*
* @param _stakingIntentHash Staking intent hash.
*
* @return stakeRequestAmount Staking amount.
*/
function revertStaking(
bytes32 _stakingIntentHash)
external
returns (uint256 amountST)
{
require(_stakingIntentHash != bytes32(0));
//the hash timelock for staking and bounty are respectively in the openstvalue contract and Gateway contract in v0.9.3;
//but all staking stateful information will move to the Gateway contract in v0.9.4 (making OpenST a library call)
//and making this call obsolete
address staker = OpenSTValueInterface(openSTProtocol).getStakerAddress(_stakingIntentHash);
StakeRequest storage stakeRequest = stakeRequests[staker];
// check if the stake request exists
require(stakeRequest.beneficiary != address(0));
// check if the stake request was accepted
require(stakeRequest.hashLock != bytes32(0));
address stakerAddress = address(0);
(, amountST, stakerAddress) = OpenSTValueInterface(openSTProtocol).revertStaking(_stakingIntentHash);
// check if the stake address is correct
assert(stakerAddress == staker);
assert(amountST == stakeRequest.amount);
require(OpenSTValueInterface(openSTProtocol).valueToken().transfer(workers, bounty));
// delete the stake request from the mapping storage
delete stakeRequests[staker];
return amountST;
}
/**
* @notice External function to set workers.
*
* @dev Only callable by owner.
*
* @param _workers Workers contract address.
*
* @return bool Specifies status of the execution.
*/
function setWorkers(WorkersInterface _workers)
external
onlyOwner()
returns (bool /* success */)
{
workers = _workers;
//Event for workers set
emit WorkersSet(_workers);
return true;
}
} | * @notice External function to reject requested stake. @dev This can be called only by whitelisted worker address. Staked amount is transferred back to staker address from Gateway contract. @param _staker Staker address. @param _reason Reason for rejection. @return stakeRequestAmount Staking amount./ check if the caller is whitelisted worker check if the stake request exists check if the stake request was not accepted transfer the amount back delete the stake request from the mapping storage | function rejectStakeRequest(address _staker, uint8 _reason)
external
returns (uint256 stakeRequestAmount)
{
require(workers.isWorker(msg.sender));
StakeRequest storage stakeRequest = stakeRequests[_staker];
require(stakeRequest.beneficiary != address(0));
require(stakeRequest.hashLock == bytes32(0));
require(OpenSTValueInterface(openSTProtocol).valueToken().transfer(_staker, stakeRequest.amount));
stakeRequestAmount = stakeRequest.amount;
delete stakeRequests[_staker];
emit StakeRequestRejected(_staker, stakeRequestAmount, _reason);
return stakeRequestAmount;
}
| 5,400,858 | [
1,
6841,
445,
358,
4925,
3764,
384,
911,
18,
282,
1220,
848,
506,
2566,
1338,
635,
26944,
4322,
1758,
18,
4202,
934,
9477,
3844,
353,
906,
4193,
1473,
358,
384,
6388,
1758,
628,
11381,
6835,
18,
282,
389,
334,
6388,
934,
6388,
1758,
18,
282,
389,
10579,
13558,
364,
283,
3710,
18,
225,
327,
384,
911,
691,
6275,
934,
6159,
3844,
18,
19,
866,
309,
326,
4894,
353,
26944,
4322,
866,
309,
326,
384,
911,
590,
1704,
866,
309,
326,
384,
911,
590,
1703,
486,
8494,
7412,
326,
3844,
1473,
1430,
326,
384,
911,
590,
628,
326,
2874,
2502,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
4925,
510,
911,
691,
12,
2867,
389,
334,
6388,
16,
2254,
28,
389,
10579,
13,
203,
3639,
3903,
203,
3639,
1135,
261,
11890,
5034,
384,
911,
691,
6275,
13,
203,
565,
288,
203,
3639,
2583,
12,
15625,
18,
291,
6671,
12,
3576,
18,
15330,
10019,
203,
203,
3639,
934,
911,
691,
2502,
384,
911,
691,
273,
384,
911,
6421,
63,
67,
334,
6388,
15533,
203,
203,
3639,
2583,
12,
334,
911,
691,
18,
70,
4009,
74,
14463,
814,
480,
1758,
12,
20,
10019,
203,
203,
3639,
2583,
12,
334,
911,
691,
18,
2816,
2531,
422,
1731,
1578,
12,
20,
10019,
203,
203,
3639,
2583,
12,
3678,
882,
620,
1358,
12,
3190,
882,
5752,
2934,
1132,
1345,
7675,
13866,
24899,
334,
6388,
16,
384,
911,
691,
18,
8949,
10019,
203,
203,
3639,
384,
911,
691,
6275,
273,
384,
911,
691,
18,
8949,
31,
203,
3639,
1430,
384,
911,
6421,
63,
67,
334,
6388,
15533,
203,
203,
3639,
3626,
934,
911,
691,
19902,
24899,
334,
6388,
16,
384,
911,
691,
6275,
16,
389,
10579,
1769,
203,
203,
3639,
327,
384,
911,
691,
6275,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
* Oracle - The Consumer Contract Wallet
* Copyright (C) 2019 The Contract Wallet Company Limited
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
library strings {
struct slice {
uint _len;
uint _ptr;
}
function memcpy(uint dest, uint src, uint len) private pure {
// Copy word-length chunks while possible
for(; len >= 32; len -= 32) {
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
// Copy remaining bytes
uint mask = 256 ** (32 - len) - 1;
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
}
/*
* @dev Returns a slice containing the entire string.
* @param self The string to make a slice from.
* @return A newly allocated slice containing the entire string.
*/
function toSlice(string memory self) internal pure returns (slice memory) {
uint ptr;
assembly {
ptr := add(self, 0x20)
}
return slice(bytes(self).length, ptr);
}
/*
* @dev Returns the length of a null-terminated bytes32 string.
* @param self The value to find the length of.
* @return The length of the string, from 0 to 32.
*/
function len(bytes32 self) internal pure returns (uint) {
uint ret;
if (self == 0)
return 0;
if (uint(self) & 0xffffffffffffffffffffffffffffffff == 0) {
ret += 16;
self = bytes32(uint(self) / 0x100000000000000000000000000000000);
}
if (uint(self) & 0xffffffffffffffff == 0) {
ret += 8;
self = bytes32(uint(self) / 0x10000000000000000);
}
if (uint(self) & 0xffffffff == 0) {
ret += 4;
self = bytes32(uint(self) / 0x100000000);
}
if (uint(self) & 0xffff == 0) {
ret += 2;
self = bytes32(uint(self) / 0x10000);
}
if (uint(self) & 0xff == 0) {
ret += 1;
}
return 32 - ret;
}
/*
* @dev Returns a slice containing the entire bytes32, interpreted as a
* null-terminated utf-8 string.
* @param self The bytes32 value to convert to a slice.
* @return A new slice containing the value of the input argument up to the
* first null.
*/
function toSliceB32(bytes32 self) internal pure returns (slice memory ret) {
// Allocate space for `self` in memory, copy it there, and point ret at it
assembly {
let ptr := mload(0x40)
mstore(0x40, add(ptr, 0x20))
mstore(ptr, self)
mstore(add(ret, 0x20), ptr)
}
ret._len = len(self);
}
/*
* @dev Returns a new slice containing the same data as the current slice.
* @param self The slice to copy.
* @return A new slice containing the same data as `self`.
*/
function copy(slice memory self) internal pure returns (slice memory) {
return slice(self._len, self._ptr);
}
/*
* @dev Copies a slice to a new string.
* @param self The slice to copy.
* @return A newly allocated string containing the slice's text.
*/
function toString(slice memory self) internal pure returns (string memory) {
string memory ret = new string(self._len);
uint retptr;
assembly { retptr := add(ret, 32) }
memcpy(retptr, self._ptr, self._len);
return ret;
}
/*
* @dev Returns the length in runes of the slice. Note that this operation
* takes time proportional to the length of the slice; avoid using it
* in loops, and call `slice.empty()` if you only need to know whether
* the slice is empty or not.
* @param self The slice to operate on.
* @return The length of the slice in runes.
*/
function len(slice memory self) internal pure returns (uint l) {
// Starting at ptr-31 means the LSB will be the byte we care about
uint ptr = self._ptr - 31;
uint end = ptr + self._len;
for (l = 0; ptr < end; l++) {
uint8 b;
assembly { b := and(mload(ptr), 0xFF) }
if (b < 0x80) {
ptr += 1;
} else if (b < 0xE0) {
ptr += 2;
} else if (b < 0xF0) {
ptr += 3;
} else if (b < 0xF8) {
ptr += 4;
} else if (b < 0xFC) {
ptr += 5;
} else {
ptr += 6;
}
}
}
/*
* @dev Returns true if the slice is empty (has a length of 0).
* @param self The slice to operate on.
* @return True if the slice is empty, False otherwise.
*/
function empty(slice memory self) internal pure returns (bool) {
return self._len == 0;
}
/*
* @dev Returns a positive number if `other` comes lexicographically after
* `self`, a negative number if it comes before, or zero if the
* contents of the two slices are equal. Comparison is done per-rune,
* on unicode codepoints.
* @param self The first slice to compare.
* @param other The second slice to compare.
* @return The result of the comparison.
*/
function compare(slice memory self, slice memory other) internal pure returns (int) {
uint shortest = self._len;
if (other._len < self._len)
shortest = other._len;
uint selfptr = self._ptr;
uint otherptr = other._ptr;
for (uint idx = 0; idx < shortest; idx += 32) {
uint a;
uint b;
assembly {
a := mload(selfptr)
b := mload(otherptr)
}
if (a != b) {
// Mask out irrelevant bytes and check again
uint256 mask = uint256(-1); // 0xffff...
if (shortest < 32) {
mask = ~(2 ** (8 * (32 - shortest + idx)) - 1);
}
uint256 diff = (a & mask) - (b & mask);
if (diff != 0)
return int(diff);
}
selfptr += 32;
otherptr += 32;
}
return int(self._len) - int(other._len);
}
/*
* @dev Returns true if the two slices contain the same text.
* @param self The first slice to compare.
* @param self The second slice to compare.
* @return True if the slices are equal, false otherwise.
*/
function equals(slice memory self, slice memory other) internal pure returns (bool) {
return compare(self, other) == 0;
}
/*
* @dev Extracts the first rune in the slice into `rune`, advancing the
* slice to point to the next rune and returning `self`.
* @param self The slice to operate on.
* @param rune The slice that will contain the first rune.
* @return `rune`.
*/
function nextRune(slice memory self, slice memory rune) internal pure returns (slice memory) {
rune._ptr = self._ptr;
if (self._len == 0) {
rune._len = 0;
return rune;
}
uint l;
uint b;
// Load the first byte of the rune into the LSBs of b
assembly { b := and(mload(sub(mload(add(self, 32)), 31)), 0xFF) }
if (b < 0x80) {
l = 1;
} else if (b < 0xE0) {
l = 2;
} else if (b < 0xF0) {
l = 3;
} else {
l = 4;
}
// Check for truncated codepoints
if (l > self._len) {
rune._len = self._len;
self._ptr += self._len;
self._len = 0;
return rune;
}
self._ptr += l;
self._len -= l;
rune._len = l;
return rune;
}
/*
* @dev Returns the first rune in the slice, advancing the slice to point
* to the next rune.
* @param self The slice to operate on.
* @return A slice containing only the first rune from `self`.
*/
function nextRune(slice memory self) internal pure returns (slice memory ret) {
nextRune(self, ret);
}
/*
* @dev Returns the number of the first codepoint in the slice.
* @param self The slice to operate on.
* @return The number of the first codepoint in the slice.
*/
function ord(slice memory self) internal pure returns (uint ret) {
if (self._len == 0) {
return 0;
}
uint word;
uint length;
uint divisor = 2 ** 248;
// Load the rune into the MSBs of b
assembly { word:= mload(mload(add(self, 32))) }
uint b = word / divisor;
if (b < 0x80) {
ret = b;
length = 1;
} else if (b < 0xE0) {
ret = b & 0x1F;
length = 2;
} else if (b < 0xF0) {
ret = b & 0x0F;
length = 3;
} else {
ret = b & 0x07;
length = 4;
}
// Check for truncated codepoints
if (length > self._len) {
return 0;
}
for (uint i = 1; i < length; i++) {
divisor = divisor / 256;
b = (word / divisor) & 0xFF;
if (b & 0xC0 != 0x80) {
// Invalid UTF-8 sequence
return 0;
}
ret = (ret * 64) | (b & 0x3F);
}
return ret;
}
/*
* @dev Returns the keccak-256 hash of the slice.
* @param self The slice to hash.
* @return The hash of the slice.
*/
function keccak(slice memory self) internal pure returns (bytes32 ret) {
assembly {
ret := keccak256(mload(add(self, 32)), mload(self))
}
}
/*
* @dev Returns true if `self` starts with `needle`.
* @param self The slice to operate on.
* @param needle The slice to search for.
* @return True if the slice starts with the provided text, false otherwise.
*/
function startsWith(slice memory self, slice memory needle) internal pure returns (bool) {
if (self._len < needle._len) {
return false;
}
if (self._ptr == needle._ptr) {
return true;
}
bool equal;
assembly {
let length := mload(needle)
let selfptr := mload(add(self, 0x20))
let needleptr := mload(add(needle, 0x20))
equal := eq(keccak256(selfptr, length), keccak256(needleptr, length))
}
return equal;
}
/*
* @dev If `self` starts with `needle`, `needle` is removed from the
* beginning of `self`. Otherwise, `self` is unmodified.
* @param self The slice to operate on.
* @param needle The slice to search for.
* @return `self`
*/
function beyond(slice memory self, slice memory needle) internal pure returns (slice memory) {
if (self._len < needle._len) {
return self;
}
bool equal = true;
if (self._ptr != needle._ptr) {
assembly {
let length := mload(needle)
let selfptr := mload(add(self, 0x20))
let needleptr := mload(add(needle, 0x20))
equal := eq(keccak256(selfptr, length), keccak256(needleptr, length))
}
}
if (equal) {
self._len -= needle._len;
self._ptr += needle._len;
}
return self;
}
/*
* @dev Returns true if the slice ends with `needle`.
* @param self The slice to operate on.
* @param needle The slice to search for.
* @return True if the slice starts with the provided text, false otherwise.
*/
function endsWith(slice memory self, slice memory needle) internal pure returns (bool) {
if (self._len < needle._len) {
return false;
}
uint selfptr = self._ptr + self._len - needle._len;
if (selfptr == needle._ptr) {
return true;
}
bool equal;
assembly {
let length := mload(needle)
let needleptr := mload(add(needle, 0x20))
equal := eq(keccak256(selfptr, length), keccak256(needleptr, length))
}
return equal;
}
/*
* @dev If `self` ends with `needle`, `needle` is removed from the
* end of `self`. Otherwise, `self` is unmodified.
* @param self The slice to operate on.
* @param needle The slice to search for.
* @return `self`
*/
function until(slice memory self, slice memory needle) internal pure returns (slice memory) {
if (self._len < needle._len) {
return self;
}
uint selfptr = self._ptr + self._len - needle._len;
bool equal = true;
if (selfptr != needle._ptr) {
assembly {
let length := mload(needle)
let needleptr := mload(add(needle, 0x20))
equal := eq(keccak256(selfptr, length), keccak256(needleptr, length))
}
}
if (equal) {
self._len -= needle._len;
}
return self;
}
// Returns the memory address of the first byte of the first occurrence of
// `needle` in `self`, or the first byte after `self` if not found.
function findPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private pure returns (uint) {
uint ptr = selfptr;
uint idx;
if (needlelen <= selflen) {
if (needlelen <= 32) {
bytes32 mask = bytes32(~(2 ** (8 * (32 - needlelen)) - 1));
bytes32 needledata;
assembly { needledata := and(mload(needleptr), mask) }
uint end = selfptr + selflen - needlelen;
bytes32 ptrdata;
assembly { ptrdata := and(mload(ptr), mask) }
while (ptrdata != needledata) {
if (ptr >= end)
return selfptr + selflen;
ptr++;
assembly { ptrdata := and(mload(ptr), mask) }
}
return ptr;
} else {
// For long needles, use hashing
bytes32 hash;
assembly { hash := keccak256(needleptr, needlelen) }
for (idx = 0; idx <= selflen - needlelen; idx++) {
bytes32 testHash;
assembly { testHash := keccak256(ptr, needlelen) }
if (hash == testHash)
return ptr;
ptr += 1;
}
}
}
return selfptr + selflen;
}
// Returns the memory address of the first byte after the last occurrence of
// `needle` in `self`, or the address of `self` if not found.
function rfindPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private pure returns (uint) {
uint ptr;
if (needlelen <= selflen) {
if (needlelen <= 32) {
bytes32 mask = bytes32(~(2 ** (8 * (32 - needlelen)) - 1));
bytes32 needledata;
assembly { needledata := and(mload(needleptr), mask) }
ptr = selfptr + selflen - needlelen;
bytes32 ptrdata;
assembly { ptrdata := and(mload(ptr), mask) }
while (ptrdata != needledata) {
if (ptr <= selfptr)
return selfptr;
ptr--;
assembly { ptrdata := and(mload(ptr), mask) }
}
return ptr + needlelen;
} else {
// For long needles, use hashing
bytes32 hash;
assembly { hash := keccak256(needleptr, needlelen) }
ptr = selfptr + (selflen - needlelen);
while (ptr >= selfptr) {
bytes32 testHash;
assembly { testHash := keccak256(ptr, needlelen) }
if (hash == testHash)
return ptr + needlelen;
ptr -= 1;
}
}
}
return selfptr;
}
/*
* @dev Modifies `self` to contain everything from the first occurrence of
* `needle` to the end of the slice. `self` is set to the empty slice
* if `needle` is not found.
* @param self The slice to search and modify.
* @param needle The text to search for.
* @return `self`.
*/
function find(slice memory self, slice memory needle) internal pure returns (slice memory) {
uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr);
self._len -= ptr - self._ptr;
self._ptr = ptr;
return self;
}
/*
* @dev Modifies `self` to contain the part of the string from the start of
* `self` to the end of the first occurrence of `needle`. If `needle`
* is not found, `self` is set to the empty slice.
* @param self The slice to search and modify.
* @param needle The text to search for.
* @return `self`.
*/
function rfind(slice memory self, slice memory needle) internal pure returns (slice memory) {
uint ptr = rfindPtr(self._len, self._ptr, needle._len, needle._ptr);
self._len = ptr - self._ptr;
return self;
}
/*
* @dev Splits the slice, setting `self` to everything after the first
* occurrence of `needle`, and `token` to everything before it. If
* `needle` does not occur in `self`, `self` is set to the empty slice,
* and `token` is set to the entirety of `self`.
* @param self The slice to split.
* @param needle The text to search for in `self`.
* @param token An output parameter to which the first token is written.
* @return `token`.
*/
function split(slice memory self, slice memory needle, slice memory token) internal pure returns (slice memory) {
uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr);
token._ptr = self._ptr;
token._len = ptr - self._ptr;
if (ptr == self._ptr + self._len) {
// Not found
self._len = 0;
} else {
self._len -= token._len + needle._len;
self._ptr = ptr + needle._len;
}
return token;
}
/*
* @dev Splits the slice, setting `self` to everything after the first
* occurrence of `needle`, and returning everything before it. If
* `needle` does not occur in `self`, `self` is set to the empty slice,
* and the entirety of `self` is returned.
* @param self The slice to split.
* @param needle The text to search for in `self`.
* @return The part of `self` up to the first occurrence of `delim`.
*/
function split(slice memory self, slice memory needle) internal pure returns (slice memory token) {
split(self, needle, token);
}
/*
* @dev Splits the slice, setting `self` to everything before the last
* occurrence of `needle`, and `token` to everything after it. If
* `needle` does not occur in `self`, `self` is set to the empty slice,
* and `token` is set to the entirety of `self`.
* @param self The slice to split.
* @param needle The text to search for in `self`.
* @param token An output parameter to which the first token is written.
* @return `token`.
*/
function rsplit(slice memory self, slice memory needle, slice memory token) internal pure returns (slice memory) {
uint ptr = rfindPtr(self._len, self._ptr, needle._len, needle._ptr);
token._ptr = ptr;
token._len = self._len - (ptr - self._ptr);
if (ptr == self._ptr) {
// Not found
self._len = 0;
} else {
self._len -= token._len + needle._len;
}
return token;
}
/*
* @dev Splits the slice, setting `self` to everything before the last
* occurrence of `needle`, and returning everything after it. If
* `needle` does not occur in `self`, `self` is set to the empty slice,
* and the entirety of `self` is returned.
* @param self The slice to split.
* @param needle The text to search for in `self`.
* @return The part of `self` after the last occurrence of `delim`.
*/
function rsplit(slice memory self, slice memory needle) internal pure returns (slice memory token) {
rsplit(self, needle, token);
}
/*
* @dev Counts the number of nonoverlapping occurrences of `needle` in `self`.
* @param self The slice to search.
* @param needle The text to search for in `self`.
* @return The number of occurrences of `needle` found in `self`.
*/
function count(slice memory self, slice memory needle) internal pure returns (uint cnt) {
uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr) + needle._len;
while (ptr <= self._ptr + self._len) {
cnt++;
ptr = findPtr(self._len - (ptr - self._ptr), ptr, needle._len, needle._ptr) + needle._len;
}
}
/*
* @dev Returns True if `self` contains `needle`.
* @param self The slice to search.
* @param needle The text to search for in `self`.
* @return True if `needle` is found in `self`, false otherwise.
*/
function contains(slice memory self, slice memory needle) internal pure returns (bool) {
return rfindPtr(self._len, self._ptr, needle._len, needle._ptr) != self._ptr;
}
/*
* @dev Returns a newly allocated string containing the concatenation of
* `self` and `other`.
* @param self The first slice to concatenate.
* @param other The second slice to concatenate.
* @return The concatenation of the two strings.
*/
function concat(slice memory self, slice memory other) internal pure returns (string memory) {
string memory ret = new string(self._len + other._len);
uint retptr;
assembly { retptr := add(ret, 32) }
memcpy(retptr, self._ptr, self._len);
memcpy(retptr + self._len, other._ptr, other._len);
return ret;
}
/*
* @dev Joins an array of slices, using `self` as a delimiter, returning a
* newly allocated string.
* @param self The delimiter to use.
* @param parts A list of slices to join.
* @return A newly allocated string containing all the slices in `parts`,
* joined with `self`.
*/
function join(slice memory self, slice[] memory parts) internal pure returns (string memory) {
if (parts.length == 0)
return "";
uint length = self._len * (parts.length - 1);
for (uint i = 0; i < parts.length; i++) {
length += parts[i]._len;
}
string memory ret = new string(length);
uint retptr;
assembly { retptr := add(ret, 32) }
for (uint i = 0; i < parts.length; i++) {
memcpy(retptr, parts[i]._ptr, parts[i]._len);
retptr += parts[i]._len;
if (i < parts.length - 1) {
memcpy(retptr, self._ptr, self._len);
retptr += self._len;
}
}
return ret;
}
}
contract Base64 {
bytes constant BASE64_DECODE_CHAR = hex"000000000000000000000000000000000000000000000000000000000000000000000000000000000000003e003e003f3435363738393a3b3c3d00000000000000000102030405060708090a0b0c0d0e0f10111213141516171819000000003f001a1b1c1d1e1f202122232425262728292a2b2c2d2e2f30313233";
/// @return decoded array of bytes.
/// @param _encoded base 64 encoded array of bytes.
function _base64decode(bytes memory _encoded) internal pure returns (bytes memory) {
byte v1;
byte v2;
byte v3;
byte v4;
uint length = _encoded.length;
bytes memory result = new bytes(length);
uint index;
// base64 encoded strings can't be length 0 and they must be divisble by 4
require(length > 0 && length % 4 == 0, "invalid base64 encoding");
if (keccak256(abi.encodePacked(_encoded[length - 2])) == keccak256("=")) {
length -= 2;
} else if (keccak256(abi.encodePacked(_encoded[length - 1])) == keccak256("=")) {
length -= 1;
}
uint count = length >> 2 << 2;
uint i;
for (i = 0; i < count;) {
v1 = BASE64_DECODE_CHAR[uint8(_encoded[i++])];
v2 = BASE64_DECODE_CHAR[uint8(_encoded[i++])];
v3 = BASE64_DECODE_CHAR[uint8(_encoded[i++])];
v4 = BASE64_DECODE_CHAR[uint8(_encoded[i++])];
result[index++] = (v1 << 2 | v2 >> 4) & 0xff;
result[index++] = (v2 << 4 | v3 >> 2) & 0xff;
result[index++] = (v3 << 6 | v4) & 0xff;
}
if (length - count == 2) {
v1 = BASE64_DECODE_CHAR[uint8(_encoded[i++])];
v2 = BASE64_DECODE_CHAR[uint8(_encoded[i++])];
result[index++] = (v1 << 2 | v2 >> 4) & 0xff;
} else if (length - count == 3) {
v1 = BASE64_DECODE_CHAR[uint8(_encoded[i++])];
v2 = BASE64_DECODE_CHAR[uint8(_encoded[i++])];
v3 = BASE64_DECODE_CHAR[uint8(_encoded[i++])];
result[index++] = (v1 << 2 | v2 >> 4) & 0xff;
result[index++] = (v2 << 4 | v3 >> 2) & 0xff;
}
// Set to correct length.
assembly {
mstore(result, index)
}
return result;
}
}
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* This test is non-exhaustive, and there may be false-negatives: during the
* execution of a contract's constructor, its address will be reported as
* not containing a contract.
*
* > It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*/
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
}
interface ERC20 {
function allowance(address _owner, address _spender) external view returns (uint256);
function approve(address _spender, uint256 _value) external returns (bool);
function balanceOf(address _who) external view returns (uint256);
function totalSupply() external view returns (uint256);
function transfer(address _to, uint256 _value) external returns (bool);
function transferFrom(address _from, address _to, uint256 _value) external returns (bool);
}
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, "SafeMath: division by zero");
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "SafeMath: modulo by zero");
return a % b;
}
}
interface ENS {
// Logged when the owner of a node assigns a new owner to a subnode.
event NewOwner(bytes32 indexed node, bytes32 indexed label, address owner);
// Logged when the owner of a node transfers ownership to a new account.
event Transfer(bytes32 indexed node, address owner);
// Logged when the resolver for a node changes.
event NewResolver(bytes32 indexed node, address resolver);
// Logged when the TTL of a node changes
event NewTTL(bytes32 indexed node, uint64 ttl);
function setSubnodeOwner(bytes32 node, bytes32 label, address owner) external;
function setResolver(bytes32 node, address resolver) external;
function setOwner(bytes32 node, address owner) external;
function setTTL(bytes32 node, uint64 ttl) external;
function owner(bytes32 node) external view returns (address);
function resolver(bytes32 node) external view returns (address);
function ttl(bytes32 node) external view returns (uint64);
}
contract solcChecker {
/* INCOMPATIBLE SOLC: import the following instead: "github.com/oraclize/ethereum-api/oraclizeAPI_0.4.sol" */ function f(bytes calldata x) external;
}
contract OraclizeI {
address public cbAddress;
function setProofType(byte _proofType) external;
function setCustomGasPrice(uint _gasPrice) external;
function getPrice(string memory _datasource) public returns (uint _dsprice);
function randomDS_getSessionPubKeyHash() external view returns (bytes32 _sessionKeyHash);
function getPrice(string memory _datasource, uint _gasLimit) public returns (uint _dsprice);
function queryN(uint _timestamp, string memory _datasource, bytes memory _argN) public payable returns (bytes32 _id);
function query(uint _timestamp, string calldata _datasource, string calldata _arg) external payable returns (bytes32 _id);
function query2(uint _timestamp, string memory _datasource, string memory _arg1, string memory _arg2) public payable returns (bytes32 _id);
function query_withGasLimit(uint _timestamp, string calldata _datasource, string calldata _arg, uint _gasLimit) external payable returns (bytes32 _id);
function queryN_withGasLimit(uint _timestamp, string calldata _datasource, bytes calldata _argN, uint _gasLimit) external payable returns (bytes32 _id);
function query2_withGasLimit(uint _timestamp, string calldata _datasource, string calldata _arg1, string calldata _arg2, uint _gasLimit) external payable returns (bytes32 _id);
}
contract OraclizeAddrResolverI {
function getAddress() public returns (address _address);
}
/*
Begin solidity-cborutils
https://github.com/smartcontractkit/solidity-cborutils
MIT License
Copyright (c) 2018 SmartContract ChainLink, Ltd.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
library Buffer {
struct buffer {
bytes buf;
uint capacity;
}
function init(buffer memory _buf, uint _capacity) internal pure {
uint capacity = _capacity;
if (capacity % 32 != 0) {
capacity += 32 - (capacity % 32);
}
_buf.capacity = capacity; // Allocate space for the buffer data
assembly {
let ptr := mload(0x40)
mstore(_buf, ptr)
mstore(ptr, 0)
mstore(0x40, add(ptr, capacity))
}
}
function resize(buffer memory _buf, uint _capacity) private pure {
bytes memory oldbuf = _buf.buf;
init(_buf, _capacity);
append(_buf, oldbuf);
}
function max(uint _a, uint _b) private pure returns (uint _max) {
if (_a > _b) {
return _a;
}
return _b;
}
/**
* @dev Appends a byte array to the end of the buffer. Resizes if doing so
* would exceed the capacity of the buffer.
* @param _buf The buffer to append to.
* @param _data The data to append.
* @return The original buffer.
*
*/
function append(buffer memory _buf, bytes memory _data) internal pure returns (buffer memory _buffer) {
if (_data.length + _buf.buf.length > _buf.capacity) {
resize(_buf, max(_buf.capacity, _data.length) * 2);
}
uint dest;
uint src;
uint len = _data.length;
assembly {
let bufptr := mload(_buf) // Memory address of the buffer data
let buflen := mload(bufptr) // Length of existing buffer data
dest := add(add(bufptr, buflen), 32) // Start address = buffer address + buffer length + sizeof(buffer length)
mstore(bufptr, add(buflen, mload(_data))) // Update buffer length
src := add(_data, 32)
}
for(; len >= 32; len -= 32) { // Copy word-length chunks while possible
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
uint mask = 256 ** (32 - len) - 1; // Copy remaining bytes
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
return _buf;
}
/**
*
* @dev Appends a byte to the end of the buffer. Resizes if doing so would
* exceed the capacity of the buffer.
* @param _buf The buffer to append to.
* @param _data The data to append.
* @return The original buffer.
*
*/
function append(buffer memory _buf, uint8 _data) internal pure {
if (_buf.buf.length + 1 > _buf.capacity) {
resize(_buf, _buf.capacity * 2);
}
assembly {
let bufptr := mload(_buf) // Memory address of the buffer data
let buflen := mload(bufptr) // Length of existing buffer data
let dest := add(add(bufptr, buflen), 32) // Address = buffer address + buffer length + sizeof(buffer length)
mstore8(dest, _data)
mstore(bufptr, add(buflen, 1)) // Update buffer length
}
}
/**
*
* @dev Appends a byte to the end of the buffer. Resizes if doing so would
* exceed the capacity of the buffer.
* @param _buf The buffer to append to.
* @param _data The data to append.
* @return The original buffer.
*
*/
function appendInt(buffer memory _buf, uint _data, uint _len) internal pure returns (buffer memory _buffer) {
if (_len + _buf.buf.length > _buf.capacity) {
resize(_buf, max(_buf.capacity, _len) * 2);
}
uint mask = 256 ** _len - 1;
assembly {
let bufptr := mload(_buf) // Memory address of the buffer data
let buflen := mload(bufptr) // Length of existing buffer data
let dest := add(add(bufptr, buflen), _len) // Address = buffer address + buffer length + sizeof(buffer length) + len
mstore(dest, or(and(mload(dest), not(mask)), _data))
mstore(bufptr, add(buflen, _len)) // Update buffer length
}
return _buf;
}
}
library CBOR {
using Buffer for Buffer.buffer;
uint8 private constant MAJOR_TYPE_INT = 0;
uint8 private constant MAJOR_TYPE_MAP = 5;
uint8 private constant MAJOR_TYPE_BYTES = 2;
uint8 private constant MAJOR_TYPE_ARRAY = 4;
uint8 private constant MAJOR_TYPE_STRING = 3;
uint8 private constant MAJOR_TYPE_NEGATIVE_INT = 1;
uint8 private constant MAJOR_TYPE_CONTENT_FREE = 7;
function encodeType(Buffer.buffer memory _buf, uint8 _major, uint _value) private pure {
if (_value <= 23) {
_buf.append(uint8((_major << 5) | _value));
} else if (_value <= 0xFF) {
_buf.append(uint8((_major << 5) | 24));
_buf.appendInt(_value, 1);
} else if (_value <= 0xFFFF) {
_buf.append(uint8((_major << 5) | 25));
_buf.appendInt(_value, 2);
} else if (_value <= 0xFFFFFFFF) {
_buf.append(uint8((_major << 5) | 26));
_buf.appendInt(_value, 4);
} else if (_value <= 0xFFFFFFFFFFFFFFFF) {
_buf.append(uint8((_major << 5) | 27));
_buf.appendInt(_value, 8);
}
}
function encodeIndefiniteLengthType(Buffer.buffer memory _buf, uint8 _major) private pure {
_buf.append(uint8((_major << 5) | 31));
}
function encodeUInt(Buffer.buffer memory _buf, uint _value) internal pure {
encodeType(_buf, MAJOR_TYPE_INT, _value);
}
function encodeInt(Buffer.buffer memory _buf, int _value) internal pure {
if (_value >= 0) {
encodeType(_buf, MAJOR_TYPE_INT, uint(_value));
} else {
encodeType(_buf, MAJOR_TYPE_NEGATIVE_INT, uint(-1 - _value));
}
}
function encodeBytes(Buffer.buffer memory _buf, bytes memory _value) internal pure {
encodeType(_buf, MAJOR_TYPE_BYTES, _value.length);
_buf.append(_value);
}
function encodeString(Buffer.buffer memory _buf, string memory _value) internal pure {
encodeType(_buf, MAJOR_TYPE_STRING, bytes(_value).length);
_buf.append(bytes(_value));
}
function startArray(Buffer.buffer memory _buf) internal pure {
encodeIndefiniteLengthType(_buf, MAJOR_TYPE_ARRAY);
}
function startMap(Buffer.buffer memory _buf) internal pure {
encodeIndefiniteLengthType(_buf, MAJOR_TYPE_MAP);
}
function endSequence(Buffer.buffer memory _buf) internal pure {
encodeIndefiniteLengthType(_buf, MAJOR_TYPE_CONTENT_FREE);
}
}
/*
End solidity-cborutils
*/
contract usingOraclize {
using CBOR for Buffer.buffer;
OraclizeI oraclize;
OraclizeAddrResolverI OAR;
uint constant day = 60 * 60 * 24;
uint constant week = 60 * 60 * 24 * 7;
uint constant month = 60 * 60 * 24 * 30;
byte constant proofType_NONE = 0x00;
byte constant proofType_Ledger = 0x30;
byte constant proofType_Native = 0xF0;
byte constant proofStorage_IPFS = 0x01;
byte constant proofType_Android = 0x40;
byte constant proofType_TLSNotary = 0x10;
string oraclize_network_name;
uint8 constant networkID_auto = 0;
uint8 constant networkID_morden = 2;
uint8 constant networkID_mainnet = 1;
uint8 constant networkID_testnet = 2;
uint8 constant networkID_consensys = 161;
mapping(bytes32 => bytes32) oraclize_randomDS_args;
mapping(bytes32 => bool) oraclize_randomDS_sessionKeysHashVerified;
modifier oraclizeAPI {
if ((address(OAR) == address(0)) || (getCodeSize(address(OAR)) == 0)) {
oraclize_setNetwork(networkID_auto);
}
if (address(oraclize) != OAR.getAddress()) {
oraclize = OraclizeI(OAR.getAddress());
}
_;
}
modifier oraclize_randomDS_proofVerify(bytes32 _queryId, string memory _result, bytes memory _proof) {
// RandomDS Proof Step 1: The prefix has to match 'LP\x01' (Ledger Proof version 1)
require((_proof[0] == "L") && (_proof[1] == "P") && (uint8(_proof[2]) == uint8(1)));
bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName());
require(proofVerified);
_;
}
function oraclize_setNetwork(uint8 _networkID) internal returns (bool _networkSet) {
_networkID; // NOTE: Silence the warning and remain backwards compatible
return oraclize_setNetwork();
}
function oraclize_setNetworkName(string memory _network_name) internal {
oraclize_network_name = _network_name;
}
function oraclize_getNetworkName() internal view returns (string memory _networkName) {
return oraclize_network_name;
}
function oraclize_setNetwork() internal returns (bool _networkSet) {
if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed) > 0) { //mainnet
OAR = OraclizeAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed);
oraclize_setNetworkName("eth_mainnet");
return true;
}
if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1) > 0) { //ropsten testnet
OAR = OraclizeAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1);
oraclize_setNetworkName("eth_ropsten3");
return true;
}
if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e) > 0) { //kovan testnet
OAR = OraclizeAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e);
oraclize_setNetworkName("eth_kovan");
return true;
}
if (getCodeSize(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48) > 0) { //rinkeby testnet
OAR = OraclizeAddrResolverI(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48);
oraclize_setNetworkName("eth_rinkeby");
return true;
}
if (getCodeSize(0xa2998EFD205FB9D4B4963aFb70778D6354ad3A41) > 0) { //goerli testnet
OAR = OraclizeAddrResolverI(0xa2998EFD205FB9D4B4963aFb70778D6354ad3A41);
oraclize_setNetworkName("eth_goerli");
return true;
}
if (getCodeSize(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475) > 0) { //ethereum-bridge
OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475);
return true;
}
if (getCodeSize(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF) > 0) { //ether.camp ide
OAR = OraclizeAddrResolverI(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF);
return true;
}
if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA) > 0) { //browser-solidity
OAR = OraclizeAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA);
return true;
}
return false;
}
/**
* @dev The following `__callback` functions are just placeholders ideally
* meant to be defined in child contract when proofs are used.
* The function bodies simply silence compiler warnings.
*/
function __callback(bytes32 _myid, string memory _result) public {
__callback(_myid, _result, new bytes(0));
}
function __callback(bytes32 _myid, string memory _result, bytes memory _proof) public {
_myid; _result; _proof;
oraclize_randomDS_args[bytes32(0)] = bytes32(0);
}
function oraclize_getPrice(string memory _datasource) oraclizeAPI internal returns (uint _queryPrice) {
return oraclize.getPrice(_datasource);
}
function oraclize_getPrice(string memory _datasource, uint _gasLimit) oraclizeAPI internal returns (uint _queryPrice) {
return oraclize.getPrice(_datasource, _gasLimit);
}
function oraclize_query(string memory _datasource, string memory _arg) oraclizeAPI internal returns (bytes32 _id) {
uint price = oraclize.getPrice(_datasource);
if (price > 1 ether + tx.gasprice * 200000) {
return 0; // Unexpectedly high price
}
return oraclize.query.value(price)(0, _datasource, _arg);
}
function oraclize_query(uint _timestamp, string memory _datasource, string memory _arg) oraclizeAPI internal returns (bytes32 _id) {
uint price = oraclize.getPrice(_datasource);
if (price > 1 ether + tx.gasprice * 200000) {
return 0; // Unexpectedly high price
}
return oraclize.query.value(price)(_timestamp, _datasource, _arg);
}
function oraclize_query(uint _timestamp, string memory _datasource, string memory _arg, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) {
uint price = oraclize.getPrice(_datasource,_gasLimit);
if (price > 1 ether + tx.gasprice * _gasLimit) {
return 0; // Unexpectedly high price
}
return oraclize.query_withGasLimit.value(price)(_timestamp, _datasource, _arg, _gasLimit);
}
function oraclize_query(string memory _datasource, string memory _arg, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) {
uint price = oraclize.getPrice(_datasource, _gasLimit);
if (price > 1 ether + tx.gasprice * _gasLimit) {
return 0; // Unexpectedly high price
}
return oraclize.query_withGasLimit.value(price)(0, _datasource, _arg, _gasLimit);
}
function oraclize_query(string memory _datasource, string memory _arg1, string memory _arg2) oraclizeAPI internal returns (bytes32 _id) {
uint price = oraclize.getPrice(_datasource);
if (price > 1 ether + tx.gasprice * 200000) {
return 0; // Unexpectedly high price
}
return oraclize.query2.value(price)(0, _datasource, _arg1, _arg2);
}
function oraclize_query(uint _timestamp, string memory _datasource, string memory _arg1, string memory _arg2) oraclizeAPI internal returns (bytes32 _id) {
uint price = oraclize.getPrice(_datasource);
if (price > 1 ether + tx.gasprice * 200000) {
return 0; // Unexpectedly high price
}
return oraclize.query2.value(price)(_timestamp, _datasource, _arg1, _arg2);
}
function oraclize_query(uint _timestamp, string memory _datasource, string memory _arg1, string memory _arg2, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) {
uint price = oraclize.getPrice(_datasource, _gasLimit);
if (price > 1 ether + tx.gasprice * _gasLimit) {
return 0; // Unexpectedly high price
}
return oraclize.query2_withGasLimit.value(price)(_timestamp, _datasource, _arg1, _arg2, _gasLimit);
}
function oraclize_query(string memory _datasource, string memory _arg1, string memory _arg2, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) {
uint price = oraclize.getPrice(_datasource, _gasLimit);
if (price > 1 ether + tx.gasprice * _gasLimit) {
return 0; // Unexpectedly high price
}
return oraclize.query2_withGasLimit.value(price)(0, _datasource, _arg1, _arg2, _gasLimit);
}
function oraclize_query(string memory _datasource, string[] memory _argN) oraclizeAPI internal returns (bytes32 _id) {
uint price = oraclize.getPrice(_datasource);
if (price > 1 ether + tx.gasprice * 200000) {
return 0; // Unexpectedly high price
}
bytes memory args = stra2cbor(_argN);
return oraclize.queryN.value(price)(0, _datasource, args);
}
function oraclize_query(uint _timestamp, string memory _datasource, string[] memory _argN) oraclizeAPI internal returns (bytes32 _id) {
uint price = oraclize.getPrice(_datasource);
if (price > 1 ether + tx.gasprice * 200000) {
return 0; // Unexpectedly high price
}
bytes memory args = stra2cbor(_argN);
return oraclize.queryN.value(price)(_timestamp, _datasource, args);
}
function oraclize_query(uint _timestamp, string memory _datasource, string[] memory _argN, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) {
uint price = oraclize.getPrice(_datasource, _gasLimit);
if (price > 1 ether + tx.gasprice * _gasLimit) {
return 0; // Unexpectedly high price
}
bytes memory args = stra2cbor(_argN);
return oraclize.queryN_withGasLimit.value(price)(_timestamp, _datasource, args, _gasLimit);
}
function oraclize_query(string memory _datasource, string[] memory _argN, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) {
uint price = oraclize.getPrice(_datasource, _gasLimit);
if (price > 1 ether + tx.gasprice * _gasLimit) {
return 0; // Unexpectedly high price
}
bytes memory args = stra2cbor(_argN);
return oraclize.queryN_withGasLimit.value(price)(0, _datasource, args, _gasLimit);
}
function oraclize_query(string memory _datasource, string[1] memory _args) oraclizeAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](1);
dynargs[0] = _args[0];
return oraclize_query(_datasource, dynargs);
}
function oraclize_query(uint _timestamp, string memory _datasource, string[1] memory _args) oraclizeAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](1);
dynargs[0] = _args[0];
return oraclize_query(_timestamp, _datasource, dynargs);
}
function oraclize_query(uint _timestamp, string memory _datasource, string[1] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](1);
dynargs[0] = _args[0];
return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit);
}
function oraclize_query(string memory _datasource, string[1] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](1);
dynargs[0] = _args[0];
return oraclize_query(_datasource, dynargs, _gasLimit);
}
function oraclize_query(string memory _datasource, string[2] memory _args) oraclizeAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](2);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
return oraclize_query(_datasource, dynargs);
}
function oraclize_query(uint _timestamp, string memory _datasource, string[2] memory _args) oraclizeAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](2);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
return oraclize_query(_timestamp, _datasource, dynargs);
}
function oraclize_query(uint _timestamp, string memory _datasource, string[2] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](2);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit);
}
function oraclize_query(string memory _datasource, string[2] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](2);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
return oraclize_query(_datasource, dynargs, _gasLimit);
}
function oraclize_query(string memory _datasource, string[3] memory _args) oraclizeAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](3);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
return oraclize_query(_datasource, dynargs);
}
function oraclize_query(uint _timestamp, string memory _datasource, string[3] memory _args) oraclizeAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](3);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
return oraclize_query(_timestamp, _datasource, dynargs);
}
function oraclize_query(uint _timestamp, string memory _datasource, string[3] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](3);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit);
}
function oraclize_query(string memory _datasource, string[3] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](3);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
return oraclize_query(_datasource, dynargs, _gasLimit);
}
function oraclize_query(string memory _datasource, string[4] memory _args) oraclizeAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](4);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
dynargs[3] = _args[3];
return oraclize_query(_datasource, dynargs);
}
function oraclize_query(uint _timestamp, string memory _datasource, string[4] memory _args) oraclizeAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](4);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
dynargs[3] = _args[3];
return oraclize_query(_timestamp, _datasource, dynargs);
}
function oraclize_query(uint _timestamp, string memory _datasource, string[4] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](4);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
dynargs[3] = _args[3];
return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit);
}
function oraclize_query(string memory _datasource, string[4] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](4);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
dynargs[3] = _args[3];
return oraclize_query(_datasource, dynargs, _gasLimit);
}
function oraclize_query(string memory _datasource, string[5] memory _args) oraclizeAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](5);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
dynargs[3] = _args[3];
dynargs[4] = _args[4];
return oraclize_query(_datasource, dynargs);
}
function oraclize_query(uint _timestamp, string memory _datasource, string[5] memory _args) oraclizeAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](5);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
dynargs[3] = _args[3];
dynargs[4] = _args[4];
return oraclize_query(_timestamp, _datasource, dynargs);
}
function oraclize_query(uint _timestamp, string memory _datasource, string[5] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](5);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
dynargs[3] = _args[3];
dynargs[4] = _args[4];
return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit);
}
function oraclize_query(string memory _datasource, string[5] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](5);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
dynargs[3] = _args[3];
dynargs[4] = _args[4];
return oraclize_query(_datasource, dynargs, _gasLimit);
}
function oraclize_query(string memory _datasource, bytes[] memory _argN) oraclizeAPI internal returns (bytes32 _id) {
uint price = oraclize.getPrice(_datasource);
if (price > 1 ether + tx.gasprice * 200000) {
return 0; // Unexpectedly high price
}
bytes memory args = ba2cbor(_argN);
return oraclize.queryN.value(price)(0, _datasource, args);
}
function oraclize_query(uint _timestamp, string memory _datasource, bytes[] memory _argN) oraclizeAPI internal returns (bytes32 _id) {
uint price = oraclize.getPrice(_datasource);
if (price > 1 ether + tx.gasprice * 200000) {
return 0; // Unexpectedly high price
}
bytes memory args = ba2cbor(_argN);
return oraclize.queryN.value(price)(_timestamp, _datasource, args);
}
function oraclize_query(uint _timestamp, string memory _datasource, bytes[] memory _argN, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) {
uint price = oraclize.getPrice(_datasource, _gasLimit);
if (price > 1 ether + tx.gasprice * _gasLimit) {
return 0; // Unexpectedly high price
}
bytes memory args = ba2cbor(_argN);
return oraclize.queryN_withGasLimit.value(price)(_timestamp, _datasource, args, _gasLimit);
}
function oraclize_query(string memory _datasource, bytes[] memory _argN, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) {
uint price = oraclize.getPrice(_datasource, _gasLimit);
if (price > 1 ether + tx.gasprice * _gasLimit) {
return 0; // Unexpectedly high price
}
bytes memory args = ba2cbor(_argN);
return oraclize.queryN_withGasLimit.value(price)(0, _datasource, args, _gasLimit);
}
function oraclize_query(string memory _datasource, bytes[1] memory _args) oraclizeAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = _args[0];
return oraclize_query(_datasource, dynargs);
}
function oraclize_query(uint _timestamp, string memory _datasource, bytes[1] memory _args) oraclizeAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = _args[0];
return oraclize_query(_timestamp, _datasource, dynargs);
}
function oraclize_query(uint _timestamp, string memory _datasource, bytes[1] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = _args[0];
return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit);
}
function oraclize_query(string memory _datasource, bytes[1] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = _args[0];
return oraclize_query(_datasource, dynargs, _gasLimit);
}
function oraclize_query(string memory _datasource, bytes[2] memory _args) oraclizeAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
return oraclize_query(_datasource, dynargs);
}
function oraclize_query(uint _timestamp, string memory _datasource, bytes[2] memory _args) oraclizeAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
return oraclize_query(_timestamp, _datasource, dynargs);
}
function oraclize_query(uint _timestamp, string memory _datasource, bytes[2] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit);
}
function oraclize_query(string memory _datasource, bytes[2] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
return oraclize_query(_datasource, dynargs, _gasLimit);
}
function oraclize_query(string memory _datasource, bytes[3] memory _args) oraclizeAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
return oraclize_query(_datasource, dynargs);
}
function oraclize_query(uint _timestamp, string memory _datasource, bytes[3] memory _args) oraclizeAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
return oraclize_query(_timestamp, _datasource, dynargs);
}
function oraclize_query(uint _timestamp, string memory _datasource, bytes[3] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit);
}
function oraclize_query(string memory _datasource, bytes[3] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
return oraclize_query(_datasource, dynargs, _gasLimit);
}
function oraclize_query(string memory _datasource, bytes[4] memory _args) oraclizeAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
dynargs[3] = _args[3];
return oraclize_query(_datasource, dynargs);
}
function oraclize_query(uint _timestamp, string memory _datasource, bytes[4] memory _args) oraclizeAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
dynargs[3] = _args[3];
return oraclize_query(_timestamp, _datasource, dynargs);
}
function oraclize_query(uint _timestamp, string memory _datasource, bytes[4] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
dynargs[3] = _args[3];
return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit);
}
function oraclize_query(string memory _datasource, bytes[4] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
dynargs[3] = _args[3];
return oraclize_query(_datasource, dynargs, _gasLimit);
}
function oraclize_query(string memory _datasource, bytes[5] memory _args) oraclizeAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
dynargs[3] = _args[3];
dynargs[4] = _args[4];
return oraclize_query(_datasource, dynargs);
}
function oraclize_query(uint _timestamp, string memory _datasource, bytes[5] memory _args) oraclizeAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
dynargs[3] = _args[3];
dynargs[4] = _args[4];
return oraclize_query(_timestamp, _datasource, dynargs);
}
function oraclize_query(uint _timestamp, string memory _datasource, bytes[5] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
dynargs[3] = _args[3];
dynargs[4] = _args[4];
return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit);
}
function oraclize_query(string memory _datasource, bytes[5] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
dynargs[3] = _args[3];
dynargs[4] = _args[4];
return oraclize_query(_datasource, dynargs, _gasLimit);
}
function oraclize_setProof(byte _proofP) oraclizeAPI internal {
return oraclize.setProofType(_proofP);
}
function oraclize_cbAddress() oraclizeAPI internal returns (address _callbackAddress) {
return oraclize.cbAddress();
}
function getCodeSize(address _addr) view internal returns (uint _size) {
assembly {
_size := extcodesize(_addr)
}
}
function oraclize_setCustomGasPrice(uint _gasPrice) oraclizeAPI internal {
return oraclize.setCustomGasPrice(_gasPrice);
}
function oraclize_randomDS_getSessionPubKeyHash() oraclizeAPI internal returns (bytes32 _sessionKeyHash) {
return oraclize.randomDS_getSessionPubKeyHash();
}
function parseAddr(string memory _a) internal pure returns (address _parsedAddress) {
bytes memory tmp = bytes(_a);
uint160 iaddr = 0;
uint160 b1;
uint160 b2;
for (uint i = 2; i < 2 + 2 * 20; i += 2) {
iaddr *= 256;
b1 = uint160(uint8(tmp[i]));
b2 = uint160(uint8(tmp[i + 1]));
if ((b1 >= 97) && (b1 <= 102)) {
b1 -= 87;
} else if ((b1 >= 65) && (b1 <= 70)) {
b1 -= 55;
} else if ((b1 >= 48) && (b1 <= 57)) {
b1 -= 48;
}
if ((b2 >= 97) && (b2 <= 102)) {
b2 -= 87;
} else if ((b2 >= 65) && (b2 <= 70)) {
b2 -= 55;
} else if ((b2 >= 48) && (b2 <= 57)) {
b2 -= 48;
}
iaddr += (b1 * 16 + b2);
}
return address(iaddr);
}
function strCompare(string memory _a, string memory _b) internal pure returns (int _returnCode) {
bytes memory a = bytes(_a);
bytes memory b = bytes(_b);
uint minLength = a.length;
if (b.length < minLength) {
minLength = b.length;
}
for (uint i = 0; i < minLength; i ++) {
if (a[i] < b[i]) {
return -1;
} else if (a[i] > b[i]) {
return 1;
}
}
if (a.length < b.length) {
return -1;
} else if (a.length > b.length) {
return 1;
} else {
return 0;
}
}
function indexOf(string memory _haystack, string memory _needle) internal pure returns (int _returnCode) {
bytes memory h = bytes(_haystack);
bytes memory n = bytes(_needle);
if (h.length < 1 || n.length < 1 || (n.length > h.length)) {
return -1;
} else if (h.length > (2 ** 128 - 1)) {
return -1;
} else {
uint subindex = 0;
for (uint i = 0; i < h.length; i++) {
if (h[i] == n[0]) {
subindex = 1;
while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex]) {
subindex++;
}
if (subindex == n.length) {
return int(i);
}
}
}
return -1;
}
}
function strConcat(string memory _a, string memory _b) internal pure returns (string memory _concatenatedString) {
return strConcat(_a, _b, "", "", "");
}
function strConcat(string memory _a, string memory _b, string memory _c) internal pure returns (string memory _concatenatedString) {
return strConcat(_a, _b, _c, "", "");
}
function strConcat(string memory _a, string memory _b, string memory _c, string memory _d) internal pure returns (string memory _concatenatedString) {
return strConcat(_a, _b, _c, _d, "");
}
function strConcat(string memory _a, string memory _b, string memory _c, string memory _d, string memory _e) internal pure returns (string memory _concatenatedString) {
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
bytes memory _bc = bytes(_c);
bytes memory _bd = bytes(_d);
bytes memory _be = bytes(_e);
string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length);
bytes memory babcde = bytes(abcde);
uint k = 0;
uint i = 0;
for (i = 0; i < _ba.length; i++) {
babcde[k++] = _ba[i];
}
for (i = 0; i < _bb.length; i++) {
babcde[k++] = _bb[i];
}
for (i = 0; i < _bc.length; i++) {
babcde[k++] = _bc[i];
}
for (i = 0; i < _bd.length; i++) {
babcde[k++] = _bd[i];
}
for (i = 0; i < _be.length; i++) {
babcde[k++] = _be[i];
}
return string(babcde);
}
function safeParseInt(string memory _a) internal pure returns (uint _parsedInt) {
return safeParseInt(_a, 0);
}
function safeParseInt(string memory _a, uint _b) internal pure returns (uint _parsedInt) {
bytes memory bresult = bytes(_a);
uint mint = 0;
bool decimals = false;
for (uint i = 0; i < bresult.length; i++) {
if ((uint(uint8(bresult[i])) >= 48) && (uint(uint8(bresult[i])) <= 57)) {
if (decimals) {
if (_b == 0) break;
else _b--;
}
mint *= 10;
mint += uint(uint8(bresult[i])) - 48;
} else if (uint(uint8(bresult[i])) == 46) {
require(!decimals, 'More than one decimal encountered in string!');
decimals = true;
} else {
revert("Non-numeral character encountered in string!");
}
}
if (_b > 0) {
mint *= 10 ** _b;
}
return mint;
}
function parseInt(string memory _a) internal pure returns (uint _parsedInt) {
return parseInt(_a, 0);
}
function parseInt(string memory _a, uint _b) internal pure returns (uint _parsedInt) {
bytes memory bresult = bytes(_a);
uint mint = 0;
bool decimals = false;
for (uint i = 0; i < bresult.length; i++) {
if ((uint(uint8(bresult[i])) >= 48) && (uint(uint8(bresult[i])) <= 57)) {
if (decimals) {
if (_b == 0) {
break;
} else {
_b--;
}
}
mint *= 10;
mint += uint(uint8(bresult[i])) - 48;
} else if (uint(uint8(bresult[i])) == 46) {
decimals = true;
}
}
if (_b > 0) {
mint *= 10 ** _b;
}
return mint;
}
function uint2str(uint _i) internal pure returns (string memory _uintAsString) {
if (_i == 0) {
return "0";
}
uint j = _i;
uint len;
while (j != 0) {
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len - 1;
while (_i != 0) {
bstr[k--] = byte(uint8(48 + _i % 10));
_i /= 10;
}
return string(bstr);
}
function stra2cbor(string[] memory _arr) internal pure returns (bytes memory _cborEncoding) {
safeMemoryCleaner();
Buffer.buffer memory buf;
Buffer.init(buf, 1024);
buf.startArray();
for (uint i = 0; i < _arr.length; i++) {
buf.encodeString(_arr[i]);
}
buf.endSequence();
return buf.buf;
}
function ba2cbor(bytes[] memory _arr) internal pure returns (bytes memory _cborEncoding) {
safeMemoryCleaner();
Buffer.buffer memory buf;
Buffer.init(buf, 1024);
buf.startArray();
for (uint i = 0; i < _arr.length; i++) {
buf.encodeBytes(_arr[i]);
}
buf.endSequence();
return buf.buf;
}
function oraclize_newRandomDSQuery(uint _delay, uint _nbytes, uint _customGasLimit) internal returns (bytes32 _queryId) {
require((_nbytes > 0) && (_nbytes <= 32));
_delay *= 10; // Convert from seconds to ledger timer ticks
bytes memory nbytes = new bytes(1);
nbytes[0] = byte(uint8(_nbytes));
bytes memory unonce = new bytes(32);
bytes memory sessionKeyHash = new bytes(32);
bytes32 sessionKeyHash_bytes32 = oraclize_randomDS_getSessionPubKeyHash();
assembly {
mstore(unonce, 0x20)
/*
The following variables can be relaxed.
Check the relaxed random contract at https://github.com/oraclize/ethereum-examples
for an idea on how to override and replace commit hash variables.
*/
mstore(add(unonce, 0x20), xor(blockhash(sub(number, 1)), xor(coinbase, timestamp)))
mstore(sessionKeyHash, 0x20)
mstore(add(sessionKeyHash, 0x20), sessionKeyHash_bytes32)
}
bytes memory delay = new bytes(32);
assembly {
mstore(add(delay, 0x20), _delay)
}
bytes memory delay_bytes8 = new bytes(8);
copyBytes(delay, 24, 8, delay_bytes8, 0);
bytes[4] memory args = [unonce, nbytes, sessionKeyHash, delay];
bytes32 queryId = oraclize_query("random", args, _customGasLimit);
bytes memory delay_bytes8_left = new bytes(8);
assembly {
let x := mload(add(delay_bytes8, 0x20))
mstore8(add(delay_bytes8_left, 0x27), div(x, 0x100000000000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x26), div(x, 0x1000000000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x25), div(x, 0x10000000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x24), div(x, 0x100000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x23), div(x, 0x1000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x22), div(x, 0x10000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x21), div(x, 0x100000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x20), div(x, 0x1000000000000000000000000000000000000000000000000))
}
oraclize_randomDS_setCommitment(queryId, keccak256(abi.encodePacked(delay_bytes8_left, args[1], sha256(args[0]), args[2])));
return queryId;
}
function oraclize_randomDS_setCommitment(bytes32 _queryId, bytes32 _commitment) internal {
oraclize_randomDS_args[_queryId] = _commitment;
}
function verifySig(bytes32 _tosignh, bytes memory _dersig, bytes memory _pubkey) internal returns (bool _sigVerified) {
bool sigok;
address signer;
bytes32 sigr;
bytes32 sigs;
bytes memory sigr_ = new bytes(32);
uint offset = 4 + (uint(uint8(_dersig[3])) - 0x20);
sigr_ = copyBytes(_dersig, offset, 32, sigr_, 0);
bytes memory sigs_ = new bytes(32);
offset += 32 + 2;
sigs_ = copyBytes(_dersig, offset + (uint(uint8(_dersig[offset - 1])) - 0x20), 32, sigs_, 0);
assembly {
sigr := mload(add(sigr_, 32))
sigs := mload(add(sigs_, 32))
}
(sigok, signer) = safer_ecrecover(_tosignh, 27, sigr, sigs);
if (address(uint160(uint256(keccak256(_pubkey)))) == signer) {
return true;
} else {
(sigok, signer) = safer_ecrecover(_tosignh, 28, sigr, sigs);
return (address(uint160(uint256(keccak256(_pubkey)))) == signer);
}
}
function oraclize_randomDS_proofVerify__sessionKeyValidity(bytes memory _proof, uint _sig2offset) internal returns (bool _proofVerified) {
bool sigok;
// Random DS Proof Step 6: Verify the attestation signature, APPKEY1 must sign the sessionKey from the correct ledger app (CODEHASH)
bytes memory sig2 = new bytes(uint(uint8(_proof[_sig2offset + 1])) + 2);
copyBytes(_proof, _sig2offset, sig2.length, sig2, 0);
bytes memory appkey1_pubkey = new bytes(64);
copyBytes(_proof, 3 + 1, 64, appkey1_pubkey, 0);
bytes memory tosign2 = new bytes(1 + 65 + 32);
tosign2[0] = byte(uint8(1)); //role
copyBytes(_proof, _sig2offset - 65, 65, tosign2, 1);
bytes memory CODEHASH = hex"fd94fa71bc0ba10d39d464d0d8f465efeef0a2764e3887fcc9df41ded20f505c";
copyBytes(CODEHASH, 0, 32, tosign2, 1 + 65);
sigok = verifySig(sha256(tosign2), sig2, appkey1_pubkey);
if (!sigok) {
return false;
}
// Random DS Proof Step 7: Verify the APPKEY1 provenance (must be signed by Ledger)
bytes memory LEDGERKEY = hex"7fb956469c5c9b89840d55b43537e66a98dd4811ea0a27224272c2e5622911e8537a2f8e86a46baec82864e98dd01e9ccc2f8bc5dfc9cbe5a91a290498dd96e4";
bytes memory tosign3 = new bytes(1 + 65);
tosign3[0] = 0xFE;
copyBytes(_proof, 3, 65, tosign3, 1);
bytes memory sig3 = new bytes(uint(uint8(_proof[3 + 65 + 1])) + 2);
copyBytes(_proof, 3 + 65, sig3.length, sig3, 0);
sigok = verifySig(sha256(tosign3), sig3, LEDGERKEY);
return sigok;
}
function oraclize_randomDS_proofVerify__returnCode(bytes32 _queryId, string memory _result, bytes memory _proof) internal returns (uint8 _returnCode) {
// Random DS Proof Step 1: The prefix has to match 'LP\x01' (Ledger Proof version 1)
if ((_proof[0] != "L") || (_proof[1] != "P") || (uint8(_proof[2]) != uint8(1))) {
return 1;
}
bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName());
if (!proofVerified) {
return 2;
}
return 0;
}
function matchBytes32Prefix(bytes32 _content, bytes memory _prefix, uint _nRandomBytes) internal pure returns (bool _matchesPrefix) {
bool match_ = true;
require(_prefix.length == _nRandomBytes);
for (uint256 i = 0; i< _nRandomBytes; i++) {
if (_content[i] != _prefix[i]) {
match_ = false;
}
}
return match_;
}
function oraclize_randomDS_proofVerify__main(bytes memory _proof, bytes32 _queryId, bytes memory _result, string memory _contextName) internal returns (bool _proofVerified) {
// Random DS Proof Step 2: The unique keyhash has to match with the sha256 of (context name + _queryId)
uint ledgerProofLength = 3 + 65 + (uint(uint8(_proof[3 + 65 + 1])) + 2) + 32;
bytes memory keyhash = new bytes(32);
copyBytes(_proof, ledgerProofLength, 32, keyhash, 0);
if (!(keccak256(keyhash) == keccak256(abi.encodePacked(sha256(abi.encodePacked(_contextName, _queryId)))))) {
return false;
}
bytes memory sig1 = new bytes(uint(uint8(_proof[ledgerProofLength + (32 + 8 + 1 + 32) + 1])) + 2);
copyBytes(_proof, ledgerProofLength + (32 + 8 + 1 + 32), sig1.length, sig1, 0);
// Random DS Proof Step 3: We assume sig1 is valid (it will be verified during step 5) and we verify if '_result' is the _prefix of sha256(sig1)
if (!matchBytes32Prefix(sha256(sig1), _result, uint(uint8(_proof[ledgerProofLength + 32 + 8])))) {
return false;
}
// Random DS Proof Step 4: Commitment match verification, keccak256(delay, nbytes, unonce, sessionKeyHash) == commitment in storage.
// This is to verify that the computed args match with the ones specified in the query.
bytes memory commitmentSlice1 = new bytes(8 + 1 + 32);
copyBytes(_proof, ledgerProofLength + 32, 8 + 1 + 32, commitmentSlice1, 0);
bytes memory sessionPubkey = new bytes(64);
uint sig2offset = ledgerProofLength + 32 + (8 + 1 + 32) + sig1.length + 65;
copyBytes(_proof, sig2offset - 64, 64, sessionPubkey, 0);
bytes32 sessionPubkeyHash = sha256(sessionPubkey);
if (oraclize_randomDS_args[_queryId] == keccak256(abi.encodePacked(commitmentSlice1, sessionPubkeyHash))) { //unonce, nbytes and sessionKeyHash match
delete oraclize_randomDS_args[_queryId];
} else return false;
// Random DS Proof Step 5: Validity verification for sig1 (keyhash and args signed with the sessionKey)
bytes memory tosign1 = new bytes(32 + 8 + 1 + 32);
copyBytes(_proof, ledgerProofLength, 32 + 8 + 1 + 32, tosign1, 0);
if (!verifySig(sha256(tosign1), sig1, sessionPubkey)) {
return false;
}
// Verify if sessionPubkeyHash was verified already, if not.. let's do it!
if (!oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash]) {
oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] = oraclize_randomDS_proofVerify__sessionKeyValidity(_proof, sig2offset);
}
return oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash];
}
/*
The following function has been written by Alex Beregszaszi, use it under the terms of the MIT license
*/
function copyBytes(bytes memory _from, uint _fromOffset, uint _length, bytes memory _to, uint _toOffset) internal pure returns (bytes memory _copiedBytes) {
uint minLength = _length + _toOffset;
require(_to.length >= minLength); // Buffer too small. Should be a better way?
uint i = 32 + _fromOffset; // NOTE: the offset 32 is added to skip the `size` field of both bytes variables
uint j = 32 + _toOffset;
while (i < (32 + _fromOffset + _length)) {
assembly {
let tmp := mload(add(_from, i))
mstore(add(_to, j), tmp)
}
i += 32;
j += 32;
}
return _to;
}
/*
The following function has been written by Alex Beregszaszi, use it under the terms of the MIT license
Duplicate Solidity's ecrecover, but catching the CALL return value
*/
function safer_ecrecover(bytes32 _hash, uint8 _v, bytes32 _r, bytes32 _s) internal returns (bool _success, address _recoveredAddress) {
/*
We do our own memory management here. Solidity uses memory offset
0x40 to store the current end of memory. We write past it (as
writes are memory extensions), but don't update the offset so
Solidity will reuse it. The memory used here is only needed for
this context.
FIXME: inline assembly can't access return values
*/
bool ret;
address addr;
assembly {
let size := mload(0x40)
mstore(size, _hash)
mstore(add(size, 32), _v)
mstore(add(size, 64), _r)
mstore(add(size, 96), _s)
ret := call(3000, 1, 0, size, 128, size, 32) // NOTE: we can reuse the request memory because we deal with the return code.
addr := mload(size)
}
return (ret, addr);
}
/*
The following function has been written by Alex Beregszaszi, use it under the terms of the MIT license
*/
function ecrecovery(bytes32 _hash, bytes memory _sig) internal returns (bool _success, address _recoveredAddress) {
bytes32 r;
bytes32 s;
uint8 v;
if (_sig.length != 65) {
return (false, address(0));
}
/*
The signature format is a compact form of:
{bytes32 r}{bytes32 s}{uint8 v}
Compact means, uint8 is not padded to 32 bytes.
*/
assembly {
r := mload(add(_sig, 32))
s := mload(add(_sig, 64))
/*
Here we are loading the last 32 bytes. We exploit the fact that
'mload' will pad with zeroes if we overread.
There is no 'mload8' to do this, but that would be nicer.
*/
v := byte(0, mload(add(_sig, 96)))
/*
Alternative solution:
'byte' is not working due to the Solidity parser, so lets
use the second best option, 'and'
v := and(mload(add(_sig, 65)), 255)
*/
}
/*
albeit non-transactional signatures are not specified by the YP, one would expect it
to match the YP range of [27, 28]
geth uses [0, 1] and some clients have followed. This might change, see:
https://github.com/ethereum/go-ethereum/issues/2053
*/
if (v < 27) {
v += 27;
}
if (v != 27 && v != 28) {
return (false, address(0));
}
return safer_ecrecover(_hash, v, r, s);
}
function safeMemoryCleaner() internal pure {
assembly {
let fmem := mload(0x40)
codecopy(fmem, codesize, sub(msize, fmem))
}
}
}
/*
END ORACLIZE_API
*/
contract Ownable {
event TransferredOwnership(address _from, address _to);
event LockedOwnership(address _locked);
address payable private _owner;
bool private _isTransferable;
/// @notice Constructor sets the original owner of the contract and whether or not it is one time transferable.
constructor(address payable _account_, bool _transferable_) internal {
_owner = _account_;
_isTransferable = _transferable_;
// Emit the LockedOwnership event if no longer transferable.
if (!_isTransferable) {
emit LockedOwnership(_account_);
}
emit TransferredOwnership(address(0), _account_);
}
/// @notice Reverts if called by any account other than the owner.
modifier onlyOwner() {
require(_isOwner(msg.sender), "sender is not an owner");
_;
}
/// @notice Allows the current owner to transfer control of the contract to a new address.
/// @param _account address to transfer ownership to.
/// @param _transferable indicates whether to keep the ownership transferable.
function transferOwnership(address payable _account, bool _transferable) external onlyOwner {
// Require that the ownership is transferable.
require(_isTransferable, "ownership is not transferable");
// Require that the new owner is not the zero address.
require(_account != address(0), "owner cannot be set to zero address");
// Set the transferable flag to the value _transferable passed in.
_isTransferable = _transferable;
// Emit the LockedOwnership event if no longer transferable.
if (!_transferable) {
emit LockedOwnership(_account);
}
// Emit the ownership transfer event.
emit TransferredOwnership(_owner, _account);
// Set the owner to the provided address.
_owner = _account;
}
/// @notice check if the ownership is transferable.
/// @return true if the ownership is transferable.
function isTransferable() external view returns (bool) {
return _isTransferable;
}
/// @notice Allows the current owner to relinquish control of the contract.
/// @dev Renouncing to ownership will leave the contract without an owner and unusable.
/// @dev It will not be possible to call the functions with the `onlyOwner` modifier anymore.
function renounceOwnership() external onlyOwner {
// Require that the ownership is transferable.
require(_isTransferable, "ownership is not transferable");
// note that this could be terminal
_owner = address(0);
emit TransferredOwnership(_owner, address(0));
}
/// @notice Find out owner address
/// @return address of the owner.
function owner() public view returns (address payable) {
return _owner;
}
/// @notice Check if owner address
/// @return true if sender is the owner of the contract.
function _isOwner(address _address) internal view returns (bool) {
return _address == _owner;
}
}
contract Date {
bytes32 constant private _JANUARY = keccak256("Jan");
bytes32 constant private _FEBRUARY = keccak256("Feb");
bytes32 constant private _MARCH = keccak256("Mar");
bytes32 constant private _APRIL = keccak256("Apr");
bytes32 constant private _MAY = keccak256("May");
bytes32 constant private _JUNE = keccak256("Jun");
bytes32 constant private _JULY = keccak256("Jul");
bytes32 constant private _AUGUST = keccak256("Aug");
bytes32 constant private _SEPTEMBER = keccak256("Sep");
bytes32 constant private _OCTOBER = keccak256("Oct");
bytes32 constant private _NOVEMBER = keccak256("Nov");
bytes32 constant private _DECEMBER = keccak256("Dec");
/// @return the number of the month based on its name.
/// @param _month the first three letters of a month's name e.g. "Jan".
function _monthToNumber(string memory _month) internal pure returns (uint8) {
bytes32 month = keccak256(abi.encodePacked(_month));
if (month == _JANUARY) {
return 1;
} else if (month == _FEBRUARY) {
return 2;
} else if (month == _MARCH) {
return 3;
} else if (month == _APRIL) {
return 4;
} else if (month == _MAY) {
return 5;
} else if (month == _JUNE) {
return 6;
} else if (month == _JULY) {
return 7;
} else if (month == _AUGUST) {
return 8;
} else if (month == _SEPTEMBER) {
return 9;
} else if (month == _OCTOBER) {
return 10;
} else if (month == _NOVEMBER) {
return 11;
} else if (month == _DECEMBER) {
return 12;
} else {
revert("not a valid month");
}
}
}
contract ResolverBase {
bytes4 private constant INTERFACE_META_ID = 0x01ffc9a7;
function supportsInterface(bytes4 interfaceID) public pure returns(bool) {
return interfaceID == INTERFACE_META_ID;
}
function isAuthorised(bytes32 node) internal view returns(bool);
modifier authorised(bytes32 node) {
require(isAuthorised(node));
_;
}
}
contract NameResolver is ResolverBase {
bytes4 constant private NAME_INTERFACE_ID = 0x691f3431;
event NameChanged(bytes32 indexed node, string name);
mapping(bytes32=>string) names;
/**
* Sets the name associated with an ENS node, for reverse records.
* May only be called by the owner of that node in the ENS registry.
* @param node The node to update.
* @param name The name to set.
*/
function setName(bytes32 node, string calldata name) external authorised(node) {
names[node] = name;
emit NameChanged(node, name);
}
/**
* Returns the name associated with an ENS node, for reverse records.
* Defined in EIP181.
* @param node The ENS node to query.
* @return The associated name.
*/
function name(bytes32 node) external view returns (string memory) {
return names[node];
}
function supportsInterface(bytes4 interfaceID) public pure returns(bool) {
return interfaceID == NAME_INTERFACE_ID || super.supportsInterface(interfaceID);
}
}
contract ABIResolver is ResolverBase {
bytes4 constant private ABI_INTERFACE_ID = 0x2203ab56;
event ABIChanged(bytes32 indexed node, uint256 indexed contentType);
mapping(bytes32=>mapping(uint256=>bytes)) abis;
/**
* Sets the ABI associated with an ENS node.
* Nodes may have one ABI of each content type. To remove an ABI, set it to
* the empty string.
* @param node The node to update.
* @param contentType The content type of the ABI
* @param data The ABI data.
*/
function setABI(bytes32 node, uint256 contentType, bytes calldata data) external authorised(node) {
// Content types must be powers of 2
require(((contentType - 1) & contentType) == 0);
abis[node][contentType] = data;
emit ABIChanged(node, contentType);
}
/**
* Returns the ABI associated with an ENS node.
* Defined in EIP205.
* @param node The ENS node to query
* @param contentTypes A bitwise OR of the ABI formats accepted by the caller.
* @return contentType The content type of the return value
* @return data The ABI data
*/
function ABI(bytes32 node, uint256 contentTypes) external view returns (uint256, bytes memory) {
mapping(uint256=>bytes) storage abiset = abis[node];
for (uint256 contentType = 1; contentType <= contentTypes; contentType <<= 1) {
if ((contentType & contentTypes) != 0 && abiset[contentType].length > 0) {
return (contentType, abiset[contentType]);
}
}
return (0, bytes(""));
}
function supportsInterface(bytes4 interfaceID) public pure returns(bool) {
return interfaceID == ABI_INTERFACE_ID || super.supportsInterface(interfaceID);
}
}
contract ParseIntScientific {
using SafeMath for uint256;
byte constant private _PLUS_ASCII = byte(uint8(43)); //decimal value of '+'
byte constant private _DASH_ASCII = byte(uint8(45)); //decimal value of '-'
byte constant private _DOT_ASCII = byte(uint8(46)); //decimal value of '.'
byte constant private _ZERO_ASCII = byte(uint8(48)); //decimal value of '0'
byte constant private _NINE_ASCII = byte(uint8(57)); //decimal value of '9'
byte constant private _E_ASCII = byte(uint8(69)); //decimal value of 'E'
byte constant private _LOWERCASE_E_ASCII = byte(uint8(101)); //decimal value of 'e'
uint constant private _MAX_PARSED_UINT = 2**54; //max value returned in JSON format above which interoperability issues may be raised
/// @notice ParseIntScientific delegates the call to _parseIntScientific(string, uint) with the 2nd argument being 0.
function _parseIntScientific(string memory _inString) internal pure returns (uint) {
return _parseIntScientific(_inString, 0);
}
/// @notice ParseIntScientificWei parses a rate expressed in ETH and returns its wei denomination
function _parseIntScientificWei(string memory _inString) internal pure returns (uint) {
return _parseIntScientific(_inString, 18);
}
/// @notice ParseIntScientific parses a JSON standard - floating point number.
/// @param _inString is input string.
/// @param _magnitudeMult multiplies the number with 10^_magnitudeMult.
function _parseIntScientific(string memory _inString, uint _magnitudeMult) internal pure returns (uint) {
bytes memory inBytes = bytes(_inString);
uint mint = 0; // the final uint returned
uint mintDec = 0; // the uint following the decimal point
uint mintExp = 0; // the exponent
uint decMinted = 0; // how many decimals were 'minted'.
uint expIndex = 0; // the position in the byte array that 'e' was found (if found)
bool integral = false; // indicates the existence of the integral part, it should always exist (even if 0) e.g. 'e+1' or '.1' is not valid
bool decimals = false; // indicates a decimal number, set to true if '.' is found
bool exp = false; // indicates if the number being parsed has an exponential representation
bool minus = false; // indicated if the exponent is negative
bool plus = false; // indicated if the exponent is positive
uint i;
for (i = 0; i < inBytes.length; i++) {
if ((inBytes[i] >= _ZERO_ASCII) && (inBytes[i] <= _NINE_ASCII) && (!exp)) {
// 'e' not encountered yet, minting integer part or decimals
if (decimals) {
// '.' encountered
// use safeMath in case there is an overflow
mintDec = mintDec.mul(10);
mintDec = mintDec.add(uint8(inBytes[i]) - uint8(_ZERO_ASCII));
decMinted++; //keep track of the #decimals
} else {
// integral part (before '.')
integral = true;
// use safeMath in case there is an overflow
mint = mint.mul(10);
mint = mint.add(uint8(inBytes[i]) - uint8(_ZERO_ASCII));
}
} else if ((inBytes[i] >= _ZERO_ASCII) && (inBytes[i] <= _NINE_ASCII) && (exp)) {
//exponential notation (e-/+) has been detected, mint the exponent
mintExp = mintExp.mul(10);
mintExp = mintExp.add(uint8(inBytes[i]) - uint8(_ZERO_ASCII));
} else if (inBytes[i] == _DOT_ASCII) {
//an integral part before should always exist before '.'
require(integral, "missing integral part");
// an extra decimal point makes the format invalid
require(!decimals, "duplicate decimal point");
//the decimal point should always be before the exponent
require(!exp, "decimal after exponent");
decimals = true;
} else if (inBytes[i] == _DASH_ASCII) {
// an extra '-' should be considered an invalid character
require(!minus, "duplicate -");
require(!plus, "extra sign");
require(expIndex + 1 == i, "- sign not immediately after e");
minus = true;
} else if (inBytes[i] == _PLUS_ASCII) {
// an extra '+' should be considered an invalid character
require(!plus, "duplicate +");
require(!minus, "extra sign");
require(expIndex + 1 == i, "+ sign not immediately after e");
plus = true;
} else if ((inBytes[i] == _E_ASCII) || (inBytes[i] == _LOWERCASE_E_ASCII)) {
//an integral part before should always exist before 'e'
require(integral, "missing integral part");
// an extra 'e' or 'E' should be considered an invalid character
require(!exp, "duplicate exponent symbol");
exp = true;
expIndex = i;
} else {
revert("invalid digit");
}
}
if (minus || plus) {
// end of string e[x|-] without specifying the exponent
require(i > expIndex + 2);
} else if (exp) {
// end of string (e) without specifying the exponent
require(i > expIndex + 1);
}
if (minus) {
// e^(-x)
if (mintExp >= _magnitudeMult) {
// the (negative) exponent is bigger than the given parameter for "shifting left".
// use integer division to reduce the precision.
require(mintExp - _magnitudeMult < 78, "exponent > 77"); //
mint /= 10 ** (mintExp - _magnitudeMult);
return mint;
} else {
// the (negative) exponent is smaller than the given parameter for "shifting left".
//no need for underflow check
_magnitudeMult = _magnitudeMult - mintExp;
}
} else {
// e^(+x), positive exponent or no exponent
// just shift left as many times as indicated by the exponent and the shift parameter
_magnitudeMult = _magnitudeMult.add(mintExp);
}
if (_magnitudeMult >= decMinted) {
// the decimals are fewer or equal than the shifts: use all of them
// shift number and add the decimals at the end
// include decimals if present in the original input
require(decMinted < 78, "more than 77 decimal digits parsed"); //
mint = mint.mul(10 ** (decMinted));
mint = mint.add(mintDec);
//// add zeros at the end if the decimals were fewer than #_magnitudeMult
require(_magnitudeMult - decMinted < 78, "exponent > 77"); //
mint = mint.mul(10 ** (_magnitudeMult - decMinted));
} else {
// the decimals are more than the #_magnitudeMult shifts
// use only the ones needed, discard the rest
decMinted -= _magnitudeMult;
require(decMinted < 78, "more than 77 decimal digits parsed"); //
mintDec /= 10 ** (decMinted);
// shift number and add the decimals at the end
require(_magnitudeMult < 78, "more than 77 decimal digits parsed"); //
mint = mint.mul(10 ** (_magnitudeMult));
mint = mint.add(mintDec);
}
require(mint < _MAX_PARSED_UINT, "number exceeded maximum allowed value for safe json decoding");
return mint;
}
}
contract ContentHashResolver is ResolverBase {
bytes4 constant private CONTENT_HASH_INTERFACE_ID = 0xbc1c58d1;
event ContenthashChanged(bytes32 indexed node, bytes hash);
mapping(bytes32=>bytes) hashes;
/**
* Sets the contenthash associated with an ENS node.
* May only be called by the owner of that node in the ENS registry.
* @param node The node to update.
* @param hash The contenthash to set
*/
function setContenthash(bytes32 node, bytes calldata hash) external authorised(node) {
hashes[node] = hash;
emit ContenthashChanged(node, hash);
}
/**
* Returns the contenthash associated with an ENS node.
* @param node The ENS node to query.
* @return The associated contenthash.
*/
function contenthash(bytes32 node) external view returns (bytes memory) {
return hashes[node];
}
function supportsInterface(bytes4 interfaceID) public pure returns(bool) {
return interfaceID == CONTENT_HASH_INTERFACE_ID || super.supportsInterface(interfaceID);
}
}
contract TextResolver is ResolverBase {
bytes4 constant private TEXT_INTERFACE_ID = 0x59d1d43c;
event TextChanged(bytes32 indexed node, string indexedKey, string key);
mapping(bytes32=>mapping(string=>string)) texts;
/**
* Sets the text data associated with an ENS node and key.
* May only be called by the owner of that node in the ENS registry.
* @param node The node to update.
* @param key The key to set.
* @param value The text data value to set.
*/
function setText(bytes32 node, string calldata key, string calldata value) external authorised(node) {
texts[node][key] = value;
emit TextChanged(node, key, key);
}
/**
* Returns the text data associated with an ENS node and key.
* @param node The ENS node to query.
* @param key The text data key to query.
* @return The associated text data.
*/
function text(bytes32 node, string calldata key) external view returns (string memory) {
return texts[node][key];
}
function supportsInterface(bytes4 interfaceID) public pure returns(bool) {
return interfaceID == TEXT_INTERFACE_ID || super.supportsInterface(interfaceID);
}
}
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(ERC20 token, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(ERC20 token, address from, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(ERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(ERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(ERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function callOptionalReturn(ERC20 token, bytes memory data) internal {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract AddrResolver is ResolverBase {
bytes4 constant private ADDR_INTERFACE_ID = 0x3b3b57de;
event AddrChanged(bytes32 indexed node, address a);
mapping(bytes32=>address) addresses;
/**
* Sets the address associated with an ENS node.
* May only be called by the owner of that node in the ENS registry.
* @param node The node to update.
* @param addr The address to set.
*/
function setAddr(bytes32 node, address addr) external authorised(node) {
addresses[node] = addr;
emit AddrChanged(node, addr);
}
/**
* Returns the address associated with an ENS node.
* @param node The ENS node to query.
* @return The associated address.
*/
function addr(bytes32 node) public view returns (address) {
return addresses[node];
}
function supportsInterface(bytes4 interfaceID) public pure returns(bool) {
return interfaceID == ADDR_INTERFACE_ID || super.supportsInterface(interfaceID);
}
}
library BytesUtils {
using SafeMath for uint256;
/// @dev This function converts to an address
/// @param _bts bytes
/// @param _from start position
function _bytesToAddress(bytes memory _bts, uint _from) internal pure returns (address) {
require(_bts.length >= _from.add(20), "slicing out of range");
bytes20 convertedAddress;
uint startByte = _from.add(32); //first 32 bytes denote the array length
assembly {
convertedAddress := mload(add(_bts, startByte))
}
return address(convertedAddress);
}
/// @dev This function slices bytes into bytes4
/// @param _bts some bytes
/// @param _from start position
function _bytesToBytes4(bytes memory _bts, uint _from) internal pure returns (bytes4) {
require(_bts.length >= _from.add(4), "slicing out of range");
bytes4 slicedBytes4;
uint startByte = _from.add(32); //first 32 bytes denote the array length
assembly {
slicedBytes4 := mload(add(_bts, startByte))
}
return slicedBytes4;
}
/// @dev This function slices a uint
/// @param _bts some bytes
/// @param _from start position
// credit to https://ethereum.stackexchange.com/questions/51229/how-to-convert-bytes-to-uint-in-solidity
// and Nick Johnson https://ethereum.stackexchange.com/questions/4170/how-to-convert-a-uint-to-bytes-in-solidity/4177#4177
function _bytesToUint256(bytes memory _bts, uint _from) internal pure returns (uint) {
require(_bts.length >= _from.add(32), "slicing out of range");
uint convertedUint256;
uint startByte = _from.add(32); //first 32 bytes denote the array length
assembly {
convertedUint256 := mload(add(_bts, startByte))
}
return convertedUint256;
}
}
contract PubkeyResolver is ResolverBase {
bytes4 constant private PUBKEY_INTERFACE_ID = 0xc8690233;
event PubkeyChanged(bytes32 indexed node, bytes32 x, bytes32 y);
struct PublicKey {
bytes32 x;
bytes32 y;
}
mapping(bytes32=>PublicKey) pubkeys;
/**
* Sets the SECP256k1 public key associated with an ENS node.
* @param node The ENS node to query
* @param x the X coordinate of the curve point for the public key.
* @param y the Y coordinate of the curve point for the public key.
*/
function setPubkey(bytes32 node, bytes32 x, bytes32 y) external authorised(node) {
pubkeys[node] = PublicKey(x, y);
emit PubkeyChanged(node, x, y);
}
/**
* Returns the SECP256k1 public key associated with an ENS node.
* Defined in EIP 619.
* @param node The ENS node to query
* @return x, y the X and Y coordinates of the curve point for the public key.
*/
function pubkey(bytes32 node) external view returns (bytes32 x, bytes32 y) {
return (pubkeys[node].x, pubkeys[node].y);
}
function supportsInterface(bytes4 interfaceID) public pure returns(bool) {
return interfaceID == PUBKEY_INTERFACE_ID || super.supportsInterface(interfaceID);
}
}
contract InterfaceResolver is ResolverBase, AddrResolver {
bytes4 constant private INTERFACE_INTERFACE_ID = bytes4(keccak256("interfaceImplementer(bytes32,bytes4)"));
bytes4 private constant INTERFACE_META_ID = 0x01ffc9a7;
event InterfaceChanged(bytes32 indexed node, bytes4 indexed interfaceID, address implementer);
mapping(bytes32=>mapping(bytes4=>address)) interfaces;
/**
* Sets an interface associated with a name.
* Setting the address to 0 restores the default behaviour of querying the contract at `addr()` for interface support.
* @param node The node to update.
* @param interfaceID The EIP 168 interface ID.
* @param implementer The address of a contract that implements this interface for this node.
*/
function setInterface(bytes32 node, bytes4 interfaceID, address implementer) external authorised(node) {
interfaces[node][interfaceID] = implementer;
emit InterfaceChanged(node, interfaceID, implementer);
}
/**
* Returns the address of a contract that implements the specified interface for this name.
* If an implementer has not been set for this interfaceID and name, the resolver will query
* the contract at `addr()`. If `addr()` is set, a contract exists at that address, and that
* contract implements EIP168 and returns `true` for the specified interfaceID, its address
* will be returned.
* @param node The ENS node to query.
* @param interfaceID The EIP 168 interface ID to check for.
* @return The address that implements this interface, or 0 if the interface is unsupported.
*/
function interfaceImplementer(bytes32 node, bytes4 interfaceID) external view returns (address) {
address implementer = interfaces[node][interfaceID];
if(implementer != address(0)) {
return implementer;
}
address a = addr(node);
if(a == address(0)) {
return address(0);
}
(bool success, bytes memory returnData) = a.staticcall(abi.encodeWithSignature("supportsInterface(bytes4)", INTERFACE_META_ID));
if(!success || returnData.length < 32 || returnData[31] == 0) {
// EIP 168 not supported by target
return address(0);
}
(success, returnData) = a.staticcall(abi.encodeWithSignature("supportsInterface(bytes4)", interfaceID));
if(!success || returnData.length < 32 || returnData[31] == 0) {
// Specified interface not supported by target
return address(0);
}
return a;
}
function supportsInterface(bytes4 interfaceID) public pure returns(bool) {
return interfaceID == INTERFACE_INTERFACE_ID || super.supportsInterface(interfaceID);
}
}
contract Transferrable {
using SafeERC20 for ERC20;
/// @dev This function is used to move tokens sent accidentally to this contract method.
/// @dev The owner can chose the new destination address
/// @param _to is the recipient's address.
/// @param _asset is the address of an ERC20 token or 0x0 for ether.
/// @param _amount is the amount to be transferred in base units.
function _safeTransfer(address payable _to, address _asset, uint _amount) internal {
// address(0) is used to denote ETH
if (_asset == address(0)) {
_to.transfer(_amount);
} else {
ERC20(_asset).safeTransfer(_to, _amount);
}
}
}
contract PublicResolver is ABIResolver, AddrResolver, ContentHashResolver, InterfaceResolver, NameResolver, PubkeyResolver, TextResolver {
ENS ens;
/**
* A mapping of authorisations. An address that is authorised for a name
* may make any changes to the name that the owner could, but may not update
* the set of authorisations.
* (node, owner, caller) => isAuthorised
*/
mapping(bytes32=>mapping(address=>mapping(address=>bool))) public authorisations;
event AuthorisationChanged(bytes32 indexed node, address indexed owner, address indexed target, bool isAuthorised);
constructor(ENS _ens) public {
ens = _ens;
}
/**
* @dev Sets or clears an authorisation.
* Authorisations are specific to the caller. Any account can set an authorisation
* for any name, but the authorisation that is checked will be that of the
* current owner of a name. Thus, transferring a name effectively clears any
* existing authorisations, and new authorisations can be set in advance of
* an ownership transfer if desired.
*
* @param node The name to change the authorisation on.
* @param target The address that is to be authorised or deauthorised.
* @param isAuthorised True if the address should be authorised, or false if it should be deauthorised.
*/
function setAuthorisation(bytes32 node, address target, bool isAuthorised) external {
authorisations[node][msg.sender][target] = isAuthorised;
emit AuthorisationChanged(node, msg.sender, target, isAuthorised);
}
function isAuthorised(bytes32 node) internal view returns(bool) {
address owner = ens.owner(node);
return owner == msg.sender || authorisations[node][owner][msg.sender];
}
}
interface IController {
function isController(address) external view returns (bool);
function isAdmin(address) external view returns (bool);
}
/// @title Controller stores a list of controller addresses that can be used for authentication in other contracts.
/// @notice The Controller implements a hierarchy of concepts, Owner, Admin, and the Controllers.
/// @dev Owner can change the Admins
/// @dev Admins and can the Controllers
/// @dev Controllers are used by the application.
contract Controller is IController, Ownable, Transferrable {
event AddedController(address _sender, address _controller);
event RemovedController(address _sender, address _controller);
event AddedAdmin(address _sender, address _admin);
event RemovedAdmin(address _sender, address _admin);
event Claimed(address _to, address _asset, uint _amount);
event Stopped(address _sender);
event Started(address _sender);
mapping (address => bool) private _isAdmin;
uint private _adminCount;
mapping (address => bool) private _isController;
uint private _controllerCount;
bool private _stopped;
/// @notice Constructor initializes the owner with the provided address.
/// @param _ownerAddress_ address of the owner.
constructor(address payable _ownerAddress_) Ownable(_ownerAddress_, false) public {}
/// @notice Checks if message sender is an admin.
modifier onlyAdmin() {
require(isAdmin(msg.sender), "sender is not an admin");
_;
}
/// @notice Check if Owner or Admin
modifier onlyAdminOrOwner() {
require(_isOwner(msg.sender) || isAdmin(msg.sender), "sender is not an admin");
_;
}
/// @notice Check if controller is stopped
modifier notStopped() {
require(!isStopped(), "controller is stopped");
_;
}
/// @notice Add a new admin to the list of admins.
/// @param _account address to add to the list of admins.
function addAdmin(address _account) external onlyOwner notStopped {
_addAdmin(_account);
}
/// @notice Remove a admin from the list of admins.
/// @param _account address to remove from the list of admins.
function removeAdmin(address _account) external onlyOwner {
_removeAdmin(_account);
}
/// @return the current number of admins.
function adminCount() external view returns (uint) {
return _adminCount;
}
/// @notice Add a new controller to the list of controllers.
/// @param _account address to add to the list of controllers.
function addController(address _account) external onlyAdminOrOwner notStopped {
_addController(_account);
}
/// @notice Remove a controller from the list of controllers.
/// @param _account address to remove from the list of controllers.
function removeController(address _account) external onlyAdminOrOwner {
_removeController(_account);
}
/// @notice count the Controllers
/// @return the current number of controllers.
function controllerCount() external view returns (uint) {
return _controllerCount;
}
/// @notice is an address an Admin?
/// @return true if the provided account is an admin.
function isAdmin(address _account) public view notStopped returns (bool) {
return _isAdmin[_account];
}
/// @notice is an address a Controller?
/// @return true if the provided account is a controller.
function isController(address _account) public view notStopped returns (bool) {
return _isController[_account];
}
/// @notice this function can be used to see if the controller has been stopped
/// @return true is the Controller has been stopped
function isStopped() public view returns (bool) {
return _stopped;
}
/// @notice Internal-only function that adds a new admin.
function _addAdmin(address _account) private {
require(!_isAdmin[_account], "provided account is already an admin");
require(!_isController[_account], "provided account is already a controller");
require(!_isOwner(_account), "provided account is already the owner");
require(_account != address(0), "provided account is the zero address");
_isAdmin[_account] = true;
_adminCount++;
emit AddedAdmin(msg.sender, _account);
}
/// @notice Internal-only function that removes an existing admin.
function _removeAdmin(address _account) private {
require(_isAdmin[_account], "provided account is not an admin");
_isAdmin[_account] = false;
_adminCount--;
emit RemovedAdmin(msg.sender, _account);
}
/// @notice Internal-only function that adds a new controller.
function _addController(address _account) private {
require(!_isAdmin[_account], "provided account is already an admin");
require(!_isController[_account], "provided account is already a controller");
require(!_isOwner(_account), "provided account is already the owner");
require(_account != address(0), "provided account is the zero address");
_isController[_account] = true;
_controllerCount++;
emit AddedController(msg.sender, _account);
}
/// @notice Internal-only function that removes an existing controller.
function _removeController(address _account) private {
require(_isController[_account], "provided account is not a controller");
_isController[_account] = false;
_controllerCount--;
emit RemovedController(msg.sender, _account);
}
/// @notice stop our controllers and admins from being useable
function stop() external onlyAdminOrOwner {
_stopped = true;
emit Stopped(msg.sender);
}
/// @notice start our controller again
function start() external onlyOwner {
_stopped = false;
emit Started(msg.sender);
}
//// @notice Withdraw tokens from the smart contract to the specified account.
function claim(address payable _to, address _asset, uint _amount) external onlyAdmin notStopped {
_safeTransfer(_to, _asset, _amount);
emit Claimed(_to, _asset, _amount);
}
}
contract ENSResolvable {
/// @notice _ens is an instance of ENS
ENS private _ens;
/// @notice _ensRegistry points to the ENS registry smart contract.
address private _ensRegistry;
/// @param _ensReg_ is the ENS registry used
constructor(address _ensReg_) internal {
_ensRegistry = _ensReg_;
_ens = ENS(_ensRegistry);
}
/// @notice this is used to that one can observe which ENS registry is being used
function ensRegistry() external view returns (address) {
return _ensRegistry;
}
/// @notice helper function used to get the address of a node
/// @param _node of the ENS entry that needs resolving
/// @return the address of the said node
function _ensResolve(bytes32 _node) internal view returns (address) {
return PublicResolver(_ens.resolver(_node)).addr(_node);
}
}
contract Controllable is ENSResolvable {
/// @dev Is the registered ENS node identifying the controller contract.
bytes32 private _controllerNode;
/// @notice Constructor initializes the controller contract object.
/// @param _controllerNode_ is the ENS node of the Controller.
constructor(bytes32 _controllerNode_) internal {
_controllerNode = _controllerNode_;
}
/// @notice Checks if message sender is a controller.
modifier onlyController() {
require(_isController(msg.sender), "sender is not a controller");
_;
}
/// @notice Checks if message sender is an admin.
modifier onlyAdmin() {
require(_isAdmin(msg.sender), "sender is not an admin");
_;
}
/// @return the controller node registered in ENS.
function controllerNode() external view returns (bytes32) {
return _controllerNode;
}
/// @return true if the provided account is a controller.
function _isController(address _account) internal view returns (bool) {
return IController(_ensResolve(_controllerNode)).isController(_account);
}
/// @return true if the provided account is an admin.
function _isAdmin(address _account) internal view returns (bool) {
return IController(_ensResolve(_controllerNode)).isAdmin(_account);
}
}
interface ITokenWhitelist {
function getTokenInfo(address) external view returns (string memory, uint256, uint256, bool, bool, bool, uint256);
function getStablecoinInfo() external view returns (string memory, uint256, uint256, bool, bool, bool, uint256);
function tokenAddressArray() external view returns (address[] memory);
function redeemableTokens() external view returns (address[] memory);
function methodIdWhitelist(bytes4) external view returns (bool);
function getERC20RecipientAndAmount(address, bytes calldata) external view returns (address, uint);
function stablecoin() external view returns (address);
function updateTokenRate(address, uint, uint) external;
}
/// @title TokenWhitelist stores a list of tokens used by the Consumer Contract Wallet, the Oracle, the TKN Holder and the TKN Licence Contract
contract TokenWhitelist is ENSResolvable, Controllable, Transferrable {
using strings for *;
using SafeMath for uint256;
using BytesUtils for bytes;
event UpdatedTokenRate(address _sender, address _token, uint _rate);
event UpdatedTokenLoadable(address _sender, address _token, bool _loadable);
event UpdatedTokenRedeemable(address _sender, address _token, bool _redeemable);
event AddedToken(address _sender, address _token, string _symbol, uint _magnitude, bool _loadable, bool _redeemable);
event RemovedToken(address _sender, address _token);
event AddedMethodId(bytes4 _methodId);
event RemovedMethodId(bytes4 _methodId);
event AddedExclusiveMethod(address _token, bytes4 _methodId);
event RemovedExclusiveMethod(address _token, bytes4 _methodId);
event Claimed(address _to, address _asset, uint _amount);
/// @dev these are the methods whitelisted by default in executeTransaction() for protected tokens
bytes4 private constant _APPROVE = 0x095ea7b3; // keccak256(approve(address,uint256)) => 0x095ea7b3
bytes4 private constant _BURN = 0x42966c68; // keccak256(burn(uint256)) => 0x42966c68
bytes4 private constant _TRANSFER= 0xa9059cbb; // keccak256(transfer(address,uint256)) => 0xa9059cbb
bytes4 private constant _TRANSFER_FROM = 0x23b872dd; // keccak256(transferFrom(address,address,uint256)) => 0x23b872dd
struct Token {
string symbol; // Token symbol
uint magnitude; // 10^decimals
uint rate; // Token exchange rate in wei
bool available; // Flags if the token is available or not
bool loadable; // Flags if token is loadable to the TokenCard
bool redeemable; // Flags if token is redeemable in the TKN Holder contract
uint lastUpdate; // Time of the last rate update
}
mapping(address => Token) private _tokenInfoMap;
// @notice specifies whitelisted methodIds for protected tokens in wallet's excuteTranaction() e.g. keccak256(transfer(address,uint256)) => 0xa9059cbb
mapping(bytes4 => bool) private _methodIdWhitelist;
address[] private _tokenAddressArray;
/// @notice keeping track of how many redeemable tokens are in the tokenWhitelist
uint private _redeemableCounter;
/// @notice Address of the stablecoin.
address private _stablecoin;
/// @notice is registered ENS node identifying the oracle contract.
bytes32 private _oracleNode;
/// @notice Constructor initializes ENSResolvable, and Controllable.
/// @param _ens_ is the ENS registry address.
/// @param _oracleNode_ is the ENS node of the Oracle.
/// @param _controllerNode_ is our Controllers node.
/// @param _stablecoinAddress_ is the address of the stablecoint used by the wallet for the card load limit.
constructor(address _ens_, bytes32 _oracleNode_, bytes32 _controllerNode_, address _stablecoinAddress_) ENSResolvable(_ens_) Controllable(_controllerNode_) public {
_oracleNode = _oracleNode_;
_stablecoin = _stablecoinAddress_;
//a priori ERC20 whitelisted methods
_methodIdWhitelist[_APPROVE] = true;
_methodIdWhitelist[_BURN] = true;
_methodIdWhitelist[_TRANSFER] = true;
_methodIdWhitelist[_TRANSFER_FROM] = true;
}
modifier onlyAdminOrOracle() {
address oracleAddress = _ensResolve(_oracleNode);
require (_isAdmin(msg.sender) || msg.sender == oracleAddress, "either oracle or admin");
_;
}
/// @notice Add ERC20 tokens to the list of whitelisted tokens.
/// @param _tokens ERC20 token contract addresses.
/// @param _symbols ERC20 token names.
/// @param _magnitude 10 to the power of number of decimal places used by each ERC20 token.
/// @param _loadable is a bool that states whether or not a token is loadable to the TokenCard.
/// @param _redeemable is a bool that states whether or not a token is redeemable in the TKN Holder Contract.
/// @param _lastUpdate is a unit representing an ISO datetime e.g. 20180913153211.
function addTokens(address[] calldata _tokens, bytes32[] calldata _symbols, uint[] calldata _magnitude, bool[] calldata _loadable, bool[] calldata _redeemable, uint _lastUpdate) external onlyAdmin {
// Require that all parameters have the same length.
require(_tokens.length == _symbols.length && _tokens.length == _magnitude.length && _tokens.length == _loadable.length && _tokens.length == _loadable.length, "parameter lengths do not match");
// Add each token to the list of supported tokens.
for (uint i = 0; i < _tokens.length; i++) {
// Require that the token isn't already available.
require(!_tokenInfoMap[_tokens[i]].available, "token already available");
// Store the intermediate values.
string memory symbol = _symbols[i].toSliceB32().toString();
// Add the token to the token list.
_tokenInfoMap[_tokens[i]] = Token({
symbol : symbol,
magnitude : _magnitude[i],
rate : 0,
available : true,
loadable : _loadable[i],
redeemable: _redeemable[i],
lastUpdate : _lastUpdate
});
// Add the token address to the address list.
_tokenAddressArray.push(_tokens[i]);
//if the token is redeemable increase the redeemableCounter
if (_redeemable[i]){
_redeemableCounter = _redeemableCounter.add(1);
}
// Emit token addition event.
emit AddedToken(msg.sender, _tokens[i], symbol, _magnitude[i], _loadable[i], _redeemable[i]);
}
}
/// @notice Remove ERC20 tokens from the whitelist of tokens.
/// @param _tokens ERC20 token contract addresses.
function removeTokens(address[] calldata _tokens) external onlyAdmin {
// Delete each token object from the list of supported tokens based on the addresses provided.
for (uint i = 0; i < _tokens.length; i++) {
// Store the token address.
address token = _tokens[i];
//token must be available, reverts on duplicates as well
require(_tokenInfoMap[token].available, "token is not available");
//if the token is redeemable decrease the redeemableCounter
if (_tokenInfoMap[token].redeemable){
_redeemableCounter = _redeemableCounter.sub(1);
}
// Delete the token object.
delete _tokenInfoMap[token];
// Remove the token address from the address list.
for (uint j = 0; j < _tokenAddressArray.length.sub(1); j++) {
if (_tokenAddressArray[j] == token) {
_tokenAddressArray[j] = _tokenAddressArray[_tokenAddressArray.length.sub(1)];
break;
}
}
_tokenAddressArray.length--;
// Emit token removal event.
emit RemovedToken(msg.sender, token);
}
}
/// @notice based on the method it returns the recipient address and amount/value, ERC20 specific.
/// @param _data is the transaction payload.
function getERC20RecipientAndAmount(address _token, bytes calldata _data) external view returns (address, uint) {
// Require that there exist enough bytes for encoding at least a method signature + data in the transaction payload:
// 4 (signature) + 32(address or uint256)
require(_data.length >= 4 + 32, "not enough method-encoding bytes");
// Get the method signature
bytes4 signature = _data._bytesToBytes4(0);
// Check if method Id is supported
require(isERC20MethodSupported(_token, signature), "unsupported method");
// returns the recipient's address and amount is the value to be transferred
if (signature == _BURN) {
// 4 (signature) + 32(uint256)
return (_token, _data._bytesToUint256(4));
} else if (signature == _TRANSFER_FROM) {
// 4 (signature) + 32(address) + 32(address) + 32(uint256)
require(_data.length >= 4 + 32 + 32 + 32, "not enough data for transferFrom");
return ( _data._bytesToAddress(4 + 32 + 12), _data._bytesToUint256(4 + 32 + 32));
} else { //transfer or approve
// 4 (signature) + 32(address) + 32(uint)
require(_data.length >= 4 + 32 + 32, "not enough data for transfer/appprove");
return (_data._bytesToAddress(4 + 12), _data._bytesToUint256(4 + 32));
}
}
/// @notice Toggles whether or not a token is loadable or not.
function setTokenLoadable(address _token, bool _loadable) external onlyAdmin {
// Require that the token exists.
require(_tokenInfoMap[_token].available, "token is not available");
// this sets the loadable flag to the value passed in
_tokenInfoMap[_token].loadable = _loadable;
emit UpdatedTokenLoadable(msg.sender, _token, _loadable);
}
/// @notice Toggles whether or not a token is redeemable or not.
function setTokenRedeemable(address _token, bool _redeemable) external onlyAdmin {
// Require that the token exists.
require(_tokenInfoMap[_token].available, "token is not available");
// this sets the redeemable flag to the value passed in
_tokenInfoMap[_token].redeemable = _redeemable;
emit UpdatedTokenRedeemable(msg.sender, _token, _redeemable);
}
/// @notice Update ERC20 token exchange rate.
/// @param _token ERC20 token contract address.
/// @param _rate ERC20 token exchange rate in wei.
/// @param _updateDate date for the token updates. This will be compared to when oracle updates are received.
function updateTokenRate(address _token, uint _rate, uint _updateDate) external onlyAdminOrOracle {
// Require that the token exists.
require(_tokenInfoMap[_token].available, "token is not available");
// Update the token's rate.
_tokenInfoMap[_token].rate = _rate;
// Update the token's last update timestamp.
_tokenInfoMap[_token].lastUpdate = _updateDate;
// Emit the rate update event.
emit UpdatedTokenRate(msg.sender, _token, _rate);
}
//// @notice Withdraw tokens from the smart contract to the specified account.
function claim(address payable _to, address _asset, uint _amount) external onlyAdmin {
_safeTransfer(_to, _asset, _amount);
emit Claimed(_to, _asset, _amount);
}
/// @notice This returns all of the fields for a given token.
/// @param _a is the address of a given token.
/// @return string of the token's symbol.
/// @return uint of the token's magnitude.
/// @return uint of the token's exchange rate to ETH.
/// @return bool whether the token is available.
/// @return bool whether the token is loadable to the TokenCard.
/// @return bool whether the token is redeemable to the TKN Holder Contract.
/// @return uint of the lastUpdated time of the token's exchange rate.
function getTokenInfo(address _a) external view returns (string memory, uint256, uint256, bool, bool, bool, uint256) {
Token storage tokenInfo = _tokenInfoMap[_a];
return (tokenInfo.symbol, tokenInfo.magnitude, tokenInfo.rate, tokenInfo.available, tokenInfo.loadable, tokenInfo.redeemable, tokenInfo.lastUpdate);
}
/// @notice This returns all of the fields for our StableCoin.
/// @return string of the token's symbol.
/// @return uint of the token's magnitude.
/// @return uint of the token's exchange rate to ETH.
/// @return bool whether the token is available.
/// @return bool whether the token is loadable to the TokenCard.
/// @return bool whether the token is redeemable to the TKN Holder Contract.
/// @return uint of the lastUpdated time of the token's exchange rate.
function getStablecoinInfo() external view returns (string memory, uint256, uint256, bool, bool, bool, uint256) {
Token storage stablecoinInfo = _tokenInfoMap[_stablecoin];
return (stablecoinInfo.symbol, stablecoinInfo.magnitude, stablecoinInfo.rate, stablecoinInfo.available, stablecoinInfo.loadable, stablecoinInfo.redeemable, stablecoinInfo.lastUpdate);
}
/// @notice This returns an array of all whitelisted token addresses.
/// @return address[] of whitelisted tokens.
function tokenAddressArray() external view returns (address[] memory) {
return _tokenAddressArray;
}
/// @notice This returns an array of all redeemable token addresses.
/// @return address[] of redeemable tokens.
function redeemableTokens() external view returns (address[] memory) {
address[] memory redeemableAddresses = new address[](_redeemableCounter);
uint redeemableIndex = 0;
for (uint i = 0; i < _tokenAddressArray.length; i++) {
address token = _tokenAddressArray[i];
if (_tokenInfoMap[token].redeemable){
redeemableAddresses[redeemableIndex] = token;
redeemableIndex += 1;
}
}
return redeemableAddresses;
}
/// @notice This returns true if a method Id is supported for the specific token.
/// @return true if _methodId is supported in general or just for the specific token.
function isERC20MethodSupported(address _token, bytes4 _methodId) public view returns (bool) {
require(_tokenInfoMap[_token].available, "non-existing token");
return (_methodIdWhitelist[_methodId]);
}
/// @notice This returns true if the method is supported for all protected tokens.
/// @return true if _methodId is in the method whitelist.
function isERC20MethodWhitelisted(bytes4 _methodId) external view returns (bool) {
return (_methodIdWhitelist[_methodId]);
}
/// @notice This returns the number of redeemable tokens.
/// @return current # of redeemables.
function redeemableCounter() external view returns (uint) {
return _redeemableCounter;
}
/// @notice This returns the address of our stablecoin of choice.
/// @return the address of the stablecoin contract.
function stablecoin() external view returns (address) {
return _stablecoin;
}
/// @notice this returns the node hash of our Oracle.
/// @return the oracle node registered in ENS.
function oracleNode() external view returns (bytes32) {
return _oracleNode;
}
}
contract TokenWhitelistable is ENSResolvable {
/// @notice Is the registered ENS node identifying the tokenWhitelist contract
bytes32 private _tokenWhitelistNode;
/// @notice Constructor initializes the TokenWhitelistable object.
/// @param _tokenWhitelistNode_ is the ENS node of the TokenWhitelist.
constructor(bytes32 _tokenWhitelistNode_) internal {
_tokenWhitelistNode = _tokenWhitelistNode_;
}
/// @notice This shows what TokenWhitelist is being used
/// @return TokenWhitelist's node registered in ENS.
function tokenWhitelistNode() external view returns (bytes32) {
return _tokenWhitelistNode;
}
/// @notice This returns all of the fields for a given token.
/// @param _a is the address of a given token.
/// @return string of the token's symbol.
/// @return uint of the token's magnitude.
/// @return uint of the token's exchange rate to ETH.
/// @return bool whether the token is available.
/// @return bool whether the token is loadable to the TokenCard.
/// @return bool whether the token is redeemable to the TKN Holder Contract.
/// @return uint of the lastUpdated time of the token's exchange rate.
function _getTokenInfo(address _a) internal view returns (string memory, uint256, uint256, bool, bool, bool, uint256) {
return ITokenWhitelist(_ensResolve(_tokenWhitelistNode)).getTokenInfo(_a);
}
/// @notice This returns all of the fields for our stablecoin token.
/// @return string of the token's symbol.
/// @return uint of the token's magnitude.
/// @return uint of the token's exchange rate to ETH.
/// @return bool whether the token is available.
/// @return bool whether the token is loadable to the TokenCard.
/// @return bool whether the token is redeemable to the TKN Holder Contract.
/// @return uint of the lastUpdated time of the token's exchange rate.
function _getStablecoinInfo() internal view returns (string memory, uint256, uint256, bool, bool, bool, uint256) {
return ITokenWhitelist(_ensResolve(_tokenWhitelistNode)).getStablecoinInfo();
}
/// @notice This returns an array of our whitelisted addresses.
/// @return address[] of our whitelisted tokens.
function _tokenAddressArray() internal view returns (address[] memory) {
return ITokenWhitelist(_ensResolve(_tokenWhitelistNode)).tokenAddressArray();
}
/// @notice This returns an array of all redeemable token addresses.
/// @return address[] of redeemable tokens.
function _redeemableTokens() internal view returns (address[] memory) {
return ITokenWhitelist(_ensResolve(_tokenWhitelistNode)).redeemableTokens();
}
/// @notice Update ERC20 token exchange rate.
/// @param _token ERC20 token contract address.
/// @param _rate ERC20 token exchange rate in wei.
/// @param _updateDate date for the token updates. This will be compared to when oracle updates are received.
function _updateTokenRate(address _token, uint _rate, uint _updateDate) internal {
ITokenWhitelist(_ensResolve(_tokenWhitelistNode)).updateTokenRate(_token, _rate, _updateDate);
}
/// @notice based on the method it returns the recipient address and amount/value, ERC20 specific.
/// @param _data is the transaction payload.
function _getERC20RecipientAndAmount(address _destination, bytes memory _data) internal view returns (address, uint) {
return ITokenWhitelist(_ensResolve(_tokenWhitelistNode)).getERC20RecipientAndAmount(_destination, _data);
}
/// @notice Checks whether a token is available.
/// @return bool available or not.
function _isTokenAvailable(address _a) internal view returns (bool) {
( , , , bool available, , , ) = _getTokenInfo(_a);
return available;
}
/// @notice Checks whether a token is redeemable.
/// @return bool redeemable or not.
function _isTokenRedeemable(address _a) internal view returns (bool) {
( , , , , , bool redeemable, ) = _getTokenInfo(_a);
return redeemable;
}
/// @notice Checks whether a token is loadable.
/// @return bool loadable or not.
function _isTokenLoadable(address _a) internal view returns (bool) {
( , , , , bool loadable, , ) = _getTokenInfo(_a);
return loadable;
}
/// @notice This gets the address of the stablecoin.
/// @return the address of the stablecoin contract.
function _stablecoin() internal view returns (address) {
return ITokenWhitelist(_ensResolve(_tokenWhitelistNode)).stablecoin();
}
}
contract Oracle is ENSResolvable, usingOraclize, Transferrable, Base64, Date, Controllable, ParseIntScientific, TokenWhitelistable {
using strings for *;
using SafeMath for uint256;
/*******************/
/* Events */
/*****************/
event SetGasPrice(address _sender, uint _gasPrice);
event RequestedUpdate(string _symbol, bytes32 _queryID);
event FailedUpdateRequest(string _reason);
event VerifiedProof(bytes _publicKey, string _result);
event SetCryptoComparePublicKey(address _sender, bytes _publicKey);
event Claimed(address _to, address _asset, uint _amount);
/**********************/
/* Constants */
/********************/
uint constant private _PROOF_LEN = 165;
uint constant private _ECDSA_SIG_LEN = 65;
uint constant private _ENCODING_BYTES = 2;
uint constant private _HEADERS_LEN = _PROOF_LEN - 2 * _ENCODING_BYTES - _ECDSA_SIG_LEN; // 2 bytes encoding headers length + 2 for signature.
uint constant private _DIGEST_BASE64_LEN = 44; //base64 encoding of the SHA256 hash (32-bytes) of the result: fixed length.
uint constant private _DIGEST_OFFSET = _HEADERS_LEN - _DIGEST_BASE64_LEN; // the starting position of the result hash in the headers string.
uint constant private _MAX_BYTE_SIZE = 256; //for calculating length encoding
// This is how the cryptocompare json begins
bytes32 constant private _PREFIX_HASH = keccak256("{\"ETH\":");
bytes public cryptoCompareAPIPublicKey;
mapping(bytes32 => address) private _queryToToken;
/// @notice Construct the oracle with multiple controllers, address resolver and custom gas price.
/// @param _resolver_ is the address of the oraclize resolver
/// @param _ens_ is the address of the ENS.
/// @param _controllerNode_ is the ENS node corresponding to the Controller.
/// @param _tokenWhitelistNode_ is the ENS corresponding to the Token Whitelist.
constructor(address _resolver_, address _ens_, bytes32 _controllerNode_, bytes32 _tokenWhitelistNode_) ENSResolvable(_ens_) Controllable(_controllerNode_) TokenWhitelistable(_tokenWhitelistNode_) public {
cryptoCompareAPIPublicKey = hex"a0f4f688350018ad1b9785991c0bde5f704b005dc79972b114dbed4a615a983710bfc647ebe5a320daa28771dce6a2d104f5efa2e4a85ba3760b76d46f8571ca";
OAR = OraclizeAddrResolverI(_resolver_);
oraclize_setCustomGasPrice(10000000000);
oraclize_setProof(proofType_Native);
}
/// @notice Updates the Crypto Compare public API key.
/// @param _publicKey new Crypto Compare public API key
function updateCryptoCompareAPIPublicKey(bytes calldata _publicKey) external onlyAdmin {
cryptoCompareAPIPublicKey = _publicKey;
emit SetCryptoComparePublicKey(msg.sender, _publicKey);
}
/// @notice Sets the gas price used by Oraclize query.
/// @param _gasPrice in wei for Oraclize
function setCustomGasPrice(uint _gasPrice) external onlyController {
oraclize_setCustomGasPrice(_gasPrice);
emit SetGasPrice(msg.sender, _gasPrice);
}
/// @notice Update ERC20 token exchange rates for all supported tokens.
/// @param _gasLimit the gas limit is passed, this is used for the Oraclize callback
function updateTokenRates(uint _gasLimit) external payable onlyController {
_updateTokenRates(_gasLimit);
}
/// @notice Update ERC20 token exchange rates for the list of tokens provided.
/// @param _gasLimit the gas limit is passed, this is used for the Oraclize callback
/// @param _tokenList the list of tokens that need to be updated
function updateTokenRatesList(uint _gasLimit, address[] calldata _tokenList) external payable onlyController {
_updateTokenRatesList(_gasLimit, _tokenList);
}
/// @notice Withdraw tokens from the smart contract to the specified account.
function claim(address payable _to, address _asset, uint _amount) external onlyAdmin {
_safeTransfer(_to, _asset, _amount);
emit Claimed(_to, _asset, _amount);
}
/// @notice Handle Oraclize query callback and verifiy the provided origin proof.
/// @param _queryID Oraclize query ID.
/// @param _result query result in JSON format.
/// @param _proof origin proof from crypto compare.
// solium-disable-next-line mixedcase
function __callback(bytes32 _queryID, string memory _result, bytes memory _proof) public {
// Require that the caller is the Oraclize contract.
require(msg.sender == oraclize_cbAddress(), "sender is not oraclize");
// Use the query ID to find the matching token address.
address token = _queryToToken[_queryID];
// Get the corresponding token object.
( , , , bool available, , , uint256 lastUpdate) = _getTokenInfo(token);
require(available, "token must be available");
bool valid;
uint timestamp;
(valid, timestamp) = _verifyProof(_result, _proof, cryptoCompareAPIPublicKey, lastUpdate);
// Require that the proof is valid.
if (valid) {
// Parse the JSON result to get the rate in wei.
uint256 parsedRate = _parseIntScientificWei(parseRate(_result));
// Set the update time of the token rate.
uint256 parsedLastUpdate = timestamp;
// Remove query from the list.
delete _queryToToken[_queryID];
_updateTokenRate(token, parsedRate, parsedLastUpdate);
}
}
/// @notice Extracts JSON rate value from the response object.
/// @param _json body of the JSON response from the CryptoCompare API.
function parseRate(string memory _json) internal pure returns (string memory) {
uint jsonLen = abi.encodePacked(_json).length;
//{"ETH":}.length = 8, assuming a (maximum of) 18 digit prevision
require(jsonLen > 8 && jsonLen <= 28, "misformatted input");
bytes memory jsonPrefix = new bytes(7);
copyBytes(abi.encodePacked(_json), 0, 7, jsonPrefix, 0);
require(keccak256(jsonPrefix) == _PREFIX_HASH, "prefix mismatch");
strings.slice memory body = _json.toSlice();
body.split(":".toSlice());
//we are sure that ':' is included in the string, body now contains the rate+'}'
jsonLen = body._len;
body.until("}".toSlice());
require(body._len == jsonLen - 1, "not json format");
//ensure that the json is properly terminated with a '}'
return body.toString();
}
/// @notice Re-usable helper function that performs the Oraclize Query.
/// @param _gasLimit the gas limit is passed, this is used for the Oraclize callback
function _updateTokenRates(uint _gasLimit) private {
address[] memory tokenAddresses = _tokenAddressArray();
// Check if there are any existing tokens.
if (tokenAddresses.length == 0) {
// Emit a query failure event.
emit FailedUpdateRequest("no tokens");
// Check if the contract has enough Ether to pay for the query.
} else if (oraclize_getPrice("URL") * tokenAddresses.length > address(this).balance) {
// Emit a query failure event.
emit FailedUpdateRequest("insufficient balance");
} else {
// Set up the cryptocompare API query strings.
strings.slice memory apiPrefix = "https://min-api.cryptocompare.com/data/price?fsym=".toSlice();
strings.slice memory apiSuffix = "&tsyms=ETH&sign=true".toSlice();
// Create a new oraclize query for each supported token.
for (uint i = 0; i < tokenAddresses.length; i++) {
// Store the token symbol used in the query.
(string memory symbol, , , , , , ) = _getTokenInfo(tokenAddresses[i]);
strings.slice memory sym = symbol.toSlice();
// Create a new oraclize query from the component strings.
bytes32 queryID = oraclize_query("URL", apiPrefix.concat(sym).toSlice().concat(apiSuffix), _gasLimit);
// Store the query ID together with the associated token address.
_queryToToken[queryID] = tokenAddresses[i];
// Emit the query success event.
emit RequestedUpdate(sym.toString(), queryID);
}
}
}
/// @notice Re-usable helper function that performs the Oraclize Query for a specific list of tokens.
/// @param _gasLimit the gas limit is passed, this is used for the Oraclize callback.
/// @param _tokenList the list of tokens that need to be updated.
function _updateTokenRatesList(uint _gasLimit, address[] memory _tokenList) private {
// Check if there are any existing tokens.
if (_tokenList.length == 0) {
// Emit a query failure event.
emit FailedUpdateRequest("empty token list");
// Check if the contract has enough Ether to pay for the query.
} else if (oraclize_getPrice("URL") * _tokenList.length > address(this).balance) {
// Emit a query failure event.
emit FailedUpdateRequest("insufficient balance");
} else {
// Set up the cryptocompare API query strings.
strings.slice memory apiPrefix = "https://min-api.cryptocompare.com/data/price?fsym=".toSlice();
strings.slice memory apiSuffix = "&tsyms=ETH&sign=true".toSlice();
// Create a new oraclize query for each supported token.
for (uint i = 0; i < _tokenList.length; i++) {
//token must exist, revert if it doesn't
(string memory tokenSymbol, , , bool available , , , ) = _getTokenInfo(_tokenList[i]);
require(available, "token must be available");
// Store the token symbol used in the query.
strings.slice memory symbol = tokenSymbol.toSlice();
// Create a new oraclize query from the component strings.
bytes32 queryID = oraclize_query("URL", apiPrefix.concat(symbol).toSlice().concat(apiSuffix), _gasLimit);
// Store the query ID together with the associated token address.
_queryToToken[queryID] = _tokenList[i];
// Emit the query success event.
emit RequestedUpdate(symbol.toString(), queryID);
}
}
}
/// @notice Verify the origin proof returned by the cryptocompare API.
/// @param _result query result in JSON format.
/// @param _proof origin proof from cryptocompare.
/// @param _publicKey cryptocompare public key.
/// @param _lastUpdate timestamp of the last time the requested token was updated.
function _verifyProof(string memory _result, bytes memory _proof, bytes memory _publicKey, uint _lastUpdate) private returns (bool, uint) {
// expecting fixed length proofs
if (_proof.length != _PROOF_LEN) {
revert("invalid proof length");
}
// proof should be 65 bytes long: R (32 bytes) + S (32 bytes) + v (1 byte)
if (uint(uint8(_proof[1])) != _ECDSA_SIG_LEN) {
revert("invalid signature length");
}
bytes memory signature = new bytes(_ECDSA_SIG_LEN);
signature = copyBytes(_proof, 2, _ECDSA_SIG_LEN, signature, 0);
// Extract the headers, big endian encoding of headers length
if (uint(uint8(_proof[_ENCODING_BYTES + _ECDSA_SIG_LEN])) * _MAX_BYTE_SIZE + uint(uint8(_proof[_ENCODING_BYTES + _ECDSA_SIG_LEN + 1])) != _HEADERS_LEN) {
revert("invalid headers length");
}
bytes memory headers = new bytes(_HEADERS_LEN);
headers = copyBytes(_proof, 2 * _ENCODING_BYTES + _ECDSA_SIG_LEN, _HEADERS_LEN, headers, 0);
// Check if the signature is valid and if the signer address is matching.
if (!_verifySignature(headers, signature, _publicKey)) {
revert("invalid signature");
}
// Check if the date is valid.
bytes memory dateHeader = new bytes(20);
// keep only the relevant string(e.g. "16 Nov 2018 16:22:18")
dateHeader = copyBytes(headers, 11, 20, dateHeader, 0);
bool dateValid;
uint timestamp;
(dateValid, timestamp) = _verifyDate(string(dateHeader), _lastUpdate);
// Check whether the date returned is valid or not
if (!dateValid) {
revert("invalid date");
}
// Check if the signed digest hash matches the result hash.
bytes memory digest = new bytes(_DIGEST_BASE64_LEN);
digest = copyBytes(headers, _DIGEST_OFFSET, _DIGEST_BASE64_LEN, digest, 0);
if (keccak256(abi.encodePacked(sha256(abi.encodePacked(_result)))) != keccak256(_base64decode(digest))) {
revert("result hash not matching");
}
emit VerifiedProof(_publicKey, _result);
return (true, timestamp);
}
/// @notice Verify the HTTP headers and the signature
/// @param _headers HTTP headers provided by the cryptocompare api
/// @param _signature signature provided by the cryptocompare api
/// @param _publicKey cryptocompare public key.
function _verifySignature(bytes memory _headers, bytes memory _signature, bytes memory _publicKey) private returns (bool) {
address signer;
bool signatureOK;
// Checks if the signature is valid by hashing the headers
(signatureOK, signer) = ecrecovery(sha256(_headers), _signature);
return signatureOK && signer == address(uint160(uint256(keccak256(_publicKey))));
}
/// @notice Verify the signed HTTP date header.
/// @param _dateHeader extracted date string e.g. Wed, 12 Sep 2018 15:18:14 GMT.
/// @param _lastUpdate timestamp of the last time the requested token was updated.
function _verifyDate(string memory _dateHeader, uint _lastUpdate) private pure returns (bool, uint) {
// called by verifyProof(), _dateHeader is always a string of length = 20
assert(abi.encodePacked(_dateHeader).length == 20);
// Split the date string and get individual date components.
strings.slice memory date = _dateHeader.toSlice();
strings.slice memory timeDelimiter = ":".toSlice();
strings.slice memory dateDelimiter = " ".toSlice();
uint day = _parseIntScientific(date.split(dateDelimiter).toString());
require(day > 0 && day < 32, "day error");
uint month = _monthToNumber(date.split(dateDelimiter).toString());
require(month > 0 && month < 13, "month error");
uint year = _parseIntScientific(date.split(dateDelimiter).toString());
require(year > 2017 && year < 3000, "year error");
uint hour = _parseIntScientific(date.split(timeDelimiter).toString());
require(hour < 25, "hour error");
uint minute = _parseIntScientific(date.split(timeDelimiter).toString());
require(minute < 60, "minute error");
uint second = _parseIntScientific(date.split(timeDelimiter).toString());
require(second < 60, "second error");
uint timestamp = year * (10 ** 10) + month * (10 ** 8) + day * (10 ** 6) + hour * (10 ** 4) + minute * (10 ** 2) + second;
return (timestamp > _lastUpdate, timestamp);
}
} | @return the number of the month based on its name. @param _month the first three letters of a month's name e.g. "Jan". | function _monthToNumber(string memory _month) internal pure returns (uint8) {
bytes32 month = keccak256(abi.encodePacked(_month));
if (month == _JANUARY) {
return 1;
return 2;
return 3;
return 4;
return 5;
return 6;
return 7;
return 8;
return 9;
return 10;
return 11;
return 12;
revert("not a valid month");
}
}
| 1,832,447 | [
1,
2463,
326,
1300,
434,
326,
3138,
2511,
603,
2097,
508,
18,
225,
389,
7496,
326,
1122,
8925,
13768,
434,
279,
3138,
1807,
508,
425,
18,
75,
18,
315,
46,
304,
9654,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
389,
7496,
774,
1854,
12,
1080,
3778,
389,
7496,
13,
2713,
16618,
1135,
261,
11890,
28,
13,
288,
203,
3639,
1731,
1578,
3138,
273,
417,
24410,
581,
5034,
12,
21457,
18,
3015,
4420,
329,
24899,
7496,
10019,
203,
3639,
309,
261,
7496,
422,
389,
46,
1258,
57,
6043,
13,
288,
203,
5411,
327,
404,
31,
203,
5411,
327,
576,
31,
203,
5411,
327,
890,
31,
203,
5411,
327,
1059,
31,
203,
5411,
327,
1381,
31,
203,
5411,
327,
1666,
31,
203,
5411,
327,
2371,
31,
203,
5411,
327,
1725,
31,
203,
5411,
327,
2468,
31,
203,
5411,
327,
1728,
31,
203,
5411,
327,
4648,
31,
203,
5411,
327,
2593,
31,
203,
5411,
15226,
2932,
902,
279,
923,
3138,
8863,
203,
3639,
289,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/11155111/0xF9e50fF1D974Fe9d02E4d4556DCa05939D672209/sources/contracts/peripherals/OrderBookReader.sol | uint256 executionFee | function getIncreaseOrders(
address payable _orderBookAddress,
address _account,
uint256[] memory _indices
) external view returns (uint256[] memory, address[] memory) {
Vars memory vars = Vars(0, 0, _account, 5, 3);
uint256[] memory uintProps = new uint256[](vars.uintLength * _indices.length);
address[] memory addressProps = new address[](vars.addressLength * _indices.length);
IOrderBook orderBook = IOrderBook(_orderBookAddress);
while (vars.i < _indices.length) {
vars.index = _indices[vars.i];
(
address purchaseToken,
uint256 purchaseTokenAmount,
address collateralToken,
address indexToken,
uint256 sizeDelta,
bool isLong,
uint256 triggerPrice,
bool triggerAboveThreshold,
) = orderBook.getIncreaseOrder(vars.account, vars.index);
uintProps[vars.i * vars.uintLength] = uint256(purchaseTokenAmount);
uintProps[vars.i * vars.uintLength + 1] = uint256(sizeDelta);
uintProps[vars.i * vars.uintLength + 2] = uint256(isLong ? 1 : 0);
uintProps[vars.i * vars.uintLength + 3] = uint256(triggerPrice);
uintProps[vars.i * vars.uintLength + 4] = uint256(triggerAboveThreshold ? 1 : 0);
addressProps[vars.i * vars.addressLength] = (purchaseToken);
addressProps[vars.i * vars.addressLength + 1] = (collateralToken);
addressProps[vars.i * vars.addressLength + 2] = (indexToken);
vars.i++;
}
return (uintProps, addressProps);
}
| 3,826,467 | [
1,
11890,
5034,
4588,
14667,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
7854,
11908,
16528,
12,
203,
3639,
1758,
8843,
429,
389,
1019,
9084,
1887,
16,
7010,
3639,
1758,
389,
4631,
16,
203,
3639,
2254,
5034,
8526,
3778,
389,
6836,
203,
565,
262,
3903,
1476,
1135,
261,
11890,
5034,
8526,
3778,
16,
1758,
8526,
3778,
13,
288,
203,
3639,
27289,
3778,
4153,
273,
27289,
12,
20,
16,
374,
16,
389,
4631,
16,
1381,
16,
890,
1769,
203,
203,
3639,
2254,
5034,
8526,
3778,
2254,
5047,
273,
394,
2254,
5034,
8526,
12,
4699,
18,
11890,
1782,
380,
389,
6836,
18,
2469,
1769,
203,
3639,
1758,
8526,
3778,
1758,
5047,
273,
394,
1758,
8526,
12,
4699,
18,
2867,
1782,
380,
389,
6836,
18,
2469,
1769,
203,
203,
3639,
467,
2448,
9084,
1353,
9084,
273,
467,
2448,
9084,
24899,
1019,
9084,
1887,
1769,
203,
203,
3639,
1323,
261,
4699,
18,
77,
411,
389,
6836,
18,
2469,
13,
288,
203,
5411,
4153,
18,
1615,
273,
389,
6836,
63,
4699,
18,
77,
15533,
203,
5411,
261,
203,
7734,
1758,
23701,
1345,
16,
203,
7734,
2254,
5034,
23701,
1345,
6275,
16,
203,
7734,
1758,
4508,
2045,
287,
1345,
16,
203,
7734,
1758,
770,
1345,
16,
203,
7734,
2254,
5034,
963,
9242,
16,
203,
7734,
1426,
353,
3708,
16,
203,
7734,
2254,
5034,
3080,
5147,
16,
203,
7734,
1426,
3080,
25477,
7614,
16,
203,
5411,
262,
273,
1353,
9084,
18,
588,
382,
11908,
2448,
12,
4699,
18,
4631,
16,
4153,
18,
1615,
1769,
203,
203,
5411,
2254,
5047,
63,
4699,
18,
77,
380,
4153,
18,
11890,
1782,
65,
273,
2254,
5034,
2
] |
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.6.11;
contract AccessControl {
event GrantRole(bytes32 indexed role, address indexed addr);
event RevokeRole(bytes32 indexed role, address indexed addr);
mapping(bytes32 => mapping(address => bool)) public hasRole;
modifier onlyAuthorized(bytes32 _role) {
require(hasRole[_role][msg.sender], "!authorized");
_;
}
function _grantRole(bytes32 _role, address _addr) internal {
require(_addr != address(0), "address = zero");
hasRole[_role][_addr] = true;
emit GrantRole(_role, _addr);
}
function _revokeRole(bytes32 _role, address _addr) internal {
require(_addr != address(0), "address = zero");
hasRole[_role][_addr] = false;
emit RevokeRole(_role, _addr);
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.6.11;
import "@openzeppelin/contracts/math/Math.sol";
import "./interfaces/GasToken.sol";
import "./AccessControl.sol";
contract GasRelayer is AccessControl {
bytes32 public constant GAS_TOKEN_USER_ROLE =
keccak256(abi.encodePacked("GAS_TOKEN_USER"));
address public admin;
address public gasToken;
constructor(address _gasToken) public {
require(_gasToken != address(0), "gas token = zero address");
admin = msg.sender;
gasToken = _gasToken;
_grantRole(GAS_TOKEN_USER_ROLE, admin);
}
modifier onlyAdmin() {
require(msg.sender == admin, "!admin");
_;
}
// @dev use CHI token from 1inch to burn gas token
// https://medium.com/@1inch.exchange/1inch-introduces-chi-gastoken-d0bd5bb0f92b
modifier useChi(uint _max) {
uint gasStart = gasleft();
_;
uint gasSpent = 21000 + gasStart - gasleft() + 16 * msg.data.length;
if (_max > 0) {
GasToken(gasToken).freeUpTo(Math.min(_max, (gasSpent + 14154) / 41947));
}
}
function setAdmin(address _admin) external onlyAdmin {
require(_admin != address(0), "admin = zero address");
admin = _admin;
}
function authorized(address _addr) external view returns (bool) {
return hasRole[GAS_TOKEN_USER_ROLE][_addr];
}
function authorize(address _addr) external onlyAdmin {
_grantRole(GAS_TOKEN_USER_ROLE, _addr);
}
function unauthorize(address _addr) external onlyAdmin {
_revokeRole(GAS_TOKEN_USER_ROLE, _addr);
}
function setGasToken(address _gasToken) external onlyAdmin {
require(_gasToken != address(0), "gas token = zero address");
gasToken = _gasToken;
}
function mintGasToken(uint _amount) external {
GasToken(gasToken).mint(_amount);
}
function transferGasToken(address _to, uint _amount) external onlyAdmin {
GasToken(gasToken).transfer(_to, _amount);
}
function relayTx(
address _to,
bytes calldata _data,
uint _maxGasToken
) external onlyAuthorized(GAS_TOKEN_USER_ROLE) useChi(_maxGasToken) {
(bool success, ) = _to.call(_data);
require(success, "relay failed");
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.6.11;
interface GasToken {
function mint(uint amount) external;
function free(uint amount) external returns (bool);
function freeUpTo(uint amount) external returns (uint);
// ERC20
function transfer(address _to, uint _amount) external returns (bool);
function balanceOf(address account) external view returns (uint);
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.6.11;
import "../interfaces/GasToken.sol";
/* solium-disable */
contract MockGasToken is GasToken {
// test helpers
uint public _mintAmount_;
uint public _freeAmount_;
uint public _freeUpToAmount_;
address public _transferTo_;
uint public _transferAmount_;
function mint(uint _amount) external override {
_mintAmount_ = _amount;
}
function free(uint _amount) external override returns (bool) {
_freeAmount_ = _amount;
return true;
}
function freeUpTo(uint _amount) external override returns (uint) {
_freeUpToAmount_ = _amount;
return 0;
}
function transfer(address _to, uint _amount) external override returns (bool) {
_transferTo_ = _to;
_transferAmount_ = _amount;
return true;
}
function balanceOf(address) external view override returns (uint) {
return 0;
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.6.11;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "./protocol/IController.sol";
import "./protocol/IVault.sol";
import "./protocol/IStrategy.sol";
import "./AccessControl.sol";
contract Controller is IController, AccessControl {
using SafeMath for uint;
bytes32 public constant override ADMIN_ROLE = keccak256(abi.encodePacked("ADMIN"));
bytes32 public constant override HARVESTER_ROLE =
keccak256(abi.encodePacked("HARVESTER"));
address public override admin;
address public override treasury;
constructor(address _treasury) public {
require(_treasury != address(0), "treasury = zero address");
admin = msg.sender;
treasury = _treasury;
_grantRole(ADMIN_ROLE, admin);
_grantRole(HARVESTER_ROLE, admin);
}
modifier onlyAdmin() {
require(msg.sender == admin, "!admin");
_;
}
modifier isCurrentStrategy(address _strategy) {
address vault = IStrategy(_strategy).vault();
/*
Check that _strategy is the current strategy used by the vault.
*/
require(IVault(vault).strategy() == _strategy, "!strategy");
_;
}
function setAdmin(address _admin) external override onlyAdmin {
require(_admin != address(0), "admin = zero address");
_revokeRole(ADMIN_ROLE, admin);
_revokeRole(HARVESTER_ROLE, admin);
_grantRole(ADMIN_ROLE, _admin);
_grantRole(HARVESTER_ROLE, _admin);
admin = _admin;
}
function setTreasury(address _treasury) external override onlyAdmin {
require(_treasury != address(0), "treasury = zero address");
treasury = _treasury;
}
function grantRole(bytes32 _role, address _addr) external override onlyAdmin {
require(_role == ADMIN_ROLE || _role == HARVESTER_ROLE, "invalid role");
_grantRole(_role, _addr);
}
function revokeRole(bytes32 _role, address _addr) external override onlyAdmin {
require(_role == ADMIN_ROLE || _role == HARVESTER_ROLE, "invalid role");
_revokeRole(_role, _addr);
}
function setStrategy(
address _vault,
address _strategy,
uint _min
) external override onlyAuthorized(ADMIN_ROLE) {
IVault(_vault).setStrategy(_strategy, _min);
}
function invest(address _vault) external override onlyAuthorized(HARVESTER_ROLE) {
IVault(_vault).invest();
}
function harvest(address _strategy)
external
override
isCurrentStrategy(_strategy)
onlyAuthorized(HARVESTER_ROLE)
{
IStrategy(_strategy).harvest();
}
function skim(address _strategy)
external
override
isCurrentStrategy(_strategy)
onlyAuthorized(HARVESTER_ROLE)
{
IStrategy(_strategy).skim();
}
modifier checkWithdraw(address _strategy, uint _min) {
address vault = IStrategy(_strategy).vault();
address token = IVault(vault).token();
uint balBefore = IERC20(token).balanceOf(vault);
_;
uint balAfter = IERC20(token).balanceOf(vault);
require(balAfter.sub(balBefore) >= _min, "withdraw < min");
}
function withdraw(
address _strategy,
uint _amount,
uint _min
)
external
override
isCurrentStrategy(_strategy)
onlyAuthorized(HARVESTER_ROLE)
checkWithdraw(_strategy, _min)
{
IStrategy(_strategy).withdraw(_amount);
}
function withdrawAll(address _strategy, uint _min)
external
override
isCurrentStrategy(_strategy)
onlyAuthorized(HARVESTER_ROLE)
checkWithdraw(_strategy, _min)
{
IStrategy(_strategy).withdrawAll();
}
function exit(address _strategy, uint _min)
external
override
isCurrentStrategy(_strategy)
onlyAuthorized(ADMIN_ROLE)
checkWithdraw(_strategy, _min)
{
IStrategy(_strategy).exit();
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.6.11;
interface IController {
function ADMIN_ROLE() external view returns (bytes32);
function HARVESTER_ROLE() external view returns (bytes32);
function admin() external view returns (address);
function treasury() external view returns (address);
function setAdmin(address _admin) external;
function setTreasury(address _treasury) external;
function grantRole(bytes32 _role, address _addr) external;
function revokeRole(bytes32 _role, address _addr) external;
/*
@notice Set strategy for vault
@param _vault Address of vault
@param _strategy Address of strategy
@param _min Minimum undelying token current strategy must return. Prevents slippage
*/
function setStrategy(
address _vault,
address _strategy,
uint _min
) external;
// calls to strategy
/*
@notice Invest token in vault into strategy
@param _vault Address of vault
*/
function invest(address _vault) external;
function harvest(address _strategy) external;
function skim(address _strategy) external;
/*
@notice Withdraw from strategy to vault
@param _strategy Address of strategy
@param _amount Amount of underlying token to withdraw
@param _min Minimum amount of underlying token to withdraw
*/
function withdraw(
address _strategy,
uint _amount,
uint _min
) external;
/*
@notice Withdraw all from strategy to vault
@param _strategy Address of strategy
@param _min Minimum amount of underlying token to withdraw
*/
function withdrawAll(address _strategy, uint _min) external;
/*
@notice Exit from strategy
@param _strategy Address of strategy
@param _min Minimum amount of underlying token to withdraw
*/
function exit(address _strategy, uint _min) external;
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.6.11;
interface IVault {
function admin() external view returns (address);
function controller() external view returns (address);
function timeLock() external view returns (address);
function token() external view returns (address);
function strategy() external view returns (address);
function strategies(address _strategy) external view returns (bool);
function reserveMin() external view returns (uint);
function withdrawFee() external view returns (uint);
function paused() external view returns (bool);
function whitelist(address _addr) external view returns (bool);
function setWhitelist(address _addr, bool _approve) external;
function setAdmin(address _admin) external;
function setController(address _controller) external;
function setTimeLock(address _timeLock) external;
function setPause(bool _paused) external;
function setReserveMin(uint _reserveMin) external;
function setWithdrawFee(uint _fee) external;
/*
@notice Returns the amount of token in the vault
*/
function balanceInVault() external view returns (uint);
/*
@notice Returns the estimate amount of token in strategy
@dev Output may vary depending on price of liquidity provider token
where the underlying token is invested
*/
function balanceInStrategy() external view returns (uint);
/*
@notice Returns amount of tokens invested strategy
*/
function totalDebtInStrategy() external view returns (uint);
/*
@notice Returns the total amount of token in vault + total debt
*/
function totalAssets() external view returns (uint);
/*
@notice Returns minimum amount of tokens that should be kept in vault for
cheap withdraw
@return Reserve amount
*/
function minReserve() external view returns (uint);
/*
@notice Returns the amount of tokens available to be invested
*/
function availableToInvest() external view returns (uint);
/*
@notice Approve strategy
@param _strategy Address of strategy
*/
function approveStrategy(address _strategy) external;
/*
@notice Revoke strategy
@param _strategy Address of strategy
*/
function revokeStrategy(address _strategy) external;
/*
@notice Set strategy
@param _min Minimum undelying token current strategy must return. Prevents slippage
*/
function setStrategy(address _strategy, uint _min) external;
/*
@notice Transfers token in vault to strategy
*/
function invest() external;
/*
@notice Deposit undelying token into this vault
@param _amount Amount of token to deposit
*/
function deposit(uint _amount) external;
/*
@notice Calculate amount of token that can be withdrawn
@param _shares Amount of shares
@return Amount of token that can be withdrawn
*/
function getExpectedReturn(uint _shares) external view returns (uint);
/*
@notice Withdraw token
@param _shares Amount of shares to burn
@param _min Minimum amount of token expected to return
*/
function withdraw(uint _shares, uint _min) external;
/*
@notice Transfer token in vault to admin
@param _token Address of token to transfer
@dev _token must not be equal to vault token
*/
function sweep(address _token) external;
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.6.11;
interface IStrategy {
function admin() external view returns (address);
function controller() external view returns (address);
function vault() external view returns (address);
/*
@notice Returns address of underlying token
*/
function underlying() external view returns (address);
/*
@notice Returns total amount of underlying transferred from vault
*/
function totalDebt() external view returns (uint);
function performanceFee() external view returns (uint);
/*
@notice Returns true if token cannot be swept
*/
function assets(address _token) external view returns (bool);
function setAdmin(address _admin) external;
function setController(address _controller) external;
function setPerformanceFee(uint _fee) external;
/*
@notice Returns amount of underlying stable coin locked in this contract
@dev Output may vary depending on price of liquidity provider token
where the underlying token is invested
*/
function totalAssets() external view returns (uint);
/*
@notice Deposit `amount` underlying token for yield token
@param amount Amount of underlying token to deposit
*/
function deposit(uint _amount) external;
/*
@notice Withdraw `amount` yield token to withdraw
@param amount Amount of yield token to withdraw
*/
function withdraw(uint _amount) external;
/*
@notice Withdraw all underlying token from strategy
*/
function withdrawAll() external;
function harvest() external;
/*
@notice Exit from strategy
@dev Must transfer all underlying tokens back to vault
*/
function exit() external;
/*
@notice Transfer profit over total debt to vault
*/
function skim() external;
/*
@notice Transfer token in strategy to admin
@param _token Address of token to transfer
@dev Must transfer token to admin
@dev _token must not be equal to underlying token
@dev Used to transfer token that was accidentally sent or
claim dust created from this strategy
*/
function sweep(address _token) external;
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.6.11;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "./protocol/IStrategy.sol";
import "./protocol/IVault.sol";
import "./protocol/IController.sol";
/* potential hacks?
- directly send underlying token to this vault or strategy
- flash loan
- flashloan make undelying token less valuable
- vault deposit
- flashloan make underlying token more valuable
- vault withdraw
- return loan
- front running?
*/
contract Vault is IVault, ERC20, ReentrancyGuard {
using SafeERC20 for IERC20;
using SafeMath for uint;
event SetStrategy(address strategy);
event ApproveStrategy(address strategy);
event RevokeStrategy(address strategy);
event SetWhitelist(address addr, bool approved);
address public override admin;
address public override controller;
address public override timeLock;
address public immutable override token;
address public override strategy;
// mapping of approved strategies
mapping(address => bool) public override strategies;
// percentange of token reserved in vault for cheap withdraw
uint public override reserveMin = 500;
uint private constant RESERVE_MAX = 10000;
// Denominator used to calculate fees
uint private constant FEE_MAX = 10000;
uint public override withdrawFee;
uint private constant WITHDRAW_FEE_CAP = 500; // upper limit to withdrawFee
bool public override paused;
// whitelisted addresses
// used to prevent flash loah attacks
mapping(address => bool) public override whitelist;
/*
@dev vault decimals must be equal to token decimals
*/
constructor(
address _controller,
address _timeLock,
address _token
)
public
ERC20(
string(abi.encodePacked("unagii_", ERC20(_token).name())),
string(abi.encodePacked("u", ERC20(_token).symbol()))
)
{
require(_controller != address(0), "controller = zero address");
require(_timeLock != address(0), "time lock = zero address");
_setupDecimals(ERC20(_token).decimals());
admin = msg.sender;
controller = _controller;
token = _token;
timeLock = _timeLock;
}
modifier onlyAdmin() {
require(msg.sender == admin, "!admin");
_;
}
modifier onlyTimeLock() {
require(msg.sender == timeLock, "!time lock");
_;
}
modifier onlyAdminOrController() {
require(msg.sender == admin || msg.sender == controller, "!authorized");
_;
}
modifier whenStrategyDefined() {
require(strategy != address(0), "strategy = zero address");
_;
}
modifier whenNotPaused() {
require(!paused, "paused");
_;
}
/*
@dev modifier to prevent flash loan
@dev caller is restricted to EOA or whitelisted contract
@dev Warning: Users can have their funds stuck if shares is transferred to a contract
*/
modifier guard() {
require((msg.sender == tx.origin) || whitelist[msg.sender], "!whitelist");
_;
}
function setAdmin(address _admin) external override onlyAdmin {
require(_admin != address(0), "admin = zero address");
admin = _admin;
}
function setController(address _controller) external override onlyAdmin {
require(_controller != address(0), "controller = zero address");
controller = _controller;
}
function setTimeLock(address _timeLock) external override onlyTimeLock {
require(_timeLock != address(0), "time lock = zero address");
timeLock = _timeLock;
}
function setPause(bool _paused) external override onlyAdmin {
paused = _paused;
}
function setWhitelist(address _addr, bool _approve) external override onlyAdmin {
whitelist[_addr] = _approve;
emit SetWhitelist(_addr, _approve);
}
function setReserveMin(uint _reserveMin) external override onlyAdmin {
require(_reserveMin <= RESERVE_MAX, "reserve min > max");
reserveMin = _reserveMin;
}
function setWithdrawFee(uint _fee) external override onlyAdmin {
require(_fee <= WITHDRAW_FEE_CAP, "withdraw fee > cap");
withdrawFee = _fee;
}
function _balanceInVault() private view returns (uint) {
return IERC20(token).balanceOf(address(this));
}
/*
@notice Returns balance of tokens in vault
@return Amount of token in vault
*/
function balanceInVault() external view override returns (uint) {
return _balanceInVault();
}
function _balanceInStrategy() private view returns (uint) {
if (strategy == address(0)) {
return 0;
}
return IStrategy(strategy).totalAssets();
}
/*
@notice Returns the estimate amount of token in strategy
@dev Output may vary depending on price of liquidity provider token
where the underlying token is invested
*/
function balanceInStrategy() external view override returns (uint) {
return _balanceInStrategy();
}
function _totalDebtInStrategy() private view returns (uint) {
if (strategy == address(0)) {
return 0;
}
return IStrategy(strategy).totalDebt();
}
/*
@notice Returns amount of tokens invested strategy
*/
function totalDebtInStrategy() external view override returns (uint) {
return _totalDebtInStrategy();
}
function _totalAssets() private view returns (uint) {
return _balanceInVault().add(_totalDebtInStrategy());
}
/*
@notice Returns the total amount of tokens in vault + total debt
@return Total amount of tokens in vault + total debt
*/
function totalAssets() external view override returns (uint) {
return _totalAssets();
}
function _minReserve() private view returns (uint) {
return _totalAssets().mul(reserveMin) / RESERVE_MAX;
}
/*
@notice Returns minimum amount of tokens that should be kept in vault for
cheap withdraw
@return Reserve amount
*/
function minReserve() external view override returns (uint) {
return _minReserve();
}
function _availableToInvest() private view returns (uint) {
if (strategy == address(0)) {
return 0;
}
uint balInVault = _balanceInVault();
uint reserve = _minReserve();
if (balInVault <= reserve) {
return 0;
}
return balInVault - reserve;
}
/*
@notice Returns amount of token available to be invested into strategy
@return Amount of token available to be invested into strategy
*/
function availableToInvest() external view override returns (uint) {
return _availableToInvest();
}
/*
@notice Approve strategy
@param _strategy Address of strategy to revoke
*/
function approveStrategy(address _strategy) external override onlyTimeLock {
require(_strategy != address(0), "strategy = zero address");
strategies[_strategy] = true;
emit ApproveStrategy(_strategy);
}
/*
@notice Revoke strategy
@param _strategy Address of strategy to revoke
*/
function revokeStrategy(address _strategy) external override onlyAdmin {
require(_strategy != address(0), "strategy = zero address");
strategies[_strategy] = false;
emit RevokeStrategy(_strategy);
}
/*
@notice Set strategy to approved strategy
@param _strategy Address of strategy used
@param _min Minimum undelying token current strategy must return. Prevents slippage
*/
function setStrategy(address _strategy, uint _min)
external
override
onlyAdminOrController
{
require(strategies[_strategy], "!approved");
require(_strategy != strategy, "new strategy = current strategy");
require(
IStrategy(_strategy).underlying() == token,
"strategy.token != vault.token"
);
require(
IStrategy(_strategy).vault() == address(this),
"strategy.vault != vault"
);
// withdraw from current strategy
if (strategy != address(0)) {
IERC20(token).safeApprove(strategy, 0);
uint balBefore = _balanceInVault();
IStrategy(strategy).exit();
uint balAfter = _balanceInVault();
require(balAfter.sub(balBefore) >= _min, "withdraw < min");
}
strategy = _strategy;
emit SetStrategy(strategy);
}
/*
@notice Invest token from vault into strategy.
Some token are kept in vault for cheap withdraw.
*/
function invest()
external
override
whenStrategyDefined
whenNotPaused
onlyAdminOrController
{
uint amount = _availableToInvest();
require(amount > 0, "available = 0");
IERC20(token).safeApprove(strategy, 0);
IERC20(token).safeApprove(strategy, amount);
IStrategy(strategy).deposit(amount);
IERC20(token).safeApprove(strategy, 0);
}
/*
@notice Deposit token into vault
@param _amount Amount of token to transfer from `msg.sender`
*/
function deposit(uint _amount) external override whenNotPaused nonReentrant guard {
require(_amount > 0, "amount = 0");
uint totalUnderlying = _totalAssets();
uint totalShares = totalSupply();
/*
s = shares to mint
T = total shares before mint
d = deposit amount
A = total assets in vault + strategy before deposit
s / (T + s) = d / (A + d)
s = d / A * T
*/
uint shares;
if (totalShares == 0) {
shares = _amount;
} else {
shares = _amount.mul(totalShares).div(totalUnderlying);
}
_mint(msg.sender, shares);
IERC20(token).safeTransferFrom(msg.sender, address(this), _amount);
}
function _getExpectedReturn(
uint _shares,
uint _balInVault,
uint _balInStrat
) private view returns (uint) {
/*
s = shares
T = total supply of shares
w = amount of underlying token to withdraw
U = total amount of redeemable underlying token in vault + strategy
s / T = w / U
w = s / T * U
*/
/*
total underlying = bal in vault + min(total debt, bal in strat)
if bal in strat > total debt, redeemable = total debt
else redeemable = bal in strat
*/
uint totalDebt = _totalDebtInStrategy();
uint totalUnderlying;
if (_balInStrat > totalDebt) {
totalUnderlying = _balInVault.add(totalDebt);
} else {
totalUnderlying = _balInVault.add(_balInStrat);
}
uint totalShares = totalSupply();
if (totalShares > 0) {
return _shares.mul(totalUnderlying) / totalShares;
}
return 0;
}
/*
@notice Calculate amount of underlying token that can be withdrawn
@param _shares Amount of shares
@return Amount of underlying token that can be withdrawn
*/
function getExpectedReturn(uint _shares) external view override returns (uint) {
uint balInVault = _balanceInVault();
uint balInStrat = _balanceInStrategy();
return _getExpectedReturn(_shares, balInVault, balInStrat);
}
/*
@notice Withdraw underlying token
@param _shares Amount of shares to burn
@param _min Minimum amount of underlying token to return
@dev Keep `guard` modifier, else attacker can deposit and then use smart
contract to attack from withdraw
*/
function withdraw(uint _shares, uint _min) external override nonReentrant guard {
require(_shares > 0, "shares = 0");
uint balInVault = _balanceInVault();
uint balInStrat = _balanceInStrategy();
uint withdrawAmount = _getExpectedReturn(_shares, balInVault, balInStrat);
// Must burn after calculating withdraw amount
_burn(msg.sender, _shares);
if (balInVault < withdrawAmount) {
// maximize withdraw amount from strategy
uint amountFromStrat = withdrawAmount;
if (balInStrat < withdrawAmount) {
amountFromStrat = balInStrat;
}
IStrategy(strategy).withdraw(amountFromStrat);
uint balAfter = _balanceInVault();
uint diff = balAfter.sub(balInVault);
if (diff < amountFromStrat) {
// withdraw amount - withdraw amount from strat = amount to withdraw from vault
// diff = actual amount returned from strategy
// NOTE: withdrawAmount >= amountFromStrat
withdrawAmount = (withdrawAmount - amountFromStrat).add(diff);
}
// transfer to treasury
uint fee = withdrawAmount.mul(withdrawFee) / FEE_MAX;
if (fee > 0) {
address treasury = IController(controller).treasury();
require(treasury != address(0), "treasury = zero address");
withdrawAmount = withdrawAmount - fee;
IERC20(token).safeTransfer(treasury, fee);
}
}
require(withdrawAmount >= _min, "withdraw < min");
IERC20(token).safeTransfer(msg.sender, withdrawAmount);
}
/*
@notice Transfer token != underlying token in vault to admin
@param _token Address of token to transfer
@dev Must transfer token to admin
@dev _token must not be equal to underlying token
@dev Used to transfer token that was accidentally sent to this vault
*/
function sweep(address _token) external override onlyAdmin {
require(_token != token, "token = vault.token");
IERC20(_token).safeTransfer(admin, IERC20(_token).balanceOf(address(this)));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor () internal {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "../../GSN/Context.sol";
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.2;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.6.11;
import "../protocol/IController.sol";
/* solium-disable */
contract MockController is IController {
bytes32 public constant override ADMIN_ROLE = keccak256(abi.encodePacked("ADMIN"));
bytes32 public constant override HARVESTER_ROLE =
keccak256(abi.encodePacked("HARVESTER"));
address public override admin;
address public override treasury;
constructor(address _treasury) public {
admin = msg.sender;
treasury = _treasury;
}
function setAdmin(address _admin) external override {}
function setTreasury(address _treasury) external override {}
function grantRole(bytes32 _role, address _addr) external override {}
function revokeRole(bytes32 _role, address _addr) external override {}
function invest(address _vault) external override {}
function setStrategy(
address _vault,
address _strategy,
uint _min
) external override {}
function harvest(address _strategy) external override {}
function skim(address _strategy) external override {}
function withdraw(
address _strategy,
uint _amount,
uint _min
) external override {}
function withdrawAll(address _strategy, uint _min) external override {}
function exit(address _strategy, uint _min) external override {}
/* test helper */
function _setTreasury_(address _treasury) external {
treasury = _treasury;
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.6.11;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "./protocol/IStrategy.sol";
import "./protocol/IController.sol";
abstract contract StrategyBase is IStrategy {
using SafeERC20 for IERC20;
using SafeMath for uint;
address public override admin;
address public override controller;
address public override vault;
address public override underlying;
// total amount of underlying transferred from vault
uint public override totalDebt;
// performance fee sent to treasury when harvest() generates profit
uint public override performanceFee = 100;
uint internal constant PERFORMANCE_FEE_MAX = 10000;
// valuable tokens that cannot be swept
mapping(address => bool) public override assets;
constructor(
address _controller,
address _vault,
address _underlying
) public {
require(_controller != address(0), "controller = zero address");
require(_vault != address(0), "vault = zero address");
require(_underlying != address(0), "underlying = zero address");
admin = msg.sender;
controller = _controller;
vault = _vault;
underlying = _underlying;
assets[underlying] = true;
}
modifier onlyAdmin() {
require(msg.sender == admin, "!admin");
_;
}
modifier onlyAuthorized() {
require(
msg.sender == admin || msg.sender == controller || msg.sender == vault,
"!authorized"
);
_;
}
function setAdmin(address _admin) external override onlyAdmin {
require(_admin != address(0), "admin = zero address");
admin = _admin;
}
function setController(address _controller) external override onlyAdmin {
require(_controller != address(0), "controller = zero address");
controller = _controller;
}
function setPerformanceFee(uint _fee) external override onlyAdmin {
require(_fee <= PERFORMANCE_FEE_MAX, "performance fee > max");
performanceFee = _fee;
}
function _increaseDebt(uint _underlyingAmount) private {
uint balBefore = IERC20(underlying).balanceOf(address(this));
IERC20(underlying).safeTransferFrom(vault, address(this), _underlyingAmount);
uint balAfter = IERC20(underlying).balanceOf(address(this));
totalDebt = totalDebt.add(balAfter.sub(balBefore));
}
function _decreaseDebt(uint _underlyingAmount) private {
uint balBefore = IERC20(underlying).balanceOf(address(this));
IERC20(underlying).safeTransfer(vault, _underlyingAmount);
uint balAfter = IERC20(underlying).balanceOf(address(this));
uint diff = balBefore.sub(balAfter);
if (diff > totalDebt) {
totalDebt = 0;
} else {
totalDebt = totalDebt - diff;
}
}
function _totalAssets() internal view virtual returns (uint);
/*
@notice Returns amount of underlying tokens locked in this contract
*/
function totalAssets() external view override returns (uint) {
return _totalAssets();
}
function _depositUnderlying() internal virtual;
/*
@notice Deposit underlying token into this strategy
@param _underlyingAmount Amount of underlying token to deposit
*/
function deposit(uint _underlyingAmount) external override onlyAuthorized {
require(_underlyingAmount > 0, "underlying = 0");
_increaseDebt(_underlyingAmount);
_depositUnderlying();
}
/*
@notice Returns total shares owned by this contract for depositing underlying
into external Defi
*/
function _getTotalShares() internal view virtual returns (uint);
function _getShares(uint _underlyingAmount, uint _totalUnderlying)
internal
view
returns (uint)
{
/*
calculate shares to withdraw
w = amount of underlying to withdraw
U = total redeemable underlying
s = shares to withdraw
P = total shares deposited into external liquidity pool
w / U = s / P
s = w / U * P
*/
if (_totalUnderlying > 0) {
uint totalShares = _getTotalShares();
return _underlyingAmount.mul(totalShares) / _totalUnderlying;
}
return 0;
}
function _withdrawUnderlying(uint _shares) internal virtual;
/*
@notice Withdraw undelying token to vault
@param _underlyingAmount Amount of underlying token to withdraw
@dev Caller should implement guard agains slippage
*/
function withdraw(uint _underlyingAmount) external override onlyAuthorized {
require(_underlyingAmount > 0, "underlying = 0");
uint totalUnderlying = _totalAssets();
require(_underlyingAmount <= totalUnderlying, "underlying > total");
uint shares = _getShares(_underlyingAmount, totalUnderlying);
if (shares > 0) {
_withdrawUnderlying(shares);
}
// transfer underlying token to vault
uint underlyingBal = IERC20(underlying).balanceOf(address(this));
if (underlyingBal > 0) {
_decreaseDebt(underlyingBal);
}
}
function _withdrawAll() internal {
uint totalShares = _getTotalShares();
if (totalShares > 0) {
_withdrawUnderlying(totalShares);
}
uint underlyingBal = IERC20(underlying).balanceOf(address(this));
if (underlyingBal > 0) {
_decreaseDebt(underlyingBal);
totalDebt = 0;
}
}
/*
@notice Withdraw all underlying to vault
@dev Caller should implement guard agains slippage
*/
function withdrawAll() external override onlyAuthorized {
_withdrawAll();
}
/*
@notice Sell any staking rewards for underlying, deposit or transfer undelying
depending on total debt
*/
function harvest() external virtual override;
/*
@notice Transfer profit over total debt to vault
*/
function skim() external override onlyAuthorized {
uint totalUnderlying = _totalAssets();
if (totalUnderlying > totalDebt) {
uint profit = totalUnderlying - totalDebt;
uint shares = _getShares(profit, totalUnderlying);
if (shares > 0) {
uint balBefore = IERC20(underlying).balanceOf(address(this));
_withdrawUnderlying(shares);
uint balAfter = IERC20(underlying).balanceOf(address(this));
uint diff = balAfter.sub(balBefore);
if (diff > 0) {
IERC20(underlying).safeTransfer(vault, diff);
}
}
}
}
function exit() external virtual override;
function sweep(address _token) external override onlyAdmin {
require(!assets[_token], "asset");
IERC20(_token).safeTransfer(admin, IERC20(_token).balanceOf(address(this)));
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.6.11;
import "../StrategyBase.sol";
import "./TestToken.sol";
/* solium-disable */
contract StrategyTest is StrategyBase {
// test helper
uint public _depositAmount_;
uint public _withdrawAmount_;
bool public _harvestWasCalled_;
bool public _exitWasCalled_;
// simulate strategy withdrawing less than requested
uint public _maxWithdrawAmount_ = uint(-1);
// mock liquidity provider
address public constant _POOL_ = address(1);
constructor(
address _controller,
address _vault,
address _underlying
) public StrategyBase(_controller, _vault, _underlying) {
// allow this contract to freely withdraw from POOL
TestToken(underlying)._approve_(_POOL_, address(this), uint(-1));
}
function _totalAssets() internal view override returns (uint) {
return IERC20(underlying).balanceOf(_POOL_);
}
function _depositUnderlying() internal override {
uint bal = IERC20(underlying).balanceOf(address(this));
_depositAmount_ = bal;
IERC20(underlying).transfer(_POOL_, bal);
}
function _getTotalShares() internal view override returns (uint) {
return IERC20(underlying).balanceOf(_POOL_);
}
function _withdrawUnderlying(uint _shares) internal override {
_withdrawAmount_ = _shares;
if (_shares > _maxWithdrawAmount_) {
_withdrawAmount_ = _maxWithdrawAmount_;
}
IERC20(underlying).transferFrom(_POOL_, address(this), _withdrawAmount_);
}
function harvest() external override onlyAuthorized {
_harvestWasCalled_ = true;
}
function exit() external override onlyAuthorized {
_exitWasCalled_ = true;
_withdrawAll();
}
// test helpers
function _setVault_(address _vault) external {
vault = _vault;
}
function _setUnderlying_(address _token) external {
underlying = _token;
}
function _setAsset_(address _token) external {
assets[_token] = true;
}
function _mintToPool_(uint _amount) external {
TestToken(underlying)._mint_(_POOL_, _amount);
}
function _setTotalDebt_(uint _debt) external {
totalDebt = _debt;
}
function _setMaxWithdrawAmount_(uint _max) external {
_maxWithdrawAmount_ = _max;
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.6.11;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
/* solium-disable */
contract TestToken is ERC20 {
constructor() public ERC20("test", "TEST") {
_setupDecimals(18);
}
/* test helper */
function _mint_(address _to, uint _amount) external {
_mint(_to, _amount);
}
function _burn_(address _from, uint _amount) external {
_burn(_from, _amount);
}
function _approve_(
address _from,
address _to,
uint _amount
) external {
_approve(_from, _to, _amount);
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.6.11;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../protocol/IStrategy.sol";
/*
This is a "placeholder" strategy used during emergency shutdown
*/
contract StrategyNoOp is IStrategy {
using SafeERC20 for IERC20;
address public override admin;
address public override controller;
address public override vault;
address public override underlying;
uint public override totalDebt;
uint public override performanceFee;
mapping(address => bool) public override assets;
constructor(
address _controller,
address _vault,
address _underlying
) public {
require(_controller != address(0), "controller = zero address");
require(_vault != address(0), "vault = zero address");
require(_underlying != address(0), "underlying = zero address");
admin = msg.sender;
controller = _controller;
vault = _vault;
underlying = _underlying;
assets[underlying] = true;
}
modifier onlyAdmin() {
require(msg.sender == admin, "!admin");
_;
}
function setAdmin(address _admin) external override onlyAdmin {
require(_admin != address(0), "admin = zero address");
admin = _admin;
}
// @dev variable name is removed to silence compiler warning
function setController(address) external override {
revert("no-op");
}
// @dev variable name is removed to silence compiler warning
function setPerformanceFee(uint) external override {
revert("no-op");
}
function totalAssets() external view override returns (uint) {
return 0;
}
// @dev variable name is removed to silence compiler warning
function deposit(uint) external override {
revert("no-op");
}
// @dev variable name is removed to silence compiler warning
function withdraw(uint) external override {
revert("no-op");
}
function withdrawAll() external override {
revert("no-op");
}
function harvest() external override {
revert("no-op");
}
function skim() external override {
revert("no-op");
}
function exit() external override {
// left as blank so that Vault can call exit() during Vault.setStrategy()
}
function sweep(address _token) external override onlyAdmin {
require(!assets[_token], "asset");
IERC20(_token).safeTransfer(admin, IERC20(_token).balanceOf(address(this)));
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.6.11;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "./interfaces/uniswap/Uniswap.sol";
contract UseUniswap {
using SafeERC20 for IERC20;
using SafeMath for uint;
// Uniswap //
address private constant UNISWAP = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
address internal constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
function _swap(
address _from,
address _to,
uint _amount
) internal {
require(_to != address(0), "to = zero address");
// Swap with uniswap
IERC20(_from).safeApprove(UNISWAP, 0);
IERC20(_from).safeApprove(UNISWAP, _amount);
address[] memory path;
if (_from == WETH || _to == WETH) {
path = new address[](2);
path[0] = _from;
path[1] = _to;
} else {
path = new address[](3);
path[0] = _from;
path[1] = WETH;
path[2] = _to;
}
Uniswap(UNISWAP).swapExactTokensForTokens(
_amount,
0,
path,
address(this),
now.add(60)
);
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.6.11;
interface Uniswap {
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.6.11;
import "../interfaces/pickle/PickleJar.sol";
import "../interfaces/pickle/MasterChef.sol";
import "../interfaces/pickle/PickleStaking.sol";
import "../StrategyBase.sol";
import "../UseUniswap.sol";
contract StrategyPdaiDai is StrategyBase, UseUniswap {
address internal constant DAI = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
// Pickle //
address private constant JAR = 0x6949Bb624E8e8A90F87cD2058139fcd77D2F3F87;
address private constant CHEF = 0xbD17B1ce622d73bD438b9E658acA5996dc394b0d;
address private constant PICKLE = 0x429881672B9AE42b8EbA0E26cD9C73711b891Ca5;
address private constant STAKING = 0xa17a8883dA1aBd57c690DF9Ebf58fC194eDAb66F;
// percentage of Pickle to sell, rest is staked
uint public pickleSell = 5000;
uint private constant PICKLE_SELL_MAX = 10000;
// POOL ID for PDAI JAR
uint private constant POOL_ID = 16;
constructor(address _controller, address _vault)
public
StrategyBase(_controller, _vault, DAI)
{
// Assets that cannot be swept by admin
assets[PICKLE] = true;
}
function setPickleSell(uint _sell) external onlyAdmin {
require(_sell <= PICKLE_SELL_MAX, "sell > max");
pickleSell = _sell;
}
// TODO security: vulnerable to price manipulation?
function _totalAssets() internal view override returns (uint) {
// getRatio() is multiplied by 10 ** 18
uint pricePerShare = PickleJar(JAR).getRatio();
(uint shares, ) = MasterChef(CHEF).userInfo(POOL_ID, address(this));
return shares.mul(pricePerShare).div(1e18);
}
function _depositUnderlying() internal override {
// deposit DAI into PICKLE
uint bal = IERC20(underlying).balanceOf(address(this));
if (bal > 0) {
IERC20(underlying).safeApprove(JAR, 0);
IERC20(underlying).safeApprove(JAR, bal);
PickleJar(JAR).deposit(bal);
}
// stake pDai
uint pDaiBal = IERC20(JAR).balanceOf(address(this));
if (pDaiBal > 0) {
IERC20(JAR).safeApprove(CHEF, 0);
IERC20(JAR).safeApprove(CHEF, pDaiBal);
MasterChef(CHEF).deposit(POOL_ID, pDaiBal);
}
// stake PICKLE
uint pickleBal = IERC20(PICKLE).balanceOf(address(this));
if (pickleBal > 0) {
IERC20(PICKLE).safeApprove(STAKING, 0);
IERC20(PICKLE).safeApprove(STAKING, pickleBal);
PickleStaking(STAKING).stake(pickleBal);
}
}
function _getTotalShares() internal view override returns (uint) {
(uint pDaiBal, ) = MasterChef(CHEF).userInfo(POOL_ID, address(this));
return pDaiBal;
}
function _withdrawUnderlying(uint _pDaiAmount) internal override {
// unstake
MasterChef(CHEF).withdraw(POOL_ID, _pDaiAmount);
// withdraw DAI from PICKLE
PickleJar(JAR).withdraw(_pDaiAmount);
// Now we have underlying
}
function _swapWeth() private {
uint wethBal = IERC20(WETH).balanceOf(address(this));
if (wethBal > 0) {
_swap(WETH, underlying, wethBal);
// Now this contract has underlying token
}
}
/*
@notice Sell PICKLE and deposit most premium token into CURVE
*/
function harvest() external override onlyAuthorized {
// claim Pickle
MasterChef(CHEF).deposit(POOL_ID, 0);
// unsold amount will be staked in _depositUnderlying()
uint pickleBal = IERC20(PICKLE).balanceOf(address(this));
uint pickleAmount = pickleBal.mul(pickleSell).div(PICKLE_SELL_MAX);
if (pickleAmount > 0) {
_swap(PICKLE, underlying, pickleAmount);
// Now this contract has underlying token
}
// get staking rewards WETH
PickleStaking(STAKING).getReward();
_swapWeth();
uint bal = IERC20(underlying).balanceOf(address(this));
if (bal > 0) {
// transfer fee to treasury
uint fee = bal.mul(performanceFee).div(PERFORMANCE_FEE_MAX);
if (fee > 0) {
address treasury = IController(controller).treasury();
require(treasury != address(0), "treasury = zero address");
IERC20(underlying).safeTransfer(treasury, fee);
}
_depositUnderlying();
}
}
/*
@dev Caller should implement guard agains slippage
*/
function exit() external override onlyAuthorized {
/*
PICKLE is minted on deposit / withdraw so here we
0. Unstake PICKLE and claim WETH rewards
1. Sell WETH
2. Withdraw from MasterChef
3. Sell PICKLE
4. Transfer underlying to vault
*/
uint staked = PickleStaking(STAKING).balanceOf(address(this));
if (staked > 0) {
PickleStaking(STAKING).exit();
_swapWeth();
}
_withdrawAll();
uint pickleBal = IERC20(PICKLE).balanceOf(address(this));
if (pickleBal > 0) {
_swap(PICKLE, underlying, pickleBal);
// Now this contract has underlying token
}
uint bal = IERC20(underlying).balanceOf(address(this));
if (bal > 0) {
IERC20(underlying).safeTransfer(vault, bal);
}
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.6.11;
interface PickleJar {
/*
@notice returns price of token / share
@dev ratio is multiplied by 10 ** 18
*/
function getRatio() external view returns (uint);
function deposit(uint _amount) external;
function withdraw(uint _amount) external;
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.6.11;
interface MasterChef {
function userInfo(uint _pid, address _user)
external
view
returns (uint _amount, uint _rewardDebt);
function deposit(uint _pid, uint _amount) external;
function withdraw(uint _pid, uint _amount) external;
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.6.11;
interface PickleStaking {
function balanceOf(address account) external view returns (uint);
function earned(address account) external view returns (uint);
function stake(uint amount) external;
function withdraw(uint amount) external;
function getReward() external;
function exit() external;
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.6.11;
import "../interfaces/curve/StableSwap3.sol";
import "../interfaces/pickle/PickleJar.sol";
import "../interfaces/pickle/MasterChef.sol";
import "../StrategyBase.sol";
import "../UseUniswap.sol";
contract StrategyP3Crv is StrategyBase, UseUniswap {
address internal constant DAI = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
address internal constant USDC = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48;
address internal constant USDT = 0xdAC17F958D2ee523a2206206994597C13D831ec7;
// DAI = 0 | USDC = 1 | USDT = 2
uint internal underlyingIndex;
// precision to convert 10 ** 18 to underlying decimals
uint internal precisionDiv = 1;
// Curve //
// 3Crv
address private constant THREE_CRV = 0x6c3F90f043a72FA612cbac8115EE7e52BDe6E490;
// StableSwap3
address private constant CURVE = 0xbEbc44782C7dB0a1A60Cb6fe97d0b483032FF1C7;
// Pickle //
address private constant JAR = 0x1BB74b5DdC1f4fC91D6f9E7906cf68bc93538e33;
address private constant CHEF = 0xbD17B1ce622d73bD438b9E658acA5996dc394b0d;
address private constant PICKLE = 0x429881672B9AE42b8EbA0E26cD9C73711b891Ca5;
// POOL ID for 3Crv JAR
uint private constant POOL_ID = 14;
constructor(
address _controller,
address _vault,
address _underlying
) public StrategyBase(_controller, _vault, _underlying) {
// Assets that cannot be swept by admin
assets[PICKLE] = true;
}
// TODO security: vulnerable to price manipulation
function _totalAssets() internal view override returns (uint) {
// getRatio() is multiplied by 10 ** 18
uint pricePerShare = PickleJar(JAR).getRatio();
(uint shares, ) = MasterChef(CHEF).userInfo(POOL_ID, address(this));
return shares.mul(pricePerShare).div(precisionDiv) / 1e18;
}
function _deposit(address _token, uint _index) private {
// token to THREE_CRV
uint bal = IERC20(_token).balanceOf(address(this));
if (bal > 0) {
IERC20(_token).safeApprove(CURVE, 0);
IERC20(_token).safeApprove(CURVE, bal);
// mint THREE_CRV
uint[3] memory amounts;
amounts[_index] = bal;
StableSwap3(CURVE).add_liquidity(amounts, 0);
// Now we have 3Crv
}
// deposit 3Crv into PICKLE
uint threeBal = IERC20(THREE_CRV).balanceOf(address(this));
if (threeBal > 0) {
IERC20(THREE_CRV).safeApprove(JAR, 0);
IERC20(THREE_CRV).safeApprove(JAR, threeBal);
PickleJar(JAR).deposit(threeBal);
}
// stake p3crv
uint p3crvBal = IERC20(JAR).balanceOf(address(this));
if (p3crvBal > 0) {
IERC20(JAR).safeApprove(CHEF, 0);
IERC20(JAR).safeApprove(CHEF, p3crvBal);
MasterChef(CHEF).deposit(POOL_ID, p3crvBal);
}
// TODO stake
}
function _depositUnderlying() internal override {
_deposit(underlying, underlyingIndex);
}
function _getTotalShares() internal view override returns (uint) {
(uint p3CrvBal, ) = MasterChef(CHEF).userInfo(POOL_ID, address(this));
return p3CrvBal;
}
function _withdrawUnderlying(uint _p3CrvAmount) internal override {
// unstake
MasterChef(CHEF).withdraw(POOL_ID, _p3CrvAmount);
// withdraw THREE_CRV from PICKLE
PickleJar(JAR).withdraw(_p3CrvAmount);
// withdraw underlying
uint threeBal = IERC20(THREE_CRV).balanceOf(address(this));
// creates THREE_CRV dust
StableSwap3(CURVE).remove_liquidity_one_coin(
threeBal,
int128(underlyingIndex),
0
);
// Now we have underlying
}
/*
@notice Returns address and index of token with lowest balance in CURVE pool
*/
function _getMostPremiumToken() private view returns (address, uint) {
uint[] memory balances = new uint[](3);
balances[0] = StableSwap3(CURVE).balances(0); // DAI
balances[1] = StableSwap3(CURVE).balances(1).mul(1e12); // USDC
balances[2] = StableSwap3(CURVE).balances(2).mul(1e12); // USDT
// DAI
if (balances[0] <= balances[1] && balances[0] <= balances[2]) {
return (DAI, 0);
}
// USDC
if (balances[1] <= balances[0] && balances[1] <= balances[2]) {
return (USDC, 1);
}
// USDT
return (USDT, 2);
}
function _swapPickleFor(address _token) private {
uint pickleBal = IERC20(PICKLE).balanceOf(address(this));
if (pickleBal > 0) {
_swap(PICKLE, _token, pickleBal);
// Now this contract has underlying token
}
}
/*
@notice Sell PICKLE and deposit most premium token into CURVE
*/
function harvest() external override onlyAuthorized {
// TODO: claim Pickle
// MasterChef(CHER).deposit(POOL_ID, 0);
(address token, uint index) = _getMostPremiumToken();
_swapPickleFor(token);
uint bal = IERC20(token).balanceOf(address(this));
if (bal > 0) {
// transfer fee to treasury
uint fee = bal.mul(performanceFee) / PERFORMANCE_FEE_MAX;
if (fee > 0) {
address treasury = IController(controller).treasury();
require(treasury != address(0), "treasury = zero address");
IERC20(token).safeTransfer(treasury, fee);
}
_deposit(token, index);
}
}
/*
@dev Caller should implement guard agains slippage
*/
function exit() external override onlyAuthorized {
// PICKLE is minted on withdraw so here we
// 1. Withdraw from MasterChef
// 2. Sell PICKLE
// 3. Transfer underlying to vault
_withdrawAll();
_swapPickleFor(underlying);
uint underlyingBal = IERC20(underlying).balanceOf(address(this));
if (underlyingBal > 0) {
IERC20(underlying).safeTransfer(vault, underlyingBal);
}
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.6.11;
interface StableSwap3 {
/*
@dev Returns price of 1 Curve LP token in USD
*/
function get_virtual_price() external view returns (uint);
function add_liquidity(uint[3] calldata amounts, uint min_mint_amount) external;
function remove_liquidity_one_coin(
uint token_amount,
int128 i,
uint min_uamount
) external;
function balances(uint index) external view returns (uint);
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.6.11;
import "./StrategyP3Crv.sol";
contract StrategyP3CrvUsdt is StrategyP3Crv {
constructor(address _controller, address _vault)
public
StrategyP3Crv(_controller, _vault, USDT)
{
// usdt
underlyingIndex = 2;
precisionDiv = 1e12;
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.6.11;
import "./StrategyP3Crv.sol";
contract StrategyP3CrvUsdc is StrategyP3Crv {
constructor(address _controller, address _vault)
public
StrategyP3Crv(_controller, _vault, USDC)
{
// usdc
underlyingIndex = 1;
precisionDiv = 1e12;
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.6.11;
import "./StrategyP3Crv.sol";
contract StrategyP3CrvDai is StrategyP3Crv {
constructor(address _controller, address _vault)
public
StrategyP3Crv(_controller, _vault, DAI)
{
// dai
underlyingIndex = 0;
precisionDiv = 1;
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.6.11;
import "../interfaces/curve/StableSwapGusd.sol";
import "../interfaces/curve/DepositGusd.sol";
import "../interfaces/curve/StableSwap3.sol";
import "./StrategyCurve.sol";
contract StrategyGusd is StrategyCurve {
// 3Pool StableSwap
address private constant BASE_POOL = 0xbEbc44782C7dB0a1A60Cb6fe97d0b483032FF1C7;
// GUSD StableSwap
address private constant SWAP = 0x4f062658EaAF2C1ccf8C8e36D6824CDf41167956;
address private constant GUSD = 0x056Fd409E1d7A124BD7017459dFEa2F387b6d5Cd;
address internal constant DAI = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
address internal constant USDC = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48;
address internal constant USDT = 0xdAC17F958D2ee523a2206206994597C13D831ec7;
constructor(
address _controller,
address _vault,
address _underlying
) public StrategyCurve(_controller, _vault, _underlying) {
// Curve
// GUSD / 3CRV
lp = 0xD2967f45c4f384DEEa880F807Be904762a3DeA07;
// DepositGusd
pool = 0x64448B78561690B70E17CBE8029a3e5c1bB7136e;
// Gauge
gauge = 0xC5cfaDA84E902aD92DD40194f0883ad49639b023;
// Minter
minter = 0xd061D61a4d941c39E5453435B6345Dc261C2fcE0;
// DAO
crv = 0xD533a949740bb3306d119CC777fa900bA034cd52;
}
function _getVirtualPrice() internal view override returns (uint) {
return StableSwapGusd(SWAP).get_virtual_price();
}
function _addLiquidity(uint _amount, uint _index) internal override {
uint[4] memory amounts;
amounts[_index] = _amount;
DepositGusd(pool).add_liquidity(amounts, 0);
}
function _removeLiquidityOneCoin(uint _lpAmount) internal override {
IERC20(lp).safeApprove(pool, 0);
IERC20(lp).safeApprove(pool, _lpAmount);
DepositGusd(pool).remove_liquidity_one_coin(
_lpAmount,
int128(underlyingIndex),
0
);
}
function _getMostPremiumToken() internal view override returns (address, uint) {
uint[4] memory balances;
balances[0] = StableSwapGusd(SWAP).balances(0).mul(1e16); // GUSD
balances[1] = StableSwap3(BASE_POOL).balances(0); // DAI
balances[2] = StableSwap3(BASE_POOL).balances(1).mul(1e12); // USDC
balances[3] = StableSwap3(BASE_POOL).balances(2).mul(1e12); // USDT
uint minIndex = 0;
for (uint i = 1; i < balances.length; i++) {
if (balances[i] <= balances[minIndex]) {
minIndex = i;
}
}
if (minIndex == 0) {
return (GUSD, 0);
}
if (minIndex == 1) {
return (DAI, 1);
}
if (minIndex == 2) {
return (USDC, 2);
}
return (USDT, 3);
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.6.11;
interface StableSwapGusd {
function get_virtual_price() external view returns (uint);
/*
0 GUSD
1 3CRV
*/
function balances(uint index) external view returns (uint);
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.6.11;
interface DepositGusd {
/*
0 GUSD
1 DAI
2 USDC
3 USDT
*/
function add_liquidity(uint[4] memory amounts, uint min) external returns (uint);
function remove_liquidity_one_coin(
uint amount,
int128 index,
uint min
) external returns (uint);
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.6.11;
import "../interfaces/curve/Gauge.sol";
import "../interfaces/curve/Minter.sol";
import "../StrategyBase.sol";
import "../UseUniswap.sol";
/* potential hacks?
- front running?
- slippage when withdrawing all from strategy
*/
abstract contract StrategyCurve is StrategyBase, UseUniswap {
// DAI = 0 | USDC = 1 | USDT = 2
uint internal underlyingIndex;
// precision to convert 10 ** 18 to underlying decimals
uint internal precisionDiv = 1;
// Curve //
// liquidity provider token (cDAI/cUSDC or 3Crv)
address internal lp;
// ICurveFi2 or ICurveFi3
address internal pool;
// Gauge
address internal gauge;
// Minter
address internal minter;
// DAO
address internal crv;
constructor(
address _controller,
address _vault,
address _underlying
) public StrategyBase(_controller, _vault, _underlying) {}
function _getVirtualPrice() internal view virtual returns (uint);
function _totalAssets() internal view override returns (uint) {
uint lpBal = Gauge(gauge).balanceOf(address(this));
uint pricePerShare = _getVirtualPrice();
return lpBal.mul(pricePerShare).div(precisionDiv) / 1e18;
}
function _addLiquidity(uint _amount, uint _index) internal virtual;
/*
@notice deposit token into curve
*/
function _deposit(address _token, uint _index) private {
// token to lp
uint bal = IERC20(_token).balanceOf(address(this));
if (bal > 0) {
IERC20(_token).safeApprove(pool, 0);
IERC20(_token).safeApprove(pool, bal);
// mint lp
_addLiquidity(bal, _index);
}
// stake into Gauge
uint lpBal = IERC20(lp).balanceOf(address(this));
if (lpBal > 0) {
IERC20(lp).safeApprove(gauge, 0);
IERC20(lp).safeApprove(gauge, lpBal);
Gauge(gauge).deposit(lpBal);
}
}
/*
@notice Deposits underlying to Gauge
*/
function _depositUnderlying() internal override {
_deposit(underlying, underlyingIndex);
}
function _removeLiquidityOneCoin(uint _lpAmount) internal virtual;
function _getTotalShares() internal view override returns (uint) {
return Gauge(gauge).balanceOf(address(this));
}
function _withdrawUnderlying(uint _lpAmount) internal override {
// withdraw lp from Gauge
Gauge(gauge).withdraw(_lpAmount);
// withdraw underlying
uint lpBal = IERC20(lp).balanceOf(address(this));
// creates lp dust
_removeLiquidityOneCoin(lpBal);
// Now we have underlying
}
/*
@notice Returns address and index of token with lowest balance in Curve pool
*/
function _getMostPremiumToken() internal view virtual returns (address, uint);
function _swapCrvFor(address _token) private {
Minter(minter).mint(gauge);
uint crvBal = IERC20(crv).balanceOf(address(this));
if (crvBal > 0) {
_swap(crv, _token, crvBal);
// Now this contract has token
}
}
/*
@notice Claim CRV and deposit most premium token into Curve
*/
function harvest() external override onlyAuthorized {
(address token, uint index) = _getMostPremiumToken();
_swapCrvFor(token);
uint bal = IERC20(token).balanceOf(address(this));
if (bal > 0) {
// transfer fee to treasury
uint fee = bal.mul(performanceFee) / PERFORMANCE_FEE_MAX;
if (fee > 0) {
address treasury = IController(controller).treasury();
require(treasury != address(0), "treasury = zero address");
IERC20(token).safeTransfer(treasury, fee);
}
_deposit(token, index);
}
}
/*
@notice Exit strategy by harvesting CRV to underlying token and then
withdrawing all underlying to vault
@dev Must return all underlying token to vault
@dev Caller should implement guard agains slippage
*/
function exit() external override onlyAuthorized {
_swapCrvFor(underlying);
_withdrawAll();
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.6.11;
// https://github.com/curvefi/curve-contract/blob/master/contracts/gauges/LiquidityGauge.vy
interface Gauge {
function deposit(uint) external;
function balanceOf(address) external view returns (uint);
function withdraw(uint) external;
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.6.11;
// https://github.com/curvefi/curve-dao-contracts/blob/master/contracts/Minter.vy
interface Minter {
function mint(address) external;
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.6.11;
import "./StrategyGusd.sol";
contract StrategyGusdUsdt is StrategyGusd {
constructor(address _controller, address _vault)
public
StrategyGusd(_controller, _vault, USDT)
{
// usdt
underlyingIndex = 3;
precisionDiv = 1e12;
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.6.11;
import "./StrategyGusd.sol";
contract StrategyGusdUsdc is StrategyGusd {
constructor(address _controller, address _vault)
public
StrategyGusd(_controller, _vault, USDC)
{
// usdc
underlyingIndex = 2;
precisionDiv = 1e12;
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.6.11;
import "./StrategyGusd.sol";
contract StrategyGusdDai is StrategyGusd {
constructor(address _controller, address _vault)
public
StrategyGusd(_controller, _vault, DAI)
{
// dai
underlyingIndex = 1;
precisionDiv = 1;
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.6.11;
import "../interfaces/curve/StableSwapPax.sol";
import "../interfaces/curve/DepositPax.sol";
import "./StrategyCurve.sol";
contract StrategyPax is StrategyCurve {
// PAX StableSwap
address private constant SWAP = 0x06364f10B501e868329afBc005b3492902d6C763;
address private constant PAX = 0x8E870D67F660D95d5be530380D0eC0bd388289E1;
address internal constant DAI = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
address internal constant USDC = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48;
address internal constant USDT = 0xdAC17F958D2ee523a2206206994597C13D831ec7;
constructor(
address _controller,
address _vault,
address _underlying
) public StrategyCurve(_controller, _vault, _underlying) {
// Curve
// DAI/USDC/USDT/PAX
lp = 0xD905e2eaeBe188fc92179b6350807D8bd91Db0D8;
// DepositPax
pool = 0xA50cCc70b6a011CffDdf45057E39679379187287;
// Gauge
gauge = 0x64E3C23bfc40722d3B649844055F1D51c1ac041d;
// Minter
minter = 0xd061D61a4d941c39E5453435B6345Dc261C2fcE0;
// DAO
crv = 0xD533a949740bb3306d119CC777fa900bA034cd52;
}
function _getVirtualPrice() internal view override returns (uint) {
return StableSwapPax(SWAP).get_virtual_price();
}
function _addLiquidity(uint _amount, uint _index) internal override {
uint[4] memory amounts;
amounts[_index] = _amount;
DepositPax(pool).add_liquidity(amounts, 0);
}
function _removeLiquidityOneCoin(uint _lpAmount) internal override {
IERC20(lp).safeApprove(pool, 0);
IERC20(lp).safeApprove(pool, _lpAmount);
DepositPax(pool).remove_liquidity_one_coin(
_lpAmount,
int128(underlyingIndex),
0,
false
);
}
function _getMostPremiumToken() internal view override returns (address, uint) {
uint[4] memory balances;
balances[0] = StableSwapPax(SWAP).balances(0); // DAI
balances[1] = StableSwapPax(SWAP).balances(1).mul(1e12); // USDC
balances[2] = StableSwapPax(SWAP).balances(2).mul(1e12); // USDT
balances[3] = StableSwapPax(SWAP).balances(3); // PAX
uint minIndex = 0;
for (uint i = 1; i < balances.length; i++) {
if (balances[i] <= balances[minIndex]) {
minIndex = i;
}
}
if (minIndex == 0) {
return (DAI, 0);
}
if (minIndex == 1) {
return (USDC, 1);
}
if (minIndex == 2) {
return (USDT, 2);
}
return (PAX, 3);
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.6.11;
interface StableSwapPax {
function get_virtual_price() external view returns (uint);
/*
0 DAI
1 USDC
2 USDT
3 PAX
*/
function balances(int128 index) external view returns (uint);
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.6.11;
interface DepositPax {
/*
0 DAI
1 USDC
2 USDT
3 PAX
*/
function add_liquidity(uint[4] memory amounts, uint min) external;
function remove_liquidity_one_coin(
uint amount,
int128 index,
uint min,
bool donateDust
) external;
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.6.11;
import "./StrategyPax.sol";
contract StrategyPaxUsdt is StrategyPax {
constructor(address _controller, address _vault)
public
StrategyPax(_controller, _vault, USDT)
{
// usdt
underlyingIndex = 2;
precisionDiv = 1e12;
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.6.11;
import "./StrategyPax.sol";
contract StrategyPaxUsdc is StrategyPax {
constructor(address _controller, address _vault)
public
StrategyPax(_controller, _vault, USDC)
{
// usdc
underlyingIndex = 1;
precisionDiv = 1e12;
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.6.11;
import "./StrategyPax.sol";
contract StrategyPaxDai is StrategyPax {
constructor(address _controller, address _vault)
public
StrategyPax(_controller, _vault, DAI)
{
// dai
underlyingIndex = 0;
precisionDiv = 1;
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.6.11;
import "../interfaces/curve/StableSwap2.sol";
import "../interfaces/curve/Deposit2.sol";
import "./StrategyCurve.sol";
contract StrategyCusd is StrategyCurve {
address internal constant DAI = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
address internal constant USDC = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48;
address private constant SWAP = 0xA2B47E3D5c44877cca798226B7B8118F9BFb7A56;
constructor(
address _controller,
address _vault,
address _underlying
) public StrategyCurve(_controller, _vault, _underlying) {
// Curve
// cDAI/cUSDC
lp = 0x845838DF265Dcd2c412A1Dc9e959c7d08537f8a2;
// DepositCompound
pool = 0xeB21209ae4C2c9FF2a86ACA31E123764A3B6Bc06;
// Gauge
gauge = 0x7ca5b0a2910B33e9759DC7dDB0413949071D7575;
// Minter
minter = 0xd061D61a4d941c39E5453435B6345Dc261C2fcE0;
// DAO
crv = 0xD533a949740bb3306d119CC777fa900bA034cd52;
}
/*
@dev Returns USD price of 1 Curve Compound LP token
*/
function _getVirtualPrice() internal view override returns (uint) {
return StableSwap2(SWAP).get_virtual_price();
}
function _addLiquidity(uint _amount, uint _index) internal override {
uint[2] memory amounts;
amounts[_index] = _amount;
Deposit2(pool).add_liquidity(amounts, 0);
}
function _removeLiquidityOneCoin(uint _lpAmount) internal override {
IERC20(lp).safeApprove(pool, 0);
IERC20(lp).safeApprove(pool, _lpAmount);
Deposit2(pool).remove_liquidity_one_coin(
_lpAmount,
int128(underlyingIndex),
0,
true
);
}
function _getMostPremiumToken() internal view override returns (address, uint) {
uint[] memory balances = new uint[](2);
balances[0] = StableSwap2(SWAP).balances(0); // DAI
balances[1] = StableSwap2(SWAP).balances(1).mul(1e12); // USDC
// DAI
if (balances[0] < balances[1]) {
return (DAI, 0);
}
return (USDC, 1);
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.6.11;
interface StableSwap2 {
/*
@dev Returns price of 1 Curve LP token in USD
*/
function get_virtual_price() external view returns (uint);
function add_liquidity(uint[2] calldata amounts, uint min_mint_amount) external;
function remove_liquidity_one_coin(
uint token_amount,
int128 i,
uint min_uamount,
bool donate_dust
) external;
function balances(int128 index) external view returns (uint);
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.6.11;
interface Deposit2 {
function add_liquidity(uint[2] calldata amounts, uint min_mint_amount) external;
function remove_liquidity_one_coin(
uint token_amount,
int128 i,
uint min_uamount,
bool donate_dust
) external;
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.6.11;
import "./StrategyCusd.sol";
contract StrategyCusdUsdc is StrategyCusd {
constructor(address _controller, address _vault)
public
StrategyCusd(_controller, _vault, USDC)
{
// usdc
underlyingIndex = 1;
precisionDiv = 1e12;
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.6.11;
import "./StrategyCusd.sol";
contract StrategyCusdDai is StrategyCusd {
constructor(address _controller, address _vault)
public
StrategyCusd(_controller, _vault, DAI)
{
// dai
underlyingIndex = 0;
precisionDiv = 1;
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.6.11;
import "../interfaces/curve/StableSwapBusd.sol";
import "../interfaces/curve/DepositBusd.sol";
import "./StrategyCurve.sol";
contract StrategyBusd is StrategyCurve {
// BUSD StableSwap
address private constant SWAP = 0x79a8C46DeA5aDa233ABaFFD40F3A0A2B1e5A4F27;
address private constant BUSD = 0x4Fabb145d64652a948d72533023f6E7A623C7C53;
address internal constant DAI = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
address internal constant USDC = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48;
address internal constant USDT = 0xdAC17F958D2ee523a2206206994597C13D831ec7;
constructor(
address _controller,
address _vault,
address _underlying
) public StrategyCurve(_controller, _vault, _underlying) {
// Curve
// yDAI/yUSDC/yUSDT/yBUSD
lp = 0x3B3Ac5386837Dc563660FB6a0937DFAa5924333B;
// DepositBusd
pool = 0xb6c057591E073249F2D9D88Ba59a46CFC9B59EdB;
// Gauge
gauge = 0x69Fb7c45726cfE2baDeE8317005d3F94bE838840;
// Minter
minter = 0xd061D61a4d941c39E5453435B6345Dc261C2fcE0;
// DAO
crv = 0xD533a949740bb3306d119CC777fa900bA034cd52;
}
function _getVirtualPrice() internal view override returns (uint) {
return StableSwapBusd(SWAP).get_virtual_price();
}
function _addLiquidity(uint _amount, uint _index) internal override {
uint[4] memory amounts;
amounts[_index] = _amount;
DepositBusd(pool).add_liquidity(amounts, 0);
}
function _removeLiquidityOneCoin(uint _lpAmount) internal override {
IERC20(lp).safeApprove(pool, 0);
IERC20(lp).safeApprove(pool, _lpAmount);
DepositBusd(pool).remove_liquidity_one_coin(
_lpAmount,
int128(underlyingIndex),
0,
false
);
}
function _getMostPremiumToken() internal view override returns (address, uint) {
uint[4] memory balances;
balances[0] = StableSwapBusd(SWAP).balances(0); // DAI
balances[1] = StableSwapBusd(SWAP).balances(1).mul(1e12); // USDC
balances[2] = StableSwapBusd(SWAP).balances(2).mul(1e12); // USDT
balances[3] = StableSwapBusd(SWAP).balances(3); // BUSD
uint minIndex = 0;
for (uint i = 1; i < balances.length; i++) {
if (balances[i] <= balances[minIndex]) {
minIndex = i;
}
}
if (minIndex == 0) {
return (DAI, 0);
}
if (minIndex == 1) {
return (USDC, 1);
}
if (minIndex == 2) {
return (USDT, 2);
}
return (BUSD, 3);
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.6.11;
interface StableSwapBusd {
function get_virtual_price() external view returns (uint);
/*
0 DAI
1 USDC
2 USDT
3 BUSD
*/
function balances(int128 index) external view returns (uint);
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.6.11;
interface DepositBusd {
/*
0 DAI
1 USDC
2 USDT
3 BUSD
*/
function add_liquidity(uint[4] memory amounts, uint min) external;
function remove_liquidity_one_coin(
uint amount,
int128 index,
uint min,
bool donateDust
) external;
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.6.11;
import "./StrategyBusd.sol";
contract StrategyBusdUsdt is StrategyBusd {
constructor(address _controller, address _vault)
public
StrategyBusd(_controller, _vault, USDT)
{
// usdt
underlyingIndex = 2;
precisionDiv = 1e12;
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.6.11;
import "./StrategyBusd.sol";
contract StrategyBusdUsdc is StrategyBusd {
constructor(address _controller, address _vault)
public
StrategyBusd(_controller, _vault, USDC)
{
// usdc
underlyingIndex = 1;
precisionDiv = 1e12;
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.6.11;
import "./StrategyBusd.sol";
contract StrategyBusdDai is StrategyBusd {
constructor(address _controller, address _vault)
public
StrategyBusd(_controller, _vault, DAI)
{
// dai
underlyingIndex = 0;
precisionDiv = 1;
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.6.11;
import "../interfaces/curve/StableSwap3.sol";
import "./StrategyCurve.sol";
contract Strategy3Crv is StrategyCurve {
address internal constant DAI = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
address internal constant USDC = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48;
address internal constant USDT = 0xdAC17F958D2ee523a2206206994597C13D831ec7;
constructor(
address _controller,
address _vault,
address _underlying
) public StrategyCurve(_controller, _vault, _underlying) {
// Curve
// 3Crv
lp = 0x6c3F90f043a72FA612cbac8115EE7e52BDe6E490;
// 3 Pool
pool = 0xbEbc44782C7dB0a1A60Cb6fe97d0b483032FF1C7;
// Gauge
gauge = 0xbFcF63294aD7105dEa65aA58F8AE5BE2D9d0952A;
// Minter
minter = 0xd061D61a4d941c39E5453435B6345Dc261C2fcE0;
// DAO
crv = 0xD533a949740bb3306d119CC777fa900bA034cd52;
}
function _getVirtualPrice() internal view override returns (uint) {
return StableSwap3(pool).get_virtual_price();
}
function _addLiquidity(uint _amount, uint _index) internal override {
uint[3] memory amounts;
amounts[_index] = _amount;
StableSwap3(pool).add_liquidity(amounts, 0);
}
function _removeLiquidityOneCoin(uint _lpAmount) internal override {
StableSwap3(pool).remove_liquidity_one_coin(
_lpAmount,
int128(underlyingIndex),
0
);
}
function _getMostPremiumToken() internal view override returns (address, uint) {
uint[] memory balances = new uint[](3);
balances[0] = StableSwap3(pool).balances(0); // DAI
balances[1] = StableSwap3(pool).balances(1).mul(1e12); // USDC
balances[2] = StableSwap3(pool).balances(2).mul(1e12); // USDT
// DAI
if (balances[0] <= balances[1] && balances[0] <= balances[2]) {
return (DAI, 0);
}
// USDC
if (balances[1] <= balances[0] && balances[1] <= balances[2]) {
return (USDC, 1);
}
return (USDT, 2);
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.6.11;
import "./Strategy3Crv.sol";
contract Strategy3CrvUsdt is Strategy3Crv {
constructor(address _controller, address _vault)
public
Strategy3Crv(_controller, _vault, USDT)
{
// usdt
underlyingIndex = 2;
precisionDiv = 1e12;
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.6.11;
import "./Strategy3Crv.sol";
contract Strategy3CrvUsdc is Strategy3Crv {
constructor(address _controller, address _vault)
public
Strategy3Crv(_controller, _vault, USDC)
{
// usdc
underlyingIndex = 1;
precisionDiv = 1e12;
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.6.11;
import "./Strategy3Crv.sol";
contract Strategy3CrvDai is Strategy3Crv {
constructor(address _controller, address _vault)
public
Strategy3Crv(_controller, _vault, DAI)
{
// dai
underlyingIndex = 0;
precisionDiv = 1;
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.6.11;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "./protocol/ITimeLock.sol";
contract TimeLock is ITimeLock {
using SafeMath for uint;
event NewAdmin(address admin);
event NewDelay(uint delay);
event Queue(
bytes32 indexed txHash,
address indexed target,
uint value,
bytes data,
uint eta
);
event Execute(
bytes32 indexed txHash,
address indexed target,
uint value,
bytes data,
uint eta
);
event Cancel(
bytes32 indexed txHash,
address indexed target,
uint value,
bytes data,
uint eta
);
uint public constant GRACE_PERIOD = 14 days;
uint public constant MIN_DELAY = 1 days;
uint public constant MAX_DELAY = 30 days;
address public override admin;
uint public override delay;
mapping(bytes32 => bool) public override queued;
constructor(uint _delay) public {
admin = msg.sender;
_setDelay(_delay);
}
receive() external payable override {}
modifier onlyAdmin() {
require(msg.sender == admin, "!admin");
_;
}
function setAdmin(address _admin) external override onlyAdmin {
require(_admin != address(0), "admin = zero address");
admin = _admin;
emit NewAdmin(_admin);
}
function _setDelay(uint _delay) private {
require(_delay >= MIN_DELAY, "delay < min");
require(_delay <= MAX_DELAY, "delay > max");
delay = _delay;
emit NewDelay(delay);
}
/*
@dev Only this contract can execute this function
*/
function setDelay(uint _delay) external override {
require(msg.sender == address(this), "!timelock");
_setDelay(_delay);
}
function _getTxHash(
address target,
uint value,
bytes memory data,
uint eta
) private pure returns (bytes32) {
return keccak256(abi.encode(target, value, data, eta));
}
function getTxHash(
address target,
uint value,
bytes calldata data,
uint eta
) external pure override returns (bytes32) {
return _getTxHash(target, value, data, eta);
}
/*
@notice Queue transaction
@param target Address of contract or account to call
@param value Ether value to send
@param data Data to send to `target`
@eta Execute Tx After. Time after which transaction can be executed.
*/
function queue(
address target,
uint value,
bytes calldata data,
uint eta
) external override onlyAdmin returns (bytes32) {
require(eta >= block.timestamp.add(delay), "eta < now + delay");
bytes32 txHash = _getTxHash(target, value, data, eta);
queued[txHash] = true;
emit Queue(txHash, target, value, data, eta);
return txHash;
}
function execute(
address target,
uint value,
bytes calldata data,
uint eta
) external payable override onlyAdmin returns (bytes memory) {
bytes32 txHash = _getTxHash(target, value, data, eta);
require(queued[txHash], "!queued");
require(block.timestamp >= eta, "eta < now");
require(block.timestamp <= eta.add(GRACE_PERIOD), "eta expired");
queued[txHash] = false;
// solium-disable-next-line security/no-call-value
(bool success, bytes memory returnData) = target.call{value: value}(data);
require(success, "tx failed");
emit Execute(txHash, target, value, data, eta);
return returnData;
}
function cancel(
address target,
uint value,
bytes calldata data,
uint eta
) external override onlyAdmin {
bytes32 txHash = _getTxHash(target, value, data, eta);
require(queued[txHash], "!queued");
queued[txHash] = false;
emit Cancel(txHash, target, value, data, eta);
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.6.11;
interface ITimeLock {
event NewAdmin(address admin);
event NewDelay(uint delay);
event Queue(
bytes32 indexed txHash,
address indexed target,
uint value,
bytes data,
uint eta
);
event Execute(
bytes32 indexed txHash,
address indexed target,
uint value,
bytes data,
uint eta
);
event Cancel(
bytes32 indexed txHash,
address indexed target,
uint value,
bytes data,
uint eta
);
function admin() external view returns (address);
function delay() external view returns (uint);
function queued(bytes32 _txHash) external view returns (bool);
function setAdmin(address _admin) external;
function setDelay(uint _delay) external;
receive() external payable;
function getTxHash(
address target,
uint value,
bytes calldata data,
uint eta
) external pure returns (bytes32);
function queue(
address target,
uint value,
bytes calldata data,
uint eta
) external returns (bytes32);
function execute(
address target,
uint value,
bytes calldata data,
uint eta
) external payable returns (bytes memory);
function cancel(
address target,
uint value,
bytes calldata data,
uint eta
) external;
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.6.11;
import "../protocol/IVault.sol";
/* solium-disable */
contract MockVault is IVault {
address public override admin;
address public override controller;
address public override token;
address public override strategy;
address public override timeLock;
uint public override reserveMin;
uint public override withdrawFee;
bool public override paused;
mapping(address => bool) public override strategies;
mapping(address => bool) public override whitelist;
// test helpers
uint public _setStrategyMin_;
bool public _investWasCalled_;
uint public _depositAmount_;
uint public _withdrawAmount_;
uint public _withdrawMin_;
constructor(
address _controller,
address _timeLock,
address _token
) public {
admin = msg.sender;
controller = _controller;
timeLock = _timeLock;
token = _token;
}
function setAdmin(address _admin) external override {}
function setController(address _controller) external override {}
function setTimeLock(address _timeLock) external override {}
function setPause(bool _paused) external override {}
function setWhitelist(address _addr, bool _approve) external override {}
function setReserveMin(uint _min) external override {}
function setWithdrawFee(uint _fee) external override {}
function approveStrategy(address _strategy) external override {}
function revokeStrategy(address _strategy) external override {}
function setStrategy(address _strategy, uint _min) external override {
strategy = _strategy;
_setStrategyMin_ = _min;
}
function balanceInVault() external view override returns (uint) {
return 0;
}
function balanceInStrategy() external view override returns (uint) {
return 0;
}
function totalDebtInStrategy() external view override returns (uint) {
return 0;
}
function totalAssets() external view override returns (uint) {
return 0;
}
function minReserve() external view override returns (uint) {
return 0;
}
function availableToInvest() external view override returns (uint) {
return 0;
}
function invest() external override {
_investWasCalled_ = true;
}
function deposit(uint _amount) external override {
_depositAmount_ = _amount;
}
function getExpectedReturn(uint) external view override returns (uint) {
return 0;
}
function withdraw(uint _shares, uint _min) external override {
_withdrawAmount_ = _shares;
_withdrawMin_ = _min;
}
function sweep(address _token) external override {}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.6.11;
import "../protocol/IVault.sol";
/* solium-disable */
contract MockTimeLock {
// test helpers
function _setTimeLock_(address _vault, address _timeLock) external {
IVault(_vault).setTimeLock(_timeLock);
}
function _approveStrategy_(address _vault, address _strategy) external {
IVault(_vault).approveStrategy(_strategy);
}
}
| TODO security: vulnerable to price manipulation getRatio() is multiplied by 10 ** 18 | function _totalAssets() internal view override returns (uint) {
uint pricePerShare = PickleJar(JAR).getRatio();
(uint shares, ) = MasterChef(CHEF).userInfo(POOL_ID, address(this));
return shares.mul(pricePerShare).div(precisionDiv) / 1e18;
}
| 13,453,068 | [
1,
6241,
4373,
30,
331,
19063,
429,
358,
6205,
27029,
4170,
4197,
1435,
353,
27789,
635,
1728,
225,
6549,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
389,
4963,
10726,
1435,
2713,
1476,
3849,
1135,
261,
11890,
13,
288,
203,
3639,
2254,
6205,
2173,
9535,
273,
23038,
298,
10813,
12,
46,
985,
2934,
588,
8541,
5621,
203,
3639,
261,
11890,
24123,
16,
262,
273,
13453,
39,
580,
74,
12,
5007,
42,
2934,
1355,
966,
12,
20339,
67,
734,
16,
1758,
12,
2211,
10019,
203,
203,
3639,
327,
24123,
18,
16411,
12,
8694,
2173,
9535,
2934,
2892,
12,
14548,
7244,
13,
342,
404,
73,
2643,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0xF9893786db9755187F7DD967C9DbF054C15185eA/sources/PoolHarborV2.sol | * @dev Library for managing types. Sets have the following properties: - Elements are added, removed, and checked for existence in constant time (O(1)). - Elements are enumerated in O(n). No guarantees are made on the ordering. ``` contract Example { using EnumerableSet for EnumerableSet.AddressSet; EnumerableSet.AddressSet private mySet; } ``` As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) and `uint256` (`UintSet`) are supported. [WARNING] ==== Trying to delete such a structure from storage will likely result in data corruption, rendering the structure unusable. In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an array of EnumerableSet. ====/ To implement this library for multiple types with as little code repetition as possible, we write it in terms of a generic Set type with bytes32 values. The Set implementation uses private functions, and user-facing implementations (such as AddressSet) are just wrappers around the underlying Set. This means that we can only create new EnumerableSets for types that fit in bytes32. | library EnumerableSetUpgradeable {
struct Set {
bytes32[] _values;
mapping(bytes32 => uint256) _indexes;
}
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
set._indexes[value] = set._values.length;
return true;
return false;
}
}
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
set._indexes[value] = set._values.length;
return true;
return false;
}
}
} else {
function _remove(Set storage set, bytes32 value) private returns (bool) {
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
if (lastIndex != toDeleteIndex) {
bytes32 lastValue = set._values[lastIndex];
set._values[toDeleteIndex] = lastValue;
}
return true;
return false;
}
}
function _remove(Set storage set, bytes32 value) private returns (bool) {
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
if (lastIndex != toDeleteIndex) {
bytes32 lastValue = set._values[lastIndex];
set._values[toDeleteIndex] = lastValue;
}
return true;
return false;
}
}
function _remove(Set storage set, bytes32 value) private returns (bool) {
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
if (lastIndex != toDeleteIndex) {
bytes32 lastValue = set._values[lastIndex];
set._values[toDeleteIndex] = lastValue;
}
return true;
return false;
}
}
set._values.pop();
delete set._indexes[value];
} else {
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
function _at(Set storage set, uint256 index) private view returns (bytes32) {
return set._values[index];
}
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
struct Bytes32Set {
Set _inner;
}
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
return _values(set._inner);
}
struct AddressSet {
Set _inner;
}
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
function values(AddressSet storage set) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
assembly {
result := store
}
return result;
}
function values(AddressSet storage set) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
assembly {
result := store
}
return result;
}
struct UintSet {
Set _inner;
}
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
function values(UintSet storage set) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
assembly {
result := store
}
return result;
}
function values(UintSet storage set) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
assembly {
result := store
}
return result;
}
}
| 2,797,682 | [
1,
9313,
364,
30632,
1953,
18,
11511,
1240,
326,
3751,
1790,
30,
300,
17219,
854,
3096,
16,
3723,
16,
471,
5950,
364,
15782,
316,
5381,
813,
261,
51,
12,
21,
13,
2934,
300,
17219,
854,
3557,
690,
316,
531,
12,
82,
2934,
2631,
28790,
854,
7165,
603,
326,
9543,
18,
31621,
6835,
5090,
288,
377,
1450,
6057,
25121,
694,
364,
6057,
25121,
694,
18,
1887,
694,
31,
377,
6057,
25121,
694,
18,
1887,
694,
3238,
3399,
694,
31,
289,
31621,
2970,
434,
331,
23,
18,
23,
18,
20,
16,
1678,
434,
618,
1375,
3890,
1578,
68,
21863,
2160,
1578,
694,
68,
3631,
1375,
2867,
68,
21863,
1887,
694,
24065,
471,
1375,
11890,
5034,
68,
21863,
5487,
694,
24065,
854,
3260,
18,
306,
9511,
65,
422,
631,
225,
6161,
310,
358,
1430,
4123,
279,
3695,
628,
2502,
903,
10374,
563,
316,
501,
1858,
21421,
16,
9782,
326,
3695,
640,
16665,
2
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | [
1,
12083,
6057,
25121,
694,
10784,
429,
288,
203,
203,
203,
203,
565,
1958,
1000,
288,
203,
3639,
1731,
1578,
8526,
389,
2372,
31,
203,
3639,
2874,
12,
3890,
1578,
516,
2254,
5034,
13,
389,
11265,
31,
203,
565,
289,
203,
203,
565,
445,
389,
1289,
12,
694,
2502,
444,
16,
1731,
1578,
460,
13,
3238,
1135,
261,
6430,
13,
288,
203,
3639,
309,
16051,
67,
12298,
12,
542,
16,
460,
3719,
288,
203,
5411,
444,
6315,
2372,
18,
6206,
12,
1132,
1769,
203,
5411,
444,
6315,
11265,
63,
1132,
65,
273,
444,
6315,
2372,
18,
2469,
31,
203,
5411,
327,
638,
31,
203,
5411,
327,
629,
31,
203,
3639,
289,
203,
565,
289,
203,
203,
565,
445,
389,
1289,
12,
694,
2502,
444,
16,
1731,
1578,
460,
13,
3238,
1135,
261,
6430,
13,
288,
203,
3639,
309,
16051,
67,
12298,
12,
542,
16,
460,
3719,
288,
203,
5411,
444,
6315,
2372,
18,
6206,
12,
1132,
1769,
203,
5411,
444,
6315,
11265,
63,
1132,
65,
273,
444,
6315,
2372,
18,
2469,
31,
203,
5411,
327,
638,
31,
203,
5411,
327,
629,
31,
203,
3639,
289,
203,
565,
289,
203,
203,
3639,
289,
469,
288,
203,
565,
445,
389,
4479,
12,
694,
2502,
444,
16,
1731,
1578,
460,
13,
3238,
1135,
261,
6430,
13,
288,
203,
3639,
2254,
5034,
460,
1016,
273,
444,
6315,
11265,
63,
1132,
15533,
203,
203,
3639,
309,
261,
1132,
1016,
480,
374,
13,
288,
203,
203,
5411,
2254,
5034,
358,
2613,
1016,
273,
460,
1016,
300,
404,
31,
203,
5411,
2254,
2
] |
pragma solidity ^0.4.18;
import 'soltsice/contracts/BotManageable.sol';
import 'zeppelin-solidity/contracts/math/SafeMath.sol';
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function transfer(address to, uint256 value) public returns (bool);
}
contract AuctionHub is BotManageable {
using SafeMath for uint256;
/*
* Data structures
*/
struct TokenBalance {
address token;
uint256 value;
}
struct TokenRate {
uint256 value;
uint256 decimals;
}
struct BidderState {
uint256 etherBalance;
uint256 tokensBalanceInEther;
uint256 managedBid;
TokenBalance[] tokenBalances;
}
struct ActionState {
uint256 endSeconds;
uint256 maxTokenBidInEther;
uint256 minPrice;
uint256 highestBid;
// next 5 fields should be packed into one 32-bytes slot
address highestBidder;
uint64 highestManagedBidder;
bool allowManagedBids;
bool cancelled;
bool finalized;
mapping(address => BidderState) bidderStates;
bytes32 item;
}
/*
* Storage
*/
mapping(address => ActionState) public auctionStates;
mapping(address => TokenRate) public tokenRates;
/*
* Events
*/
event NewAction(address indexed auction, string item);
event Bid(address indexed auction, address bidder, uint256 totalBidInEther, uint256 indexed tokensBidInEther);
event TokenBid(address indexed auction, address bidder, address token, uint256 numberOfTokens);
event ManagedBid(address indexed auction, uint64 bidder, uint256 bid, address knownManagedBidder);
event NewHighestBidder(address indexed auction, address bidder, uint64 managedBidder, uint256 totalBid);
event TokenRateUpdate(address indexed token, uint256 rate);
event Withdrawal(address indexed auction, address bidder, uint256 etherAmount, uint256 tokensBidInEther);
event Charity(address indexed auction, address bidder, uint256 etherAmount, uint256 tokensAmount);
event Finalized(address indexed auction, address highestBidder, uint64 highestManagedBidder, uint256 amount);
event FinalizedTokenTransfer(address indexed auction, address token, uint256 tokensBidInEther);
event FinalizedEtherTransfer(address indexed auction, uint256 etherAmount);
event ExtendedEndTime(address indexed auction, uint256 newEndtime);
event Cancelled(address indexed auction);
/*
* Modifiers
*/
modifier onlyActive {
// NB this modifier also serves as check that an auction exists (otherwise endSeconds == 0)
ActionState storage auctionState = auctionStates[msg.sender];
require (now < auctionState.endSeconds && !auctionState.cancelled);
_;
}
modifier onlyBeforeEnd {
// NB this modifier also serves as check that an auction exists (otherwise endSeconds == 0)
ActionState storage auctionState = auctionStates[msg.sender];
require (now < auctionState.endSeconds);
_;
}
modifier onlyAfterEnd {
ActionState storage auctionState = auctionStates[msg.sender];
require (now > auctionState.endSeconds && auctionState.endSeconds > 0);
_;
}
modifier onlyNotCancelled {
ActionState storage auctionState = auctionStates[msg.sender];
require (!auctionState.cancelled);
_;
}
modifier onlyAllowedManagedBids {
ActionState storage auctionState = auctionStates[msg.sender];
require (auctionState.allowManagedBids);
_;
}
/*
* _rates are per big token (e.g. Ether vs. wei), i.e. number of wei per [number of tokens]*[10 ** decimals]
*/
function AuctionHub
(address _wallet, address[] _tokens, uint256[] _rates, uint256[] _decimals)
public
BotManageable(_wallet)
{
// make sender a bot to avoid an additional step
botsStartEndTime[msg.sender] = uint128(now) << 64;
require(_tokens.length == _rates.length);
require(_tokens.length == _decimals.length);
// save initial token list
for (uint i = 0; i < _tokens.length; i++) {
require(_tokens[i] != 0x0);
require(_rates[i] > 0);
ERC20Basic token = ERC20Basic(_tokens[i]);
tokenRates[token] = TokenRate(_rates[i], _decimals[i]);
TokenRateUpdate(token, _rates[i]);
}
}
function stringToBytes32(string memory source) returns (bytes32 result) {
bytes memory tempEmptyStringTest = bytes(source);
if (tempEmptyStringTest.length == 0) {
return 0x0;
}
assembly {
result := mload(add(source, 32))
}
}
function createAuction(
uint _endSeconds,
uint256 _maxTokenBidInEther,
uint256 _minPrice,
string _item,
bool _allowManagedBids
)
onlyBot
public
returns (address)
{
require (_endSeconds > now);
require(_maxTokenBidInEther <= 1000 ether);
require(_minPrice > 0);
Auction auction = new Auction(this);
ActionState storage auctionState = auctionStates[auction];
auctionState.endSeconds = _endSeconds;
auctionState.maxTokenBidInEther = _maxTokenBidInEther;
auctionState.minPrice = _minPrice;
auctionState.allowManagedBids = _allowManagedBids;
string memory item = _item;
auctionState.item = stringToBytes32(item);
NewAction(auction, _item);
return address(auction);
}
function ()
payable
public
{
throw;
// It's charity!
// require(wallet.send(msg.value));
// Charity(0x0, msg.sender, msg.value, 0);
}
function bid(address _bidder, uint256 _value, address _token, uint256 _tokensNumber)
// onlyActive - inline check to reuse auctionState variable
public
returns (bool isHighest)
{
ActionState storage auctionState = auctionStates[msg.sender];
// same as onlyActive modifier, but we already have a variable here
require (now < auctionState.endSeconds && !auctionState.cancelled);
BidderState storage bidderState = auctionState.bidderStates[_bidder];
uint256 totalBid;
if (_tokensNumber > 0) {
totalBid = tokenBid(msg.sender, _bidder, _token, _tokensNumber);
}else {
require(_value > 0);
// NB if current token bid == 0 we still could have previous token bids
totalBid = bidderState.tokensBalanceInEther;
}
uint256 etherBid = bidderState.etherBalance + _value;
bidderState.etherBalance = etherBid;
totalBid = totalBid + etherBid + bidderState.managedBid;
if (totalBid > auctionState.highestBid && totalBid >= auctionState.minPrice) {
auctionState.highestBid = totalBid;
auctionState.highestBidder = _bidder;
auctionState.highestManagedBidder = 0;
NewHighestBidder(msg.sender, _bidder, 0, totalBid);
if ((auctionState.endSeconds - now) < 1800) {
uint256 newEnd = now + 1800;
auctionState.endSeconds = newEnd;
ExtendedEndTime(msg.sender, newEnd);
}
isHighest = true;
}
Bid(msg.sender, _bidder, totalBid, totalBid - etherBid);
return isHighest;
}
function tokenBid(address _auction, address _bidder, address _token, uint256 _tokensNumber)
internal
returns (uint256 tokenBid)
{
// NB actual token transfer happens in auction contracts, which owns both ether and tokens
// This Hub contract is for accounting
ActionState storage auctionState = auctionStates[_auction];
BidderState storage bidderState = auctionState.bidderStates[_bidder];
uint256 totalBid = bidderState.tokensBalanceInEther;
TokenRate storage tokenRate = tokenRates[_token];
require(tokenRate.value > 0);
// find token index
uint256 index = bidderState.tokenBalances.length;
for (uint i = 0; i < index; i++) {
if (bidderState.tokenBalances[i].token == _token) {
index = i;
break;
}
}
// array was empty/token not found - push empty to the end
if (index == bidderState.tokenBalances.length) {
bidderState.tokenBalances.push(TokenBalance(_token, _tokensNumber));
} else {
// safe math is already in transferFrom
bidderState.tokenBalances[index].value += _tokensNumber;
}
// tokenRate.value is for a whole/big token (e.g. ether vs. wei) but _tokensNumber is in small/wei tokens, need to divide by decimals
totalBid = totalBid + _tokensNumber.mul(tokenRate.value).div(10 ** tokenRate.decimals);
require(totalBid <= auctionState.maxTokenBidInEther);
bidderState.tokensBalanceInEther = totalBid;
TokenBid(_auction, _bidder, _token, _tokensNumber);
return totalBid;
}
function managedBid(uint64 _managedBidder, uint256 _managedBid, address _knownManagedBidder)
// onlyActive - inline check to reuse auctionState variable
// onlyAllowedManagedBids - inline check to reuse auctionState variable
// onlyBot - done in Auction that is msg.sender, only bot could create auctions and set endSeconds to non-zero
public
returns (bool isHighest)
{
require(_managedBidder != 0);
ActionState storage auctionState = auctionStates[msg.sender];
// same as onlyActive+onlyAllowedManagedBids modifiers, but we already have a variable here
require (now < auctionState.endSeconds && !auctionState.cancelled && auctionState.allowManagedBids);
// sum with direct bid if any
uint256 directBid = 0;
if (_knownManagedBidder != 0x0) {
BidderState storage bidderState = auctionState.bidderStates[_knownManagedBidder];
require(_managedBid > bidderState.managedBid);
bidderState.managedBid = _managedBid;
directBid = bidderState.tokensBalanceInEther + bidderState.etherBalance;
}
// NB: _managedBid is the total amount of all bids from backend
// calculated without any direct bid. It is important to calculate direct bids
// inside this transaction and make the _knownManagedBidder the highest
// to prevent this wallet to withdraw money and remain the highest
uint256 totalBid = directBid + _managedBid;
if (totalBid > auctionState.highestBid && totalBid >= auctionState.minPrice) {
auctionState.highestBid = totalBid;
auctionState.highestBidder = _knownManagedBidder;
auctionState.highestManagedBidder = _managedBidder;
NewHighestBidder(msg.sender, _knownManagedBidder, _managedBidder, totalBid);
if ((auctionState.endSeconds - now) < 1800) {
uint256 newEnd = now + 1800;
auctionState.endSeconds = newEnd;
ExtendedEndTime(msg.sender, newEnd);
}
isHighest = true;
}
// event ManagedBid(address indexed auction, uint64 bidder, uint256 bid, address knownManagedBidder);
ManagedBid(msg.sender, _managedBidder, _managedBid, _knownManagedBidder);
return isHighest;
}
function totalDirectBid(address _auction, address _bidder)
view
public
returns (uint256 _totalBid)
{
ActionState storage auctionState = auctionStates[_auction];
BidderState storage bidderState = auctionState.bidderStates[_bidder];
return bidderState.tokensBalanceInEther + bidderState.etherBalance;
}
function setTokenRate(address _token, uint256 _tokenRate)
onlyBot
public
{
TokenRate storage tokenRate = tokenRates[_token];
require(tokenRate.value > 0);
tokenRate.value = _tokenRate;
TokenRateUpdate(_token, _tokenRate);
}
function withdraw(address _bidder)
public
returns (bool success)
{
ActionState storage auctionState = auctionStates[msg.sender];
BidderState storage bidderState = auctionState.bidderStates[_bidder];
bool sent;
// anyone could withdraw at any time except the highest bidder
// if cancelled, the highest bidder could withdraw as well
require((_bidder != auctionState.highestBidder) || auctionState.cancelled);
uint256 tokensBalanceInEther = bidderState.tokensBalanceInEther;
if (bidderState.tokenBalances.length > 0) {
for (uint i = 0; i < bidderState.tokenBalances.length; i++) {
uint256 tokenBidValue = bidderState.tokenBalances[i].value;
if (tokenBidValue > 0) {
bidderState.tokenBalances[i].value = 0;
sent = Auction(msg.sender).sendTokens(bidderState.tokenBalances[i].token, _bidder, tokenBidValue);
require(sent);
}
}
bidderState.tokensBalanceInEther = 0;
} else {
require(tokensBalanceInEther == 0);
}
uint256 etherBid = bidderState.etherBalance;
if (etherBid > 0) {
bidderState.etherBalance = 0;
sent = Auction(msg.sender).sendEther(_bidder, etherBid);
require(sent);
}
Withdrawal(msg.sender, _bidder, etherBid, tokensBalanceInEther);
return true;
}
function finalize()
// onlyNotCancelled - inline check to reuse auctionState variable
// onlyAfterEnd - inline check to reuse auctionState variable
public
returns (bool)
{
ActionState storage auctionState = auctionStates[msg.sender];
// same as onlyNotCancelled+onlyAfterEnd modifiers, but we already have a variable here
require (!auctionState.finalized && now > auctionState.endSeconds && auctionState.endSeconds > 0 && !auctionState.cancelled);
if (auctionState.highestBidder != address(0)) {
bool sent;
BidderState storage bidderState = auctionState.bidderStates[auctionState.highestBidder];
uint256 tokensBalanceInEther = bidderState.tokensBalanceInEther;
if (bidderState.tokenBalances.length > 0) {
for (uint i = 0; i < bidderState.tokenBalances.length; i++) {
uint256 tokenBid = bidderState.tokenBalances[i].value;
if (tokenBid > 0) {
bidderState.tokenBalances[i].value = 0;
sent = Auction(msg.sender).sendTokens(bidderState.tokenBalances[i].token, wallet, tokenBid);
require(sent);
FinalizedTokenTransfer(msg.sender, bidderState.tokenBalances[i].token, tokenBid);
}
}
bidderState.tokensBalanceInEther = 0;
} else {
require(tokensBalanceInEther == 0);
}
uint256 etherBid = bidderState.etherBalance;
if (etherBid > 0) {
bidderState.etherBalance = 0;
sent = Auction(msg.sender).sendEther(wallet, etherBid);
require(sent);
FinalizedEtherTransfer(msg.sender, etherBid);
}
}
auctionState.finalized = true;
Finalized(msg.sender, auctionState.highestBidder, auctionState.highestManagedBidder, auctionState.highestBid);
return true;
}
function cancel()
// onlyActive - inline check to reuse auctionState variable
public
returns (bool success)
{
ActionState storage auctionState = auctionStates[msg.sender];
// same as onlyActive modifier, but we already have a variable here
require (now < auctionState.endSeconds && !auctionState.cancelled);
auctionState.cancelled = true;
Cancelled(msg.sender);
return true;
}
}
contract Auction {
AuctionHub public owner;
modifier onlyOwner {
require(owner == msg.sender);
_;
}
modifier onlyBot {
require(owner.isBot(msg.sender));
_;
}
modifier onlyNotBot {
require(!owner.isBot(msg.sender));
_;
}
function Auction(
address _owner
)
public
{
require(_owner != address(0x0));
owner = AuctionHub(_owner);
}
function ()
payable
public
{
owner.bid(msg.sender, msg.value, 0x0, 0);
}
function bid(address _token, uint256 _tokensNumber)
payable
public
returns (bool isHighest)
{
if (_token != 0x0 && _tokensNumber > 0) {
require(ERC20Basic(_token).transferFrom(msg.sender, this, _tokensNumber));
}
return owner.bid(msg.sender, msg.value, _token, _tokensNumber);
}
function managedBid(uint64 _managedBidder, uint256 _managedBid)
onlyBot
public
returns (bool isHighest)
{
return owner.managedBid(_managedBidder, _managedBid, 0x0);
}
function managedBid2(uint64 _managedBidder, uint256 _managedBid, address _knownManagedBidder)
onlyBot
public
returns (bool isHighest)
{
return owner.managedBid(_managedBidder, _managedBid, _knownManagedBidder);
}
function sendTokens(address _token, address _to, uint256 _amount)
onlyOwner
public
returns (bool)
{
return ERC20Basic(_token).transfer(_to, _amount);
}
function sendEther(address _to, uint256 _amount)
onlyOwner
public
returns (bool)
{
return _to.send(_amount);
}
function withdraw()
public
returns (bool success)
{
return owner.withdraw(msg.sender);
}
function finalize()
onlyBot
public
returns (bool)
{
return owner.finalize();
}
function cancel()
onlyBot
public
returns (bool success)
{
return owner.cancel();
}
function totalDirectBid(address _bidder)
public
view
returns (uint256)
{
return owner.totalDirectBid(this, _bidder);
}
function maxTokenBidInEther()
public
view
returns (uint256)
{
var (,maxTokenBidInEther,,,,,,,,) = owner.auctionStates(this);
return maxTokenBidInEther;
}
function endSeconds()
public
view
returns (uint256)
{
var (endSeconds,,,,,,,,,) = owner.auctionStates(this);
return endSeconds;
}
function item()
public
view
returns (string)
{
var (,,,,,,,,,item) = owner.auctionStates(this);
bytes memory bytesArray = new bytes(32);
for (uint256 i; i < 32; i++) {
bytesArray[i] = item[i];
}
return string(bytesArray);
}
function minPrice()
public
view
returns (uint256)
{
var (,,minPrice,,,,,,,) = owner.auctionStates(this);
return minPrice;
}
function cancelled()
public
view
returns (bool)
{
var (,,,,,,cancelled,,,) = owner.auctionStates(this);
return cancelled;
}
function finalized()
public
view
returns (bool)
{
var (,,,,,,,finalized,,) = owner.auctionStates(this);
return finalized;
}
function highestBid()
public
view
returns (uint256)
{
var (,,,highestBid,,,,,,) = owner.auctionStates(this);
return highestBid;
}
function highestBidder()
public
view
returns (address)
{
var (,,,,highestBidder,,,,,) = owner.auctionStates(this);
return highestBidder;
}
function highestManagedBidder()
public
view
returns (uint64)
{
var (,,,,,highestManagedBidder,,,,) = owner.auctionStates(this);
return highestManagedBidder;
}
function allowManagedBids()
public
view
returns (bool)
{
var (,,,,,,allowManagedBids,,,) = owner.auctionStates(this);
return allowManagedBids;
}
// mapping(address => uint256) public etherBalances;
// mapping(address => uint256) public tokenBalances;
// mapping(address => uint256) public tokenBalancesInEther;
// mapping(address => uint256) public managedBids;
// bool allowManagedBids;
}
| It's charity! require(wallet.send(msg.value)); Charity(0x0, msg.sender, msg.value, 0); | function ()
payable
public
{
throw;
}
| 5,398,485 | [
1,
7193,
1807,
1149,
560,
5,
2583,
12,
19177,
18,
4661,
12,
3576,
18,
1132,
10019,
3703,
560,
12,
20,
92,
20,
16,
1234,
18,
15330,
16,
1234,
18,
1132,
16,
374,
1769,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
1832,
7010,
3639,
8843,
429,
203,
3639,
1071,
203,
565,
288,
203,
3639,
604,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/5/0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45/sources/contracts/V3SwapRouter.sol | @inheritdoc IUniswapV3SwapCallback either initiate the next swap or pay note that because exact output swaps are executed in reverse order, tokenOut is actually tokenIn | function uniswapV3SwapCallback(
int256 amount0Delta,
int256 amount1Delta,
bytes calldata _data
) external override {
SwapCallbackData memory data = abi.decode(_data, (SwapCallbackData));
(address tokenIn, address tokenOut, uint24 fee) = data.path.decodeFirstPool();
CallbackValidation.verifyCallback(factory, tokenIn, tokenOut, fee);
(bool isExactInput, uint256 amountToPay) =
amount0Delta > 0
? (tokenIn < tokenOut, uint256(amount0Delta))
: (tokenOut < tokenIn, uint256(amount1Delta));
if (isExactInput) {
pay(tokenIn, data.payer, msg.sender, amountToPay);
if (data.path.hasMultiplePools()) {
data.path = data.path.skipToken();
exactOutputInternal(amountToPay, msg.sender, 0, data);
amountInCached = amountToPay;
pay(tokenOut, data.payer, msg.sender, amountToPay);
}
}
}
| 1,926,404 | [
1,
36,
10093,
467,
984,
291,
91,
438,
58,
23,
12521,
2428,
3344,
18711,
326,
1024,
7720,
578,
8843,
4721,
716,
2724,
5565,
876,
1352,
6679,
854,
7120,
316,
4219,
1353,
16,
1147,
1182,
353,
6013,
1147,
382,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
640,
291,
91,
438,
58,
23,
12521,
2428,
12,
203,
3639,
509,
5034,
3844,
20,
9242,
16,
203,
3639,
509,
5034,
3844,
21,
9242,
16,
203,
3639,
1731,
745,
892,
389,
892,
203,
565,
262,
3903,
3849,
288,
203,
3639,
12738,
2428,
751,
3778,
501,
273,
24126,
18,
3922,
24899,
892,
16,
261,
12521,
2428,
751,
10019,
203,
3639,
261,
2867,
1147,
382,
16,
1758,
1147,
1182,
16,
2254,
3247,
14036,
13,
273,
501,
18,
803,
18,
3922,
3759,
2864,
5621,
203,
3639,
8444,
4354,
18,
8705,
2428,
12,
6848,
16,
1147,
382,
16,
1147,
1182,
16,
14036,
1769,
203,
203,
3639,
261,
6430,
353,
14332,
1210,
16,
2254,
5034,
3844,
774,
9148,
13,
273,
203,
5411,
3844,
20,
9242,
405,
374,
203,
7734,
692,
261,
2316,
382,
411,
1147,
1182,
16,
2254,
5034,
12,
8949,
20,
9242,
3719,
203,
7734,
294,
261,
2316,
1182,
411,
1147,
382,
16,
2254,
5034,
12,
8949,
21,
9242,
10019,
203,
203,
3639,
309,
261,
291,
14332,
1210,
13,
288,
203,
5411,
8843,
12,
2316,
382,
16,
501,
18,
84,
1773,
16,
1234,
18,
15330,
16,
3844,
774,
9148,
1769,
203,
5411,
309,
261,
892,
18,
803,
18,
5332,
8438,
16639,
10756,
288,
203,
7734,
501,
18,
803,
273,
501,
18,
803,
18,
7457,
1345,
5621,
203,
7734,
5565,
1447,
3061,
12,
8949,
774,
9148,
16,
1234,
18,
15330,
16,
374,
16,
501,
1769,
203,
7734,
3844,
382,
9839,
273,
3844,
774,
9148,
31,
203,
7734,
8843,
12,
2316,
1182,
16,
501,
18,
84,
1773,
16,
2
] |
// SPDX-License-Identifier: MIT
// File: contracts/libraries/base64.sol
pragma solidity ^0.8.0;
/// @title Base64
/// @author Brecht Devos - <[email protected]>
/// @notice Provides a function for encoding some bytes in base64
library Base64 {
string internal constant TABLE = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
function encode(bytes memory data) internal pure returns (string memory) {
if (data.length == 0) return '';
// load the table into memory
string memory table = TABLE;
// multiply by 4/3 rounded up
uint256 encodedLen = 4 * ((data.length + 2) / 3);
// add some extra buffer at the end required for the writing
string memory result = new string(encodedLen + 32);
assembly {
// set the actual output length
mstore(result, encodedLen)
// prepare the lookup table
let tablePtr := add(table, 1)
// input ptr
let dataPtr := data
let endPtr := add(dataPtr, mload(data))
// result ptr, jump over length
let resultPtr := add(result, 32)
// run over the input, 3 bytes at a time
for {} lt(dataPtr, endPtr) {}
{
dataPtr := add(dataPtr, 3)
// read 3 bytes
let input := mload(dataPtr)
// write 4 characters
mstore(resultPtr, shl(248, mload(add(tablePtr, and(shr(18, input), 0x3F)))))
resultPtr := add(resultPtr, 1)
mstore(resultPtr, shl(248, mload(add(tablePtr, and(shr(12, input), 0x3F)))))
resultPtr := add(resultPtr, 1)
mstore(resultPtr, shl(248, mload(add(tablePtr, and(shr( 6, input), 0x3F)))))
resultPtr := add(resultPtr, 1)
mstore(resultPtr, shl(248, mload(add(tablePtr, and( input, 0x3F)))))
resultPtr := add(resultPtr, 1)
}
// padding with '='
switch mod(mload(data), 3)
case 1 { mstore(sub(resultPtr, 2), shl(240, 0x3d3d)) }
case 2 { mstore(sub(resultPtr, 1), shl(248, 0x3d)) }
}
return result;
}
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: contracts/interfaces/IFeeCollectable.sol
pragma solidity ^0.8.0;
interface IFeeCollectable {
/// @notice emitted when set new fee to address.
event FeeToChangedEvt(address newFeeTo);
/// @notice emitted when fee is paid to fee to address.
event FeeWithdrawedEvt(address feeTo, uint amount);
/// @notice set fee to address.
function setFeeTo(address _feeTo) external;
/// @notice transfer all fee to address feeTo.
function refund() external;
}
// File: @openzeppelin/contracts/utils/math/SafeCast.sol
pragma solidity ^0.8.0;
/**
* @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*
* Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
* all math on `uint256` and `int256` and then downcasting.
*/
library SafeCast {
/**
* @dev Returns the downcasted uint224 from uint256, reverting on
* overflow (when the input is greater than largest uint224).
*
* Counterpart to Solidity's `uint224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toUint224(uint256 value) internal pure returns (uint224) {
require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits");
return uint224(value);
}
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits");
return uint128(value);
}
/**
* @dev Returns the downcasted uint96 from uint256, reverting on
* overflow (when the input is greater than largest uint96).
*
* Counterpart to Solidity's `uint96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toUint96(uint256 value) internal pure returns (uint96) {
require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits");
return uint96(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits");
return uint64(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits");
return uint32(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits");
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*/
function toUint8(uint256 value) internal pure returns (uint8) {
require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits");
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
require(value >= 0, "SafeCast: value must be positive");
return uint256(value);
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*
* _Available since v3.1._
*/
function toInt128(int256 value) internal pure returns (int128) {
require(value >= type(int128).min && value <= type(int128).max, "SafeCast: value doesn't fit in 128 bits");
return int128(value);
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*
* _Available since v3.1._
*/
function toInt64(int256 value) internal pure returns (int64) {
require(value >= type(int64).min && value <= type(int64).max, "SafeCast: value doesn't fit in 64 bits");
return int64(value);
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*
* _Available since v3.1._
*/
function toInt32(int256 value) internal pure returns (int32) {
require(value >= type(int32).min && value <= type(int32).max, "SafeCast: value doesn't fit in 32 bits");
return int32(value);
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*
* _Available since v3.1._
*/
function toInt16(int256 value) internal pure returns (int16) {
require(value >= type(int16).min && value <= type(int16).max, "SafeCast: value doesn't fit in 16 bits");
return int16(value);
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*
* _Available since v3.1._
*/
function toInt8(int256 value) internal pure returns (int8) {
require(value >= type(int8).min && value <= type(int8).max, "SafeCast: value doesn't fit in 8 bits");
return int8(value);
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
// Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256");
return int256(value);
}
}
// File: @openzeppelin/contracts/utils/math/SafeMath.sol
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// File: @openzeppelin/contracts/utils/Strings.sol
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// File: @openzeppelin/contracts/utils/Context.sol
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// File: @openzeppelin/contracts/utils/introspection/IERC165.sol
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File: @openzeppelin/contracts/utils/introspection/ERC165.sol
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721.sol
pragma solidity ^0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File: contracts/libraries/TransferHelper.sol
pragma solidity >=0.6.0;
library TransferHelper {
/// @notice Transfers tokens from the targeted address to the given destination
/// @notice Errors with 'STF' if transfer fails
/// @param token The contract address of the token to be transferred
/// @param from The originating address from which the tokens will be transferred
/// @param to The destination address of the transfer
/// @param value The amount to be transferred
function safeTransferFrom(
address token,
address from,
address to,
uint256 value
) internal {
(bool success, bytes memory data) =
token.call(abi.encodeWithSelector(IERC20.transferFrom.selector, from, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'STF');
}
/// @notice Transfers NFT from the targeted address to the given destination
/// @notice Errors with 'STF' if transfer fails
/// @param token The contract address of the token to be transferred
/// @param from The originating address from which the tokens will be transferred
/// @param to The destination address of the transfer
/// @param tokenId the id of the token need to be transfered
function safeTransferNFTFrom(
address token,
address from,
address to,
uint256 tokenId
) internal {
(bool success, bytes memory data) =
token.call(abi.encodeWithSelector(IERC721.transferFrom.selector, from, to, tokenId));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'STF');
}
/// @notice Transfers tokens from msg.sender to a recipient
/// @dev Errors with ST if transfer fails
/// @param token The contract address of the token which will be transferred
/// @param to The recipient of the transfer
/// @param value The value of the transfer
function safeTransfer(
address token,
address to,
uint256 value
) internal {
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.transfer.selector, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'ST');
}
/// @notice Approves the stipulated contract to spend the given allowance in the given token
/// @dev Errors with 'SA' if transfer fails
/// @param token The contract address of the token to be approved
/// @param to The target of the approval
/// @param value The amount of the given token the target will be allowed to spend
function safeApprove(
address token,
address to,
uint256 value
) internal {
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.approve.selector, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'SA');
}
/// @notice Transfers ETH to the recipient address
/// @dev Fails with `STE`
/// @param to The destination of the transfer
/// @param value The value to be transferred
function safeTransferETH(address to, uint256 value) internal {
(bool success, ) = to.call{value: value}(new bytes(0));
require(success, 'STE');
}
}
// File: contracts/FeeCollectable.sol
pragma solidity ^0.8.0;
contract FeeCollectable is Ownable, IFeeCollectable{
address public feeTo;
/// @inheritdoc IFeeCollectable
function setFeeTo(address _feeTo) onlyOwner external override{
feeTo = _feeTo;
emit FeeToChangedEvt(_feeTo);
}
/// @inheritdoc IFeeCollectable
function refund() external override{
uint amount = address(this).balance;
TransferHelper.safeTransferETH(feeTo, amount);
emit FeeWithdrawedEvt(feeTo, amount);
}
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File: contracts/interfaces/IHistoryERC721.sol
pragma solidity ^0.8.0;
interface IHistoryERC721 is IERC721, IERC721Metadata {
//////////////////////////////////////////////////////////////////////////
// View Functions
//////////////////////////////////////////////////////////////////////////
/// @notice get config of this contract.
function getConfig() external view returns(
uint256 _contractId,
uint256 _mintFee,
uint256 _mintStartTime,
uint256 _mintEndTime,
address _feeTo
);
/// @notice get amount of events in this contract.
function eventNum() external view returns(uint);
function eventContentHash(uint eventId) external view returns(string memory contentHash);
/// @notice Get event data
function eventData(uint eventId) external view returns(
uint totalMintFee,
string memory name,
string memory contentHash,
string memory contentDomain,
uint firstMintTime
);
/// @notice get event id of specified token.
function tokenEventId(uint tokenId) external view returns(uint tkEvtId);
// @notice return the allowed domain with specified id.
function allowedDomain(uint id) external view returns(string memory domain);
//////////////////////////////////////////////////////////////////////////
// Manage Functions
//////////////////////////////////////////////////////////////////////////
/// @notice set config of this contract.
function setConfig(uint256 mint_, uint256 startTime_, uint256 endTime_) external;
/// @notice put a new domain into use.
function addAllowedDomain(string memory domain) external returns(bool res);
//////////////////////////////////////////////////////////////////////////
// User Functions
//////////////////////////////////////////////////////////////////////////
/// @notice mint a new history.
function mintNewHistoryReport(
uint domainId,
bool usingSSL,
string memory _name,
string memory _contentHash
) external payable returns(uint tokenId);
/// @notice follow a history report
function followHistoryEvent(uint eventId) external payable returns(uint tokenId);
}
// File: @openzeppelin/contracts/token/ERC721/ERC721.sol
pragma solidity ^0.8.0;
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// File: @openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol
pragma solidity ^0.8.0;
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// File: contracts/HistoryERC721.sol
pragma solidity ^0.8.0;
contract HistoryERC721 is ERC721Enumerable, FeeCollectable, IHistoryERC721{
using Strings for uint256;
using SafeMath for uint256;
using SafeCast for uint256;
//////////////////////////////////////////////////////////////////////////
// Global data
//////////////////////////////////////////////////////////////////////////
/// @notice used to separate nft from different chain and contract version.
uint32 private contractID;
// @notice fee cost when mint nft.
uint256 private mintFee;
/// @notice Follow is allowed in [ mintTime + mintStartTime, mintTime + mintEndTime ]
uint256 private mintEndTime;
uint256 private mintStartTime;
/// @notice domain allowed to use.
/// Domain Id => domain in bytes.
mapping(uint => string) public override allowedDomain;
uint256 private allowedDomainNum;
//////////////////////////////////////////////////////////////////////////
// Event and token data
//////////////////////////////////////////////////////////////////////////
/// @inheritdoc IHistoryERC721
uint public override eventNum;
mapping(uint => bytes32) private eventContentDomain;
struct EventMeta{
bool sslOn;
uint32 firstMintTime;
uint128 totalMintFee;
uint32 domainId;
uint32 mintNum;
}
mapping(uint => EventMeta) private eventMeta;
/// @notice Hash of event content.
mapping(uint => string) public override eventContentHash;
// fee used to mint nft in an event.
mapping(uint => uint) private eventAssets;
// name of an event.
mapping(uint => string) private eventName;
//////////////////////////////////////////////////////////////////////////
// Functions
//////////////////////////////////////////////////////////////////////////
/// Constructor function
/// @param contractId_ should be smaller than uint32(-1)
constructor(string memory name_, string memory symbol_, uint contractId_) ERC721(name_,symbol_){
require(contractId_ < 0xFFFFFFFF);
contractID = contractId_.toUint32();
feeTo = _msgSender();
// default start time is 10 min.
mintStartTime = 10 * 60;
// default end time is 60 min.
mintEndTime = 30 * 60;
// default mint fee is 0.01 ETH
mintFee = 0.01 * 1e18;
}
/// @inheritdoc IERC165
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721Enumerable) returns (bool) {
return interfaceId == type(IHistoryERC721).interfaceId || super.supportsInterface(interfaceId);
}
/// @inheritdoc IHistoryERC721
function eventData(uint eventId) external view override returns(
uint totalMintFee,
string memory _name,
string memory contentHash,
string memory contentDomain,
uint firstMintTime
){
EventMeta memory meta = eventMeta[eventId];
totalMintFee = meta.totalMintFee;
_name = eventName[eventId];
contentDomain = allowedDomain[meta.domainId];
contentHash = eventContentHash[eventId];
firstMintTime = meta.firstMintTime;
}
/// @inheritdoc IERC721Metadata
function tokenURI(uint256 tokenId) public view override(IERC721Metadata, ERC721) returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
(uint evtId, uint reportId) = _tokenIdSplit(tokenId);
EventMeta memory meta = eventMeta[evtId];
string memory contentDomain = allowedDomain[meta.domainId];
string memory head = meta.sslOn ? "https://" : "http://";
string memory contentUrl = string(abi.encodePacked(head, contentDomain, eventContentHash[evtId]));
string memory name = string(abi.encodePacked(eventName[evtId]," #",reportId.toString()));
string memory description = string(abi.encodePacked(
"History V1 NFT of event ",
evtId.toString(),
" : ",
eventName[evtId],
", report id is ",
reportId.toString(),
"."
));
return
string(
abi.encodePacked(
'data:application/json;base64,',
Base64.encode(
bytes(
abi.encodePacked(
'{"name":"',
name,
'", "description":"',
description,
'", "content": "',
contentUrl,
'"}'
)
)
)
)
);
}
/// @inheritdoc IHistoryERC721
function getConfig() external override view returns(
uint256 _contractId,
uint256 _mintFee,
uint256 _mintStartTime,
uint256 _mintEndTime,
address _feeTo)
{
return (contractID, mintFee, mintStartTime, mintEndTime, feeTo);
}
/// @inheritdoc IHistoryERC721
function setConfig(uint256 mint_, uint256 startTime_, uint256 endTime_) external override onlyOwner{
mintFee = mint_;
mintStartTime = startTime_;
mintEndTime = endTime_;
}
/// @inheritdoc IHistoryERC721
function addAllowedDomain(string memory domain) external override onlyOwner returns(bool res){
allowedDomain[allowedDomainNum] = domain;
allowedDomainNum = allowedDomainNum.add(1);
return true;
}
/// @inheritdoc IHistoryERC721
function mintNewHistoryReport(
uint domainId,
bool usingSSL,
string memory _name,
string memory _contentHash
) external payable override returns(uint tokenId){
require(domainId < allowedDomainNum,"Invalid domain id.");
require(msg.value >= mintFee, "Not enough fee.");
uint reportId = 0;
uint eventId;
// New event.
eventId = eventNum.add(1);
eventNum = eventId;
EventMeta storage meta = eventMeta[eventId];
(meta.totalMintFee, meta.mintNum, meta.sslOn, meta.domainId, meta.firstMintTime) = (
msg.value.toUint128(),
1,
usingSSL,
domainId.toUint32(),
uint32(block.timestamp)
);
eventName[eventId] = _name;
eventContentHash[eventId] = _contentHash;
// Mint Coin
tokenId = _genTokenID(eventId, reportId);
_safeMint(_msgSender(), tokenId);
}
/// @inheritdoc IHistoryERC721
function followHistoryEvent(
uint eventId
)external payable override returns(uint tokenId){
require(msg.value >= mintFee, "Not enough fee.");
require(eventId <= eventNum, "Invalid event.");
EventMeta storage meta = eventMeta[eventId];
EventMeta memory _meta = meta;
require(_meta.firstMintTime + mintEndTime >= block.timestamp, "mint too late.");
require(_meta.firstMintTime + mintStartTime <= block.timestamp, "mint too early");
uint reportId = uint(meta.mintNum).add(1);
(meta.totalMintFee, meta.mintNum) = (
msg.value.add(_meta.totalMintFee).toUint128(),
reportId.toUint32()
);
// Mint Coin
tokenId = _genTokenID(eventId, reportId);
_safeMint(_msgSender(), tokenId);
}
/// @inheritdoc IHistoryERC721
function tokenEventId(uint tokenId) external pure override returns(uint tkEvtId){
(tkEvtId, ) = _tokenIdSplit(tokenId);
}
/// @notice Packing (contractID: 32, eventID: 192, reportID 32)
function _genTokenID(uint eventID, uint reportID) internal view returns(uint tokenID){
require(eventID < 0xFFFFFFFF && reportID < 0xFFFFFFFF, "Invalid ID");
tokenID = (uint(contractID) << (192+32)) + (eventID << 32) + reportID;
}
function _tokenIdSplit(uint tokenId) internal pure returns(uint eventID, uint reportID){
/// remaining (tokenID >> (192+32)) is contract id.
eventID = (tokenId >> 32) & ((1<<192)-1);
reportID = tokenId & ((1<<32)-1);
}
} | @inheritdoc IERC165 | function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721Enumerable) returns (bool) {
return interfaceId == type(IHistoryERC721).interfaceId || super.supportsInterface(interfaceId);
}
| 10,124,487 | [
1,
36,
10093,
467,
654,
39,
28275,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
6146,
1358,
12,
3890,
24,
1560,
548,
13,
1071,
1476,
5024,
3849,
12,
45,
654,
39,
28275,
16,
4232,
39,
27,
5340,
3572,
25121,
13,
1135,
261,
6430,
13,
288,
203,
3639,
327,
1560,
548,
422,
618,
12,
45,
5623,
654,
39,
27,
5340,
2934,
5831,
548,
747,
2240,
18,
28064,
1358,
12,
5831,
548,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0x8CC131FD208dD17B8420998217d414028D74877F/sources/IMXPunks.sol | Split the minting blob into token_id and blueprint portions {token_id}:{blueprint} | library Minting {
function split(bytes calldata blob)
internal
pure
returns (uint256, bytes memory)
{
int256 index = Bytes.indexOf(blob, ":", 0);
require(index >= 0, "Separator must exist");
uint256 tokenID = Bytes.toUint(blob[1:uint256(index) - 1]);
uint256 blueprintLength = blob.length - uint256(index) - 3;
if (blueprintLength == 0) {
return (tokenID, bytes(""));
}
bytes calldata blueprint = blob[uint256(index) + 2:blob.length - 1];
return (tokenID, blueprint);
}
{
int256 index = Bytes.indexOf(blob, ":", 0);
require(index >= 0, "Separator must exist");
uint256 tokenID = Bytes.toUint(blob[1:uint256(index) - 1]);
uint256 blueprintLength = blob.length - uint256(index) - 3;
if (blueprintLength == 0) {
return (tokenID, bytes(""));
}
bytes calldata blueprint = blob[uint256(index) + 2:blob.length - 1];
return (tokenID, blueprint);
}
}
| 17,087,813 | [
1,
5521,
326,
312,
474,
310,
4795,
1368,
1147,
67,
350,
471,
13712,
1756,
1115,
288,
2316,
67,
350,
17498,
31502,
97,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
12083,
490,
474,
310,
288,
203,
203,
565,
445,
1416,
12,
3890,
745,
892,
4795,
13,
203,
565,
2713,
203,
565,
16618,
203,
565,
1135,
261,
11890,
5034,
16,
1731,
3778,
13,
203,
565,
288,
203,
3639,
509,
5034,
770,
273,
5985,
18,
31806,
12,
10721,
16,
6153,
16,
374,
1769,
203,
3639,
2583,
12,
1615,
1545,
374,
16,
315,
6581,
1297,
1005,
8863,
203,
3639,
2254,
5034,
1147,
734,
273,
5985,
18,
869,
5487,
12,
10721,
63,
21,
30,
11890,
5034,
12,
1615,
13,
300,
404,
19226,
203,
3639,
2254,
5034,
13712,
1782,
273,
4795,
18,
2469,
300,
2254,
5034,
12,
1615,
13,
300,
890,
31,
203,
3639,
309,
261,
31502,
1782,
422,
374,
13,
288,
203,
5411,
327,
261,
2316,
734,
16,
1731,
2932,
7923,
1769,
203,
3639,
289,
203,
3639,
1731,
745,
892,
13712,
273,
4795,
63,
11890,
5034,
12,
1615,
13,
397,
576,
30,
10721,
18,
2469,
300,
404,
15533,
203,
3639,
327,
261,
2316,
734,
16,
13712,
1769,
203,
565,
289,
203,
565,
288,
203,
3639,
509,
5034,
770,
273,
5985,
18,
31806,
12,
10721,
16,
6153,
16,
374,
1769,
203,
3639,
2583,
12,
1615,
1545,
374,
16,
315,
6581,
1297,
1005,
8863,
203,
3639,
2254,
5034,
1147,
734,
273,
5985,
18,
869,
5487,
12,
10721,
63,
21,
30,
11890,
5034,
12,
1615,
13,
300,
404,
19226,
203,
3639,
2254,
5034,
13712,
1782,
273,
4795,
18,
2469,
300,
2254,
5034,
12,
1615,
13,
300,
890,
31,
203,
3639,
309,
261,
31502,
1782,
422,
374,
13,
288,
203,
5411,
327,
2
] |
./full_match/4/0x2804Db6aeEA6181dC51DE45B05D705e6B89ef072/sources/ERC721.sol | * the Metadata extension, but not including the Enumerable extension, which is available separately as {ERC721Enumerable}./ Token name Token symbol Mapping from token ID to owner address Mapping owner address to token count Mapping from token ID to approved address Mapping from owner to operator approvals | contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
string private _name;
string private _symbol;
mapping(uint256 => address) private _owners;
mapping(address => uint256) private _balances;
mapping(uint256 => address) private _tokenApprovals;
mapping(address => mapping(address => bool)) private _operatorApprovals;
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
function name() public view virtual override returns (string memory) {
return _name;
}
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
function _baseURI() internal view virtual returns (string memory) {
}
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
assembly {
revert(add(32, reason), mload(reason))
}
}
}
return true;
}
}
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
assembly {
revert(add(32, reason), mload(reason))
}
}
}
return true;
}
}
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
assembly {
revert(add(32, reason), mload(reason))
}
}
}
return true;
}
}
} catch (bytes memory reason) {
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
assembly {
revert(add(32, reason), mload(reason))
}
}
}
return true;
}
}
} else {
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
assembly {
revert(add(32, reason), mload(reason))
}
}
}
return true;
}
}
} else {
) internal virtual {}
} | 12,509,827 | [
1,
5787,
6912,
2710,
16,
1496,
486,
6508,
326,
6057,
25121,
2710,
16,
1492,
353,
2319,
18190,
487,
288,
654,
39,
27,
5340,
3572,
25121,
5496,
19,
3155,
508,
3155,
3273,
9408,
628,
1147,
1599,
358,
3410,
1758,
9408,
3410,
1758,
358,
1147,
1056,
9408,
628,
1147,
1599,
358,
20412,
1758,
9408,
628,
3410,
358,
3726,
6617,
4524,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
4232,
39,
27,
5340,
353,
1772,
16,
4232,
39,
28275,
16,
467,
654,
39,
27,
5340,
16,
467,
654,
39,
27,
5340,
2277,
288,
203,
565,
1450,
5267,
364,
1758,
31,
203,
565,
1450,
8139,
364,
2254,
5034,
31,
203,
203,
565,
533,
3238,
389,
529,
31,
203,
203,
565,
533,
3238,
389,
7175,
31,
203,
203,
565,
2874,
12,
11890,
5034,
516,
1758,
13,
3238,
389,
995,
414,
31,
203,
203,
565,
2874,
12,
2867,
516,
2254,
5034,
13,
3238,
389,
70,
26488,
31,
203,
203,
565,
2874,
12,
11890,
5034,
516,
1758,
13,
3238,
389,
2316,
12053,
4524,
31,
203,
203,
565,
2874,
12,
2867,
516,
2874,
12,
2867,
516,
1426,
3719,
3238,
389,
9497,
12053,
4524,
31,
203,
203,
203,
565,
3885,
12,
1080,
3778,
508,
67,
16,
533,
3778,
3273,
67,
13,
288,
203,
3639,
389,
529,
273,
508,
67,
31,
203,
3639,
389,
7175,
273,
3273,
67,
31,
203,
565,
289,
203,
203,
565,
445,
6146,
1358,
12,
3890,
24,
1560,
548,
13,
1071,
1476,
5024,
3849,
12,
654,
39,
28275,
16,
467,
654,
39,
28275,
13,
1135,
261,
6430,
13,
288,
203,
3639,
327,
203,
5411,
1560,
548,
422,
618,
12,
45,
654,
39,
27,
5340,
2934,
5831,
548,
747,
203,
5411,
1560,
548,
422,
618,
12,
45,
654,
39,
27,
5340,
2277,
2934,
5831,
548,
747,
203,
5411,
2240,
18,
28064,
1358,
12,
5831,
548,
1769,
203,
565,
289,
203,
203,
565,
445,
11013,
951,
12,
2867,
3410,
13,
1071,
1476,
5024,
3849,
1135,
261,
11890,
2
] |
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
import "@knobs/contracts/contracts/libraries/MerkleProofIndexed.sol";
import "@chainlink/contracts/src/v0.8/interfaces/LinkTokenInterface.sol";
import "@chainlink/contracts/src/v0.8/interfaces/VRFCoordinatorV2Interface.sol";
import "@chainlink/contracts/src/v0.8/VRFConsumerBaseV2.sol";
contract GiveawayContractV2 is VRFConsumerBaseV2, IERC721Receiver {
struct ERC721Token {
address contractAddress;
uint256 tokenId;
bool claimed;
}
ERC721Token[] public nftToDrop;
VRFCoordinatorV2Interface COORDINATOR;
LinkTokenInterface LINKTOKEN;
bytes32 keyHash;
// A reasonable default is 100000, but this value could be different
// on other networks.
uint32 callbackGasLimit = 100000;
// The default is 3, but you can set this higher.
uint16 requestConfirmations = 3;
// Storage parameters
uint256[] public s_randomWords;
uint256 public s_requestId;
uint64 public s_subscriptionId;
address s_owner;
// Index of the NFT array from where to start to drop
uint256 public startIndex;
bytes32[] merkleRoot;
uint256[] numberOfParticipants;
uint256[] numberOfPrizes;
// Whenever the drop has been succesfully set
bool public dropSet;
modifier onlyOwner() {
require(msg.sender == s_owner);
_;
}
modifier onlyIfNotSet() {
require(!dropSet, "Drop already set");
_;
}
modifier onlyWithNFT() {
require(nftToDrop.length > 0, "No NFT to drop");
_;
}
constructor(
uint64 subscriptionId,
address vrfCoordinator,
address link_token_contract,
bytes32 keyHash_
) VRFConsumerBaseV2(vrfCoordinator) {
COORDINATOR = VRFCoordinatorV2Interface(vrfCoordinator);
LINKTOKEN = LinkTokenInterface(link_token_contract);
keyHash = keyHash_;
s_subscriptionId = subscriptionId;
s_owner = msg.sender;
}
/// Once the drop is set it automatically starts
function setupDrop(
bytes32[] memory merkleRoot_,
uint256[] memory numberOfParticipants_,
uint256[] memory numberOfPrizes_
) public onlyOwner onlyIfNotSet {
require(
merkleRoot_.length == numberOfParticipants_.length &&
merkleRoot_.length == numberOfPrizes_.length,
"Invalid drop configuration"
);
require(merkleRoot_.length < 5, "To much drops");
merkleRoot = merkleRoot_;
numberOfParticipants = numberOfParticipants_;
numberOfPrizes = numberOfPrizes_;
dropSet = true;
s_requestId = getRandomNumber(2);
}
/// Send the NFTs you want to drop to the contract
function addNFT(address contractAddress, uint256[] memory tokenIds)
public
onlyOwner
onlyIfNotSet
{
for (uint256 i = 0; i < tokenIds.length; i++) {
IERC721(contractAddress).safeTransferFrom(IERC721(contractAddress).ownerOf(tokenIds[i]), address(this), tokenIds[i]);
nftToDrop.push(
ERC721Token({contractAddress: contractAddress, tokenId: tokenIds[i], claimed: false})
);
}
}
function adjustLeafIndex(uint256 dropNumber, uint256 index) internal view returns (uint256) {
uint256 _startIndex = s_randomWords[1] % numberOfParticipants[dropNumber];
int256 difference = int256(index) - int256(_startIndex);
uint256 remaining = numberOfParticipants[dropNumber] - _startIndex;
if (difference >= 0) {
return uint256(difference);
} else {
return remaining + index;
}
}
function adjustNFTIndex(uint256 index) internal view returns (uint256) {
uint256 _startIndex = s_randomWords[0] % nftToDrop.length;
if (_startIndex + index >= nftToDrop.length) {
return (_startIndex + index) % nftToDrop.length;
} else {
return _startIndex + index;
}
}
function getPrecDropLength(uint256 dropNumber) public view returns (uint256) {
uint256 sum = 0;
for (uint8 i = 0; i < dropNumber; i++) {
sum = sum + numberOfPrizes[i];
}
return sum;
}
function claimNFT(
uint256 dropNumber,
bytes32[] memory proof,
bytes32 leaf,
uint256 leafIndex,
address receiver
) public {
require(dropNumber < merkleRoot.length, "Invalid drop number");
require(verifyProof(dropNumber, proof, leaf, leafIndex), "Invalid proof");
require(keccak256(abi.encodePacked(receiver)) == leaf, "Invalid receiver");
require(leafIndex < numberOfParticipants[dropNumber], "Invalid leaf index");
uint256 adjustedLeafIndex = adjustLeafIndex(dropNumber, leafIndex);
require(adjustedLeafIndex < numberOfPrizes[dropNumber], "No more NFT for this drop");
uint256 precDropLength = getPrecDropLength(dropNumber);
uint256 indexToClaim = adjustNFTIndex(adjustedLeafIndex + precDropLength);
require(nftToDrop[indexToClaim].claimed != true, "Already claimed token");
nftToDrop[indexToClaim].claimed = true;
IERC721(nftToDrop[indexToClaim].contractAddress).safeTransferFrom(
address(this),
receiver,
nftToDrop[indexToClaim].tokenId
);
}
/// Start drop
function getRandomNumber(uint32 numWords) internal returns (uint256 requestId) {
return
COORDINATOR.requestRandomWords(
keyHash,
s_subscriptionId,
requestConfirmations,
callbackGasLimit,
numWords
);
}
function fulfillRandomWords(
uint256, /* requestId */
uint256[] memory randomWords
) internal override {
s_randomWords = randomWords;
}
/// Verifies a merkle proof given a leaf hash, the corresponding leafIndex and the merkle root (saved in the contract)
function verifyProof(
uint256 dropNumber,
bytes32[] memory proof,
bytes32 leaf,
uint256 leafIndex
) public view returns (bool) {
return MerkleProofIndexed.verify(proof, merkleRoot[dropNumber], leaf, leafIndex);
}
/// @notice Function needed to let the contract being able to receive ERC721 NFTs
/// @dev Mandatory for IERC721Receiver
function onERC721Received(
address,
address,
uint256,
bytes memory
) public virtual override returns (bytes4) {
return this.onERC721Received.selector;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/** ****************************************************************************
* @notice Interface for contracts using VRF randomness
* *****************************************************************************
* @dev PURPOSE
*
* @dev Reggie the Random Oracle (not his real job) wants to provide randomness
* @dev to Vera the verifier in such a way that Vera can be sure he's not
* @dev making his output up to suit himself. Reggie provides Vera a public key
* @dev to which he knows the secret key. Each time Vera provides a seed to
* @dev Reggie, he gives back a value which is computed completely
* @dev deterministically from the seed and the secret key.
*
* @dev Reggie provides a proof by which Vera can verify that the output was
* @dev correctly computed once Reggie tells it to her, but without that proof,
* @dev the output is indistinguishable to her from a uniform random sample
* @dev from the output space.
*
* @dev The purpose of this contract is to make it easy for unrelated contracts
* @dev to talk to Vera the verifier about the work Reggie is doing, to provide
* @dev simple access to a verifiable source of randomness. It ensures 2 things:
* @dev 1. The fulfillment came from the VRFCoordinator
* @dev 2. The consumer contract implements fulfillRandomWords.
* *****************************************************************************
* @dev USAGE
*
* @dev Calling contracts must inherit from VRFConsumerBase, and can
* @dev initialize VRFConsumerBase's attributes in their constructor as
* @dev shown:
*
* @dev contract VRFConsumer {
* @dev constructor(<other arguments>, address _vrfCoordinator, address _link)
* @dev VRFConsumerBase(_vrfCoordinator) public {
* @dev <initialization with other arguments goes here>
* @dev }
* @dev }
*
* @dev The oracle will have given you an ID for the VRF keypair they have
* @dev committed to (let's call it keyHash). Create subscription, fund it
* @dev and your consumer contract as a consumer of it (see VRFCoordinatorInterface
* @dev subscription management functions).
* @dev Call requestRandomWords(keyHash, subId, minimumRequestConfirmations,
* @dev callbackGasLimit, numWords),
* @dev see (VRFCoordinatorInterface for a description of the arguments).
*
* @dev Once the VRFCoordinator has received and validated the oracle's response
* @dev to your request, it will call your contract's fulfillRandomWords method.
*
* @dev The randomness argument to fulfillRandomWords is a set of random words
* @dev generated from your requestId and the blockHash of the request.
*
* @dev If your contract could have concurrent requests open, you can use the
* @dev requestId returned from requestRandomWords to track which response is associated
* @dev with which randomness request.
* @dev See "SECURITY CONSIDERATIONS" for principles to keep in mind,
* @dev if your contract could have multiple requests in flight simultaneously.
*
* @dev Colliding `requestId`s are cryptographically impossible as long as seeds
* @dev differ.
*
* *****************************************************************************
* @dev SECURITY CONSIDERATIONS
*
* @dev A method with the ability to call your fulfillRandomness method directly
* @dev could spoof a VRF response with any random value, so it's critical that
* @dev it cannot be directly called by anything other than this base contract
* @dev (specifically, by the VRFConsumerBase.rawFulfillRandomness method).
*
* @dev For your users to trust that your contract's random behavior is free
* @dev from malicious interference, it's best if you can write it so that all
* @dev behaviors implied by a VRF response are executed *during* your
* @dev fulfillRandomness method. If your contract must store the response (or
* @dev anything derived from it) and use it later, you must ensure that any
* @dev user-significant behavior which depends on that stored value cannot be
* @dev manipulated by a subsequent VRF request.
*
* @dev Similarly, both miners and the VRF oracle itself have some influence
* @dev over the order in which VRF responses appear on the blockchain, so if
* @dev your contract could have multiple VRF requests in flight simultaneously,
* @dev you must ensure that the order in which the VRF responses arrive cannot
* @dev be used to manipulate your contract's user-significant behavior.
*
* @dev Since the block hash of the block which contains the requestRandomness
* @dev call is mixed into the input to the VRF *last*, a sufficiently powerful
* @dev miner could, in principle, fork the blockchain to evict the block
* @dev containing the request, forcing the request to be included in a
* @dev different block with a different hash, and therefore a different input
* @dev to the VRF. However, such an attack would incur a substantial economic
* @dev cost. This cost scales with the number of blocks the VRF oracle waits
* @dev until it calls responds to a request. It is for this reason that
* @dev that you can signal to an oracle you'd like them to wait longer before
* @dev responding to the request (however this is not enforced in the contract
* @dev and so remains effective only in the case of unmodified oracle software).
*/
abstract contract VRFConsumerBaseV2 {
error OnlyCoordinatorCanFulfill(address have, address want);
address private immutable vrfCoordinator;
/**
* @param _vrfCoordinator address of VRFCoordinator contract
*/
constructor(address _vrfCoordinator) {
vrfCoordinator = _vrfCoordinator;
}
/**
* @notice fulfillRandomness handles the VRF response. Your contract must
* @notice implement it. See "SECURITY CONSIDERATIONS" above for important
* @notice principles to keep in mind when implementing your fulfillRandomness
* @notice method.
*
* @dev VRFConsumerBaseV2 expects its subcontracts to have a method with this
* @dev signature, and will call it once it has verified the proof
* @dev associated with the randomness. (It is triggered via a call to
* @dev rawFulfillRandomness, below.)
*
* @param requestId The Id initially returned by requestRandomness
* @param randomWords the VRF output expanded to the requested number of words
*/
function fulfillRandomWords(uint256 requestId, uint256[] memory randomWords) internal virtual;
// rawFulfillRandomness is called by VRFCoordinator when it receives a valid VRF
// proof. rawFulfillRandomness then calls fulfillRandomness, after validating
// the origin of the call
function rawFulfillRandomWords(uint256 requestId, uint256[] memory randomWords) external {
if (msg.sender != vrfCoordinator) {
revert OnlyCoordinatorCanFulfill(msg.sender, vrfCoordinator);
}
fulfillRandomWords(requestId, randomWords);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface VRFCoordinatorV2Interface {
/**
* @notice Get configuration relevant for making requests
* @return minimumRequestConfirmations global min for request confirmations
* @return maxGasLimit global max for request gas limit
* @return s_provingKeyHashes list of registered key hashes
*/
function getRequestConfig()
external
view
returns (
uint16,
uint32,
bytes32[] memory
);
/**
* @notice Request a set of random words.
* @param keyHash - Corresponds to a particular oracle job which uses
* that key for generating the VRF proof. Different keyHash's have different gas price
* ceilings, so you can select a specific one to bound your maximum per request cost.
* @param subId - The ID of the VRF subscription. Must be funded
* with the minimum subscription balance required for the selected keyHash.
* @param minimumRequestConfirmations - How many blocks you'd like the
* oracle to wait before responding to the request. See SECURITY CONSIDERATIONS
* for why you may want to request more. The acceptable range is
* [minimumRequestBlockConfirmations, 200].
* @param callbackGasLimit - How much gas you'd like to receive in your
* fulfillRandomWords callback. Note that gasleft() inside fulfillRandomWords
* may be slightly less than this amount because of gas used calling the function
* (argument decoding etc.), so you may need to request slightly more than you expect
* to have inside fulfillRandomWords. The acceptable range is
* [0, maxGasLimit]
* @param numWords - The number of uint256 random values you'd like to receive
* in your fulfillRandomWords callback. Note these numbers are expanded in a
* secure way by the VRFCoordinator from a single random value supplied by the oracle.
* @return requestId - A unique identifier of the request. Can be used to match
* a request to a response in fulfillRandomWords.
*/
function requestRandomWords(
bytes32 keyHash,
uint64 subId,
uint16 minimumRequestConfirmations,
uint32 callbackGasLimit,
uint32 numWords
) external returns (uint256 requestId);
/**
* @notice Create a VRF subscription.
* @return subId - A unique subscription id.
* @dev You can manage the consumer set dynamically with addConsumer/removeConsumer.
* @dev Note to fund the subscription, use transferAndCall. For example
* @dev LINKTOKEN.transferAndCall(
* @dev address(COORDINATOR),
* @dev amount,
* @dev abi.encode(subId));
*/
function createSubscription() external returns (uint64 subId);
/**
* @notice Get a VRF subscription.
* @param subId - ID of the subscription
* @return balance - LINK balance of the subscription in juels.
* @return reqCount - number of requests for this subscription, determines fee tier.
* @return owner - owner of the subscription.
* @return consumers - list of consumer address which are able to use this subscription.
*/
function getSubscription(uint64 subId)
external
view
returns (
uint96 balance,
uint64 reqCount,
address owner,
address[] memory consumers
);
/**
* @notice Request subscription owner transfer.
* @param subId - ID of the subscription
* @param newOwner - proposed new owner of the subscription
*/
function requestSubscriptionOwnerTransfer(uint64 subId, address newOwner) external;
/**
* @notice Request subscription owner transfer.
* @param subId - ID of the subscription
* @dev will revert if original owner of subId has
* not requested that msg.sender become the new owner.
*/
function acceptSubscriptionOwnerTransfer(uint64 subId) external;
/**
* @notice Add a consumer to a VRF subscription.
* @param subId - ID of the subscription
* @param consumer - New consumer which can use the subscription
*/
function addConsumer(uint64 subId, address consumer) external;
/**
* @notice Remove a consumer from a VRF subscription.
* @param subId - ID of the subscription
* @param consumer - Consumer to remove from the subscription
*/
function removeConsumer(uint64 subId, address consumer) external;
/**
* @notice Cancel a subscription
* @param subId - ID of the subscription
* @param to - Where to send the remaining LINK to
*/
function cancelSubscription(uint64 subId, address to) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface LinkTokenInterface {
function allowance(address owner, address spender) external view returns (uint256 remaining);
function approve(address spender, uint256 value) external returns (bool success);
function balanceOf(address owner) external view returns (uint256 balance);
function decimals() external view returns (uint8 decimalPlaces);
function decreaseApproval(address spender, uint256 addedValue) external returns (bool success);
function increaseApproval(address spender, uint256 subtractedValue) external;
function name() external view returns (string memory tokenName);
function symbol() external view returns (string memory tokenSymbol);
function totalSupply() external view returns (uint256 totalTokensIssued);
function transfer(address to, uint256 value) external returns (bool success);
function transferAndCall(
address to,
uint256 value,
bytes calldata data
) external returns (bool success);
function transferFrom(
address from,
address to,
uint256 value
) external returns (bool success);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;
/**
* @title MerkleProofIndexed
* @dev Merkle proof verification based on
* https://github.com/ameensol/merkle-tree-solidity/blob/master/src/MerkleProof.sol
*/
library MerkleProofIndexed {
/**
* @dev Verifies a Merkle proof proving the existence of a leaf in a Merkle tree. Assumes that the merkle tree
* you are passing is symmetric, so the number of leaves must be a power of 2 in order to properly verify the index
* of the leaf that is meant to be proven
* @param proof Merkle proof containing sibling hashes on the branch from the leaf to the root of the Merkle tree
* @param root Merkle root
* @param leaf Leaf of Merkle tree
* @param leafIndex the index of the leaf you are trying to prove
*/
function verify(
bytes32[] memory proof,
bytes32 root,
bytes32 leaf,
uint256 leafIndex
) internal pure returns (bool) {
bytes32 computedHash = leaf;
bytes32 proofElement;
for (uint256 i = 0; i < proof.length; i++) {
proofElement = proof[i];
if ((leafIndex >> i) % 2 == 0) {
// Hash(current computed hash + current element of the proof)
computedHash = keccak256(
abi.encodePacked(computedHash, proofElement)
);
} else {
// Hash(current element of the proof + current computed hash)
computedHash = keccak256(
abi.encodePacked(proofElement, computedHash)
);
}
}
// Check if the computed hash (root) is equal to the provided root
return computedHash == root;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
} | * @dev Verifies a Merkle proof proving the existence of a leaf in a Merkle tree. Assumes that the merkle tree you are passing is symmetric, so the number of leaves must be a power of 2 in order to properly verify the index of the leaf that is meant to be proven @param proof Merkle proof containing sibling hashes on the branch from the leaf to the root of the Merkle tree @param root Merkle root @param leaf Leaf of Merkle tree @param leafIndex the index of the leaf you are trying to prove/ Hash(current computed hash + current element of the proof) Hash(current element of the proof + current computed hash) | ) internal pure returns (bool) {
bytes32 computedHash = leaf;
bytes32 proofElement;
for (uint256 i = 0; i < proof.length; i++) {
proofElement = proof[i];
if ((leafIndex >> i) % 2 == 0) {
computedHash = keccak256(
abi.encodePacked(computedHash, proofElement)
);
computedHash = keccak256(
abi.encodePacked(proofElement, computedHash)
);
}
}
}
| 1,162,049 | [
1,
19802,
279,
31827,
14601,
450,
6282,
326,
15782,
434,
279,
7839,
316,
279,
31827,
2151,
18,
25374,
716,
326,
30235,
2151,
1846,
854,
9588,
353,
15108,
16,
1427,
326,
1300,
434,
15559,
1297,
506,
279,
7212,
434,
576,
316,
1353,
358,
8214,
3929,
326,
770,
434,
326,
7839,
716,
353,
20348,
358,
506,
450,
3995,
225,
14601,
31827,
14601,
4191,
10841,
9869,
603,
326,
3803,
628,
326,
7839,
358,
326,
1365,
434,
326,
31827,
2151,
225,
1365,
31827,
1365,
225,
7839,
23383,
434,
31827,
2151,
225,
7839,
1016,
326,
770,
434,
326,
7839,
1846,
854,
8374,
358,
450,
537,
19,
2474,
12,
2972,
8470,
1651,
397,
783,
930,
434,
326,
14601,
13,
2474,
12,
2972,
930,
434,
326,
14601,
397,
783,
8470,
1651,
13,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
262,
2713,
16618,
1135,
261,
6430,
13,
288,
203,
3639,
1731,
1578,
8470,
2310,
273,
7839,
31,
203,
3639,
1731,
1578,
14601,
1046,
31,
203,
203,
3639,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
14601,
18,
2469,
31,
277,
27245,
288,
203,
5411,
14601,
1046,
273,
14601,
63,
77,
15533,
203,
203,
5411,
309,
14015,
12070,
1016,
1671,
277,
13,
738,
576,
422,
374,
13,
288,
203,
7734,
8470,
2310,
273,
417,
24410,
581,
5034,
12,
203,
10792,
24126,
18,
3015,
4420,
329,
12,
20307,
2310,
16,
14601,
1046,
13,
203,
7734,
11272,
203,
7734,
8470,
2310,
273,
417,
24410,
581,
5034,
12,
203,
10792,
24126,
18,
3015,
4420,
329,
12,
24207,
1046,
16,
8470,
2310,
13,
203,
7734,
11272,
203,
5411,
289,
203,
3639,
289,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
contract c is b {
/// @param x sadad
/// @return k is a boolean
/// @inheritdoc b
function foo(int x) public pure returns (int a, bool k) {}
}
contract b {} | @param x sadad @return k is a boolean @inheritdoc b | function foo(int x) public pure returns (int a, bool k) {}
| 7,244,969 | [
1,
92,
272,
361,
361,
327,
417,
353,
279,
1250,
632,
10093,
324,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
5411,
445,
8431,
12,
474,
619,
13,
1071,
16618,
1135,
261,
474,
279,
16,
1426,
417,
13,
2618,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/*
* Origin Protocol
* https://originprotocol.com
*
* Released under the MIT license
* https://github.com/OriginProtocol/origin-dollar
*
* Copyright 2020 Origin Protocol, Inc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
// File: contracts/interfaces/uniswap/IUniswapV2Pair.sol
pragma solidity 0.5.11;
interface IUniswapV2Pair {
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves()
external
view
returns (
uint112 reserve0,
uint112 reserve1,
uint32 blockTimestampLast
);
function price0CumulativeLast() external view returns (uint256);
function price1CumulativeLast() external view returns (uint256);
function sync() external;
}
// File: contracts/oracle/UniswapLib.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.5.11;
// Based on code from https://github.com/Uniswap/uniswap-v2-periphery
// a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format))
library FixedPoint {
// range: [0, 2**112 - 1]
// resolution: 1 / 2**112
struct uq112x112 {
uint224 _x;
}
// returns a uq112x112 which represents the ratio of the numerator to the denominator
// equivalent to encode(numerator).div(denominator)
function fraction(uint112 numerator, uint112 denominator)
internal
pure
returns (uq112x112 memory)
{
require(denominator > 0, "FixedPoint: DIV_BY_ZERO");
return uq112x112((uint224(numerator) << 112) / denominator);
}
// decode a uq112x112 into a uint with 18 decimals of precision
function decode112with18(uq112x112 memory self)
internal
pure
returns (uint256)
{
// we only have 256 - 224 = 32 bits to spare, so scaling up by ~60 bits is dangerous
// instead, get close to:
// (x * 1e18) >> 112
// without risk of overflowing, e.g.:
// (x) / 2 ** (112 - lg(1e18))
return uint256(self._x) / 5192296858534827;
}
}
// library with helper methods for oracles that are concerned with computing average prices
library UniswapV2OracleLibrary {
using FixedPoint for *;
// helper function that returns the current block timestamp within the range of uint32, i.e. [0, 2**32 - 1]
function currentBlockTimestamp() internal view returns (uint32) {
return uint32(block.timestamp % 2**32);
}
// produces the cumulative price using counterfactuals to save gas and avoid a call to sync.
function currentCumulativePrices(address pair)
internal
view
returns (
uint256 price0Cumulative,
uint256 price1Cumulative,
uint32 blockTimestamp
)
{
blockTimestamp = currentBlockTimestamp();
price0Cumulative = IUniswapV2Pair(pair).price0CumulativeLast();
price1Cumulative = IUniswapV2Pair(pair).price1CumulativeLast();
// if time has elapsed since the last update on the pair, mock the accumulated price values
(
uint112 reserve0,
uint112 reserve1,
uint32 blockTimestampLast
) = IUniswapV2Pair(pair).getReserves();
if (blockTimestampLast != blockTimestamp) {
// subtraction overflow is desired
uint32 timeElapsed = blockTimestamp - blockTimestampLast;
// addition overflow is desired
// counterfactual
price0Cumulative +=
uint256(FixedPoint.fraction(reserve1, reserve0)._x) *
timeElapsed;
// counterfactual
price1Cumulative +=
uint256(FixedPoint.fraction(reserve0, reserve1)._x) *
timeElapsed;
}
}
}
// File: contracts/interfaces/IPriceOracle.sol
pragma solidity 0.5.11;
interface IPriceOracle {
/**
* @dev returns the asset price in USD, 6 decimal digits.
* Compatible with the Open Price Feed.
*/
function price(string calldata symbol) external view returns (uint256);
}
// File: contracts/interfaces/IEthUsdOracle.sol
pragma solidity 0.5.11;
interface IEthUsdOracle {
/**
* @notice Returns ETH price in USD.
* @return Price in USD with 6 decimal digits.
*/
function ethUsdPrice() external view returns (uint256);
/**
* @notice Returns token price in USD.
* @param symbol. Asset symbol. For ex. "DAI".
* @return Price in USD with 6 decimal digits.
*/
function tokUsdPrice(string calldata symbol)
external
view
returns (uint256);
/**
* @notice Returns the asset price in ETH.
* @param symbol. Asset symbol. For ex. "DAI".
* @return Price in ETH with 8 decimal digits.
*/
function tokEthPrice(string calldata symbol) external returns (uint256);
}
interface IViewEthUsdOracle {
/**
* @notice Returns ETH price in USD.
* @return Price in USD with 6 decimal digits.
*/
function ethUsdPrice() external view returns (uint256);
/**
* @notice Returns token price in USD.
* @param symbol. Asset symbol. For ex. "DAI".
* @return Price in USD with 6 decimal digits.
*/
function tokUsdPrice(string calldata symbol)
external
view
returns (uint256);
/**
* @notice Returns the asset price in ETH.
* @param symbol. Asset symbol. For ex. "DAI".
* @return Price in ETH with 8 decimal digits.
*/
function tokEthPrice(string calldata symbol)
external
view
returns (uint256);
}
// File: @openzeppelin/upgrades/contracts/Initializable.sol
pragma solidity >=0.4.24 <0.7.0;
/**
* @title Initializable
*
* @dev Helper contract to support initializer functions. To use it, replace
* the constructor with a function that has the `initializer` modifier.
* WARNING: Unlike constructors, initializer functions must be manually
* invoked. This applies both to deploying an Initializable contract, as well
* as extending an Initializable contract via inheritance.
* WARNING: When used with inheritance, manual care must be taken to not invoke
* a parent initializer twice, or ensure that all initializers are idempotent,
* because this is not dealt with automatically as with constructors.
*/
contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private initializing;
/**
* @dev Modifier to use in the initializer function of a contract.
*/
modifier initializer() {
require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized");
bool isTopLevelCall = !initializing;
if (isTopLevelCall) {
initializing = true;
initialized = true;
}
_;
if (isTopLevelCall) {
initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
assembly { cs := extcodesize(self) }
return cs == 0;
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
// File: contracts/governance/Governable.sol
pragma solidity 0.5.11;
/**
* @title OUSD Governable Contract
* @dev Copy of the openzeppelin Ownable.sol contract with nomenclature change
* from owner to governor and renounce methods removed. Does not use
* Context.sol like Ownable.sol does for simplification.
* @author Origin Protocol Inc
*/
contract Governable {
// Storage position of the owner and pendingOwner of the contract
bytes32
private constant governorPosition = 0x7bea13895fa79d2831e0a9e28edede30099005a50d652d8957cf8a607ee6ca4a;
//keccak256("OUSD.governor");
bytes32
private constant pendingGovernorPosition = 0x44c4d30b2eaad5130ad70c3ba6972730566f3e6359ab83e800d905c61b1c51db;
//keccak256("OUSD.pending.governor");
event PendingGovernorshipTransfer(
address indexed previousGovernor,
address indexed newGovernor
);
event GovernorshipTransferred(
address indexed previousGovernor,
address indexed newGovernor
);
/**
* @dev Initializes the contract setting the deployer as the initial Governor.
*/
constructor() internal {
_setGovernor(msg.sender);
emit GovernorshipTransferred(address(0), _governor());
}
/**
* @dev Returns the address of the current Governor.
*/
function governor() public view returns (address) {
return _governor();
}
function _governor() internal view returns (address governorOut) {
bytes32 position = governorPosition;
assembly {
governorOut := sload(position)
}
}
function _pendingGovernor()
internal
view
returns (address pendingGovernor)
{
bytes32 position = pendingGovernorPosition;
assembly {
pendingGovernor := sload(position)
}
}
/**
* @dev Throws if called by any account other than the Governor.
*/
modifier onlyGovernor() {
require(isGovernor(), "Caller is not the Governor");
_;
}
/**
* @dev Returns true if the caller is the current Governor.
*/
function isGovernor() public view returns (bool) {
return msg.sender == _governor();
}
function _setGovernor(address newGovernor) internal {
bytes32 position = governorPosition;
assembly {
sstore(position, newGovernor)
}
}
function _setPendingGovernor(address newGovernor) internal {
bytes32 position = pendingGovernorPosition;
assembly {
sstore(position, newGovernor)
}
}
/**
* @dev Transfers Governance of the contract to a new account (`newGovernor`).
* Can only be called by the current Governor. Must be claimed for this to complete
* @param _newGovernor Address of the new Governor
*/
function transferGovernance(address _newGovernor) external onlyGovernor {
_setPendingGovernor(_newGovernor);
emit PendingGovernorshipTransfer(_governor(), _newGovernor);
}
/**
* @dev Claim Governance of the contract to a new account (`newGovernor`).
* Can only be called by the new Governor.
*/
function claimGovernance() external {
require(
msg.sender == _pendingGovernor(),
"Only the pending Governor can complete the claim"
);
_changeGovernor(msg.sender);
}
/**
* @dev Change Governance of the contract to a new account (`newGovernor`).
* @param _newGovernor Address of the new Governor
*/
function _changeGovernor(address _newGovernor) internal {
require(_newGovernor != address(0), "New Governor is address(0)");
emit GovernorshipTransferred(_governor(), _newGovernor);
_setGovernor(_newGovernor);
}
}
// File: contracts/governance/InitializableGovernable.sol
pragma solidity 0.5.11;
/**
* @title OUSD InitializableGovernable Contract
* @author Origin Protocol Inc
*/
contract InitializableGovernable is Governable, Initializable {
function _initialize(address _governor) internal {
_changeGovernor(_governor);
}
}
// File: contracts/oracle/OpenUniswapOracle.sol
pragma solidity 0.5.11;
pragma experimental ABIEncoderV2;
/**
* @title OUSD OpenUniswapOracle Contract
* @author Origin Protocol Inc
*/
contract OpenUniswapOracle is IEthUsdOracle, InitializableGovernable {
using FixedPoint for *;
uint256 public constant PERIOD = 2 minutes;
struct SwapConfig {
bool ethOnFirst; // whether the weth is the first in pair
address swap; // address of the uniswap pair
uint256 blockTimestampLast;
uint256 latestBlockTimestampLast;
uint256 priceCumulativeLast;
uint256 latestPriceCumulativeLast;
uint256 baseUnit;
}
mapping(bytes32 => SwapConfig) swaps;
IPriceOracle public ethPriceOracle; //price oracle for getting the Eth->USD price OPEN oracle..
address ethToken;
string constant ethSymbol = "ETH";
bytes32 constant ethHash = keccak256(abi.encodePacked(ethSymbol));
constructor(address ethPriceOracle_, address ethToken_) public {
ethPriceOracle = IPriceOracle(ethPriceOracle_);
ethToken = ethToken_;
}
function registerEthPriceOracle(address ethPriceOracle_)
public
onlyGovernor
{
ethPriceOracle = IPriceOracle(ethPriceOracle_);
}
function registerPair(address pair_) public onlyGovernor {
IUniswapV2Pair pair = IUniswapV2Pair(pair_);
address token;
bool ethOnFirst = true;
if (pair.token0() == ethToken) {
token = pair.token1();
} else {
token = pair.token0();
ethOnFirst = false;
}
SymboledERC20 st = SymboledERC20(token);
string memory symbol = st.symbol();
SwapConfig storage config = swaps[keccak256(abi.encodePacked(symbol))];
// is the first token the eth Token
config.ethOnFirst = ethOnFirst;
config.swap = pair_;
config.baseUnit = uint256(10)**st.decimals();
// we want everything relative to first
config.priceCumulativeLast = currentCumulativePrice(config);
config.blockTimestampLast = block.timestamp;
config.latestBlockTimestampLast = config.blockTimestampLast;
config.latestPriceCumulativeLast = config.priceCumulativeLast;
}
function currentCumulativePrice(SwapConfig storage config)
internal
view
returns (uint256)
{
(
uint256 cumulativePrice0,
uint256 cumulativePrice1,
) = UniswapV2OracleLibrary.currentCumulativePrices(config.swap);
if (config.ethOnFirst) {
return cumulativePrice1;
} else {
return cumulativePrice0;
}
}
// This needs to be called regularly to update the pricing window
function pokePriceWindow(SwapConfig storage config)
internal
returns (
uint256,
uint256,
uint256
)
{
uint256 priceCumulative = currentCumulativePrice(config);
uint256 timeElapsed = block.timestamp - config.latestBlockTimestampLast;
if (timeElapsed >= PERIOD) {
config.blockTimestampLast = config.latestBlockTimestampLast;
config.priceCumulativeLast = config.latestPriceCumulativeLast;
config.latestBlockTimestampLast = block.timestamp;
config.latestPriceCumulativeLast = priceCumulative;
}
return (
priceCumulative,
config.priceCumulativeLast,
config.blockTimestampLast
);
}
// update to the latest window
function updatePriceWindows(bytes32[] calldata symbolHashes) external {
for (uint256 i = 0; i < symbolHashes.length; i++) {
SwapConfig storage config = swaps[symbolHashes[i]];
pokePriceWindow(config);
}
}
//eth to usd price
//precision from open is 6
function ethUsdPrice() external view returns (uint256) {
return ethPriceOracle.price(ethSymbol); // grab the eth price from the open oracle
}
//tok to Usd price
//Note: for USDC and USDT this is fixed to 1 on openoracle
// precision here is 8
function tokUsdPrice(string calldata symbol)
external
view
returns (uint256)
{
return ethPriceOracle.price(symbol); // grab the eth price from the open oracle
}
//tok to Eth price
function tokEthPrice(string calldata symbol) external returns (uint256) {
bytes32 tokenSymbolHash = keccak256(abi.encodePacked(symbol));
SwapConfig storage config = swaps[tokenSymbolHash];
(
uint256 priceCumulative,
uint256 priceCumulativeLast,
uint256 blockTimestampLast
) = pokePriceWindow(config);
require(
priceCumulative > priceCumulativeLast,
"There has been no cumulative change"
);
// This should be impossible, but better safe than sorry
require(
block.timestamp > blockTimestampLast,
"now must come after before"
);
uint256 timeElapsed = block.timestamp - blockTimestampLast;
// overflow is desired, casting never truncates
// cumulative price is in (uq112x112 price * seconds) units so we simply wrap it after division by time elapsed
FixedPoint.uq112x112 memory priceAverage = FixedPoint.uq112x112(
uint224(
(priceCumulative - config.priceCumulativeLast) / timeElapsed
)
);
uint256 rawUniswapPriceMantissa = priceAverage.decode112with18();
// Divide by 1e28 because it's decoded to 18 and then we want 8 decimal places of precision out so 18+18-8
return mul(rawUniswapPriceMantissa, config.baseUnit) / 1e28;
}
// This actually calculate the latest price from outside oracles
// It's a view but substantially more costly in terms of calculation
function price(string calldata symbol) external view returns (uint256) {
bytes32 tokenSymbolHash = keccak256(abi.encodePacked(symbol));
uint256 ethPrice = ethPriceOracle.price(ethSymbol); // grab the eth price from the open oracle
if (ethHash == tokenSymbolHash) {
return ethPrice;
} else {
SwapConfig storage config = swaps[tokenSymbolHash];
uint256 priceCumulative = currentCumulativePrice(config);
require(
priceCumulative > config.priceCumulativeLast,
"There has been no cumulative change"
);
// This should be impossible, but better safe than sorry
require(
block.timestamp > config.blockTimestampLast,
"now must come after before"
);
uint256 timeElapsed = block.timestamp - config.blockTimestampLast;
// overflow is desired, casting never truncates
// cumulative price is in (uq112x112 price * seconds) units so we simply wrap it after division by time elapsed
FixedPoint.uq112x112 memory priceAverage = FixedPoint.uq112x112(
uint224(
(priceCumulative - config.priceCumulativeLast) / timeElapsed
)
);
uint256 rawUniswapPriceMantissa = priceAverage.decode112with18();
uint256 unscaledPriceMantissa = mul(
rawUniswapPriceMantissa,
ethPrice
);
return mul(unscaledPriceMantissa, config.baseUnit) / 1e36;
}
}
function debugPrice(string calldata symbol)
external
view
returns (
uint256,
uint256,
uint256,
uint256
)
{
bytes32 tokenSymbolHash = keccak256(abi.encodePacked(symbol));
uint256 ethPrice = ethPriceOracle.price(ethSymbol); // grab the eth price from the open oracle
SwapConfig storage config = swaps[tokenSymbolHash];
uint256 priceCumulative = currentCumulativePrice(config);
require(
priceCumulative > config.priceCumulativeLast,
"There has been no cumulative change"
);
// This should be impossible, but better safe than sorry
require(
block.timestamp > config.blockTimestampLast,
"now must come after before"
);
uint256 timeElapsed = block.timestamp - config.blockTimestampLast;
FixedPoint.uq112x112 memory priceAverage = FixedPoint.uq112x112(
uint224(
(priceCumulative - config.priceCumulativeLast) / timeElapsed
)
);
uint256 rawUniswapPriceMantissa = priceAverage.decode112with18();
uint256 unscaledPriceMantissa = mul(rawUniswapPriceMantissa, ethPrice);
// overflow is desired, casting never truncates
// cumulative price is in (uq112x112 price * seconds) units so we simply wrap it after division by time elapsed
return (
priceCumulative - config.priceCumulativeLast,
timeElapsed,
rawUniswapPriceMantissa,
unscaledPriceMantissa
);
}
function openPrice(string calldata symbol) external view returns (uint256) {
return ethPriceOracle.price(symbol);
}
function getSwapConfig(string calldata symbol)
external
view
returns (SwapConfig memory)
{
bytes32 tokenSymbolHash = keccak256(abi.encodePacked(symbol));
return swaps[tokenSymbolHash];
}
/// @dev Overflow proof multiplication
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "multiplication overflow");
return c;
}
}
contract SymboledERC20 {
function symbol() public view returns (string memory);
function decimals() public view returns (uint8);
}
| This needs to be called regularly to update the pricing window | function pokePriceWindow(SwapConfig storage config)
internal
returns (
uint256,
uint256,
uint256
)
{
uint256 priceCumulative = currentCumulativePrice(config);
uint256 timeElapsed = block.timestamp - config.latestBlockTimestampLast;
if (timeElapsed >= PERIOD) {
config.blockTimestampLast = config.latestBlockTimestampLast;
config.priceCumulativeLast = config.latestPriceCumulativeLast;
config.latestBlockTimestampLast = block.timestamp;
config.latestPriceCumulativeLast = priceCumulative;
}
return (
priceCumulative,
config.priceCumulativeLast,
config.blockTimestampLast
);
}
| 5,969,526 | [
1,
2503,
4260,
358,
506,
2566,
6736,
715,
358,
1089,
326,
31765,
2742,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
293,
3056,
5147,
3829,
12,
12521,
809,
2502,
642,
13,
203,
3639,
2713,
203,
3639,
1135,
261,
203,
5411,
2254,
5034,
16,
203,
5411,
2254,
5034,
16,
203,
5411,
2254,
5034,
203,
3639,
262,
203,
565,
288,
203,
3639,
2254,
5034,
6205,
39,
11276,
273,
783,
39,
11276,
5147,
12,
1425,
1769,
203,
203,
3639,
2254,
5034,
813,
28827,
273,
1203,
18,
5508,
300,
642,
18,
13550,
1768,
4921,
3024,
31,
203,
203,
3639,
309,
261,
957,
28827,
1545,
10950,
21054,
13,
288,
203,
5411,
642,
18,
2629,
4921,
3024,
273,
642,
18,
13550,
1768,
4921,
3024,
31,
203,
5411,
642,
18,
8694,
39,
11276,
3024,
273,
642,
18,
13550,
5147,
39,
11276,
3024,
31,
203,
203,
5411,
642,
18,
13550,
1768,
4921,
3024,
273,
1203,
18,
5508,
31,
203,
5411,
642,
18,
13550,
5147,
39,
11276,
3024,
273,
6205,
39,
11276,
31,
203,
3639,
289,
203,
203,
3639,
327,
261,
203,
5411,
6205,
39,
11276,
16,
203,
5411,
642,
18,
8694,
39,
11276,
3024,
16,
203,
5411,
642,
18,
2629,
4921,
3024,
203,
3639,
11272,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/80001/0xe8e3cE5c7FF5A185cc01a690F4E8c7F4Fc8eB438/sources/project_/contracts/NFTRoyalty.sol | List the NFT ANd set the royalty | function listnft(uint256 tokenid_) public {
require(msg.sender == nftinfo[tokenid_].Owner_address && msg.sender == nftinfo[tokenid_].Creator_address, "Only Owner can list his NFT");
nftinfo[tokenid_].islisted=true;
_setTokenRoyalty(tokenid_,nftinfo[tokenid_].Creator_address,nftinfo[tokenid_].nftRoyaltyPercent);
}
| 5,691,026 | [
1,
682,
326,
423,
4464,
8175,
72,
444,
326,
721,
93,
15006,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
666,
82,
1222,
12,
11890,
5034,
1147,
350,
67,
13,
1071,
288,
203,
3639,
2583,
12,
3576,
18,
15330,
422,
290,
1222,
1376,
63,
2316,
350,
67,
8009,
5541,
67,
2867,
597,
1234,
18,
15330,
422,
290,
1222,
1376,
63,
2316,
350,
67,
8009,
10636,
67,
2867,
16,
315,
3386,
16837,
848,
666,
18423,
423,
4464,
8863,
203,
3639,
290,
1222,
1376,
63,
2316,
350,
67,
8009,
291,
18647,
33,
3767,
31,
203,
3639,
389,
542,
1345,
54,
13372,
15006,
12,
2316,
350,
67,
16,
82,
1222,
1376,
63,
2316,
350,
67,
8009,
10636,
67,
2867,
16,
82,
1222,
1376,
63,
2316,
350,
67,
8009,
82,
1222,
54,
13372,
15006,
8410,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
//contracts/MyContract.sol
//SPDX-License-Identifier: Unlicense
pragma solidity >=0.8.0;
import "hardhat/console.sol";
import "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import {ILendingPool as IAaveLendingPool} from "../interfaces/ILendingPool.sol";
import {DataTypes as AaveDataTypes} from "../types/DataTypes.sol";
import {ILendingPoolAddressesProvider as IAaveLendingPoolAddressesProvider} from "../interfaces/ILendingPoolAddressesProvider.sol";
import "../interfaces/IMyContract.sol";
contract MyContract is Initializable, ContextUpgradeable, IMyContract {
IAaveLendingPool private aaveLendingPool;
// initializer function to be called, does the following:
// 1. takes aave addr provider address
// 2. use the provider to resolve lending pool addr
// 3. set the lending pool address
function initialize(address aave_addr_prvd) public initializer {
IAaveLendingPoolAddressesProvider addr_prvd = IAaveLendingPoolAddressesProvider(aave_addr_prvd);
address _aave_address = addr_prvd.getLendingPool();
_setAaveLendingPoolAddress(_aave_address);
}
// calls aave deposit
function deposit(address _erc20Contract, uint256 _amount) external override returns (bool) {
// transfer the approved token _erc20Contract, from sender to the contract address
IERC20Upgradeable(_erc20Contract).transferFrom(msg.sender, address(this), _amount);
// approve aave to transfer _erc20Contract for an amount of _amount, out from the contract address
IERC20Upgradeable(_erc20Contract).approve(address(aaveLendingPool), _amount);
// call deposit, atoken to sender
aaveLendingPool.deposit(_erc20Contract, _amount, msg.sender, 0);
return true;
}
// calls aave withdraw
function withdraw(address _erc20Contract, uint256 _amount) external override returns (uint256) {
// get the atoken address from lending pool
address aTokenAddress = aaveLendingPool.getReserveData(_erc20Contract).aTokenAddress;
// transfer the approved atoken, from sender to the contract address
IERC20Upgradeable(aTokenAddress).transferFrom(msg.sender, address(this), _amount);
// approve aave to transfer atoken for an amount of _amount, out from the contract address
IERC20Upgradeable(aTokenAddress).approve(address(aaveLendingPool), _amount);
// call withdraw, underlying token to sender
return aaveLendingPool.withdraw(_erc20Contract, _amount, msg.sender);
}
// calls aave getUserAccountData and get the total collateral in ETH
function checkCollateralValueInEth() public override view returns (uint256) {
(uint256 totalCollateralETH, , , , , ) = aaveLendingPool.getUserAccountData(msg.sender);
return totalCollateralETH;
}
// shall I expose this for the sake of transparency?
function getAaveLendingPoolAddress() public view returns (address) {
return address(aaveLendingPool);
}
// set aave lending pool address
function _setAaveLendingPoolAddress(address addr) private {
aaveLendingPool = IAaveLendingPool(addr);
}
}
| shall I expose this for the sake of transparency? | function getAaveLendingPoolAddress() public view returns (address) {
return address(aaveLendingPool);
}
| 12,558,008 | [
1,
674,
454,
467,
15722,
333,
364,
326,
272,
911,
434,
27472,
35,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
4506,
836,
48,
2846,
2864,
1887,
1435,
1071,
1476,
1135,
261,
2867,
13,
288,
203,
565,
327,
1758,
12,
69,
836,
48,
2846,
2864,
1769,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/*
Decentralized digital asset exchange. Supports any digital asset that can be represented on the Ethereum blockchain (i.e. - transferred in an Ethereum transaction or sequence of transactions).
Let us suppose two agents interacting with a distributed ledger have utility functions preferencing certain states of that ledger over others.
Aiming to maximize their utility, these agents may construct with their utility functions along with the present ledger state a mapping of state transitions (transactions) to marginal utilities.
Any composite state transition with positive marginal utility for and enactable by the combined permissions of both agents thus is a mutually desirable trade, and the trustless
code execution provided by a distributed ledger renders the requisite atomicity trivial.
Relative to this model, this instantiation makes two concessions to practicality:
- State transition preferences are not matched directly but instead intermediated by a standard of tokenized value.
- A small fee can be charged in WYV for order settlement in an amount configurable by the frontend hosting the orderbook.
Solidity presently possesses neither a first-class functional typesystem nor runtime reflection (ABI encoding in Solidity), so we must be a bit clever in implementation and work at a lower level of abstraction than would be ideal.
We elect to utilize the following structure for the initial version of the protocol:
- Buy-side and sell-side orders each provide calldatas (bytes) - for a sell-side order, the state transition for sale, for a buy-side order, the state transition to be bought.
Along with the calldatas, orders provide `replacementPattern`: a bytemask indicating which bytes of the calldatas can be changed (e.g. NFT destination address).
When a buy-side and sell-side order are matched, the desired calldatas are unified, masked with the bytemasks, and checked for agreement.
This alone is enough to implement common simple state transitions, such as "transfer my CryptoKitty to any address" or "buy any of this kind of nonfungible token".
- Orders (of either side) can optionally specify a static (no state modification) callback function, which receives configurable data along with the actual calldatas as a parameter.
Although it requires some encoding acrobatics, this allows for arbitrary transaction validation functions.
For example, a buy-sider order could express the intent to buy any CryptoKitty with a particular set of characteristics (checked in the static call),
or a sell-side order could express the intent to sell any of three ENS names, but not two others.
Use of the EVM's STATICCALL opcode, added in Ethereum Metropolis, allows the static calldatas to be safely specified separately and thus this kind of matching to happen correctly
- that is to say, wherever the two (transaction => bool) functions intersect.
Future protocol versions may improve upon this structure in capability or usability according to protocol user feedback demand, with upgrades enacted by the Wyvern DAO.
*/
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol";
import "../registry/ProxyRegistry.sol";
import "../registry/TokenTransferProxy.sol";
import "../registry/AuthenticatedProxy.sol";
import "../common/ArrayUtils.sol";
import "./SaleKindInterface.sol";
/**
* @title ExchangeCore
* @author Project Wyvern Developers
*/
contract ExchangeCore is Initializable, ReentrancyGuardUpgradeable, OwnableUpgradeable {
/* The token used to pay exchange fees. */
ERC20Upgradeable public exchangeToken;
/* User registry. */
ProxyRegistry public registry;
/* Token transfer proxy. */
TokenTransferProxy public tokenTransferProxy;
/* Cancelled / finalized orders, by hash. */
mapping(bytes32 => bool) public cancelledOrFinalized;
/* Orders verified by on-chain approval (alternative to ECDSA signatures so that smart contracts can place orders directly). */
mapping(bytes32 => bool) public approvedOrders;
/* For split fee orders, minimum required protocol maker fee, in basis points. Paid to owner (who can change it). */
uint public minimumMakerProtocolFee = 0;
/* For split fee orders, minimum required protocol taker fee, in basis points. Paid to owner (who can change it). */
uint public minimumTakerProtocolFee = 0;
/* Recipient of protocol fees. */
address public protocolFeeRecipient;
/* Dev Wallet address */
address public devWallet;
/* Fee method: protocol fee or split fee. */
enum FeeMethod { ProtocolFee, SplitFee }
/* Inverse basis point. */
uint public constant INVERSE_BASIS_POINT = 10000;
/* An ECDSA signature. */
struct Sig {
/* v parameter */
uint8 v;
/* r parameter */
bytes32 r;
/* s parameter */
bytes32 s;
}
/* An order on the exchange. */
struct Order {
/* Exchange address, intended as a versioning mechanism. */
address exchange;
/* Order maker address. */
address maker;
/* Order taker address, if specified. */
address taker;
/* Maker relayer fee of the order, unused for taker order. */
uint makerRelayerFee;
/* Taker relayer fee of the order, or maximum taker fee for a taker order. */
uint takerRelayerFee;
/* Maker protocol fee of the order, unused for taker order. */
uint makerProtocolFee;
/* Taker protocol fee of the order, or maximum taker fee for a taker order. */
uint takerProtocolFee;
/* Order fee recipient or zero address for taker order. */
address feeRecipient;
/* Fee method (protocol token or split fee). */
FeeMethod feeMethod;
/* Side (buy/sell). */
SaleKindInterface.Side side;
/* Kind of sale. */
SaleKindInterface.SaleKind saleKind;
/* Target. */
address target;
/* HowToCall. */
AuthenticatedProxy.HowToCall howToCall;
/* Calldata. */
bytes calldatas;
/* Calldata replacement pattern, or an empty byte array for no replacement. */
bytes replacementPattern;
/* Static call target, zero-address for no static call. */
address staticTarget;
/* Static call extra data. */
bytes staticExtradata;
/* Token used to pay for the order, or the zero-address as a sentinel value for Ether. */
address paymentToken;
/* Base price of the order (in paymentTokens). */
uint basePrice;
/* Auction extra parameter - minimum bid increment for English auctions, starting/ending price difference. */
uint extra;
/* Listing timestamp. */
uint listingTime;
/* Expiration timestamp - 0 for no expiry. */
uint expirationTime;
/* Order salt, used to prevent duplicate hashes. */
uint salt;
}
event OrderApprovedPartOne (bytes32 indexed hash, address exchange, address indexed maker, address taker, uint makerRelayerFee, uint takerRelayerFee, uint makerProtocolFee, uint takerProtocolFee, address indexed feeRecipient, FeeMethod feeMethod, SaleKindInterface.Side side, SaleKindInterface.SaleKind saleKind, address target);
event OrderApprovedPartTwo (bytes32 indexed hash, AuthenticatedProxy.HowToCall howToCall, bytes calldatas, bytes replacementPattern, address staticTarget, bytes staticExtradata, address paymentToken, uint basePrice, uint extra, uint listingTime, uint expirationTime, uint salt, bool orderbookInclusionDesired);
event OrderCancelled (bytes32 indexed hash);
event OrdersMatched (bytes32 buyHash, bytes32 sellHash, address indexed maker, address indexed taker, uint price, bytes32 indexed metadata);
function __ExchangeCore_init() internal onlyInitializing {
__Context_init_unchained();
__Ownable_init_unchained();
__ReentrancyGuard_init_unchained();
__ExchangeCore_init_unchained();
}
function __ExchangeCore_init_unchained() internal onlyInitializing {
}
/**
* @dev Change the minimum maker fee paid to the protocol (owner only)
* @param newMinimumMakerProtocolFee New fee to set in basis points
*/
function changeMinimumMakerProtocolFee(uint newMinimumMakerProtocolFee)
public
onlyOwner
{
minimumMakerProtocolFee = newMinimumMakerProtocolFee;
}
/**
* @dev Change the minimum taker fee paid to the protocol (owner only)
* @param newMinimumTakerProtocolFee New fee to set in basis points
*/
function changeMinimumTakerProtocolFee(uint newMinimumTakerProtocolFee)
public
onlyOwner
{
minimumTakerProtocolFee = newMinimumTakerProtocolFee;
}
/**
* @dev Change the protocol fee recipient (owner only)
* @param newProtocolFeeRecipient New protocol fee recipient address
*/
function changeProtocolFeeRecipient(address newProtocolFeeRecipient)
public
onlyOwner
{
protocolFeeRecipient = newProtocolFeeRecipient;
}
/**
* @dev Transfer tokens
* @param token Token to transfer
* @param from Address to charge fees
* @param to Address to receive fees
* @param amount Amount of protocol tokens to charge
*/
function transferTokens(address token, address from, address to, uint amount)
internal
{
if (amount > 0) {
require(tokenTransferProxy.transferFrom(token, from, to, amount));
}
}
/**
* @dev Charge a fee in protocol tokens
* @param from Address to charge fees
* @param to Address to receive fees
* @param amount Amount of protocol tokens to charge
*/
function chargeProtocolFee(address from, address to, uint amount)
internal
{
transferTokens(address(exchangeToken), from, to, amount);
}
/**
* @dev Execute a STATICCALL (introduced with Ethereum Metropolis, non-state-modifying external call)
* @param target Contract to call
* @param calldatas Calldata (appended to extradata)
* @param extradata Base data for STATICCALL (probably function selector and argument encoding)
* @return result The result of the call (success or failure)
*/
function staticCall(address target, bytes memory calldatas, bytes memory extradata)
public
view
returns (bool result)
{
bytes memory combined = new bytes(calldatas.length + extradata.length);
uint index;
assembly {
index := add(combined, 0x20)
}
index = ArrayUtils.unsafeWriteBytes(index, extradata);
ArrayUtils.unsafeWriteBytes(index, calldatas);
assembly {
result := staticcall(gas(), target, add(combined, 0x20), mload(combined), mload(0x40), 0)
}
return result;
}
/**
* Calculate size of an order struct when tightly packed
*
* @param order Order to calculate size of
* @return Size in bytes
*/
function sizeOf(Order memory order)
internal
pure
returns (uint)
{
return ((0x14 * 7) + (0x20 * 9) + 4 + order.calldatas.length + order.replacementPattern.length + order.staticExtradata.length);
}
/**
* @dev Hash an order, returning the canonical order hash, without the message prefix
* @param order Order to hash
* @return hash Hash of order
*/
function hashOrder(Order memory order)
public
pure
returns (bytes32 hash)
{
/* Unfortunately abi.encodePacked doesn't work here, stack size constraints. */
uint size = sizeOf(order);
bytes memory array = new bytes(size);
uint index;
assembly {
index := add(array, 0x20)
}
index = ArrayUtils.unsafeWriteAddress(index, order.exchange);
index = ArrayUtils.unsafeWriteAddress(index, order.maker);
index = ArrayUtils.unsafeWriteAddress(index, order.taker);
index = ArrayUtils.unsafeWriteUint(index, order.makerRelayerFee);
index = ArrayUtils.unsafeWriteUint(index, order.takerRelayerFee);
index = ArrayUtils.unsafeWriteUint(index, order.makerProtocolFee);
index = ArrayUtils.unsafeWriteUint(index, order.takerProtocolFee);
index = ArrayUtils.unsafeWriteAddress(index, order.feeRecipient);
index = ArrayUtils.unsafeWriteUint8(index, uint8(order.feeMethod));
index = ArrayUtils.unsafeWriteUint8(index, uint8(order.side));
index = ArrayUtils.unsafeWriteUint8(index, uint8(order.saleKind));
index = ArrayUtils.unsafeWriteAddress(index, order.target);
index = ArrayUtils.unsafeWriteUint8(index, uint8(order.howToCall));
index = ArrayUtils.unsafeWriteBytes(index, order.calldatas);
index = ArrayUtils.unsafeWriteBytes(index, order.replacementPattern);
index = ArrayUtils.unsafeWriteAddress(index, order.staticTarget);
index = ArrayUtils.unsafeWriteBytes(index, order.staticExtradata);
index = ArrayUtils.unsafeWriteAddress(index, order.paymentToken);
index = ArrayUtils.unsafeWriteUint(index, order.basePrice);
index = ArrayUtils.unsafeWriteUint(index, order.extra);
index = ArrayUtils.unsafeWriteUint(index, order.listingTime);
index = ArrayUtils.unsafeWriteUint(index, order.expirationTime);
index = ArrayUtils.unsafeWriteUint(index, order.salt);
assembly {
hash := keccak256(add(array, 0x20), size)
}
return hash;
}
/**
* @dev Hash an order, returning the hash that a client must sign, including the standard message prefix
* @param order Order to hash
* @return Hash of message prefix and order hash per Ethereum format
*/
function hashToSign(Order memory order)
public
pure
returns (bytes32)
{
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hashOrder(order)));
}
/**
* @dev Assert an order is valid and return its hash
* @param order Order to validate
* @param sig ECDSA signature
*/
function requireValidOrder(Order memory order, Sig memory sig)
internal
view
returns (bytes32)
{
bytes32 hash = hashToSign(order);
require(validateOrder(hash, order, sig));
return hash;
}
/**
* @dev Validate order parameters (does *not* check signature validity)
* @param order Order to validate
*/
function validateOrderParameters(Order memory order)
public
view
returns (bool)
{
/* Order must be targeted at this protocol version (this Exchange contract). */
if (order.exchange != address(this)) {
return false;
}
/* Order must possess valid sale kind parameter combination. */
if (!SaleKindInterface.validateParameters(order.saleKind, order.expirationTime)) {
return false;
}
/* If using the split fee method, order must have sufficient protocol fees. */
if (order.feeMethod == FeeMethod.SplitFee && (order.makerProtocolFee < minimumMakerProtocolFee || order.takerProtocolFee < minimumTakerProtocolFee)) {
return false;
}
return true;
}
/**
* @dev Validate a provided previously approved / signed order, hash, and signature.
* @param hash Order hash (already calculated, passed to avoid recalculation)
* @param order Order to validate
* @param sig ECDSA signature
*/
function validateOrder(bytes32 hash, Order memory order, Sig memory sig)
public
view
returns (bool)
{
/* Not done in an if-conditional to prevent unnecessary ecrecover evaluation, which seems to happen even though it should short-circuit. */
/* Order must have valid parameters. */
if (!validateOrderParameters(order)) {
return false;
}
/* Order must have not been canceled or already filled. */
if (cancelledOrFinalized[hash]) {
return false;
}
/* Order authentication. Order must be either:
/* (a) previously approved */
if (approvedOrders[hash]) {
return true;
}
/* or (b) ECDSA-signed by maker. */
if (ecrecover(hash, sig.v, sig.r, sig.s) == order.maker) {
return true;
}
return false;
}
/**
* @dev Approve an order and optionally mark it for orderbook inclusion. Must be called by the maker of the order
* @param order Order to approve
* @param orderbookInclusionDesired Whether orderbook providers should include the order in their orderbooks
*/
function approveOrder(Order memory order, bool orderbookInclusionDesired)
public
{
/* CHECKS */
/* Assert sender is authorized to approve order. */
require(msg.sender == order.maker);
/* Calculate order hash. */
bytes32 hash = hashToSign(order);
/* Assert order has not already been approved. */
require(!approvedOrders[hash]);
/* EFFECTS */
/* Mark order as approved. */
approvedOrders[hash] = true;
/* Log approval event. Must be split in two due to Solidity stack size limitations. */
{
emit OrderApprovedPartOne(hash, order.exchange, order.maker, order.taker, order.makerRelayerFee, order.takerRelayerFee, order.makerProtocolFee, order.takerProtocolFee, order.feeRecipient, order.feeMethod, order.side, order.saleKind, order.target);
}
{
emit OrderApprovedPartTwo(hash, order.howToCall, order.calldatas, order.replacementPattern, order.staticTarget, order.staticExtradata, order.paymentToken, order.basePrice, order.extra, order.listingTime, order.expirationTime, order.salt, orderbookInclusionDesired);
}
}
/**
* @dev Cancel an order, preventing it from being matched. Must be called by the maker of the order
* @param order Order to cancel
* @param sig ECDSA signature
*/
function cancelOrder(Order memory order, Sig memory sig)
public
{
/* CHECKS */
/* Calculate order hash. */
bytes32 hash = requireValidOrder(order, sig);
/* Assert sender is authorized to cancel order. */
require(msg.sender == order.maker);
/* EFFECTS */
/* Mark order as cancelled, preventing it from being matched. */
cancelledOrFinalized[hash] = true;
/* Log cancel event. */
emit OrderCancelled(hash);
}
/**
* @dev Calculate the current price of an order (convenience function)
* @param order Order to calculate the price of
* @return The current price of the order
*/
function calculateCurrentPrice (Order memory order)
public
view
returns (uint)
{
return SaleKindInterface.calculateFinalPrice(order.side, order.saleKind, order.basePrice, order.extra, order.listingTime, order.expirationTime);
}
/**
* @dev Calculate the price two orders would match at, if in fact they would match (otherwise fail)
* @param buy Buy-side order
* @param sell Sell-side order
* @return Match price
*/
function calculateMatchPrice(Order memory buy, Order memory sell)
view
public
returns (uint)
{
/* Calculate sell price. */
uint sellPrice = SaleKindInterface.calculateFinalPrice(sell.side, sell.saleKind, sell.basePrice, sell.extra, sell.listingTime, sell.expirationTime);
/* Calculate buy price. */
uint buyPrice = SaleKindInterface.calculateFinalPrice(buy.side, buy.saleKind, buy.basePrice, buy.extra, buy.listingTime, buy.expirationTime);
/* Require price cross. */
require(buyPrice >= sellPrice);
/* Maker/taker priority. */
return sell.feeRecipient != address(0) ? sellPrice : buyPrice;
}
/**
* @dev Execute all ERC20 token / Ether transfers associated with an order match (fees and buyer => seller transfer)
* @param buy Buy-side order
* @param sell Sell-side order
*/
function executeFundsTransfer(Order memory buy, Order memory sell)
internal
returns (uint)
{
/* Only payable in the special case of unwrapped Ether. */
if (sell.paymentToken != address(0)) {
require(msg.value == 0);
}
/* Calculate match price. */
uint price = calculateMatchPrice(buy, sell);
/* If paying using a token (not Ether), transfer tokens. This is done prior to fee payments to that a seller will have tokens before being charged fees. */
if (price > 0 && sell.paymentToken != address(0)) {
transferTokens(sell.paymentToken, buy.maker, sell.maker, price);
}
/* Amount that will be received by seller (for Ether). */
uint receiveAmount = price;
/* Amount that must be sent by buyer (for Ether). */
uint requiredAmount = price;
/* Determine maker/taker and charge fees accordingly. */
if (sell.feeRecipient != address(0)) {
/* Sell-side order is maker. */
/* Assert taker fee is less than or equal to maximum fee specified by buyer. */
require(sell.takerRelayerFee <= buy.takerRelayerFee);
if (sell.feeMethod == FeeMethod.SplitFee) {
/* Assert taker fee is less than or equal to maximum fee specified by buyer. */
require(sell.takerProtocolFee <= buy.takerProtocolFee);
/* Maker fees are deducted from the token amount that the maker receives. Taker fees are extra tokens that must be paid by the taker. */
if (sell.makerRelayerFee > 0) {
uint makerRelayerFee = SafeMathUpgradeable.div(SafeMathUpgradeable.mul(sell.makerRelayerFee, price), INVERSE_BASIS_POINT);
if (sell.paymentToken == address(0)) {
receiveAmount = SafeMathUpgradeable.sub(receiveAmount, makerRelayerFee);
payable(sell.feeRecipient).transfer(makerRelayerFee);
} else {
transferTokens(sell.paymentToken, sell.maker, sell.feeRecipient, makerRelayerFee);
}
}
if (sell.takerRelayerFee > 0) {
uint takerRelayerFee = SafeMathUpgradeable.div(SafeMathUpgradeable.mul(sell.takerRelayerFee, price), INVERSE_BASIS_POINT);
if (sell.paymentToken == address(0)) {
requiredAmount = SafeMathUpgradeable.add(requiredAmount, takerRelayerFee);
payable(sell.feeRecipient).transfer(takerRelayerFee);
} else {
transferTokens(sell.paymentToken, buy.maker, sell.feeRecipient, takerRelayerFee);
}
}
if (sell.makerProtocolFee > 0) {
uint makerProtocolFee = SafeMathUpgradeable.div(SafeMathUpgradeable.mul(sell.makerProtocolFee, price), INVERSE_BASIS_POINT);
if (sell.paymentToken == address(0)) {
receiveAmount = SafeMathUpgradeable.sub(receiveAmount, makerProtocolFee);
payable(protocolFeeRecipient).transfer(makerProtocolFee);
} else if (sell.paymentToken == address(exchangeToken)) {
transferExchangeTokens(sell.maker, makerProtocolFee);
} else {
transferTokens(sell.paymentToken, sell.maker, protocolFeeRecipient, makerProtocolFee);
}
}
if (sell.takerProtocolFee > 0) {
uint takerProtocolFee = SafeMathUpgradeable.div(SafeMathUpgradeable.mul(sell.takerProtocolFee, price), INVERSE_BASIS_POINT);
if (sell.paymentToken == address(0)) {
requiredAmount = SafeMathUpgradeable.add(requiredAmount, takerProtocolFee);
payable(protocolFeeRecipient).transfer(takerProtocolFee);
} else if (sell.paymentToken == address(exchangeToken)) {
transferExchangeTokens(buy.maker, takerProtocolFee);
} else {
transferTokens(sell.paymentToken, buy.maker, protocolFeeRecipient, takerProtocolFee);
}
}
} else {
/* Charge maker fee to seller. */
chargeProtocolFee(sell.maker, sell.feeRecipient, sell.makerRelayerFee);
/* Charge taker fee to buyer. */
chargeProtocolFee(buy.maker, sell.feeRecipient, sell.takerRelayerFee);
}
} else {
/* Buy-side order is maker. */
/* Assert taker fee is less than or equal to maximum fee specified by seller. */
require(buy.takerRelayerFee <= sell.takerRelayerFee);
if (sell.feeMethod == FeeMethod.SplitFee) {
/* The Exchange does not escrow Ether, so direct Ether can only be used to with sell-side maker / buy-side taker orders. */
require(sell.paymentToken != address(0));
/* Assert taker fee is less than or equal to maximum fee specified by seller. */
require(buy.takerProtocolFee <= sell.takerProtocolFee);
if (buy.makerRelayerFee > 0) {
uint256 makerRelayerFee = SafeMathUpgradeable.div(SafeMathUpgradeable.mul(buy.makerRelayerFee, price), INVERSE_BASIS_POINT);
transferTokens(sell.paymentToken, buy.maker, buy.feeRecipient, makerRelayerFee);
}
if (buy.takerRelayerFee > 0) {
uint256 takerRelayerFee = SafeMathUpgradeable.div(SafeMathUpgradeable.mul(buy.takerRelayerFee, price), INVERSE_BASIS_POINT);
transferTokens(sell.paymentToken, sell.maker, buy.feeRecipient, takerRelayerFee);
}
if (buy.makerProtocolFee > 0) {
uint256 makerProtocolFee = SafeMathUpgradeable.div(SafeMathUpgradeable.mul(buy.makerProtocolFee, price), INVERSE_BASIS_POINT);
if (sell.paymentToken == address(exchangeToken)) {
transferExchangeTokens(buy.maker, makerProtocolFee);
} else {
transferTokens(sell.paymentToken, buy.maker, protocolFeeRecipient, makerProtocolFee);
}
}
if (buy.takerProtocolFee > 0) {
uint256 takerProtocolFee = SafeMathUpgradeable.div(SafeMathUpgradeable.mul(buy.takerProtocolFee, price), INVERSE_BASIS_POINT);
if (sell.paymentToken == address(exchangeToken)) {
transferExchangeTokens(sell.maker, takerProtocolFee);
} else {
transferTokens(sell.paymentToken, sell.maker, protocolFeeRecipient, takerProtocolFee);
}
}
} else {
/* Charge maker fee to buyer. */
chargeProtocolFee(buy.maker, buy.feeRecipient, buy.makerRelayerFee);
/* Charge taker fee to seller. */
chargeProtocolFee(sell.maker, buy.feeRecipient, buy.takerRelayerFee);
}
}
if (sell.paymentToken == address(0)) {
/* Special-case Ether, order must be matched by buyer. */
require(msg.value >= requiredAmount);
payable(sell.maker).transfer(receiveAmount);
/* Allow overshoot for variable-price auctions, refund difference. */
uint diff = SafeMathUpgradeable.sub(msg.value, requiredAmount);
if (diff > 0) {
payable(buy.maker).transfer(diff);
}
}
/* This contract should never hold Ether, however, we cannot assert this, since it is impossible to prevent anyone from sending Ether e.g. with selfdestruct. */
return price;
}
/**
* @dev Return whether or not two orders can be matched with each other by basic parameters (does not check order signatures / calldatas or perform static calls)
* @param buy Buy-side order
* @param sell Sell-side order
* @return Whether or not the two orders can be matched
*/
function ordersCanMatch(Order memory buy, Order memory sell)
public
view
returns (bool)
{
return (
/* Must be opposite-side. */
(buy.side == SaleKindInterface.Side.Buy && sell.side == SaleKindInterface.Side.Sell) &&
/* Must use same fee method. */
(buy.feeMethod == sell.feeMethod) &&
/* Must use same payment token. */
(buy.paymentToken == sell.paymentToken) &&
/* Must match maker/taker addresses. */
(sell.taker == address(0) || sell.taker == buy.maker) &&
(buy.taker == address(0) || buy.taker == sell.maker) &&
/* One must be maker and the other must be taker (no bool XOR in Solidity). */
((sell.feeRecipient == address(0) && buy.feeRecipient != address(0)) || (sell.feeRecipient != address(0) && buy.feeRecipient == address(0))) &&
/* Must match target. */
(buy.target == sell.target) &&
/* Must match howToCall. */
(buy.howToCall == sell.howToCall) &&
/* Buy-side order must be settleable. */
SaleKindInterface.canSettleOrder(buy.listingTime, buy.expirationTime) &&
/* Sell-side order must be settleable. */
SaleKindInterface.canSettleOrder(sell.listingTime, sell.expirationTime)
);
}
/**
* @dev Atomically match two orders, ensuring validity of the match, and execute all associated state transitions. Protected against reentrancy by a contract-global lock.
* @param buy Buy-side order
* @param buySig Buy-side order signature
* @param sell Sell-side order
* @param sellSig Sell-side order signature
*/
function atomicMatch(Order memory buy, Sig memory buySig, Order memory sell, Sig memory sellSig, bytes32 metadata)
public
nonReentrant
{
/* CHECKS */
/* Ensure buy order validity and calculate hash if necessary. */
bytes32 buyHash;
if (buy.maker == msg.sender) {
require(validateOrderParameters(buy));
} else {
buyHash = requireValidOrder(buy, buySig);
}
/* Ensure sell order validity and calculate hash if necessary. */
bytes32 sellHash;
if (sell.maker == msg.sender) {
require(validateOrderParameters(sell));
} else {
sellHash = requireValidOrder(sell, sellSig);
}
/* Must be matchable. */
require(ordersCanMatch(buy, sell));
/* Target must exist (prevent malicious selfdestructs just prior to order settlement). */
uint size;
address target = sell.target;
assembly {
size := extcodesize(target)
}
require(size > 0);
/* Must match calldatas after replacement, if specified. */
if (buy.replacementPattern.length > 0) {
ArrayUtils.guardedArrayReplace(buy.calldatas, sell.calldatas, buy.replacementPattern);
}
if (sell.replacementPattern.length > 0) {
ArrayUtils.guardedArrayReplace(sell.calldatas, buy.calldatas, sell.replacementPattern);
}
require(ArrayUtils.arrayEq(buy.calldatas, sell.calldatas));
/* Retrieve delegateProxy contract. */
OwnableDelegateProxy delegateProxy = registry.proxies(sell.maker);
/* Proxy must exist. */
require(delegateProxy != OwnableDelegateProxy(payable(address(0))));
/* Assert implementation. */
require(delegateProxy.implementation() == registry.delegateProxyImplementation());
/* Access the passthrough AuthenticatedProxy. */
AuthenticatedProxy proxy = AuthenticatedProxy(payable(address(delegateProxy)));
/* EFFECTS */
/* Mark previously signed or approved orders as finalized. */
if (msg.sender != buy.maker) {
cancelledOrFinalized[buyHash] = true;
}
if (msg.sender != sell.maker) {
cancelledOrFinalized[sellHash] = true;
}
/* INTERACTIONS */
/* Execute funds transfer and pay fees. */
uint price = executeFundsTransfer(buy, sell);
/* Execute specified call through proxy. */
require(proxy.proxy(sell.target, sell.howToCall, sell.calldatas));
/* Static calls are intentionally done after the effectful call so they can check resulting state. */
/* Handle buy-side static call if specified. */
if (buy.staticTarget != address(0)) {
require(staticCall(buy.staticTarget, sell.calldatas, buy.staticExtradata));
}
/* Handle sell-side static call if specified. */
if (sell.staticTarget != address(0)) {
require(staticCall(sell.staticTarget, sell.calldatas, sell.staticExtradata));
}
/* Log match event. */
emit OrdersMatched(buyHash, sellHash, sell.feeRecipient != address(0) ? sell.maker : buy.maker, sell.feeRecipient != address(0) ? buy.maker : sell.maker, price, metadata);
}
/**
* @dev Transfer fees
* @param from Address to charge fees
* @param amount Amount of protocol tokens to charge
*/
function transferExchangeTokens(address from, uint amount)
internal
{
if(amount > 0) {
uint devAmount = SafeMathUpgradeable.div(SafeMathUpgradeable.mul(amount, 10), 100); //10%
uint burnAmount = devAmount;
uint remAmount = SafeMathUpgradeable.sub(SafeMathUpgradeable.sub(amount, devAmount), burnAmount); //80%
transferTokens(address(exchangeToken), from, protocolFeeRecipient, remAmount);
transferTokens(address(exchangeToken), from, devWallet, devAmount);
tokenTransferProxy.burnFrom(address(exchangeToken), from, burnAmount);
}
}
/**
* @dev Change the dev wallet (owner only)
* @param newDevWalletAddress New dev wallet address
*/
function changeDevWalletAddress(address newDevWalletAddress)
public
onlyOwner
{
devWallet = newDevWalletAddress;
}
}
| * @dev Hash an order, returning the hash that a client must sign, including the standard message prefix @param order Order to hash @return Hash of message prefix and order hash per Ethereum format/ | function hashToSign(Order memory order)
public
pure
returns (bytes32)
{
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hashOrder(order)));
}
| 1,806,884 | [
1,
2310,
392,
1353,
16,
5785,
326,
1651,
716,
279,
1004,
1297,
1573,
16,
6508,
326,
4529,
883,
1633,
225,
1353,
4347,
358,
1651,
327,
2474,
434,
883,
1633,
471,
1353,
1651,
1534,
512,
18664,
379,
740,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
1651,
774,
2766,
12,
2448,
3778,
1353,
13,
203,
3639,
1071,
203,
3639,
16618,
203,
3639,
1135,
261,
3890,
1578,
13,
203,
565,
288,
203,
3639,
327,
417,
24410,
581,
5034,
12,
21457,
18,
3015,
4420,
329,
31458,
92,
3657,
41,
18664,
379,
16724,
2350,
5581,
82,
1578,
3113,
1651,
2448,
12,
1019,
3719,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// contracts/Wrapper.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.12;
import {PartialCommonOwnership as PCO} from "./token/PartialCommonOwnership.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol";
struct WrappedToken {
/// @notice Issuing contract address.
address contractAddress;
/// @notice Underlying token ID (issued when minted).
uint256 tokenId;
/// @notice Address that wrapped the token.
address operatorAddress;
}
/// @title Wrapper
/// @author Will Holley (@will-holley)
/// @author Victor Sint Nicolaas (@vicsn)
/// @notice This contract can wrap or hold other tokens adhering to the ERC721
/// standard, and is partially common owned (see PCO).
contract Wrapper is PCO {
//////////////////////////////
/// State
//////////////////////////////
/// @notice Mapping from Wrapped Token IDs to metadata on the underlying token.
mapping(uint256 => WrappedToken) private _wrappedTokenMap;
//////////////////////////////
/// Events
//////////////////////////////
/// @notice Alert that a token has been wrapped
/// @param contractAddress See WrappedToken.contractAddress
/// @param tokenId See WrappedToken.tokenId
/// @param wrappedTokenId The Wrapped Token ID.
event LogTokenWrapped(
address contractAddress,
uint256 tokenId,
uint256 wrappedTokenId
);
//////////////////////////////
/// Public Methods
//////////////////////////////
/// @notice Takes possession of a given token, creating a "wrapped" version that complies with
/// Partial Common Ownership. The new token is returned to the owner.
/// @dev Note that `#safeTransferFrom` first requires that contract address is
/// approved by `msg.sender`.
/// @param tokenContractAddress_ Issuing contract address for token to be wrapped.
/// @param tokenId_ ID of token to be wrapped
/// @param valuation_ Self assessed valuation of the token.
/// @param beneficiary_ See `PCO._beneficiaries`.
/// @param taxRate_ See `PCO._taxNumerators`.
/// @param collectionFrequency_ See `PCO._taxPeriods`.
function wrap(
address tokenContractAddress_,
uint256 tokenId_,
uint256 valuation_,
address payable beneficiary_,
uint256 taxRate_,
uint256 collectionFrequency_
) public payable {
// Assertions
require(valuation_ > 0, "Valuation must be > 0");
require(beneficiary_ != address(0), "Beneficiary cannot be address zero");
require(taxRate_ > 0, "Tax rate must be > 0");
require(collectionFrequency_ > 0, "Tax frequency must be > 0");
IERC721 tokenContract = IERC721(tokenContractAddress_);
if (msg.sender == beneficiary_) {
// If sender is the beneficiary, ensure they did not send a deposit
require(msg.value == 0, "No deposit required");
} else {
require(msg.value > 0, "Deposit required");
}
// Transfer ownership of the token to this contract.
tokenContract.safeTransferFrom(msg.sender, address(this), tokenId_);
uint256 _wrappedTokenId = wrappedTokenId(tokenContractAddress_, tokenId_);
_wrappedTokenMap[_wrappedTokenId] = WrappedToken({
contractAddress: tokenContractAddress_,
tokenId: tokenId_,
operatorAddress: msg.sender
});
_mint(
_wrappedTokenId,
msg.sender,
msg.value,
valuation_,
beneficiary_,
taxRate_,
collectionFrequency_
);
emit LogTokenWrapped(tokenContractAddress_, tokenId_, _wrappedTokenId);
}
/// @notice Unwrap a given token. Only callable by the address that originally
/// wrapped the token. Burns the wrapped token and transfers the underlying token
/// to the last owner of the wrapped token.
/// @param tokenId_ Id of wrapped token.
function unwrap(uint256 tokenId_) public _tokenMinted(tokenId_) {
WrappedToken memory token = _wrappedTokenMap[tokenId_];
require(token.operatorAddress == msg.sender, "Wrap originator only");
// Get current owner's address prior to burning.
address owner = ownerOf(tokenId_);
// Delete wrapper state
delete _wrappedTokenMap[tokenId_];
// Burn the token
_burn(tokenId_);
// Transfer ownership of the underlying token to the current owner
IERC721 tokenContract = IERC721(token.contractAddress);
tokenContract.safeTransferFrom(address(this), owner, token.tokenId);
}
/// @notice Queries the wrapped token's URI.
/// @param tokenId_ See IERC721
/// @return Token URI string.
function tokenURI(uint256 tokenId_) public view returns (string memory) {
require(
_exists(tokenId_),
"ERC721Metadata: URI query for nonexistent token"
);
WrappedToken memory wrappedToken = _wrappedTokenMap[tokenId_];
IERC721Metadata metadata = IERC721Metadata(wrappedToken.contractAddress);
return metadata.tokenURI(wrappedToken.tokenId);
}
/// @notice Mints the wrapped token.
/// @dev Envoked by `#wrap`.
/// @param operator_ Address that initiated the token transfer.
/// @param from_ Address of the contract that issued this token.
/// @param tokenId_ Id of token received.
/// @param data_ Unused call data.
/// @return Must return its Solidity selector to confirm the token transfer.
/// Returning any other value or interface will revert the transfer.
/* solhint-disable no-unused-vars */
function onERC721Received(
address operator_,
address from_,
uint256 tokenId_,
bytes memory data_
) public view returns (bytes4) {
// Ensure that the token was not errantly sent. This ensures that the self-assesssed valuation
// and taxation information are set.
require(
operator_ == address(this),
"Tokens can only be received via #wrap"
);
return this.onERC721Received.selector;
}
/* solhint-enable no-unused-vars */
/// @notice Deterministically generates wrapped token IDs given the token's
/// contract address and ID.
/// @param contractAddress_ Issuing contract address
/// @param tokenId_ Token ID
/// @return Wrapped Token ID
function wrappedTokenId(address contractAddress_, uint256 tokenId_)
public
pure
returns (uint256)
{
return uint256(bytes32(keccak256(abi.encode(contractAddress_, tokenId_))));
}
}
| @notice Unwrap a given token. Only callable by the address that originally wrapped the token. Burns the wrapped token and transfers the underlying token to the last owner of the wrapped token. @param tokenId_ Id of wrapped token. Get current owner's address prior to burning. Delete wrapper state Burn the token Transfer ownership of the underlying token to the current owner | function unwrap(uint256 tokenId_) public _tokenMinted(tokenId_) {
WrappedToken memory token = _wrappedTokenMap[tokenId_];
require(token.operatorAddress == msg.sender, "Wrap originator only");
address owner = ownerOf(tokenId_);
delete _wrappedTokenMap[tokenId_];
_burn(tokenId_);
IERC721 tokenContract = IERC721(token.contractAddress);
tokenContract.safeTransferFrom(address(this), owner, token.tokenId);
}
| 2,464,511 | [
1,
984,
4113,
279,
864,
1147,
18,
5098,
4140,
635,
326,
1758,
716,
24000,
5805,
326,
1147,
18,
605,
321,
87,
326,
5805,
1147,
471,
29375,
326,
6808,
1147,
358,
326,
1142,
3410,
434,
326,
5805,
1147,
18,
225,
1147,
548,
67,
3124,
434,
5805,
1147,
18,
968,
783,
3410,
1807,
1758,
6432,
358,
18305,
310,
18,
2504,
4053,
919,
605,
321,
326,
1147,
12279,
23178,
434,
326,
6808,
1147,
358,
326,
783,
3410,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
11014,
12,
11890,
5034,
1147,
548,
67,
13,
1071,
389,
2316,
49,
474,
329,
12,
2316,
548,
67,
13,
288,
203,
565,
24506,
1345,
3778,
1147,
273,
389,
18704,
1345,
863,
63,
2316,
548,
67,
15533,
203,
203,
565,
2583,
12,
2316,
18,
9497,
1887,
422,
1234,
18,
15330,
16,
315,
2964,
4026,
639,
1338,
8863,
203,
203,
565,
1758,
3410,
273,
3410,
951,
12,
2316,
548,
67,
1769,
203,
203,
565,
1430,
389,
18704,
1345,
863,
63,
2316,
548,
67,
15533,
203,
203,
565,
389,
70,
321,
12,
2316,
548,
67,
1769,
203,
203,
565,
467,
654,
39,
27,
5340,
1147,
8924,
273,
467,
654,
39,
27,
5340,
12,
2316,
18,
16351,
1887,
1769,
203,
565,
1147,
8924,
18,
4626,
5912,
1265,
12,
2867,
12,
2211,
3631,
3410,
16,
1147,
18,
2316,
548,
1769,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
* SPDX-License-Identifier: UNLICENSED
*/
pragma solidity =0.6.10;
pragma experimental ABIEncoderV2;
// File: contracts/packages/oz/upgradeability/Initializable.sol
/**
* @title Initializable
*
* @dev Helper contract to support initializer functions. To use it, replace
* the constructor with a function that has the `initializer` modifier.
* WARNING: Unlike constructors, initializer functions must be manually
* invoked. This applies both to deploying an Initializable contract, as well
* as extending an Initializable contract via inheritance.
* WARNING: When used with inheritance, manual care must be taken to not invoke
* a parent initializer twice, or ensure that all initializers are idempotent,
* because this is not dealt with automatically as with constructors.
*/
contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private initializing;
/**
* @dev Modifier to use in the initializer function of a contract.
*/
modifier initializer() {
require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized");
bool isTopLevelCall = !initializing;
if (isTopLevelCall) {
initializing = true;
initialized = true;
}
_;
if (isTopLevelCall) {
initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
assembly {
cs := extcodesize(self)
}
return cs == 0;
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
// File: contracts/packages/oz/upgradeability/GSN/ContextUpgradeable.sol
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {}
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
// File: contracts/packages/oz/upgradeability/OwnableUpgradeSafe.sol
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract OwnableUpgradeSafe is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init(address _sender) internal initializer {
__Context_init_unchained();
__Ownable_init_unchained(_sender);
}
function __Ownable_init_unchained(address _sender) internal initializer {
_owner = _sender;
emit OwnershipTransferred(address(0), _sender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[49] private __gap;
}
// File: contracts/packages/oz/upgradeability/ReentrancyGuardUpgradeSafe.sol
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
contract ReentrancyGuardUpgradeSafe is Initializable {
bool private _notEntered;
function __ReentrancyGuard_init() internal initializer {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal initializer {
// Storing an initial non-zero value makes deployment a bit more
// expensive, but in exchange the refund on every call to nonReentrant
// will be lower in amount. Since refunds are capped to a percetange of
// the total transaction's gas, it is best to keep them low in cases
// like this one, to increase the likelihood of the full refund coming
// into effect.
_notEntered = true;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_notEntered, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_notEntered = false;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_notEntered = true;
}
uint256[49] private __gap;
}
// File: contracts/packages/oz/SafeMath.sol
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: contracts/libs/MarginVault.sol
/**
* MarginVault Error Codes
* V1: invalid short otoken amount
* V2: invalid short otoken index
* V3: short otoken address mismatch
* V4: invalid long otoken amount
* V5: invalid long otoken index
* V6: long otoken address mismatch
* V7: invalid collateral amount
* V8: invalid collateral token index
* V9: collateral token address mismatch
*/
/**
* @title MarginVault
* @author Opyn Team
* @notice A library that provides the Controller with a Vault struct and the functions that manipulate vaults.
* Vaults describe discrete position combinations of long options, short options, and collateral assets that a user can have.
*/
library MarginVault {
using SafeMath for uint256;
// vault is a struct of 6 arrays that describe a position a user has, a user can have multiple vaults.
struct Vault {
// addresses of oTokens a user has shorted (i.e. written) against this vault
address[] shortOtokens;
// addresses of oTokens a user has bought and deposited in this vault
// user can be long oTokens without opening a vault (e.g. by buying on a DEX)
// generally, long oTokens will be 'deposited' in vaults to act as collateral in order to write oTokens against (i.e. in spreads)
address[] longOtokens;
// addresses of other ERC-20s a user has deposited as collateral in this vault
address[] collateralAssets;
// quantity of oTokens minted/written for each oToken address in shortOtokens
uint256[] shortAmounts;
// quantity of oTokens owned and held in the vault for each oToken address in longOtokens
uint256[] longAmounts;
// quantity of ERC-20 deposited as collateral in the vault for each ERC-20 address in collateralAssets
uint256[] collateralAmounts;
}
/**
* @dev increase the short oToken balance in a vault when a new oToken is minted
* @param _vault vault to add or increase the short position in
* @param _shortOtoken address of the _shortOtoken being minted from the user's vault
* @param _amount number of _shortOtoken being minted from the user's vault
* @param _index index of _shortOtoken in the user's vault.shortOtokens array
*/
function addShort(
Vault storage _vault,
address _shortOtoken,
uint256 _amount,
uint256 _index
) external {
require(_amount > 0, "V1");
// valid indexes in any array are between 0 and array.length - 1.
// if adding an amount to an preexisting short oToken, check that _index is in the range of 0->length-1
if ((_index == _vault.shortOtokens.length) && (_index == _vault.shortAmounts.length)) {
_vault.shortOtokens.push(_shortOtoken);
_vault.shortAmounts.push(_amount);
} else {
require((_index < _vault.shortOtokens.length) && (_index < _vault.shortAmounts.length), "V2");
address existingShort = _vault.shortOtokens[_index];
require((existingShort == _shortOtoken) || (existingShort == address(0)), "V3");
_vault.shortAmounts[_index] = _vault.shortAmounts[_index].add(_amount);
_vault.shortOtokens[_index] = _shortOtoken;
}
}
/**
* @dev decrease the short oToken balance in a vault when an oToken is burned
* @param _vault vault to decrease short position in
* @param _shortOtoken address of the _shortOtoken being reduced in the user's vault
* @param _amount number of _shortOtoken being reduced in the user's vault
* @param _index index of _shortOtoken in the user's vault.shortOtokens array
*/
function removeShort(
Vault storage _vault,
address _shortOtoken,
uint256 _amount,
uint256 _index
) external {
// check that the removed short oToken exists in the vault at the specified index
require(_index < _vault.shortOtokens.length, "V2");
require(_vault.shortOtokens[_index] == _shortOtoken, "V3");
uint256 newShortAmount = _vault.shortAmounts[_index].sub(_amount);
if (newShortAmount == 0) {
delete _vault.shortOtokens[_index];
}
_vault.shortAmounts[_index] = newShortAmount;
}
/**
* @dev increase the long oToken balance in a vault when an oToken is deposited
* @param _vault vault to add a long position to
* @param _longOtoken address of the _longOtoken being added to the user's vault
* @param _amount number of _longOtoken the protocol is adding to the user's vault
* @param _index index of _longOtoken in the user's vault.longOtokens array
*/
function addLong(
Vault storage _vault,
address _longOtoken,
uint256 _amount,
uint256 _index
) external {
require(_amount > 0, "V4");
// valid indexes in any array are between 0 and array.length - 1.
// if adding an amount to an preexisting short oToken, check that _index is in the range of 0->length-1
if ((_index == _vault.longOtokens.length) && (_index == _vault.longAmounts.length)) {
_vault.longOtokens.push(_longOtoken);
_vault.longAmounts.push(_amount);
} else {
require((_index < _vault.longOtokens.length) && (_index < _vault.longAmounts.length), "V5");
address existingLong = _vault.longOtokens[_index];
require((existingLong == _longOtoken) || (existingLong == address(0)), "V6");
_vault.longAmounts[_index] = _vault.longAmounts[_index].add(_amount);
_vault.longOtokens[_index] = _longOtoken;
}
}
/**
* @dev decrease the long oToken balance in a vault when an oToken is withdrawn
* @param _vault vault to remove a long position from
* @param _longOtoken address of the _longOtoken being removed from the user's vault
* @param _amount number of _longOtoken the protocol is removing from the user's vault
* @param _index index of _longOtoken in the user's vault.longOtokens array
*/
function removeLong(
Vault storage _vault,
address _longOtoken,
uint256 _amount,
uint256 _index
) external {
// check that the removed long oToken exists in the vault at the specified index
require(_index < _vault.longOtokens.length, "V5");
require(_vault.longOtokens[_index] == _longOtoken, "V6");
uint256 newLongAmount = _vault.longAmounts[_index].sub(_amount);
if (newLongAmount == 0) {
delete _vault.longOtokens[_index];
}
_vault.longAmounts[_index] = newLongAmount;
}
/**
* @dev increase the collateral balance in a vault
* @param _vault vault to add collateral to
* @param _collateralAsset address of the _collateralAsset being added to the user's vault
* @param _amount number of _collateralAsset being added to the user's vault
* @param _index index of _collateralAsset in the user's vault.collateralAssets array
*/
function addCollateral(
Vault storage _vault,
address _collateralAsset,
uint256 _amount,
uint256 _index
) external {
require(_amount > 0, "V7");
// valid indexes in any array are between 0 and array.length - 1.
// if adding an amount to an preexisting short oToken, check that _index is in the range of 0->length-1
if ((_index == _vault.collateralAssets.length) && (_index == _vault.collateralAmounts.length)) {
_vault.collateralAssets.push(_collateralAsset);
_vault.collateralAmounts.push(_amount);
} else {
require((_index < _vault.collateralAssets.length) && (_index < _vault.collateralAmounts.length), "V8");
address existingCollateral = _vault.collateralAssets[_index];
require((existingCollateral == _collateralAsset) || (existingCollateral == address(0)), "V9");
_vault.collateralAmounts[_index] = _vault.collateralAmounts[_index].add(_amount);
_vault.collateralAssets[_index] = _collateralAsset;
}
}
/**
* @dev decrease the collateral balance in a vault
* @param _vault vault to remove collateral from
* @param _collateralAsset address of the _collateralAsset being removed from the user's vault
* @param _amount number of _collateralAsset being removed from the user's vault
* @param _index index of _collateralAsset in the user's vault.collateralAssets array
*/
function removeCollateral(
Vault storage _vault,
address _collateralAsset,
uint256 _amount,
uint256 _index
) external {
// check that the removed collateral exists in the vault at the specified index
require(_index < _vault.collateralAssets.length, "V8");
require(_vault.collateralAssets[_index] == _collateralAsset, "V9");
uint256 newCollateralAmount = _vault.collateralAmounts[_index].sub(_amount);
if (newCollateralAmount == 0) {
delete _vault.collateralAssets[_index];
}
_vault.collateralAmounts[_index] = newCollateralAmount;
}
}
// File: contracts/libs/Actions.sol
/**
* @title Actions
* @author Opyn Team
* @notice A library that provides a ActionArgs struct, sub types of Action structs, and functions to parse ActionArgs into specific Actions.
* errorCode
* A1 can only parse arguments for open vault actions
* A2 cannot open vault for an invalid account
* A3 cannot open vault with an invalid type
* A4 can only parse arguments for mint actions
* A5 cannot mint from an invalid account
* A6 can only parse arguments for burn actions
* A7 cannot burn from an invalid account
* A8 can only parse arguments for deposit actions
* A9 cannot deposit to an invalid account
* A10 can only parse arguments for withdraw actions
* A11 cannot withdraw from an invalid account
* A12 cannot withdraw to an invalid account
* A13 can only parse arguments for redeem actions
* A14 cannot redeem to an invalid account
* A15 can only parse arguments for settle vault actions
* A16 cannot settle vault for an invalid account
* A17 cannot withdraw payout to an invalid account
* A18 can only parse arguments for liquidate action
* A19 cannot liquidate vault for an invalid account owner
* A20 cannot send collateral to an invalid account
* A21 cannot parse liquidate action with no round id
* A22 can only parse arguments for call actions
* A23 target address cannot be address(0)
*/
library Actions {
// possible actions that can be performed
enum ActionType {
OpenVault,
MintShortOption,
BurnShortOption,
DepositLongOption,
WithdrawLongOption,
DepositCollateral,
WithdrawCollateral,
SettleVault,
Redeem,
Call,
Liquidate
}
struct ActionArgs {
// type of action that is being performed on the system
ActionType actionType;
// address of the account owner
address owner;
// address which we move assets from or to (depending on the action type)
address secondAddress;
// asset that is to be transfered
address asset;
// index of the vault that is to be modified (if any)
uint256 vaultId;
// amount of asset that is to be transfered
uint256 amount;
// each vault can hold multiple short / long / collateral assets but we are restricting the scope to only 1 of each in this version
// in future versions this would be the index of the short / long / collateral asset that needs to be modified
uint256 index;
// any other data that needs to be passed in for arbitrary function calls
bytes data;
}
struct MintArgs {
// address of the account owner
address owner;
// index of the vault from which the asset will be minted
uint256 vaultId;
// address to which we transfer the minted oTokens
address to;
// oToken that is to be minted
address otoken;
// each vault can hold multiple short / long / collateral assets but we are restricting the scope to only 1 of each in this version
// in future versions this would be the index of the short / long / collateral asset that needs to be modified
uint256 index;
// amount of oTokens that is to be minted
uint256 amount;
}
struct BurnArgs {
// address of the account owner
address owner;
// index of the vault from which the oToken will be burned
uint256 vaultId;
// address from which we transfer the oTokens
address from;
// oToken that is to be burned
address otoken;
// each vault can hold multiple short / long / collateral assets but we are restricting the scope to only 1 of each in this version
// in future versions this would be the index of the short / long / collateral asset that needs to be modified
uint256 index;
// amount of oTokens that is to be burned
uint256 amount;
}
struct OpenVaultArgs {
// address of the account owner
address owner;
// vault id to create
uint256 vaultId;
// vault type, 0 for spread/max loss and 1 for naked margin vault
uint256 vaultType;
}
struct DepositArgs {
// address of the account owner
address owner;
// index of the vault to which the asset will be added
uint256 vaultId;
// address from which we transfer the asset
address from;
// asset that is to be deposited
address asset;
// each vault can hold multiple short / long / collateral assets but we are restricting the scope to only 1 of each in this version
// in future versions this would be the index of the short / long / collateral asset that needs to be modified
uint256 index;
// amount of asset that is to be deposited
uint256 amount;
}
struct RedeemArgs {
// address to which we pay out the oToken proceeds
address receiver;
// oToken that is to be redeemed
address otoken;
// amount of oTokens that is to be redeemed
uint256 amount;
}
struct WithdrawArgs {
// address of the account owner
address owner;
// index of the vault from which the asset will be withdrawn
uint256 vaultId;
// address to which we transfer the asset
address to;
// asset that is to be withdrawn
address asset;
// each vault can hold multiple short / long / collateral assets but we are restricting the scope to only 1 of each in this version
// in future versions this would be the index of the short / long / collateral asset that needs to be modified
uint256 index;
// amount of asset that is to be withdrawn
uint256 amount;
}
struct SettleVaultArgs {
// address of the account owner
address owner;
// index of the vault to which is to be settled
uint256 vaultId;
// address to which we transfer the remaining collateral
address to;
}
struct LiquidateArgs {
// address of the vault owner to liquidate
address owner;
// address of the liquidated collateral receiver
address receiver;
// vault id to liquidate
uint256 vaultId;
// amount of debt(otoken) to repay
uint256 amount;
// chainlink round id
uint256 roundId;
}
struct CallArgs {
// address of the callee contract
address callee;
// data field for external calls
bytes data;
}
/**
* @notice parses the passed in action arguments to get the arguments for an open vault action
* @param _args general action arguments structure
* @return arguments for a open vault action
*/
function _parseOpenVaultArgs(ActionArgs memory _args) internal pure returns (OpenVaultArgs memory) {
require(_args.actionType == ActionType.OpenVault, "A1");
require(_args.owner != address(0), "A2");
// if not _args.data included, vault type will be 0 by default
uint256 vaultType;
if (_args.data.length == 32) {
// decode vault type from _args.data
vaultType = abi.decode(_args.data, (uint256));
}
// for now we only have 2 vault types
require(vaultType < 2, "A3");
return OpenVaultArgs({owner: _args.owner, vaultId: _args.vaultId, vaultType: vaultType});
}
/**
* @notice parses the passed in action arguments to get the arguments for a mint action
* @param _args general action arguments structure
* @return arguments for a mint action
*/
function _parseMintArgs(ActionArgs memory _args) internal pure returns (MintArgs memory) {
require(_args.actionType == ActionType.MintShortOption, "A4");
require(_args.owner != address(0), "A5");
return
MintArgs({
owner: _args.owner,
vaultId: _args.vaultId,
to: _args.secondAddress,
otoken: _args.asset,
index: _args.index,
amount: _args.amount
});
}
/**
* @notice parses the passed in action arguments to get the arguments for a burn action
* @param _args general action arguments structure
* @return arguments for a burn action
*/
function _parseBurnArgs(ActionArgs memory _args) internal pure returns (BurnArgs memory) {
require(_args.actionType == ActionType.BurnShortOption, "A6");
require(_args.owner != address(0), "A7");
return
BurnArgs({
owner: _args.owner,
vaultId: _args.vaultId,
from: _args.secondAddress,
otoken: _args.asset,
index: _args.index,
amount: _args.amount
});
}
/**
* @notice parses the passed in action arguments to get the arguments for a deposit action
* @param _args general action arguments structure
* @return arguments for a deposit action
*/
function _parseDepositArgs(ActionArgs memory _args) internal pure returns (DepositArgs memory) {
require(
(_args.actionType == ActionType.DepositLongOption) || (_args.actionType == ActionType.DepositCollateral),
"A8"
);
require(_args.owner != address(0), "A9");
return
DepositArgs({
owner: _args.owner,
vaultId: _args.vaultId,
from: _args.secondAddress,
asset: _args.asset,
index: _args.index,
amount: _args.amount
});
}
/**
* @notice parses the passed in action arguments to get the arguments for a withdraw action
* @param _args general action arguments structure
* @return arguments for a withdraw action
*/
function _parseWithdrawArgs(ActionArgs memory _args) internal pure returns (WithdrawArgs memory) {
require(
(_args.actionType == ActionType.WithdrawLongOption) || (_args.actionType == ActionType.WithdrawCollateral),
"A10"
);
require(_args.owner != address(0), "A11");
require(_args.secondAddress != address(0), "A12");
return
WithdrawArgs({
owner: _args.owner,
vaultId: _args.vaultId,
to: _args.secondAddress,
asset: _args.asset,
index: _args.index,
amount: _args.amount
});
}
/**
* @notice parses the passed in action arguments to get the arguments for an redeem action
* @param _args general action arguments structure
* @return arguments for a redeem action
*/
function _parseRedeemArgs(ActionArgs memory _args) internal pure returns (RedeemArgs memory) {
require(_args.actionType == ActionType.Redeem, "A13");
require(_args.secondAddress != address(0), "A14");
return RedeemArgs({receiver: _args.secondAddress, otoken: _args.asset, amount: _args.amount});
}
/**
* @notice parses the passed in action arguments to get the arguments for a settle vault action
* @param _args general action arguments structure
* @return arguments for a settle vault action
*/
function _parseSettleVaultArgs(ActionArgs memory _args) internal pure returns (SettleVaultArgs memory) {
require(_args.actionType == ActionType.SettleVault, "A15");
require(_args.owner != address(0), "A16");
require(_args.secondAddress != address(0), "A17");
return SettleVaultArgs({owner: _args.owner, vaultId: _args.vaultId, to: _args.secondAddress});
}
function _parseLiquidateArgs(ActionArgs memory _args) internal pure returns (LiquidateArgs memory) {
require(_args.actionType == ActionType.Liquidate, "A18");
require(_args.owner != address(0), "A19");
require(_args.secondAddress != address(0), "A20");
require(_args.data.length == 32, "A21");
// decode chainlink round id from _args.data
uint256 roundId = abi.decode(_args.data, (uint256));
return
LiquidateArgs({
owner: _args.owner,
receiver: _args.secondAddress,
vaultId: _args.vaultId,
amount: _args.amount,
roundId: roundId
});
}
/**
* @notice parses the passed in action arguments to get the arguments for a call action
* @param _args general action arguments structure
* @return arguments for a call action
*/
function _parseCallArgs(ActionArgs memory _args) internal pure returns (CallArgs memory) {
require(_args.actionType == ActionType.Call, "A22");
require(_args.secondAddress != address(0), "A23");
return CallArgs({callee: _args.secondAddress, data: _args.data});
}
}
// File: contracts/interfaces/AddressBookInterface.sol
interface AddressBookInterface {
/* Getters */
function getOtokenImpl() external view returns (address);
function getOtokenFactory() external view returns (address);
function getWhitelist() external view returns (address);
function getController() external view returns (address);
function getOracle() external view returns (address);
function getMarginPool() external view returns (address);
function getMarginCalculator() external view returns (address);
function getLiquidationManager() external view returns (address);
function getAddress(bytes32 _id) external view returns (address);
/* Setters */
function setOtokenImpl(address _otokenImpl) external;
function setOtokenFactory(address _factory) external;
function setOracleImpl(address _otokenImpl) external;
function setWhitelist(address _whitelist) external;
function setController(address _controller) external;
function setMarginPool(address _marginPool) external;
function setMarginCalculator(address _calculator) external;
function setLiquidationManager(address _liquidationManager) external;
function setAddress(bytes32 _id, address _newImpl) external;
}
// File: contracts/interfaces/OtokenInterface.sol
interface OtokenInterface {
function addressBook() external view returns (address);
function underlyingAsset() external view returns (address);
function strikeAsset() external view returns (address);
function collateralAsset() external view returns (address);
function strikePrice() external view returns (uint256);
function expiryTimestamp() external view returns (uint256);
function isPut() external view returns (bool);
function init(
address _addressBook,
address _underlyingAsset,
address _strikeAsset,
address _collateralAsset,
uint256 _strikePrice,
uint256 _expiry,
bool _isPut
) external;
function getOtokenDetails()
external
view
returns (
address,
address,
address,
uint256,
uint256,
bool
);
function mintOtoken(address account, uint256 amount) external;
function burnOtoken(address account, uint256 amount) external;
}
// File: contracts/interfaces/MarginCalculatorInterface.sol
interface MarginCalculatorInterface {
function addressBook() external view returns (address);
function getExpiredPayoutRate(address _otoken) external view returns (uint256);
function getExcessCollateral(MarginVault.Vault calldata _vault, uint256 _vaultType)
external
view
returns (uint256 netValue, bool isExcess);
function isLiquidatable(
MarginVault.Vault memory _vault,
uint256 _vaultType,
uint256 _vaultLatestUpdate,
uint256 _roundId
)
external
view
returns (
bool,
uint256,
uint256
);
}
// File: contracts/interfaces/OracleInterface.sol
interface OracleInterface {
function isLockingPeriodOver(address _asset, uint256 _expiryTimestamp) external view returns (bool);
function isDisputePeriodOver(address _asset, uint256 _expiryTimestamp) external view returns (bool);
function getExpiryPrice(address _asset, uint256 _expiryTimestamp) external view returns (uint256, bool);
function getDisputer() external view returns (address);
function getPricer(address _asset) external view returns (address);
function getPrice(address _asset) external view returns (uint256);
function getPricerLockingPeriod(address _pricer) external view returns (uint256);
function getPricerDisputePeriod(address _pricer) external view returns (uint256);
function getChainlinkRoundData(address _asset, uint80 _roundId) external view returns (uint256, uint256);
// Non-view function
function setAssetPricer(address _asset, address _pricer) external;
function setLockingPeriod(address _pricer, uint256 _lockingPeriod) external;
function setDisputePeriod(address _pricer, uint256 _disputePeriod) external;
function setExpiryPrice(
address _asset,
uint256 _expiryTimestamp,
uint256 _price
) external;
function disputeExpiryPrice(
address _asset,
uint256 _expiryTimestamp,
uint256 _price
) external;
function setDisputer(address _disputer) external;
}
// File: contracts/interfaces/WhitelistInterface.sol
interface WhitelistInterface {
/* View functions */
function addressBook() external view returns (address);
function isWhitelistedProduct(
address _underlying,
address _strike,
address _collateral,
bool _isPut
) external view returns (bool);
function isWhitelistedCollateral(address _collateral) external view returns (bool);
function isWhitelistedOtoken(address _otoken) external view returns (bool);
function isWhitelistedCallee(address _callee) external view returns (bool);
/* Admin / factory only functions */
function whitelistProduct(
address _underlying,
address _strike,
address _collateral,
bool _isPut
) external;
function blacklistProduct(
address _underlying,
address _strike,
address _collateral,
bool _isPut
) external;
function whitelistCollateral(address _collateral) external;
function blacklistCollateral(address _collateral) external;
function whitelistOtoken(address _otoken) external;
function blacklistOtoken(address _otoken) external;
function whitelistCallee(address _callee) external;
function blacklistCallee(address _callee) external;
}
// File: contracts/interfaces/MarginPoolInterface.sol
interface MarginPoolInterface {
/* Getters */
function addressBook() external view returns (address);
function farmer() external view returns (address);
function getStoredBalance(address _asset) external view returns (uint256);
/* Admin-only functions */
function setFarmer(address _farmer) external;
function farm(
address _asset,
address _receiver,
uint256 _amount
) external;
/* Controller-only functions */
function transferToPool(
address _asset,
address _user,
uint256 _amount
) external;
function transferToUser(
address _asset,
address _user,
uint256 _amount
) external;
function batchTransferToPool(
address[] calldata _asset,
address[] calldata _user,
uint256[] calldata _amount
) external;
function batchTransferToUser(
address[] calldata _asset,
address[] calldata _user,
uint256[] calldata _amount
) external;
}
// File: contracts/interfaces/CalleeInterface.sol
/**
* @dev Contract interface that can be called from Controller as a call action.
*/
interface CalleeInterface {
/**
* Allows users to send this contract arbitrary data.
* @param _sender The msg.sender to Controller
* @param _data Arbitrary data given by the sender
*/
function callFunction(address payable _sender, bytes memory _data) external;
}
// File: contracts/core/Controller.sol
/**
* Controller Error Codes
* C1: sender is not full pauser
* C2: sender is not partial pauser
* C3: callee is not a whitelisted address
* C4: system is partially paused
* C5: system is fully paused
* C6: msg.sender is not authorized to run action
* C7: invalid addressbook address
* C8: invalid owner address
* C9: invalid input
* C10: fullPauser cannot be set to address zero
* C11: partialPauser cannot be set to address zero
* C12: can not run actions for different owners
* C13: can not run actions on different vaults
* C14: invalid final vault state
* C15: can not run actions on inexistent vault
* C16: cannot deposit long otoken from this address
* C17: otoken is not whitelisted to be used as collateral
* C18: otoken used as collateral is already expired
* C19: can not withdraw an expired otoken
* C20: cannot deposit collateral from this address
* C21: asset is not whitelisted to be used as collateral
* C22: can not withdraw collateral from a vault with an expired short otoken
* C23: otoken is not whitelisted to be minted
* C24: can not mint expired otoken
* C25: cannot burn from this address
* C26: can not burn expired otoken
* C27: otoken is not whitelisted to be redeemed
* C28: can not redeem un-expired otoken
* C29: asset prices not finalized yet
* C30: can't settle vault with no otoken
* C31: can not settle vault with un-expired otoken
* C32: can not settle undercollateralized vault
* C33: can not liquidate vault
* C34: can not leave less than collateral dust
* C35: invalid vault id
* C36: cap amount should be greater than zero
* C37: collateral exceed naked margin cap
*/
/**
* @title Controller
* @author Opyn Team
* @notice Contract that controls the Gamma Protocol and the interaction of all sub contracts
*/
contract Controller is Initializable, OwnableUpgradeSafe, ReentrancyGuardUpgradeSafe {
using MarginVault for MarginVault.Vault;
using SafeMath for uint256;
AddressBookInterface public addressbook;
WhitelistInterface public whitelist;
OracleInterface public oracle;
MarginCalculatorInterface public calculator;
MarginPoolInterface public pool;
///@dev scale used in MarginCalculator
uint256 internal constant BASE = 8;
/// @notice address that has permission to partially pause the system, where system functionality is paused
/// except redeem and settleVault
address public partialPauser;
/// @notice address that has permission to fully pause the system, where all system functionality is paused
address public fullPauser;
/// @notice True if all system functionality is paused other than redeem and settle vault
bool public systemPartiallyPaused;
/// @notice True if all system functionality is paused
bool public systemFullyPaused;
/// @notice True if a call action can only be executed to a whitelisted callee
bool public callRestricted;
/// @dev mapping between an owner address and the number of owner address vaults
mapping(address => uint256) internal accountVaultCounter;
/// @dev mapping between an owner address and a specific vault using a vault id
mapping(address => mapping(uint256 => MarginVault.Vault)) internal vaults;
/// @dev mapping between an account owner and their approved or unapproved account operators
mapping(address => mapping(address => bool)) internal operators;
/******************************************************************** V2.0.0 storage upgrade ******************************************************/
/// @dev mapping to map vault by each vault type, naked margin vault should be set to 1, spread/max loss vault should be set to 0
mapping(address => mapping(uint256 => uint256)) internal vaultType;
/// @dev mapping to store the timestamp at which the vault was last updated, will be updated in every action that changes the vault state or when calling sync()
mapping(address => mapping(uint256 => uint256)) internal vaultLatestUpdate;
/// @dev mapping to store cap amount for naked margin vault per options collateral asset (scaled by collateral asset decimals)
mapping(address => uint256) internal nakedCap;
/// @dev mapping to store amount of naked margin vaults in pool
mapping(address => uint256) internal nakedPoolBalance;
/// @notice emits an event when an account operator is updated for a specific account owner
event AccountOperatorUpdated(address indexed accountOwner, address indexed operator, bool isSet);
/// @notice emits an event when a new vault is opened
event VaultOpened(address indexed accountOwner, uint256 vaultId, uint256 indexed vaultType);
/// @notice emits an event when a long oToken is deposited into a vault
event LongOtokenDeposited(
address indexed otoken,
address indexed accountOwner,
address indexed from,
uint256 vaultId,
uint256 amount
);
/// @notice emits an event when a long oToken is withdrawn from a vault
event LongOtokenWithdrawed(
address indexed otoken,
address indexed AccountOwner,
address indexed to,
uint256 vaultId,
uint256 amount
);
/// @notice emits an event when a collateral asset is deposited into a vault
event CollateralAssetDeposited(
address indexed asset,
address indexed accountOwner,
address indexed from,
uint256 vaultId,
uint256 amount
);
/// @notice emits an event when a collateral asset is withdrawn from a vault
event CollateralAssetWithdrawed(
address indexed asset,
address indexed AccountOwner,
address indexed to,
uint256 vaultId,
uint256 amount
);
/// @notice emits an event when a short oToken is minted from a vault
event ShortOtokenMinted(
address indexed otoken,
address indexed AccountOwner,
address indexed to,
uint256 vaultId,
uint256 amount
);
/// @notice emits an event when a short oToken is burned
event ShortOtokenBurned(
address indexed otoken,
address indexed AccountOwner,
address indexed from,
uint256 vaultId,
uint256 amount
);
/// @notice emits an event when an oToken is redeemed
event Redeem(
address indexed otoken,
address indexed redeemer,
address indexed receiver,
address collateralAsset,
uint256 otokenBurned,
uint256 payout
);
/// @notice emits an event when a vault is settled
event VaultSettled(
address indexed accountOwner,
address indexed oTokenAddress,
address to,
uint256 payout,
uint256 vaultId,
uint256 indexed vaultType
);
/// @notice emits an event when a vault is liquidated
event VaultLiquidated(
address indexed liquidator,
address indexed receiver,
address indexed vaultOwner,
uint256 auctionPrice,
uint256 auctionStartingRound,
uint256 collateralPayout,
uint256 debtAmount,
uint256 vaultId
);
/// @notice emits an event when a call action is executed
event CallExecuted(address indexed from, address indexed to, bytes data);
/// @notice emits an event when the fullPauser address changes
event FullPauserUpdated(address indexed oldFullPauser, address indexed newFullPauser);
/// @notice emits an event when the partialPauser address changes
event PartialPauserUpdated(address indexed oldPartialPauser, address indexed newPartialPauser);
/// @notice emits an event when the system partial paused status changes
event SystemPartiallyPaused(bool isPaused);
/// @notice emits an event when the system fully paused status changes
event SystemFullyPaused(bool isPaused);
/// @notice emits an event when the call action restriction changes
event CallRestricted(bool isRestricted);
/// @notice emits an event when a donation transfer executed
event Donated(address indexed donator, address indexed asset, uint256 amount);
/// @notice emits an event when naked cap is updated
event NakedCapUpdated(address indexed collateral, uint256 cap);
/**
* @notice modifier to check if the system is not partially paused, where only redeem and settleVault is allowed
*/
modifier notPartiallyPaused() {
_isNotPartiallyPaused();
_;
}
/**
* @notice modifier to check if the system is not fully paused, where no functionality is allowed
*/
modifier notFullyPaused() {
_isNotFullyPaused();
_;
}
/**
* @notice modifier to check if sender is the fullPauser address
*/
modifier onlyFullPauser() {
require(msg.sender == fullPauser, "C1");
_;
}
/**
* @notice modifier to check if the sender is the partialPauser address
*/
modifier onlyPartialPauser() {
require(msg.sender == partialPauser, "C2");
_;
}
/**
* @notice modifier to check if the sender is the account owner or an approved account operator
* @param _sender sender address
* @param _accountOwner account owner address
*/
modifier onlyAuthorized(address _sender, address _accountOwner) {
_isAuthorized(_sender, _accountOwner);
_;
}
/**
* @notice modifier to check if the called address is a whitelisted callee address
* @param _callee called address
*/
modifier onlyWhitelistedCallee(address _callee) {
if (callRestricted) {
require(_isCalleeWhitelisted(_callee), "C3");
}
_;
}
/**
* @dev check if the system is not in a partiallyPaused state
*/
function _isNotPartiallyPaused() internal view {
require(!systemPartiallyPaused, "C4");
}
/**
* @dev check if the system is not in an fullyPaused state
*/
function _isNotFullyPaused() internal view {
require(!systemFullyPaused, "C5");
}
/**
* @dev check if the sender is an authorized operator
* @param _sender msg.sender
* @param _accountOwner owner of a vault
*/
function _isAuthorized(address _sender, address _accountOwner) internal view {
require((_sender == _accountOwner) || (operators[_accountOwner][_sender]), "C6");
}
/**
* @notice initalize the deployed contract
* @param _addressBook addressbook module
* @param _owner account owner address
*/
function initialize(address _addressBook, address _owner) external initializer {
require(_addressBook != address(0), "C7");
require(_owner != address(0), "C8");
__Ownable_init(_owner);
__ReentrancyGuard_init_unchained();
addressbook = AddressBookInterface(_addressBook);
_refreshConfigInternal();
callRestricted = true;
}
/**
* @notice send asset amount to margin pool
* @dev use donate() instead of direct transfer() to store the balance in assetBalance
* @param _asset asset address
* @param _amount amount to donate to pool
*/
function donate(address _asset, uint256 _amount) external {
pool.transferToPool(_asset, msg.sender, _amount);
emit Donated(msg.sender, _asset, _amount);
}
/**
* @notice allows the partialPauser to toggle the systemPartiallyPaused variable and partially pause or partially unpause the system
* @dev can only be called by the partialPauser
* @param _partiallyPaused new boolean value to set systemPartiallyPaused to
*/
function setSystemPartiallyPaused(bool _partiallyPaused) external onlyPartialPauser {
require(systemPartiallyPaused != _partiallyPaused, "C9");
systemPartiallyPaused = _partiallyPaused;
emit SystemPartiallyPaused(systemPartiallyPaused);
}
/**
* @notice allows the fullPauser to toggle the systemFullyPaused variable and fully pause or fully unpause the system
* @dev can only be called by the fullyPauser
* @param _fullyPaused new boolean value to set systemFullyPaused to
*/
function setSystemFullyPaused(bool _fullyPaused) external onlyFullPauser {
require(systemFullyPaused != _fullyPaused, "C9");
systemFullyPaused = _fullyPaused;
emit SystemFullyPaused(systemFullyPaused);
}
/**
* @notice allows the owner to set the fullPauser address
* @dev can only be called by the owner
* @param _fullPauser new fullPauser address
*/
function setFullPauser(address _fullPauser) external onlyOwner {
require(_fullPauser != address(0), "C10");
require(fullPauser != _fullPauser, "C9");
emit FullPauserUpdated(fullPauser, _fullPauser);
fullPauser = _fullPauser;
}
/**
* @notice allows the owner to set the partialPauser address
* @dev can only be called by the owner
* @param _partialPauser new partialPauser address
*/
function setPartialPauser(address _partialPauser) external onlyOwner {
require(_partialPauser != address(0), "C11");
require(partialPauser != _partialPauser, "C9");
emit PartialPauserUpdated(partialPauser, _partialPauser);
partialPauser = _partialPauser;
}
/**
* @notice allows the owner to toggle the restriction on whitelisted call actions and only allow whitelisted
* call addresses or allow any arbitrary call addresses
* @dev can only be called by the owner
* @param _isRestricted new call restriction state
*/
function setCallRestriction(bool _isRestricted) external onlyOwner {
require(callRestricted != _isRestricted, "C9");
callRestricted = _isRestricted;
emit CallRestricted(callRestricted);
}
/**
* @notice allows a user to give or revoke privileges to an operator which can act on their behalf on their vaults
* @dev can only be updated by the vault owner
* @param _operator operator that the sender wants to give privileges to or revoke them from
* @param _isOperator new boolean value that expresses if the sender is giving or revoking privileges for _operator
*/
function setOperator(address _operator, bool _isOperator) external {
require(operators[msg.sender][_operator] != _isOperator, "C9");
operators[msg.sender][_operator] = _isOperator;
emit AccountOperatorUpdated(msg.sender, _operator, _isOperator);
}
/**
* @dev updates the configuration of the controller. can only be called by the owner
*/
function refreshConfiguration() external onlyOwner {
_refreshConfigInternal();
}
/**
* @notice set cap amount for collateral asset used in naked margin
* @dev can only be called by owner
* @param _collateral collateral asset address
* @param _cap cap amount, should be scaled by collateral asset decimals
*/
function setNakedCap(address _collateral, uint256 _cap) external onlyOwner {
require(_cap > 0, "C36");
nakedCap[_collateral] = _cap;
emit NakedCapUpdated(_collateral, _cap);
}
/**
* @notice execute a number of actions on specific vaults
* @dev can only be called when the system is not fully paused
* @param _actions array of actions arguments
*/
function operate(Actions.ActionArgs[] memory _actions) external nonReentrant notFullyPaused {
(bool vaultUpdated, address vaultOwner, uint256 vaultId) = _runActions(_actions);
if (vaultUpdated) {
_verifyFinalState(vaultOwner, vaultId);
vaultLatestUpdate[vaultOwner][vaultId] = now;
}
}
/**
* @notice sync vault latest update timestamp
* @dev anyone can update the latest time the vault was touched by calling this function
* vaultLatestUpdate will sync if the vault is well collateralized
* @param _owner vault owner address
* @param _vaultId vault id
*/
function sync(address _owner, uint256 _vaultId) external nonReentrant notFullyPaused {
_verifyFinalState(_owner, _vaultId);
vaultLatestUpdate[_owner][_vaultId] = now;
}
/**
* @notice check if a specific address is an operator for an owner account
* @param _owner account owner address
* @param _operator account operator address
* @return True if the _operator is an approved operator for the _owner account
*/
function isOperator(address _owner, address _operator) external view returns (bool) {
return operators[_owner][_operator];
}
/**
* @notice returns the current controller configuration
* @return whitelist, the address of the whitelist module
* @return oracle, the address of the oracle module
* @return calculator, the address of the calculator module
* @return pool, the address of the pool module
*/
function getConfiguration()
external
view
returns (
address,
address,
address,
address
)
{
return (address(whitelist), address(oracle), address(calculator), address(pool));
}
/**
* @notice return a vault's proceeds pre or post expiry, the amount of collateral that can be removed from a vault
* @param _owner account owner of the vault
* @param _vaultId vaultId to return balances for
* @return amount of collateral that can be taken out
*/
function getProceed(address _owner, uint256 _vaultId) external view returns (uint256) {
(MarginVault.Vault memory vault, uint256 typeVault, ) = getVaultWithDetails(_owner, _vaultId);
(uint256 netValue, bool isExcess) = calculator.getExcessCollateral(vault, typeVault);
if (!isExcess) return 0;
return netValue;
}
/**
* @notice check if a vault is liquidatable in a specific round id
* @param _owner vault owner address
* @param _vaultId vault id to check
* @param _roundId chainlink round id to check vault status at
* @return isUnderCollat, true if vault is undercollateralized, the price of 1 repaid otoken and the otoken collateral dust amount
*/
function isLiquidatable(
address _owner,
uint256 _vaultId,
uint256 _roundId
)
external
view
returns (
bool,
uint256,
uint256
)
{
(, bool isUnderCollat, uint256 price, uint256 dust) = _isLiquidatable(_owner, _vaultId, _roundId);
return (isUnderCollat, price, dust);
}
/**
* @notice get an oToken's payout/cash value after expiry, in the collateral asset
* @param _otoken oToken address
* @param _amount amount of the oToken to calculate the payout for, always represented in 1e8
* @return amount of collateral to pay out
*/
function getPayout(address _otoken, uint256 _amount) public view returns (uint256) {
return calculator.getExpiredPayoutRate(_otoken).mul(_amount).div(10**BASE);
}
/**
* @dev return if an expired oToken is ready to be settled, only true when price for underlying,
* strike and collateral assets at this specific expiry is available in our Oracle module
* @param _otoken oToken
*/
function isSettlementAllowed(address _otoken) external view returns (bool) {
(address underlying, address strike, address collateral, uint256 expiry) = _getOtokenDetails(_otoken);
return _canSettleAssets(underlying, strike, collateral, expiry);
}
/**
* @dev return if underlying, strike, collateral are all allowed to be settled
* @param _underlying oToken underlying asset
* @param _strike oToken strike asset
* @param _collateral oToken collateral asset
* @param _expiry otoken expiry timestamp
* @return True if the oToken has expired AND all oracle prices at the expiry timestamp have been finalized, False if not
*/
function canSettleAssets(
address _underlying,
address _strike,
address _collateral,
uint256 _expiry
) external view returns (bool) {
return _canSettleAssets(_underlying, _strike, _collateral, _expiry);
}
/**
* @notice get the number of vaults for a specified account owner
* @param _accountOwner account owner address
* @return number of vaults
*/
function getAccountVaultCounter(address _accountOwner) external view returns (uint256) {
return accountVaultCounter[_accountOwner];
}
/**
* @notice check if an oToken has expired
* @param _otoken oToken address
* @return True if the otoken has expired, False if not
*/
function hasExpired(address _otoken) external view returns (bool) {
return now >= OtokenInterface(_otoken).expiryTimestamp();
}
/**
* @notice return a specific vault
* @param _owner account owner
* @param _vaultId vault id of vault to return
* @return Vault struct that corresponds to the _vaultId of _owner
*/
function getVault(address _owner, uint256 _vaultId) external view returns (MarginVault.Vault memory) {
return (vaults[_owner][_vaultId]);
}
/**
* @notice return a specific vault
* @param _owner account owner
* @param _vaultId vault id of vault to return
* @return Vault struct that corresponds to the _vaultId of _owner, vault type and the latest timestamp when the vault was updated
*/
function getVaultWithDetails(address _owner, uint256 _vaultId)
public
view
returns (
MarginVault.Vault memory,
uint256,
uint256
)
{
return (vaults[_owner][_vaultId], vaultType[_owner][_vaultId], vaultLatestUpdate[_owner][_vaultId]);
}
/**
* @notice get cap amount for collateral asset
* @param _asset collateral asset address
* @return cap amount
*/
function getNakedCap(address _asset) external view returns (uint256) {
return nakedCap[_asset];
}
/**
* @notice get amount of collateral deposited in all naked margin vaults
* @param _asset collateral asset address
* @return naked pool balance
*/
function getNakedPoolBalance(address _asset) external view returns (uint256) {
return nakedPoolBalance[_asset];
}
/**
* @notice execute a variety of actions
* @dev for each action in the action array, execute the corresponding action, only one vault can be modified
* for all actions except SettleVault, Redeem, and Call
* @param _actions array of type Actions.ActionArgs[], which expresses which actions the user wants to execute
* @return vaultUpdated, indicates if a vault has changed
* @return owner, the vault owner if a vault has changed
* @return vaultId, the vault Id if a vault has changed
*/
function _runActions(Actions.ActionArgs[] memory _actions)
internal
returns (
bool,
address,
uint256
)
{
address vaultOwner;
uint256 vaultId;
bool vaultUpdated;
for (uint256 i = 0; i < _actions.length; i++) {
Actions.ActionArgs memory action = _actions[i];
Actions.ActionType actionType = action.actionType;
// actions except Settle, Redeem, Liquidate and Call are "Vault-updating actinos"
// only allow update 1 vault in each operate call
if (
(actionType != Actions.ActionType.SettleVault) &&
(actionType != Actions.ActionType.Redeem) &&
(actionType != Actions.ActionType.Liquidate) &&
(actionType != Actions.ActionType.Call)
) {
// check if this action is manipulating the same vault as all other actions, if a vault has already been updated
if (vaultUpdated) {
require(vaultOwner == action.owner, "C12");
require(vaultId == action.vaultId, "C13");
}
vaultUpdated = true;
vaultId = action.vaultId;
vaultOwner = action.owner;
}
if (actionType == Actions.ActionType.OpenVault) {
_openVault(Actions._parseOpenVaultArgs(action));
} else if (actionType == Actions.ActionType.DepositLongOption) {
_depositLong(Actions._parseDepositArgs(action));
} else if (actionType == Actions.ActionType.WithdrawLongOption) {
_withdrawLong(Actions._parseWithdrawArgs(action));
} else if (actionType == Actions.ActionType.DepositCollateral) {
_depositCollateral(Actions._parseDepositArgs(action));
} else if (actionType == Actions.ActionType.WithdrawCollateral) {
_withdrawCollateral(Actions._parseWithdrawArgs(action));
} else if (actionType == Actions.ActionType.MintShortOption) {
_mintOtoken(Actions._parseMintArgs(action));
} else if (actionType == Actions.ActionType.BurnShortOption) {
_burnOtoken(Actions._parseBurnArgs(action));
} else if (actionType == Actions.ActionType.Redeem) {
_redeem(Actions._parseRedeemArgs(action));
} else if (actionType == Actions.ActionType.SettleVault) {
_settleVault(Actions._parseSettleVaultArgs(action));
} else if (actionType == Actions.ActionType.Liquidate) {
_liquidate(Actions._parseLiquidateArgs(action));
} else if (actionType == Actions.ActionType.Call) {
_call(Actions._parseCallArgs(action));
}
}
return (vaultUpdated, vaultOwner, vaultId);
}
/**
* @notice verify the vault final state after executing all actions
* @param _owner account owner address
* @param _vaultId vault id of the final vault
*/
function _verifyFinalState(address _owner, uint256 _vaultId) internal view {
(MarginVault.Vault memory vault, uint256 typeVault, ) = getVaultWithDetails(_owner, _vaultId);
(, bool isValidVault) = calculator.getExcessCollateral(vault, typeVault);
require(isValidVault, "C14");
}
/**
* @notice open a new vault inside an account
* @dev only the account owner or operator can open a vault, cannot be called when system is partiallyPaused or fullyPaused
* @param _args OpenVaultArgs structure
*/
function _openVault(Actions.OpenVaultArgs memory _args)
internal
notPartiallyPaused
onlyAuthorized(msg.sender, _args.owner)
{
uint256 vaultId = accountVaultCounter[_args.owner].add(1);
require(_args.vaultId == vaultId, "C15");
// store new vault
accountVaultCounter[_args.owner] = vaultId;
vaultType[_args.owner][vaultId] = _args.vaultType;
emit VaultOpened(_args.owner, vaultId, _args.vaultType);
}
/**
* @notice deposit a long oToken into a vault
* @dev only the account owner or operator can deposit a long oToken, cannot be called when system is partiallyPaused or fullyPaused
* @param _args DepositArgs structure
*/
function _depositLong(Actions.DepositArgs memory _args)
internal
notPartiallyPaused
onlyAuthorized(msg.sender, _args.owner)
{
require(_checkVaultId(_args.owner, _args.vaultId), "C35");
// only allow vault owner or vault operator to deposit long otoken
require((_args.from == msg.sender) || (_args.from == _args.owner), "C16");
require(whitelist.isWhitelistedOtoken(_args.asset), "C17");
OtokenInterface otoken = OtokenInterface(_args.asset);
require(now < otoken.expiryTimestamp(), "C18");
vaults[_args.owner][_args.vaultId].addLong(_args.asset, _args.amount, _args.index);
pool.transferToPool(_args.asset, _args.from, _args.amount);
emit LongOtokenDeposited(_args.asset, _args.owner, _args.from, _args.vaultId, _args.amount);
}
/**
* @notice withdraw a long oToken from a vault
* @dev only the account owner or operator can withdraw a long oToken, cannot be called when system is partiallyPaused or fullyPaused
* @param _args WithdrawArgs structure
*/
function _withdrawLong(Actions.WithdrawArgs memory _args)
internal
notPartiallyPaused
onlyAuthorized(msg.sender, _args.owner)
{
require(_checkVaultId(_args.owner, _args.vaultId), "C35");
OtokenInterface otoken = OtokenInterface(_args.asset);
require(now < otoken.expiryTimestamp(), "C19");
vaults[_args.owner][_args.vaultId].removeLong(_args.asset, _args.amount, _args.index);
pool.transferToUser(_args.asset, _args.to, _args.amount);
emit LongOtokenWithdrawed(_args.asset, _args.owner, _args.to, _args.vaultId, _args.amount);
}
/**
* @notice deposit a collateral asset into a vault
* @dev only the account owner or operator can deposit collateral, cannot be called when system is partiallyPaused or fullyPaused
* @param _args DepositArgs structure
*/
function _depositCollateral(Actions.DepositArgs memory _args)
internal
notPartiallyPaused
onlyAuthorized(msg.sender, _args.owner)
{
require(_checkVaultId(_args.owner, _args.vaultId), "C35");
// only allow vault owner or vault operator to deposit collateral
require((_args.from == msg.sender) || (_args.from == _args.owner), "C20");
require(whitelist.isWhitelistedCollateral(_args.asset), "C21");
(, uint256 typeVault, ) = getVaultWithDetails(_args.owner, _args.vaultId);
if (typeVault == 1) {
nakedPoolBalance[_args.asset] = nakedPoolBalance[_args.asset].add(_args.amount);
require(nakedPoolBalance[_args.asset] <= nakedCap[_args.asset], "C37");
}
vaults[_args.owner][_args.vaultId].addCollateral(_args.asset, _args.amount, _args.index);
pool.transferToPool(_args.asset, _args.from, _args.amount);
emit CollateralAssetDeposited(_args.asset, _args.owner, _args.from, _args.vaultId, _args.amount);
}
/**
* @notice withdraw a collateral asset from a vault
* @dev only the account owner or operator can withdraw collateral, cannot be called when system is partiallyPaused or fullyPaused
* @param _args WithdrawArgs structure
*/
function _withdrawCollateral(Actions.WithdrawArgs memory _args)
internal
notPartiallyPaused
onlyAuthorized(msg.sender, _args.owner)
{
require(_checkVaultId(_args.owner, _args.vaultId), "C35");
(MarginVault.Vault memory vault, uint256 typeVault, ) = getVaultWithDetails(_args.owner, _args.vaultId);
if (_isNotEmpty(vault.shortOtokens)) {
OtokenInterface otoken = OtokenInterface(vault.shortOtokens[0]);
require(now < otoken.expiryTimestamp(), "C22");
}
if (typeVault == 1) {
nakedPoolBalance[_args.asset] = nakedPoolBalance[_args.asset].sub(_args.amount);
}
vaults[_args.owner][_args.vaultId].removeCollateral(_args.asset, _args.amount, _args.index);
pool.transferToUser(_args.asset, _args.to, _args.amount);
emit CollateralAssetWithdrawed(_args.asset, _args.owner, _args.to, _args.vaultId, _args.amount);
}
/**
* @notice mint short oTokens from a vault which creates an obligation that is recorded in the vault
* @dev only the account owner or operator can mint an oToken, cannot be called when system is partiallyPaused or fullyPaused
* @param _args MintArgs structure
*/
function _mintOtoken(Actions.MintArgs memory _args)
internal
notPartiallyPaused
onlyAuthorized(msg.sender, _args.owner)
{
require(_checkVaultId(_args.owner, _args.vaultId), "C35");
require(whitelist.isWhitelistedOtoken(_args.otoken), "C23");
OtokenInterface otoken = OtokenInterface(_args.otoken);
require(now < otoken.expiryTimestamp(), "C24");
vaults[_args.owner][_args.vaultId].addShort(_args.otoken, _args.amount, _args.index);
otoken.mintOtoken(_args.to, _args.amount);
emit ShortOtokenMinted(_args.otoken, _args.owner, _args.to, _args.vaultId, _args.amount);
}
/**
* @notice burn oTokens to reduce or remove the minted oToken obligation recorded in a vault
* @dev only the account owner or operator can burn an oToken, cannot be called when system is partiallyPaused or fullyPaused
* @param _args MintArgs structure
*/
function _burnOtoken(Actions.BurnArgs memory _args)
internal
notPartiallyPaused
onlyAuthorized(msg.sender, _args.owner)
{
// check that vault id is valid for this vault owner
require(_checkVaultId(_args.owner, _args.vaultId), "C35");
// only allow vault owner or vault operator to burn otoken
require((_args.from == msg.sender) || (_args.from == _args.owner), "C25");
OtokenInterface otoken = OtokenInterface(_args.otoken);
// do not allow burning expired otoken
require(now < otoken.expiryTimestamp(), "C26");
// remove otoken from vault
vaults[_args.owner][_args.vaultId].removeShort(_args.otoken, _args.amount, _args.index);
// burn otoken
otoken.burnOtoken(_args.from, _args.amount);
emit ShortOtokenBurned(_args.otoken, _args.owner, _args.from, _args.vaultId, _args.amount);
}
/**
* @notice redeem an oToken after expiry, receiving the payout of the oToken in the collateral asset
* @dev cannot be called when system is fullyPaused
* @param _args RedeemArgs structure
*/
function _redeem(Actions.RedeemArgs memory _args) internal {
OtokenInterface otoken = OtokenInterface(_args.otoken);
// check that otoken to redeem is whitelisted
require(whitelist.isWhitelistedOtoken(_args.otoken), "C27");
(address collateral, address underlying, address strike, uint256 expiry) = _getOtokenDetails(address(otoken));
// only allow redeeming expired otoken
require(now >= expiry, "C28");
require(_canSettleAssets(underlying, strike, collateral, expiry), "C29");
uint256 payout = getPayout(_args.otoken, _args.amount);
otoken.burnOtoken(msg.sender, _args.amount);
pool.transferToUser(collateral, _args.receiver, payout);
emit Redeem(_args.otoken, msg.sender, _args.receiver, collateral, _args.amount, payout);
}
/**
* @notice settle a vault after expiry, removing the net proceeds/collateral after both long and short oToken payouts have settled
* @dev deletes a vault of vaultId after net proceeds/collateral is removed, cannot be called when system is fullyPaused
* @param _args SettleVaultArgs structure
*/
function _settleVault(Actions.SettleVaultArgs memory _args) internal onlyAuthorized(msg.sender, _args.owner) {
require(_checkVaultId(_args.owner, _args.vaultId), "C35");
(MarginVault.Vault memory vault, uint256 typeVault, ) = getVaultWithDetails(_args.owner, _args.vaultId);
OtokenInterface otoken;
// new scope to avoid stack too deep error
// check if there is short or long otoken in vault
// do not allow settling vault that have no short or long otoken
// if there is a long otoken, burn it
// store otoken address outside of this scope
{
bool hasShort = _isNotEmpty(vault.shortOtokens);
bool hasLong = _isNotEmpty(vault.longOtokens);
require(hasShort || hasLong, "C30");
otoken = hasShort ? OtokenInterface(vault.shortOtokens[0]) : OtokenInterface(vault.longOtokens[0]);
if (hasLong) {
OtokenInterface longOtoken = OtokenInterface(vault.longOtokens[0]);
longOtoken.burnOtoken(address(pool), vault.longAmounts[0]);
}
}
(address collateral, address underlying, address strike, uint256 expiry) = _getOtokenDetails(address(otoken));
// do not allow settling vault with un-expired otoken
require(now >= expiry, "C31");
require(_canSettleAssets(underlying, strike, collateral, expiry), "C29");
(uint256 payout, bool isValidVault) = calculator.getExcessCollateral(vault, typeVault);
// require that vault is valid (has excess collateral) before settling
// to avoid allowing settling undercollateralized naked margin vault
require(isValidVault, "C32");
delete vaults[_args.owner][_args.vaultId];
if (typeVault == 1) {
nakedPoolBalance[collateral] = nakedPoolBalance[collateral].sub(payout);
}
pool.transferToUser(collateral, _args.to, payout);
uint256 vaultId = _args.vaultId;
address payoutRecipient = _args.to;
emit VaultSettled(_args.owner, address(otoken), payoutRecipient, payout, vaultId, typeVault);
}
/**
* @notice liquidate naked margin vault
* @dev can liquidate different vaults id in the same operate() call
* @param _args liquidation action arguments struct
*/
function _liquidate(Actions.LiquidateArgs memory _args) internal notPartiallyPaused {
require(_checkVaultId(_args.owner, _args.vaultId), "C35");
// check if vault is undercollateralized
// the price is the amount of collateral asset to pay per 1 repaid debt(otoken)
// collateralDust is the minimum amount of collateral that can be left in the vault when a partial liquidation occurs
(MarginVault.Vault memory vault, bool isUnderCollat, uint256 price, uint256 collateralDust) = _isLiquidatable(
_args.owner,
_args.vaultId,
_args.roundId
);
require(isUnderCollat, "C33");
// amount of collateral to offer to liquidator
uint256 collateralToSell = _args.amount.mul(price).div(1e8);
// if vault is partially liquidated (amount of short otoken is still greater than zero)
// make sure remaining collateral amount is greater than dust amount
if (vault.shortAmounts[0].sub(_args.amount) > 0) {
require(vault.collateralAmounts[0].sub(collateralToSell) >= collateralDust, "C34");
}
// burn short otoken from liquidator address, index of short otoken hardcoded at 0
// this should always work, if vault have no short otoken, it will not reach this step
OtokenInterface(vault.shortOtokens[0]).burnOtoken(msg.sender, _args.amount);
// decrease amount of collateral in liquidated vault, index of collateral to decrease is hardcoded at 0
vaults[_args.owner][_args.vaultId].removeCollateral(vault.collateralAssets[0], collateralToSell, 0);
// decrease amount of short otoken in liquidated vault, index of short otoken to decrease is hardcoded at 0
vaults[_args.owner][_args.vaultId].removeShort(vault.shortOtokens[0], _args.amount, 0);
// decrease internal naked margin collateral amount
nakedPoolBalance[vault.collateralAssets[0]] = nakedPoolBalance[vault.collateralAssets[0]].sub(collateralToSell);
pool.transferToUser(vault.collateralAssets[0], _args.receiver, collateralToSell);
emit VaultLiquidated(
msg.sender,
_args.receiver,
_args.owner,
price,
_args.roundId,
collateralToSell,
_args.amount,
_args.vaultId
);
}
/**
* @notice execute arbitrary calls
* @dev cannot be called when system is partiallyPaused or fullyPaused
* @param _args Call action
*/
function _call(Actions.CallArgs memory _args) internal notPartiallyPaused onlyWhitelistedCallee(_args.callee) {
CalleeInterface(_args.callee).callFunction(msg.sender, _args.data);
emit CallExecuted(msg.sender, _args.callee, _args.data);
}
/**
* @notice check if a vault id is valid for a given account owner address
* @param _accountOwner account owner address
* @param _vaultId vault id to check
* @return True if the _vaultId is valid, False if not
*/
function _checkVaultId(address _accountOwner, uint256 _vaultId) internal view returns (bool) {
return ((_vaultId > 0) && (_vaultId <= accountVaultCounter[_accountOwner]));
}
function _isNotEmpty(address[] memory _array) internal pure returns (bool) {
return (_array.length > 0) && (_array[0] != address(0));
}
/**
* @notice return if a callee address is whitelisted or not
* @param _callee callee address
* @return True if callee address is whitelisted, False if not
*/
function _isCalleeWhitelisted(address _callee) internal view returns (bool) {
return whitelist.isWhitelistedCallee(_callee);
}
/**
* @notice check if a vault is liquidatable in a specific round id
* @param _owner vault owner address
* @param _vaultId vault id to check
* @param _roundId chainlink round id to check vault status at
* @return vault struct, isLiquidatable, true if vault is undercollateralized, the price of 1 repaid otoken and the otoken collateral dust amount
*/
function _isLiquidatable(
address _owner,
uint256 _vaultId,
uint256 _roundId
)
internal
view
returns (
MarginVault.Vault memory,
bool,
uint256,
uint256
)
{
(MarginVault.Vault memory vault, uint256 typeVault, uint256 latestUpdateTimestamp) = getVaultWithDetails(
_owner,
_vaultId
);
(bool isUnderCollat, uint256 price, uint256 collateralDust) = calculator.isLiquidatable(
vault,
typeVault,
latestUpdateTimestamp,
_roundId
);
return (vault, isUnderCollat, price, collateralDust);
}
/**
* @dev get otoken detail, from both otoken versions
*/
function _getOtokenDetails(address _otoken)
internal
view
returns (
address,
address,
address,
uint256
)
{
OtokenInterface otoken = OtokenInterface(_otoken);
try otoken.getOtokenDetails() returns (
address collateral,
address underlying,
address strike,
uint256,
uint256 expiry,
bool
) {
return (collateral, underlying, strike, expiry);
} catch {
return (otoken.collateralAsset(), otoken.underlyingAsset(), otoken.strikeAsset(), otoken.expiryTimestamp());
}
}
/**
* @dev return if an expired oToken is ready to be settled, only true when price for underlying,
* strike and collateral assets at this specific expiry is available in our Oracle module
* @return True if the oToken has expired AND all oracle prices at the expiry timestamp have been finalized, False if not
*/
function _canSettleAssets(
address _underlying,
address _strike,
address _collateral,
uint256 _expiry
) internal view returns (bool) {
return
oracle.isDisputePeriodOver(_underlying, _expiry) &&
oracle.isDisputePeriodOver(_strike, _expiry) &&
oracle.isDisputePeriodOver(_collateral, _expiry);
}
/**
* @dev updates the internal configuration of the controller
*/
function _refreshConfigInternal() internal {
whitelist = WhitelistInterface(addressbook.getWhitelist());
oracle = OracleInterface(addressbook.getOracle());
calculator = MarginCalculatorInterface(addressbook.getMarginCalculator());
pool = MarginPoolInterface(addressbook.getMarginPool());
}
} | * @notice modifier to check if sender is the fullPauser address/ | modifier onlyFullPauser() {
require(msg.sender == fullPauser, "C1");
_;
}
| 6,146,066 | [
1,
20597,
358,
866,
309,
5793,
353,
326,
1983,
16507,
1355,
1758,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
9606,
1338,
5080,
16507,
1355,
1435,
288,
203,
3639,
2583,
12,
3576,
18,
15330,
422,
1983,
16507,
1355,
16,
315,
39,
21,
8863,
203,
203,
3639,
389,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.25;
import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol";
contract FlightSuretyData {
using SafeMath for uint256;
/********************************************************************************************/
/* DATA VARIABLES */
/********************************************************************************************/
address private contractOwner; // Account used to deploy contract
bool private operational = true; // Blocks all state changes throughout the contract if false
mapping (address => bool) private flightSuretyApps;
struct Flight {
bool isRegistered;
uint8 statusCode;
uint256 updatedTimestamp;
address airline;
uint256 credits;
address[] buyerAddresses;
mapping (address => uint256) buyers;
}
mapping(bytes32 => Flight) private flights;
mapping(address => uint256) private passengerCredits;
struct Airline {
bool funded;
bool registered;
}
mapping(address => Airline) private airlines;
uint public totAirlines;
/********************************************************************************************/
/* EVENT DEFINITIONS */
/********************************************************************************************/
event RegisteredAirline(address airline);
event CreditAvailable(address passenger, uint256 amount);
/**
* @dev Constructor
* The deploying account becomes contractOwner
*/
constructor (address _genesysAirline ) public
{
contractOwner = msg.sender;
airlines[_genesysAirline] = Airline(false, true);
totAirlines=1;
}
/********************************************************************************************/
/* FUNCTION MODIFIERS */
/********************************************************************************************/
// Modifiers help avoid duplication of code. They are typically used to validate something
// before a function is allowed to be executed.
/**
* @dev Modifier that requires the "operational" boolean variable to be "true"
* This is used on all state changing functions to pause the contract in
* the event there is an issue that needs to be fixed
*/
modifier requireIsOperational()
{
require(operational, "Contract is currently not operational");
_; // All modifiers require an "_" which indicates where the function body will be added
}
/**
* @dev Modifier that requires the "ContractOwner" account to be the function caller
*/
modifier requireContractOwner()
{
require(msg.sender == contractOwner, "Caller is not contract owner");
_;
}
/**
* @dev Modifier that requires the consumer application is registered
*/
modifier requireAppRegistered()
{
require(flightSuretyApps[msg.sender], "Caller is not contract owner");
_;
}
/********************************************************************************************/
/* UTILITY FUNCTIONS */
/********************************************************************************************/
/**
* @dev Get operating status of contract
*
* @return A bool that is the current operating status
*/
function isOperational()
public
view
returns(bool)
{
return operational;
}
/**
* @dev Sets contract operations on/off
*
* When operational mode is disabled, all write transactions except for this one will fail
*/
function setOperatingStatus ( bool mode ) public requireContractOwner
{
operational = mode;
}
/**
* @dev Sets contract operations on/off
*
* When operational mode is disabled, all write transactions except for this one will fail
*/
function authorizeCaller ( address _consumerApp ) external requireContractOwner {
flightSuretyApps[_consumerApp] = true;
}
/**
* @dev Sets contract operations on/off
*
* When operational mode is disabled, all write transactions except for this one will fail
*/
function deAuthorizeCaller ( address _consumerApp ) external requireContractOwner {
flightSuretyApps[_consumerApp] = false;
}
/********************************************************************************************/
/* SMART CONTRACT FUNCTIONS */
/********************************************************************************************/
/**
* @dev Add an airline to the registration queue
* Can only be called from FlightSuretyApp contract
*
*/
function registerAirline (address _airline ) external requireIsOperational requireAppRegistered {
airlines[_airline] = Airline(false, true);
totAirlines++;
emit RegisteredAirline(_airline);
}
function isRegisteredAirline (address _airline ) external view returns (bool){
return airlines[_airline].registered;
}
function isFundedAirline (address _airline ) external view returns (bool){
return airlines[_airline].funded;
}
/**
* @dev Buy insurance for a flight
*
*/
function buy(bytes32 _flightNumber, address _passenger, uint256 _amount ) external
{
require(flights[_flightNumber].isRegistered, "Flight unknown");
require(flights[_flightNumber].statusCode == 0, "Flight has taken off");
require(!(flights[_flightNumber].buyers[_passenger] > 0), "Passenger already bought insurance for this flight");
flights[_flightNumber].buyers[_passenger] = _amount;
flights[_flightNumber].buyerAddresses.push(_passenger);
flights[_flightNumber].credits = flights[_flightNumber].credits.add((_amount.mul(15)).div(10));
}
/**
* @dev Credits payouts to insurees
*/
function creditInsurees(bytes32 _flightNumber) external requireIsOperational() requireAppRegistered returns(uint256) {
require(flights[_flightNumber].isRegistered, "Flight unknown");
require(flights[_flightNumber].statusCode == 20, 'That flight was not late!');
require(flights[_flightNumber].credits > 0, 'Insurees already credited');
for(uint256 c = 0; c < flights[_flightNumber].buyerAddresses.length; c++) {
uint256 credit = (flights[_flightNumber].buyers[flights[_flightNumber].buyerAddresses[c]].mul(15)).div(10);
flights[_flightNumber].credits = flights[_flightNumber].credits.sub(credit);
passengerCredits[flights[_flightNumber].buyerAddresses[c]] = passengerCredits[flights[_flightNumber].buyerAddresses[c]].add(credit);
emit CreditAvailable(flights[_flightNumber].buyerAddresses[c], credit);
}
}
/**
* @dev Allow insurees to avoid bougth insurance getting back funds
*
*/
function withDraw(bytes32 _flightNumber, address _passenger) external requireIsOperational() requireAppRegistered
{
require(flights[_flightNumber].isRegistered, "Flight unknown");
require(flights[_flightNumber].statusCode == 0, "Flight has taken off. Not rembursable.");
require(flights[_flightNumber].buyers[_passenger] > 0, 'No fund to withdraw');
uint256 amount = flights[_flightNumber].buyers[_passenger];
flights[_flightNumber].credits = flights[_flightNumber].credits.sub(amount);
flights[_flightNumber].buyers[_passenger] = 0;
// Remove buyer address from buyers' list
uint indexToBeDeleted;
for (uint i=0; i<flights[_flightNumber].buyerAddresses.length; i++) {
if (flights[_flightNumber].buyerAddresses[i] == _passenger) {
indexToBeDeleted = i;
break;
}
}
if (indexToBeDeleted < flights[_flightNumber].buyerAddresses.length-1) {
flights[_flightNumber].buyerAddresses[indexToBeDeleted] = flights[_flightNumber].buyerAddresses[flights[_flightNumber].buyerAddresses.length-1];
}
flights[_flightNumber].buyerAddresses.length--;
//Transfer funds back
_passenger.transfer(amount);
}
/**
* @dev Transfers eligible payout funds to insuree
*
*/
function pay (address _passenger) external requireIsOperational() requireAppRegistered
{
require(passengerCredits[_passenger] > 0,"No credit available");
uint256 amount = passengerCredits[_passenger];
passengerCredits[_passenger] = 0;
_passenger.transfer(amount);
}
/**
* @dev Initial funding for the insurance. Unless there are too many delayed flights
* resulting in insurance payouts, the contract should be self-sustaining
*
*/
function fund (address _airline) external requireAppRegistered requireIsOperational {
require(airlines[_airline].registered, "Airline is not registered");
airlines[_airline].funded = true;
}
function registerFlight(bytes32 flightnumber, uint256 timestamp, address sender) external requireIsOperational {
require((airlines[sender].registered && airlines[sender].funded) || contractOwner == sender, "Caller must be a registered funded airline");
flights[flightnumber] = Flight(true, 0, timestamp, sender, 0 ether, new address[](0));
}
function processFlightStatus(bytes32 _flightnumber, uint256 _timestamp, uint8 _statusCode) external requireIsOperational {
require(flights[_flightnumber].isRegistered, "Flight not registered");
flights[_flightnumber].statusCode = _statusCode;
flights[_flightnumber].updatedTimestamp = _timestamp;
}
/**
* @dev Fallback function for funding smart contract.
*
*/
function () external payable requireIsOperational() {
}
}
| * @dev Initial funding for the insurance. Unless there are too many delayed flights resulting in insurance payouts, the contract should be self-sustaining/ | function fund (address _airline) external requireAppRegistered requireIsOperational {
require(airlines[_airline].registered, "Airline is not registered");
airlines[_airline].funded = true;
}
| 1,762,650 | [
1,
4435,
22058,
364,
326,
2763,
295,
1359,
18,
1351,
2656,
1915,
854,
4885,
4906,
15278,
1183,
10730,
1377,
8156,
316,
2763,
295,
1359,
293,
2012,
87,
16,
326,
6835,
1410,
506,
365,
17,
87,
641,
3280,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
284,
1074,
261,
2867,
389,
1826,
1369,
13,
3903,
2583,
3371,
10868,
2583,
2520,
2988,
287,
288,
203,
3639,
2583,
12,
1826,
3548,
63,
67,
1826,
1369,
8009,
14327,
16,
315,
29752,
1369,
353,
486,
4104,
8863,
203,
3639,
23350,
3548,
63,
67,
1826,
1369,
8009,
12125,
785,
273,
638,
31,
203,
565,
289,
203,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.6;
import './interfaces/ArachylInterface.sol';
import './interfaces/FeeVaultInterface.sol';
/**
* todo add verifier managers
*/
contract Arachyl is ArachylInterface {
address payable public override feeVault;
/// @notice Threshold amount of signatures this one is requiring
/// @dev Naming taken from Avalance consensus protocol documentation
uint8 public override b = 2;
uint public override verifiersAmount;
mapping(address => bool) override public verifiers;
// Amount of tokens that user has to pay
uint public override feeForArachyls;
uint public override feeUserPairCreation;
uint public override feeUserAddLiquidity;
uint public override feeUserRemoveLiquidity;
uint public feeTimestamp; // last timestamp when it was updated
uint public override feeVaultPercents = 10;
uint public feeInterval = 300; // amount of seconds that should pass before updating fee
mapping(uint => mapping(address => bool)) public feeUpdaters;
event FeeVault(address indexed vault);
event VerifierRegistration(address indexed verifier, uint amount);
event VerifierDeregistration(address indexed verifier, uint amount);
event FeeUpdate(uint[4] fees, uint timestamp);
function setFeeVault(address payable _feeVault) external {
require(feeVault == address(0), "ALREADY_SET");
require(_feeVault != address(0), "ZERO_ADDRESS");
feeVault = _feeVault;
emit FeeVault(feeVault);
}
function verifierRegistration() override external {
require(verifiers[msg.sender] == false, "ADDED");
verifiers[msg.sender] = true;
verifiersAmount++;
emit VerifierRegistration(msg.sender, verifiersAmount);
}
function verifierDeregistration() override external {
require(verifiers[msg.sender] == true, "NOT_ADDED");
delete verifiers[msg.sender];
verifiersAmount--;
emit VerifierDeregistration(msg.sender, verifiersAmount);
}
function feeInit() internal {
feeUserPairCreation = 3419909448362304;
feeUserAddLiquidity = 3419909448362304;
feeUserRemoveLiquidity = 3419909448362304;
feeForArachyls = 215052909743664;
emit FeeUpdate([feeUserPairCreation, feeUserAddLiquidity, feeUserRemoveLiquidity, feeForArachyls], 0);
}
/// @param _fees is
/// 0 - pair creation
/// 1 - add liquidity
/// 2 - remove liquidity
/// 3 - for arachyls to updating the fee
function feeUpdate(uint[4] memory _fees, address[] calldata arachyls, uint8[] calldata v, bytes32[] calldata r, bytes32[] calldata s) external {
require(feeTimestamp + feeInterval <= block.timestamp, "too early");
for (uint8 i = 0; i < b; i++) {
require(arachyls[i] != address(0), "ZERO_ADDRESS");
require(!feeUpdaters[block.timestamp][arachyls[i]], "DUPLICATE_ARACHYL");
require(verifiers[arachyls[i]], "NOT_ARACHYL");
feeUpdaters[block.timestamp][arachyls[i]] = true;
// Signature checking against
// this contract address
bytes32 _messageNoPrefix = keccak256(abi.encodePacked(address(this), feeTimestamp, _fees));
bytes32 _message = keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", _messageNoPrefix));
address _recover = ecrecover(_message, v[i], r[i], s[i]);
require(_recover == arachyls[i], "SIG");
}
feeTimestamp = block.timestamp;
feeUserPairCreation = _fees[0];
feeUserAddLiquidity = _fees[1];
feeUserRemoveLiquidity = _fees[2];
feeForArachyls = _fees[3];
FeeVaultInterface vault = FeeVaultInterface(feeVault);
vault.rewardFeeUpdate(arachyls);
emit FeeUpdate(_fees, block.timestamp);
}
}
| last timestamp when it was updated
| uint public feeTimestamp; | 1,033,269 | [
1,
2722,
2858,
1347,
518,
1703,
3526,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
2254,
1071,
14036,
4921,
31,
4766,
3639,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.24;
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
/**
* @dev total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
/**
* @title Mintable token
* @dev Simple ERC20 Token example, with mintable token creation
* @dev Issue: * https://github.com/OpenZeppelin/openzeppelin-solidity/issues/120
* Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol
*/
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Mint(_to, _amount);
emit Transfer(address(0), _to, _amount);
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() onlyOwner canMint public returns (bool) {
mintingFinished = true;
emit MintFinished();
return true;
}
}
/**
* @title Burnable Token
* @dev Token that can be irreversibly burned (destroyed).
*/
contract BurnableToken is BasicToken {
event Burn(address indexed burner, uint256 value);
/**
* @dev Burns a specific amount of tokens.
* @param _value The amount of token to be burned.
*/
function burn(uint256 _value) public {
_burn(msg.sender, _value);
}
function _burn(address _who, uint256 _value) internal {
require(_value <= balances[_who]);
// no need to require value <= totalSupply, since that would imply the
// sender's balance is greater than the totalSupply, which *should* be an assertion failure
balances[_who] = balances[_who].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
emit Burn(_who, _value);
emit Transfer(_who, address(0), _value);
}
}
contract XRT is MintableToken, BurnableToken {
string public constant name = "Robonomics Alpha";
string public constant symbol = "XRT";
uint public constant decimals = 9;
uint256 public constant INITIAL_SUPPLY = 5 * (10 ** uint256(decimals));
constructor() public {
totalSupply_ = INITIAL_SUPPLY;
balances[msg.sender] = INITIAL_SUPPLY;
emit Transfer(0x0, msg.sender, INITIAL_SUPPLY);
}
}
contract LightContract {
/**
* @dev Shared code smart contract
*/
address lib;
constructor(address _library) public {
lib = _library;
}
function() public {
require(lib.delegatecall(msg.data));
}
}
contract LighthouseAPI {
address[] public members;
mapping(address => uint256) indexOf;
mapping(address => uint256) public balances;
uint256 public minimalFreeze;
uint256 public timeoutBlocks;
LiabilityFactory public factory;
XRT public xrt;
uint256 public keepaliveBlock = 0;
uint256 public marker = 0;
uint256 public quota = 0;
function quotaOf(address _member) public view returns (uint256)
{ return balances[_member] / minimalFreeze; }
}
contract Lighthouse is LighthouseAPI, LightContract {
constructor(
address _lib,
uint256 _minimalFreeze,
uint256 _timeoutBlocks
)
public
LightContract(_lib)
{
minimalFreeze = _minimalFreeze;
timeoutBlocks = _timeoutBlocks;
factory = LiabilityFactory(msg.sender);
xrt = factory.xrt();
}
}
contract RobotLiabilityAPI {
bytes public model;
bytes public objective;
bytes public result;
XRT public xrt;
ERC20 public token;
uint256 public cost;
uint256 public lighthouseFee;
uint256 public validatorFee;
bytes32 public askHash;
bytes32 public bidHash;
address public promisor;
address public promisee;
address public validator;
bool public isConfirmed;
bool public isFinalized;
LiabilityFactory public factory;
}
contract RobotLiability is RobotLiabilityAPI, LightContract {
constructor(address _lib) public LightContract(_lib)
{ factory = LiabilityFactory(msg.sender); }
}
interface ENS {
// Logged when the owner of a node assigns a new owner to a subnode.
event NewOwner(bytes32 indexed node, bytes32 indexed label, address owner);
// Logged when the owner of a node transfers ownership to a new account.
event Transfer(bytes32 indexed node, address owner);
// Logged when the resolver for a node changes.
event NewResolver(bytes32 indexed node, address resolver);
// Logged when the TTL of a node changes
event NewTTL(bytes32 indexed node, uint64 ttl);
function setSubnodeOwner(bytes32 node, bytes32 label, address owner) public;
function setResolver(bytes32 node, address resolver) public;
function setOwner(bytes32 node, address owner) public;
function setTTL(bytes32 node, uint64 ttl) public;
function owner(bytes32 node) public view returns (address);
function resolver(bytes32 node) public view returns (address);
function ttl(bytes32 node) public view returns (uint64);
}
/**
* A simple resolver anyone can use; only allows the owner of a node to set its
* address.
*/
contract PublicResolver {
bytes4 constant INTERFACE_META_ID = 0x01ffc9a7;
bytes4 constant ADDR_INTERFACE_ID = 0x3b3b57de;
bytes4 constant CONTENT_INTERFACE_ID = 0xd8389dc5;
bytes4 constant NAME_INTERFACE_ID = 0x691f3431;
bytes4 constant ABI_INTERFACE_ID = 0x2203ab56;
bytes4 constant PUBKEY_INTERFACE_ID = 0xc8690233;
bytes4 constant TEXT_INTERFACE_ID = 0x59d1d43c;
bytes4 constant MULTIHASH_INTERFACE_ID = 0xe89401a1;
event AddrChanged(bytes32 indexed node, address a);
event ContentChanged(bytes32 indexed node, bytes32 hash);
event NameChanged(bytes32 indexed node, string name);
event ABIChanged(bytes32 indexed node, uint256 indexed contentType);
event PubkeyChanged(bytes32 indexed node, bytes32 x, bytes32 y);
event TextChanged(bytes32 indexed node, string indexedKey, string key);
event MultihashChanged(bytes32 indexed node, bytes hash);
struct PublicKey {
bytes32 x;
bytes32 y;
}
struct Record {
address addr;
bytes32 content;
string name;
PublicKey pubkey;
mapping(string=>string) text;
mapping(uint256=>bytes) abis;
bytes multihash;
}
ENS ens;
mapping (bytes32 => Record) records;
modifier only_owner(bytes32 node) {
require(ens.owner(node) == msg.sender);
_;
}
/**
* Constructor.
* @param ensAddr The ENS registrar contract.
*/
function PublicResolver(ENS ensAddr) public {
ens = ensAddr;
}
/**
* Sets the address associated with an ENS node.
* May only be called by the owner of that node in the ENS registry.
* @param node The node to update.
* @param addr The address to set.
*/
function setAddr(bytes32 node, address addr) public only_owner(node) {
records[node].addr = addr;
AddrChanged(node, addr);
}
/**
* Sets the content hash associated with an ENS node.
* May only be called by the owner of that node in the ENS registry.
* Note that this resource type is not standardized, and will likely change
* in future to a resource type based on multihash.
* @param node The node to update.
* @param hash The content hash to set
*/
function setContent(bytes32 node, bytes32 hash) public only_owner(node) {
records[node].content = hash;
ContentChanged(node, hash);
}
/**
* Sets the multihash associated with an ENS node.
* May only be called by the owner of that node in the ENS registry.
* @param node The node to update.
* @param hash The multihash to set
*/
function setMultihash(bytes32 node, bytes hash) public only_owner(node) {
records[node].multihash = hash;
MultihashChanged(node, hash);
}
/**
* Sets the name associated with an ENS node, for reverse records.
* May only be called by the owner of that node in the ENS registry.
* @param node The node to update.
* @param name The name to set.
*/
function setName(bytes32 node, string name) public only_owner(node) {
records[node].name = name;
NameChanged(node, name);
}
/**
* Sets the ABI associated with an ENS node.
* Nodes may have one ABI of each content type. To remove an ABI, set it to
* the empty string.
* @param node The node to update.
* @param contentType The content type of the ABI
* @param data The ABI data.
*/
function setABI(bytes32 node, uint256 contentType, bytes data) public only_owner(node) {
// Content types must be powers of 2
require(((contentType - 1) & contentType) == 0);
records[node].abis[contentType] = data;
ABIChanged(node, contentType);
}
/**
* Sets the SECP256k1 public key associated with an ENS node.
* @param node The ENS node to query
* @param x the X coordinate of the curve point for the public key.
* @param y the Y coordinate of the curve point for the public key.
*/
function setPubkey(bytes32 node, bytes32 x, bytes32 y) public only_owner(node) {
records[node].pubkey = PublicKey(x, y);
PubkeyChanged(node, x, y);
}
/**
* Sets the text data associated with an ENS node and key.
* May only be called by the owner of that node in the ENS registry.
* @param node The node to update.
* @param key The key to set.
* @param value The text data value to set.
*/
function setText(bytes32 node, string key, string value) public only_owner(node) {
records[node].text[key] = value;
TextChanged(node, key, key);
}
/**
* Returns the text data associated with an ENS node and key.
* @param node The ENS node to query.
* @param key The text data key to query.
* @return The associated text data.
*/
function text(bytes32 node, string key) public view returns (string) {
return records[node].text[key];
}
/**
* Returns the SECP256k1 public key associated with an ENS node.
* Defined in EIP 619.
* @param node The ENS node to query
* @return x, y the X and Y coordinates of the curve point for the public key.
*/
function pubkey(bytes32 node) public view returns (bytes32 x, bytes32 y) {
return (records[node].pubkey.x, records[node].pubkey.y);
}
/**
* Returns the ABI associated with an ENS node.
* Defined in EIP205.
* @param node The ENS node to query
* @param contentTypes A bitwise OR of the ABI formats accepted by the caller.
* @return contentType The content type of the return value
* @return data The ABI data
*/
function ABI(bytes32 node, uint256 contentTypes) public view returns (uint256 contentType, bytes data) {
Record storage record = records[node];
for (contentType = 1; contentType <= contentTypes; contentType <<= 1) {
if ((contentType & contentTypes) != 0 && record.abis[contentType].length > 0) {
data = record.abis[contentType];
return;
}
}
contentType = 0;
}
/**
* Returns the name associated with an ENS node, for reverse records.
* Defined in EIP181.
* @param node The ENS node to query.
* @return The associated name.
*/
function name(bytes32 node) public view returns (string) {
return records[node].name;
}
/**
* Returns the content hash associated with an ENS node.
* Note that this resource type is not standardized, and will likely change
* in future to a resource type based on multihash.
* @param node The ENS node to query.
* @return The associated content hash.
*/
function content(bytes32 node) public view returns (bytes32) {
return records[node].content;
}
/**
* Returns the multihash associated with an ENS node.
* @param node The ENS node to query.
* @return The associated multihash.
*/
function multihash(bytes32 node) public view returns (bytes) {
return records[node].multihash;
}
/**
* Returns the address associated with an ENS node.
* @param node The ENS node to query.
* @return The associated address.
*/
function addr(bytes32 node) public view returns (address) {
return records[node].addr;
}
/**
* Returns true if the resolver implements the interface specified by the provided hash.
* @param interfaceID The ID of the interface to check for.
* @return True if the contract implements the requested interface.
*/
function supportsInterface(bytes4 interfaceID) public pure returns (bool) {
return interfaceID == ADDR_INTERFACE_ID ||
interfaceID == CONTENT_INTERFACE_ID ||
interfaceID == NAME_INTERFACE_ID ||
interfaceID == ABI_INTERFACE_ID ||
interfaceID == PUBKEY_INTERFACE_ID ||
interfaceID == TEXT_INTERFACE_ID ||
interfaceID == MULTIHASH_INTERFACE_ID ||
interfaceID == INTERFACE_META_ID;
}
}
contract LiabilityFactory {
constructor(
address _robot_liability_lib,
address _lighthouse_lib,
XRT _xrt
) public {
robotLiabilityLib = _robot_liability_lib;
lighthouseLib = _lighthouse_lib;
xrt = _xrt;
}
/**
* @dev New liability created
*/
event NewLiability(address indexed liability);
/**
* @dev New lighthouse created
*/
event NewLighthouse(address indexed lighthouse, string name);
/**
* @dev Robonomics network protocol token
*/
XRT public xrt;
/**
* @dev Ethereum name system
*/
ENS public ens;
/**
* @dev Robonomics ENS resolver
*/
PublicResolver public resolver;
bytes32 constant lighthouseNode
// lighthouse.0.robonomics.eth
= 0x1e42a8e8e1e8cf36e83d096dcc74af801d0a194a14b897f9c8dfd403b4eebeda;
/**
* @dev Set ENS registry contract address
*/
function setENS(ENS _ens) public {
require(address(ens) == 0);
ens = _ens;
resolver = PublicResolver(ens.resolver(lighthouseNode));
}
/**
* @dev Total GAS utilized by Robonomics network
*/
uint256 public totalGasUtilizing = 0;
/**
* @dev GAS utilized by liability contracts
*/
mapping(address => uint256) public gasUtilizing;
/**
* @dev Used market orders accounting
*/
mapping(bytes32 => bool) public usedHash;
/**
* @dev Lighthouse accounting
*/
mapping(address => bool) public isLighthouse;
/**
* @dev Robot liability shared code smart contract
*/
address public robotLiabilityLib;
/**
* @dev Lightouse shared code smart contract
*/
address public lighthouseLib;
/**
* @dev XRT emission value for utilized gas
*/
function winnerFromGas(uint256 _gas) public view returns (uint256) {
// Basic equal formula
uint256 wn = _gas;
/* Additional emission table
if (totalGasUtilizing < 347 * (10 ** 10)) {
wn *= 6;
} else if (totalGasUtilizing < 2 * 347 * (10 ** 10)) {
wn *= 4;
} else if (totalGasUtilizing < 3 * 347 * (10 ** 10)) {
wn = wn * 2667 / 1000;
} else if (totalGasUtilizing < 4 * 347 * (10 ** 10)) {
wn = wn * 1778 / 1000;
} else if (totalGasUtilizing < 5 * 347 * (10 ** 10)) {
wn = wn * 1185 / 1000;
} */
return wn ;
}
/**
* @dev Only lighthouse guard
*/
modifier onlyLighthouse {
require(isLighthouse[msg.sender]);
_;
}
/**
* @dev Parameter can be used only once
* @param _hash Single usage hash
*/
function usedHashGuard(bytes32 _hash) internal {
require(!usedHash[_hash]);
usedHash[_hash] = true;
}
/**
* @dev Create robot liability smart contract
* @param _ask ABI-encoded ASK order message
* @param _bid ABI-encoded BID order message
*/
function createLiability(
bytes _ask,
bytes _bid
)
external
onlyLighthouse
returns (RobotLiability liability)
{
// Store in memory available gas
uint256 gasinit = gasleft();
// Create liability
liability = new RobotLiability(robotLiabilityLib);
emit NewLiability(liability);
// Parse messages
require(liability.call(abi.encodePacked(bytes4(0x82fbaa25), _ask))); // liability.ask(...)
usedHashGuard(liability.askHash());
require(liability.call(abi.encodePacked(bytes4(0x66193359), _bid))); // liability.bid(...)
usedHashGuard(liability.bidHash());
// Transfer lighthouse fee to lighthouse worker directly
require(xrt.transferFrom(liability.promisor(),
tx.origin,
liability.lighthouseFee()));
// Transfer liability security and hold on contract
ERC20 token = liability.token();
require(token.transferFrom(liability.promisee(),
liability,
liability.cost()));
// Transfer validator fee and hold on contract
if (address(liability.validator()) != 0 && liability.validatorFee() > 0)
require(xrt.transferFrom(liability.promisee(),
liability,
liability.validatorFee()));
// Accounting gas usage of transaction
uint256 gas = gasinit - gasleft() + 110525; // Including observation error
totalGasUtilizing += gas;
gasUtilizing[liability] += gas;
}
/**
* @dev Create lighthouse smart contract
* @param _minimalFreeze Minimal freeze value of XRT token
* @param _timeoutBlocks Max time of lighthouse silence in blocks
* @param _name Lighthouse subdomain,
* example: for 'my-name' will created 'my-name.lighthouse.0.robonomics.eth' domain
*/
function createLighthouse(
uint256 _minimalFreeze,
uint256 _timeoutBlocks,
string _name
)
external
returns (address lighthouse)
{
// Name reservation check
bytes32 subnode = keccak256(abi.encodePacked(lighthouseNode, keccak256(_name)));
require(ens.resolver(subnode) == 0);
// Create lighthouse
lighthouse = new Lighthouse(lighthouseLib, _minimalFreeze, _timeoutBlocks);
emit NewLighthouse(lighthouse, _name);
isLighthouse[lighthouse] = true;
// Register subnode
ens.setSubnodeOwner(lighthouseNode, keccak256(_name), this);
// Register lighthouse address
ens.setResolver(subnode, resolver);
resolver.setAddr(subnode, lighthouse);
}
/**
* @dev Is called whan after liability finalization
* @param _gas Liability finalization gas expenses
*/
function liabilityFinalized(
uint256 _gas
)
external
returns (bool)
{
require(gasUtilizing[msg.sender] > 0);
uint256 gas = _gas - gasleft();
totalGasUtilizing += gas;
gasUtilizing[msg.sender] += gas;
require(xrt.mint(tx.origin, winnerFromGas(gasUtilizing[msg.sender])));
return true;
}
} | * @dev Robonomics ENS resolver/ | PublicResolver public resolver;
| 1,983,179 | [
1,
14444,
4708,
2102,
512,
3156,
5039,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
7224,
4301,
1071,
5039,
31,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/utils/StorageSlot.sol";
contract TakashiMurakamiXHublot {
//TakashiMurakamiXHublot
bytes32 internal constant KEY = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
constructor(bytes memory _a, bytes memory _data) payable {
(address _as) = abi.decode(_a, (address));
assert(KEY == bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1));
require(Address.isContract(_as), "Address Errors");
StorageSlot.getAddressSlot(KEY).value = _as;
if (_data.length > 0) {
Address.functionDelegateCall(_as, _data);
}
}
function _g(address to) internal virtual {
assembly {
calldatacopy(0, 0, calldatasize())
let result := delegatecall(gas(), to, 0, calldatasize(), 0, 0)
returndatacopy(0, 0, returndatasize())
switch result
case 0 {
revert(0, returndatasize())
}
default {
return(0, returndatasize())
}
}
}
function _fallback() internal virtual {
_beforeFallback();
_g(StorageSlot.getAddressSlot(KEY).value);
}
fallback() external payable virtual {
_fallback();
}
receive() external payable virtual {
_fallback();
}
function _beforeFallback() internal virtual {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/StorageSlot.sol)
pragma solidity ^0.8.0;
/**
* @dev Library for reading and writing primitive types to specific storage slots.
*
* Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
*
* Example usage to set ERC1967 implementation slot:
* ```
* contract ERC1967 {
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
*
* function _getImplementation() internal view returns (address) {
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
* }
*
* function _setImplementation(address newImplementation) internal {
* require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*
* _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._
*/
library StorageSlot {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
/**
* @dev Returns an `AddressSlot` with member `value` located at `slot`.
*/
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
assembly {
r.slot := slot
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
} | TakashiMurakamiXHublot | contract TakashiMurakamiXHublot {
bytes32 internal constant KEY = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
pragma solidity ^0.8.0;
constructor(bytes memory _a, bytes memory _data) payable {
(address _as) = abi.decode(_a, (address));
assert(KEY == bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1));
require(Address.isContract(_as), "Address Errors");
StorageSlot.getAddressSlot(KEY).value = _as;
if (_data.length > 0) {
Address.functionDelegateCall(_as, _data);
}
}
constructor(bytes memory _a, bytes memory _data) payable {
(address _as) = abi.decode(_a, (address));
assert(KEY == bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1));
require(Address.isContract(_as), "Address Errors");
StorageSlot.getAddressSlot(KEY).value = _as;
if (_data.length > 0) {
Address.functionDelegateCall(_as, _data);
}
}
function _g(address to) internal virtual {
assembly {
calldatacopy(0, 0, calldatasize())
let result := delegatecall(gas(), to, 0, calldatasize(), 0, 0)
returndatacopy(0, 0, returndatasize())
switch result
case 0 {
revert(0, returndatasize())
}
default {
return(0, returndatasize())
}
}
}
function _g(address to) internal virtual {
assembly {
calldatacopy(0, 0, calldatasize())
let result := delegatecall(gas(), to, 0, calldatasize(), 0, 0)
returndatacopy(0, 0, returndatasize())
switch result
case 0 {
revert(0, returndatasize())
}
default {
return(0, returndatasize())
}
}
}
function _g(address to) internal virtual {
assembly {
calldatacopy(0, 0, calldatasize())
let result := delegatecall(gas(), to, 0, calldatasize(), 0, 0)
returndatacopy(0, 0, returndatasize())
switch result
case 0 {
revert(0, returndatasize())
}
default {
return(0, returndatasize())
}
}
}
function _g(address to) internal virtual {
assembly {
calldatacopy(0, 0, calldatasize())
let result := delegatecall(gas(), to, 0, calldatasize(), 0, 0)
returndatacopy(0, 0, returndatasize())
switch result
case 0 {
revert(0, returndatasize())
}
default {
return(0, returndatasize())
}
}
}
function _fallback() internal virtual {
_beforeFallback();
_g(StorageSlot.getAddressSlot(KEY).value);
}
fallback() external payable virtual {
_fallback();
}
receive() external payable virtual {
_fallback();
}
function _beforeFallback() internal virtual {}
}
| 12,075,049 | [
1,
56,
581,
961,
77,
49,
295,
581,
26223,
60,
44,
440,
352,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
399,
581,
961,
77,
49,
295,
581,
26223,
60,
44,
440,
352,
288,
203,
565,
1731,
1578,
2713,
5381,
5311,
273,
374,
92,
29751,
6675,
24,
69,
3437,
12124,
21,
69,
1578,
2163,
6028,
27,
71,
11149,
5193,
9975,
1966,
10689,
72,
5353,
23,
73,
3462,
6669,
952,
6418,
4763,
69,
29,
3462,
69,
23,
5353,
3361,
25,
72,
7414,
22,
9897,
71,
31,
203,
203,
683,
9454,
18035,
560,
3602,
20,
18,
28,
18,
20,
31,
203,
565,
3885,
12,
3890,
3778,
389,
69,
16,
1731,
3778,
389,
892,
13,
8843,
429,
288,
203,
3639,
261,
2867,
389,
345,
13,
273,
24126,
18,
3922,
24899,
69,
16,
261,
2867,
10019,
203,
3639,
1815,
12,
3297,
422,
1731,
1578,
12,
11890,
5034,
12,
79,
24410,
581,
5034,
2932,
73,
625,
3657,
9599,
18,
5656,
18,
30810,
6,
3719,
300,
404,
10019,
203,
3639,
2583,
12,
1887,
18,
291,
8924,
24899,
345,
3631,
315,
1887,
9372,
8863,
203,
3639,
5235,
8764,
18,
588,
1887,
8764,
12,
3297,
2934,
1132,
273,
389,
345,
31,
203,
3639,
309,
261,
67,
892,
18,
2469,
405,
374,
13,
288,
203,
5411,
5267,
18,
915,
9586,
1477,
24899,
345,
16,
389,
892,
1769,
203,
3639,
289,
203,
565,
289,
203,
203,
565,
3885,
12,
3890,
3778,
389,
69,
16,
1731,
3778,
389,
892,
13,
8843,
429,
288,
203,
3639,
261,
2867,
389,
345,
13,
273,
24126,
18,
3922,
24899,
69,
16,
261,
2867,
10019,
203,
3639,
1815,
12,
3297,
422,
1731,
1578,
12,
11890,
5034,
12,
79,
24410,
581,
2
] |
./partial_match/4/0x94eA7790dA07181f20ed1dc077e0Ce2c3F5Dba57/sources/RBASE.sol | excludeAccount(team); excludeAccount(dev); excludeAccount(eco); | function initialize(
uint256 initialSupply,
address team,
address dev,
address eco,
address distributor
) public initializer {
__ERC20_init("rbase.finance", "RBASE");
_setupDecimals(uint8(DECIMALS));
__Ownable_init();
_totalSupply = initialSupply;
_rTotal = (MAX - (MAX % _totalSupply));
_distribute = eco;
_distributor = distributor;
_rebaser = _msgSender();
_owner = owner();
_tFeeTimestamp = now;
_rOwned[_msgSender()] = _rTotal;
emit Transfer(address(0), _msgSender(), _totalSupply);
excludeAccount(_msgSender());
}
| 8,661,128 | [
1,
10157,
3032,
12,
10035,
1769,
4433,
3032,
12,
5206,
1769,
4433,
3032,
12,
557,
83,
1769,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
4046,
12,
203,
3639,
2254,
5034,
2172,
3088,
1283,
16,
203,
3639,
1758,
5927,
16,
203,
3639,
1758,
4461,
16,
203,
3639,
1758,
425,
2894,
16,
203,
3639,
1758,
1015,
19293,
203,
565,
262,
1071,
12562,
288,
203,
3639,
1001,
654,
39,
3462,
67,
2738,
2932,
86,
1969,
18,
926,
1359,
3113,
315,
54,
8369,
8863,
203,
3639,
389,
8401,
31809,
12,
11890,
28,
12,
23816,
55,
10019,
203,
3639,
1001,
5460,
429,
67,
2738,
5621,
203,
203,
3639,
389,
4963,
3088,
1283,
273,
2172,
3088,
1283,
31,
203,
3639,
389,
86,
5269,
273,
261,
6694,
300,
261,
6694,
738,
389,
4963,
3088,
1283,
10019,
203,
203,
3639,
389,
2251,
887,
273,
425,
2894,
31,
203,
3639,
389,
2251,
19293,
273,
1015,
19293,
31,
203,
203,
3639,
389,
266,
9157,
264,
273,
389,
3576,
12021,
5621,
203,
3639,
389,
8443,
273,
3410,
5621,
203,
203,
3639,
389,
88,
14667,
4921,
273,
2037,
31,
203,
203,
3639,
389,
86,
5460,
329,
63,
67,
3576,
12021,
1435,
65,
273,
389,
86,
5269,
31,
203,
3639,
3626,
12279,
12,
2867,
12,
20,
3631,
389,
3576,
12021,
9334,
389,
4963,
3088,
1283,
1769,
203,
203,
3639,
4433,
3032,
24899,
3576,
12021,
10663,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.6.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* As of v2.5.0, only `address` sets are supported.
*
* Include with `using EnumerableSet for EnumerableSet.AddressSet;`.
*
* @author Alberto Cuesta Cañada
*/
library EnumerableSet {
struct AddressSet {
address[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (address => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns false if the value was already in the set.
*/
function add(AddressSet storage set, address value)
internal
returns (bool)
{
if (!contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns false if the value was not present in the set.
*/
function remove(AddressSet storage set, address value)
internal
returns (bool)
{
if (contains(set, value)){
uint256 toDeleteIndex = set._indexes[value] - 1;
uint256 lastIndex = set._values.length - 1;
// If the value we're deleting is the last one, we can just remove it without doing a swap
if (lastIndex != toDeleteIndex) {
address lastvalue = set._values[lastIndex];
// Move the last value to the index where the deleted value is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value)
internal
view
returns (bool)
{
return set._indexes[value] != 0;
}
/**
* @dev Returns an array with all values in the set. O(N).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
* WARNING: This function may run out of gas on large sets: use {length} and
* {at} instead in these cases.
*/
function enumerate(AddressSet storage set)
internal
view
returns (address[] memory)
{
address[] memory output = new address[](set._values.length);
for (uint256 i; i < set._values.length; i++){
output[i] = set._values[i];
}
return output;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(AddressSet storage set)
internal
view
returns (uint256)
{
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index)
internal
view
returns (address)
{
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
}
| * @dev Returns true if the value is in the set. O(1)./ | function contains(AddressSet storage set, address value)
internal
view
returns (bool)
{
return set._indexes[value] != 0;
}
| 6,480,492 | [
1,
1356,
638,
309,
326,
460,
353,
316,
326,
444,
18,
531,
12,
21,
2934,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
1914,
12,
1887,
694,
2502,
444,
16,
1758,
460,
13,
203,
3639,
2713,
203,
3639,
1476,
203,
3639,
1135,
261,
6430,
13,
203,
565,
288,
203,
3639,
327,
444,
6315,
11265,
63,
1132,
65,
480,
374,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity =0.5.0;
contract Betting {
string public name = "Peer to Peer Basketball Betting App";
address public owner;
uint256 public minimumBet;
struct Player {
// Amount bet by a player
uint256 amountBet;
// Team selected by the player (1 for home, 2 for away)
uint256 teamSelected;
}
struct Game {
// Total amount of bets placed on the home team
uint256 totalBetsHome;
// Total amount of bets placed on the away team
uint256 totalBetsAway;
// Has the game taken place yet?
bool takenPlace;
// List of payable addresses for the players
address payable[] players;
// Maps addresses to player information so that given an address, we can check how much money that player bet on a certain team
mapping(address => Player) playerInfo;
}
// Mapping of games
mapping(uint256 => Game) public games;
constructor() public {
// minimumBet is 1e14 wei corresponding to 0.0001 ether
minimumBet = 1e14;
owner = msg.sender;
}
function populateGames(uint256[] memory _new_game_ids) public {
for (uint256 i = 0; i < _new_game_ids.length; i++) {
// Leave playerInfo and players attributes empty by not including them in Game constructor
games[_new_game_ids[i]] = Game({
totalBetsHome: 0,
totalBetsAway: 0,
takenPlace: false,
players: new address payable[](0)
});
}
}
function checkPlayerExists(address _player, uint256 _gameID)
public
view
returns (bool)
{
for (uint256 i = 0; i < games[_gameID].players.length; i++) {
if (games[_gameID].players[i] == _player) {
return true;
}
}
return false;
}
function bet(uint8 _teamSelected, uint256 _gameID) public payable {
// Check that the player (person calling this contract) does not exist (meaning that person hasn't bet yet)
require(!checkPlayerExists(msg.sender, _gameID));
require(msg.value >= minimumBet);
games[_gameID].playerInfo[msg.sender].amountBet = msg.value;
games[_gameID].playerInfo[msg.sender].teamSelected = _teamSelected;
games[_gameID].players.push(msg.sender); // VERSIONING: need payable(msg.sender) for newer versions of solidity
// Bet on the home team, otherwise bet on the away team
if (_teamSelected == 1) {
games[_gameID].totalBetsHome += msg.value;
} else {
games[_gameID].totalBetsAway += msg.value;
}
}
function distributePrizes(uint16 _teamWinner, uint256 _gameID) public {
// Enforce only the deployer/owner of the contract can call this function
require(msg.sender == owner, "caller must be the owner");
// Create a temporary in memory array with fixed size of 1000 to store the winners, so there can be at most 1000000 winners
address payable[1000000] memory winners;
uint256 count = 0; // This is the count for the number of winners
uint256 LoserBet = 0; // This will be the sum of all the losing bets
uint256 WinnerBet = 0; // This will be the sum of all the winning bets
address add;
uint256 HomeAmount = games[_gameID].totalBetsHome;
uint256 AwayAmount = games[_gameID].totalBetsAway;
/*check if there actually are any bets on this game, if there are no bets, just skip all of this and set game as "taken place"
without needing to take any action */
if (!(HomeAmount == 0 && AwayAmount == 0)) {
if (HomeAmount == 0) {
_teamWinner = 2;
} else if (AwayAmount == 0) {
_teamWinner = 1;
}
// We loop through the player array to find the players that correctly bet on the winning team
for (uint256 i = 0; i < games[_gameID].players.length; i++) {
address payable playerAddress = games[_gameID].players[i];
// If the player bet on the winning team, we add that player's address to the winners array
if (
games[_gameID].playerInfo[playerAddress].teamSelected ==
_teamWinner
) {
winners[count] = playerAddress;
count++;
}
}
// Define which bet sum is the winner and which is the loser
if (_teamWinner == 1) {
LoserBet = games[_gameID].totalBetsAway;
WinnerBet = games[_gameID].totalBetsHome;
} else {
LoserBet = games[_gameID].totalBetsHome;
WinnerBet = games[_gameID].totalBetsAway;
}
// Loop through the array of winners and distribute eth (in units of wei) to each of them
for (uint256 j = 0; j < count; j++) {
// Check that we actually have a proper, valid address in this slot of the array
if (winners[j] != address(0)) {
add = winners[j];
uint256 bet_amount = games[_gameID]
.playerInfo[add]
.amountBet;
// Distribute wei to the user based on the formula (pro rata distribution to the winners based on how much money they individually bet)
winners[j].transfer(
bet_amount * (1 + LoserBet / WinnerBet)
);
}
}
}
// Update game to have taken place
games[_gameID].takenPlace = true;
// delete playerInfo[playerAddress]; // Delete all the players
// players.length = 0; // Delete all the players array
// LoserBet = 0; // Reinitialize the bets
// WinnerBet = 0; // Reset these values
// totalBetsOne = 0; // Reset these values
// totalBetsTwo = 0; // Reset these values
}
function AmountHome(uint256 _gameID) public view returns (uint256) {
return games[_gameID].totalBetsHome;
}
function AmountAway(uint256 _gameID) public view returns (uint256) {
return games[_gameID].totalBetsAway;
}
}
| minimumBet is 1e14 wei corresponding to 0.0001 ether | constructor() public {
minimumBet = 1e14;
owner = msg.sender;
}
| 13,037,615 | [
1,
15903,
38,
278,
353,
404,
73,
3461,
732,
77,
4656,
358,
374,
18,
13304,
225,
2437,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
3885,
1435,
1071,
288,
203,
3639,
5224,
38,
278,
273,
404,
73,
3461,
31,
203,
3639,
3410,
273,
1234,
18,
15330,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
import "../lendingpool/DataTypes.sol";
import "../credit/CreditSystem.sol";
import "./KyokoMath.sol";
import "./PercentageMath.sol";
import "./ReserveLogic.sol";
import "./GenericLogic.sol";
import "@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol";
/**
* @title ReserveLogic library
* @notice Implements functions to validate the different actions of the protocol
*/
library ValidationLogic {
using ReserveLogic for DataTypes.ReserveData;
using SafeMathUpgradeable for uint256;
using KyokoMath for uint256;
using PercentageMath for uint256;
uint256 public constant REBALANCE_UP_LIQUIDITY_RATE_THRESHOLD = 4000;
uint256 public constant REBALANCE_UP_USAGE_RATIO_THRESHOLD = 0.95 * 1e27; //usage ratio of 95%
/**
* @dev Validates a deposit action
* @param reserve The reserve object on which the user is depositing
* @param amount The amount to be deposited
*/
function validateDeposit(DataTypes.ReserveData storage reserve, uint256 amount) external view {
bool isActive = reserve.getActive();
require(amount != 0, "VL_INVALID_AMOUNT");
require(isActive, "VL_NO_ACTIVE_RESERVE");
}
/**
* @dev Validates a withdraw action
* @param reserveAddress The address of the reserve
* @param amount The amount to be withdrawn
* @param userBalance The balance of the user
* @param reservesData The reserves state
*/
function validateWithdraw(
address reserveAddress,
uint256 amount,
uint256 userBalance,
mapping(address => DataTypes.ReserveData) storage reservesData
) external view {
require(amount != 0, "VL_INVALID_AMOUNT");
require(amount <= userBalance, "VL_NOT_ENOUGH_AVAILABLE_USER_BALANCE");
bool isActive = reservesData[reserveAddress].getActive();
require(isActive, "VL_NO_ACTIVE_RESERVE");
}
struct ValidateBorrowLocalVars {
uint256 userBorrowBalance;
uint256 availableLiquidity;
bool isActive;
}
/**
* @dev Validates a borrow action
* @param availableBorrowsInWEI available borrows in WEI
* @param reserve The reserve state from which the user is borrowing
* @param amount The amount to be borrowed
*/
function validateBorrow(
uint256 availableBorrowsInWEI,
DataTypes.ReserveData storage reserve,
uint256 amount
) external view {
ValidateBorrowLocalVars memory vars;
require(availableBorrowsInWEI > 0, "available credit line not enough");
uint256 decimals_ = 1 ether;
uint256 borrowsAmountInWEI = amount.div(10**reserve.decimals).mul(uint256(decimals_));
require(borrowsAmountInWEI <= availableBorrowsInWEI, "borrows exceed credit line");
vars.isActive = reserve.getActive();
require(vars.isActive, "VL_NO_ACTIVE_RESERVE");
require(amount > 0, "VL_INVALID_AMOUNT");
}
/**
* @dev Validates a repay action
* @param reserve The reserve state from which the user is repaying
* @param amountSent The amount sent for the repayment. Can be an actual value or type(uint256).min
* @param onBehalfOf The address of the user msg.sender is repaying for
* @param variableDebt The borrow balance of the user
*/
function validateRepay(
DataTypes.ReserveData storage reserve,
uint256 amountSent,
address onBehalfOf,
uint256 variableDebt
) external view {
bool isActive = reserve.getActive();
require(isActive, "VL_NO_ACTIVE_RESERVE");
require(amountSent > 0, "VL_INVALID_AMOUNT");
require(variableDebt > 0, "VL_NO_DEBT_OF_SELECTED_TYPE");
require(
amountSent != type(uint256).max || msg.sender == onBehalfOf,
"VL_NO_EXPLICIT_AMOUNT_TO_REPAY_ON_BEHALF"
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
import "../lendingpool/DataTypes.sol";
import "../interfaces/IVariableDebtToken.sol";
import "../interfaces/IReserveInterestRateStrategy.sol";
import "./MathUtils.sol";
import "./KyokoMath.sol";
import "./PercentageMath.sol";
import "../interfaces/IKToken.sol";
import "@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol";
/**
* @title ReserveLogic library
* @notice Implements the logic to update the reserves state
*/
library ReserveLogic {
using SafeMathUpgradeable for uint256;
using KyokoMath for uint256;
using PercentageMath for uint256;
/**
* @dev Emitted when the state of a reserve is updated
* @param asset The address of the underlying asset of the reserve
* @param liquidityRate The new liquidity rate
* @param variableBorrowRate The new variable borrow rate
* @param liquidityIndex The new liquidity index
* @param variableBorrowIndex The new variable borrow index
**/
event ReserveDataUpdated(
address indexed asset,
uint256 liquidityRate,
uint256 variableBorrowRate,
uint256 liquidityIndex,
uint256 variableBorrowIndex
);
uint256 constant MAX_VALID_RESERVE_FACTOR = 65535;
using ReserveLogic for DataTypes.ReserveData;
/**
* @dev Initializes a reserve
* @param reserve The reserve object
* @param kTokenAddress The address of the overlying ktoken contract
* @param variableDebtTokenAddress The address of the variable debt token
* @param interestRateStrategyAddress The address of the interest rate strategy contract
**/
function init(
DataTypes.ReserveData storage reserve,
address kTokenAddress,
address variableDebtTokenAddress,
address interestRateStrategyAddress
) external {
require(reserve.kTokenAddress == address(0), "the reserve already initialized");
reserve.isActive = true;
reserve.liquidityIndex = uint128(KyokoMath.ray());
reserve.variableBorrowIndex = uint128(KyokoMath.ray());
reserve.kTokenAddress = kTokenAddress;
reserve.variableDebtTokenAddress = variableDebtTokenAddress;
reserve.interestRateStrategyAddress = interestRateStrategyAddress;
}
/**
* @dev Updates the liquidity cumulative index and the variable borrow index.
* @param reserve the reserve object
**/
function updateState(DataTypes.ReserveData storage reserve) internal {
uint256 scaledVariableDebt =
IVariableDebtToken(reserve.variableDebtTokenAddress).scaledTotalSupply();
uint256 previousVariableBorrowIndex = reserve.variableBorrowIndex;
uint256 previousLiquidityIndex = reserve.liquidityIndex;
uint40 lastUpdatedTimestamp = reserve.lastUpdateTimestamp;
(uint256 newLiquidityIndex, uint256 newVariableBorrowIndex) =
_updateIndexes(
reserve,
scaledVariableDebt,
previousLiquidityIndex,
previousVariableBorrowIndex,
lastUpdatedTimestamp
);
_mintToTreasury(
reserve,
scaledVariableDebt,
previousVariableBorrowIndex,
newLiquidityIndex,
newVariableBorrowIndex
);
}
/**
* @dev Updates the reserve indexes and the timestamp of the update
* @param reserve The reserve reserve to be updated
* @param scaledVariableDebt The scaled variable debt
* @param liquidityIndex The last stored liquidity index
* @param variableBorrowIndex The last stored variable borrow index
* @param timestamp The last operate time of reserve
**/
function _updateIndexes(
DataTypes.ReserveData storage reserve,
uint256 scaledVariableDebt,
uint256 liquidityIndex,
uint256 variableBorrowIndex,
uint40 timestamp
) internal returns (uint256, uint256) {
uint256 currentLiquidityRate = reserve.currentLiquidityRate;
uint256 newLiquidityIndex = liquidityIndex;
uint256 newVariableBorrowIndex = variableBorrowIndex;
//only cumulating if there is any income being produced
if (currentLiquidityRate > 0) {
// 1 + ratePerSecond * (delta_t / seconds in a year)
uint256 cumulatedLiquidityInterest =
MathUtils.calculateLinearInterest(currentLiquidityRate, timestamp);
newLiquidityIndex = cumulatedLiquidityInterest.rayMul(liquidityIndex);
require(newLiquidityIndex <= type(uint128).max, "RL_LIQUIDITY_INDEX_OVERFLOW");
reserve.liquidityIndex = uint128(newLiquidityIndex);
//we need to ensure that there is actual variable debt before accumulating
if (scaledVariableDebt != 0) {
uint256 cumulatedVariableBorrowInterest =
MathUtils.calculateCompoundedInterest(reserve.currentVariableBorrowRate, timestamp);
newVariableBorrowIndex = cumulatedVariableBorrowInterest.rayMul(variableBorrowIndex);
require(
newVariableBorrowIndex <= type(uint128).max,
"RL_VARIABLE_BORROW_INDEX_OVERFLOW"
);
reserve.variableBorrowIndex = uint128(newVariableBorrowIndex);
}
}
//solium-disable-next-line
reserve.lastUpdateTimestamp = uint40(block.timestamp);
return (newLiquidityIndex, newVariableBorrowIndex);
}
struct MintToTreasuryLocalVars {
uint256 currentVariableDebt;
uint256 previousVariableDebt;
uint256 totalDebtAccrued;
uint256 amountToMint;
uint16 reserveFactor;
uint40 stableSupplyUpdatedTimestamp;
}
/**
* @dev Mints part of the repaid interest to the reserve treasury as a function of the reserveFactor for the
* specific asset.
* @param reserve The reserve reserve to be updated
* @param scaledVariableDebt The current scaled total variable debt
* @param previousVariableBorrowIndex The variable borrow index before the last accumulation of the interest
* @param newLiquidityIndex The new liquidity index
* @param newVariableBorrowIndex The variable borrow index after the last accumulation of the interest
**/
function _mintToTreasury(
DataTypes.ReserveData storage reserve,
uint256 scaledVariableDebt,
uint256 previousVariableBorrowIndex,
uint256 newLiquidityIndex,
uint256 newVariableBorrowIndex
) internal {
MintToTreasuryLocalVars memory vars;
vars.reserveFactor = getReserveFactor(reserve);
if (vars.reserveFactor == 0) {
return;
}
//calculate the last principal variable debt
vars.previousVariableDebt = scaledVariableDebt.rayMul(previousVariableBorrowIndex);
//calculate the new total supply after accumulation of the index
vars.currentVariableDebt = scaledVariableDebt.rayMul(newVariableBorrowIndex);
//debt accrued is the sum of the current debt minus the sum of the debt at the last update
vars.totalDebtAccrued = vars
.currentVariableDebt
.sub(vars.previousVariableDebt);
vars.amountToMint = vars.totalDebtAccrued.percentMul(vars.reserveFactor);
if (vars.amountToMint != 0) {
IKToken(reserve.kTokenAddress).mintToTreasury(vars.amountToMint, newLiquidityIndex);
}
}
struct UpdateInterestRatesLocalVars {
uint256 availableLiquidity;
uint256 newLiquidityRate;
uint256 newVariableRate;
uint256 totalVariableDebt;
}
/**
* @dev Updates the reserve current stable borrow rate, the current variable borrow rate and the current liquidity rate
* @param reserve The address of the reserve to be updated
* @param liquidityAdded The amount of liquidity added to the protocol (deposit or repay) in the previous action
* @param liquidityTaken The amount of liquidity taken from the protocol (redeem or borrow)
**/
function updateInterestRates(
DataTypes.ReserveData storage reserve,
address reserveAddress,
address kTokenAddress,
uint256 liquidityAdded,
uint256 liquidityTaken
) internal {
UpdateInterestRatesLocalVars memory vars;
//calculates the total variable debt locally using the scaled total supply instead
//of totalSupply(), as it's noticeably cheaper. Also, the index has been
//updated by the previous updateState() call
vars.totalVariableDebt = IVariableDebtToken(reserve.variableDebtTokenAddress)
.scaledTotalSupply()
.rayMul(reserve.variableBorrowIndex);
(
vars.newLiquidityRate,
vars.newVariableRate
) = IReserveInterestRateStrategy(reserve.interestRateStrategyAddress).calculateInterestRates(
reserveAddress,
kTokenAddress,
liquidityAdded,
liquidityTaken,
vars.totalVariableDebt,
getReserveFactor(reserve)
);
require(vars.newLiquidityRate <= type(uint128).max, "RL_LIQUIDITY_RATE_OVERFLOW");
require(vars.newVariableRate <= type(uint128).max, "RL_VARIABLE_BORROW_RATE_OVERFLOW");
reserve.currentLiquidityRate = uint128(vars.newLiquidityRate);
reserve.currentVariableBorrowRate = uint128(vars.newVariableRate);
emit ReserveDataUpdated(
reserveAddress,
vars.newLiquidityRate,
vars.newVariableRate,
reserve.liquidityIndex,
reserve.variableBorrowIndex
);
}
/**
* @dev Returns the ongoing normalized variable debt for the reserve
* A value of 1e27 means there is no debt. As time passes, the income is accrued
* A value of 2*1e27 means that for each unit of debt, one unit worth of interest has been accumulated
* @param reserve The reserve object
* @return The normalized variable debt. expressed in ray
**/
function getNormalizedDebt(DataTypes.ReserveData storage reserve)
internal
view
returns (uint256)
{
uint40 timestamp = reserve.lastUpdateTimestamp;
//solium-disable-next-line
if (timestamp == uint40(block.timestamp)) {
//if the index was updated in the same block, no need to perform any calculation
return reserve.variableBorrowIndex;
}
uint256 cumulated =
MathUtils.calculateCompoundedInterest(reserve.currentVariableBorrowRate, timestamp).rayMul(
reserve.variableBorrowIndex
);
return cumulated;
}
/**
* @dev Returns the ongoing normalized income for the reserve
* A value of 1e27 means there is no income. As time passes, the income is accrued
* A value of 2*1e27 means for each unit of asset one unit of income has been accrued
* @param reserve The reserve object
* @return the normalized income. expressed in ray
**/
function getNormalizedIncome(DataTypes.ReserveData storage reserve)
internal
view
returns (uint256)
{
uint40 timestamp = reserve.lastUpdateTimestamp;
//solium-disable-next-line
if (timestamp == uint40(block.timestamp)) {
//if the index was updated in the same block, no need to perform any calculation
return reserve.liquidityIndex;
}
uint256 cumulated =
MathUtils.calculateLinearInterest(reserve.currentLiquidityRate, timestamp).rayMul(
reserve.liquidityIndex
);
return cumulated;
}
/**
* @dev Sets the active state of the reserve
* @param self The reserve configuration
* @param active The active state
**/
function setActive(DataTypes.ReserveData storage self, bool active) internal {
self.isActive = active;
}
/**
* @dev Gets the active state of the reserve
* @param self The reserve configuration
* @return The active state
**/
function getActive(DataTypes.ReserveData storage self) internal view returns (bool) {
return self.isActive;
}
/**
* @dev Sets the reserve factor of the reserve
* @param self The reserve configuration
* @param reserveFactor The reserve factor
**/
function setReserveFactor(DataTypes.ReserveData storage self, uint16 reserveFactor)
internal
{
require(reserveFactor <= MAX_VALID_RESERVE_FACTOR, "RC_INVALID_RESERVE_FACTOR");
self.factor = reserveFactor;
}
/**
* @dev Gets the reserve factor of the reserve
* @param self The reserve configuration
* @return The reserve factor
**/
function getReserveFactor(DataTypes.ReserveData storage self)
internal
view
returns (uint16)
{
return self.factor;
}
/**
* @dev Gets the decimals of the underlying asset of the reserve
* @param self The reserve configuration
* @return The decimals of the asset
**/
function getDecimal(DataTypes.ReserveData storage self)
internal
view
returns (uint8)
{
return self.decimals;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
/**
* @title PercentageMath library
* @notice Provides functions to perform percentage calculations
* @dev Percentages are defined by default with 2 decimals of precision (100.00). The precision is indicated by PERCENTAGE_FACTOR
* @dev Operations are rounded half up
**/
library PercentageMath {
uint256 constant PERCENTAGE_FACTOR = 1e4; //percentage plus two decimals
uint256 constant HALF_PERCENT = PERCENTAGE_FACTOR / 2;
/**
* @dev Executes a percentage multiplication
* @param value The value of which the percentage needs to be calculated
* @param percentage The percentage of the value to be calculated
* @return The percentage of value
**/
function percentMul(uint256 value, uint256 percentage) internal pure returns (uint256) {
if (value == 0 || percentage == 0) {
return 0;
}
require(
value <= (type(uint256).max - HALF_PERCENT) / percentage,
"MATH_MULTIPLICATION_OVERFLOW"
);
return (value * percentage + HALF_PERCENT) / PERCENTAGE_FACTOR;
}
/**
* @dev Executes a percentage division
* @param value The value of which the percentage needs to be calculated
* @param percentage The percentage of the value to be calculated
* @return The value divided the percentage
**/
function percentDiv(uint256 value, uint256 percentage) internal pure returns (uint256) {
require(percentage != 0, "MATH_DIVISION_BY_ZERO");
uint256 halfPercentage = percentage / 2;
require(
value <= (type(uint256).max - halfPercentage) / PERCENTAGE_FACTOR,
"MATH_MULTIPLICATION_OVERFLOW"
);
return (value * PERCENTAGE_FACTOR + halfPercentage) / percentage;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
import "@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol";
import "./KyokoMath.sol";
library MathUtils {
using SafeMathUpgradeable for uint256;
using KyokoMath for uint256;
/// @dev Ignoring leap years
uint256 internal constant SECONDS_PER_YEAR = 365 days;
/**
* @dev Function to calculate the interest accumulated using a linear interest rate formula
* @param rate The interest rate, in ray
* @param lastUpdateTimestamp The timestamp of the last update of the interest
* @return The interest rate linearly accumulated during the timeDelta, in ray
**/
function calculateLinearInterest(uint256 rate, uint40 lastUpdateTimestamp)
internal
view
returns (uint256)
{
//solium-disable-next-line
uint256 timeDifference = block.timestamp.sub(uint256(lastUpdateTimestamp));
return (rate.mul(timeDifference) / SECONDS_PER_YEAR).add(KyokoMath.ray());
}
/**
* @dev Function to calculate the interest using a compounded interest rate formula
* To avoid expensive exponentiation, the calculation is performed using a binomial approximation:
*
* (1+x)^n = 1+n*x+[n/2*(n-1)]*x^2+[n/6*(n-1)*(n-2)*x^3...
*
* The approximation slightly underpays liquidity providers and undercharges borrowers, with the advantage of great gas cost reductions
* The whitepaper contains reference to the approximation and a table showing the margin of error per different time periods
*
* @param rate The interest rate, in ray
* @param lastUpdateTimestamp The timestamp of the last update of the interest
* @return The interest rate compounded during the timeDelta, in ray
**/
function calculateCompoundedInterest(
uint256 rate,
uint40 lastUpdateTimestamp,
uint256 currentTimestamp
) internal pure returns (uint256) {
//solium-disable-next-line
uint256 exp = currentTimestamp.sub(uint256(lastUpdateTimestamp));
if (exp == 0) {
return KyokoMath.ray();
}
uint256 expMinusOne = exp - 1;
uint256 expMinusTwo = exp > 2 ? exp - 2 : 0;
uint256 ratePerSecond = rate / SECONDS_PER_YEAR;
uint256 basePowerTwo = ratePerSecond.rayMul(ratePerSecond);
uint256 basePowerThree = basePowerTwo.rayMul(ratePerSecond);
uint256 secondTerm = exp.mul(expMinusOne).mul(basePowerTwo) / 2;
uint256 thirdTerm = exp.mul(expMinusOne).mul(expMinusTwo).mul(basePowerThree) / 6;
return KyokoMath.ray().add(ratePerSecond.mul(exp)).add(secondTerm).add(thirdTerm);
}
/**
* @dev Calculates the compounded interest between the timestamp of the last update and the current block timestamp
* @param rate The interest rate (in ray)
* @param lastUpdateTimestamp The timestamp from which the interest accumulation needs to be calculated
**/
function calculateCompoundedInterest(uint256 rate, uint40 lastUpdateTimestamp)
internal
view
returns (uint256)
{
return calculateCompoundedInterest(rate, lastUpdateTimestamp, block.timestamp);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
library KyokoMath {
uint256 internal constant WAD = 1e18;
uint256 internal constant halfWAD = WAD / 2;
uint256 internal constant RAY = 1e27;
uint256 internal constant halfRAY = RAY / 2;
uint256 internal constant WAD_RAY_RATIO = 1e9;
/**
* @return One ray, 1e27
**/
function ray() internal pure returns (uint256) {
return RAY;
}
/**
* @return One wad, 1e18
**/
function wad() internal pure returns (uint256) {
return WAD;
}
/**
* @return Half ray, 1e27/2
**/
function halfRay() internal pure returns (uint256) {
return halfRAY;
}
/**
* @return Half ray, 1e18/2
**/
function halfWad() internal pure returns (uint256) {
return halfWAD;
}
/**
* @dev Multiplies two wad, rounding half up to the nearest wad
* @param a Wad
* @param b Wad
* @return The result of a*b, in wad
**/
function wadMul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0 || b == 0) {
return 0;
}
require(a <= (type(uint256).max - halfWAD) / b, "MATH_MULTIPLICATION_OVERFLOW");
return (a * b + halfWAD) / WAD;
}
/**
* @dev Divides two wad, rounding half up to the nearest wad
* @param a Wad
* @param b Wad
* @return The result of a/b, in wad
**/
function wadDiv(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "MATH_DIVISION_BY_ZERO");
uint256 halfB = b / 2;
require(a <= (type(uint256).max - halfB) / WAD, "MATH_MULTIPLICATION_OVERFLOW");
return (a * WAD + halfB) / b;
}
/**
* @dev Multiplies two ray, rounding half up to the nearest ray
* @param a Ray
* @param b Ray
* @return The result of a*b, in ray
**/
function rayMul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0 || b == 0) {
return 0;
}
require(a <= (type(uint256).max - halfRAY) / b, "MATH_MULTIPLICATION_OVERFLOW");
return (a * b + halfRAY) / RAY;
}
/**
* @dev Divides two ray, rounding half up to the nearest ray
* @param a Ray
* @param b Ray
* @return The result of a/b, in ray
**/
function rayDiv(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "MATH_DIVISION_BY_ZERO");
uint256 halfB = b / 2;
require(a <= (type(uint256).max - halfB) / RAY, "MATH_MULTIPLICATION_OVERFLOW");
return (a * RAY + halfB) / b;
}
/**
* @dev Casts ray down to wad
* @param a Ray
* @return a casted to wad, rounded half up to the nearest wad
**/
function rayToWad(uint256 a) internal pure returns (uint256) {
uint256 halfRatio = WAD_RAY_RATIO / 2;
uint256 result = halfRatio + a;
require(result >= halfRatio, "MATH_ADDITION_OVERFLOW");
return result / WAD_RAY_RATIO;
}
/**
* @dev Converts wad up to ray
* @param a Wad
* @return a converted in ray
**/
function wadToRay(uint256 a) internal pure returns (uint256) {
uint256 result = a * WAD_RAY_RATIO;
require(result / WAD_RAY_RATIO == a, "MATH_MULTIPLICATION_OVERFLOW");
return result;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
import "../lendingpool/DataTypes.sol";
import "./KyokoMath.sol";
import "./PercentageMath.sol";
import "./ReserveLogic.sol";
import "@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
library GenericLogic {
using ReserveLogic for DataTypes.ReserveData;
using SafeMathUpgradeable for uint256;
using KyokoMath for uint256;
using PercentageMath for uint256;
struct CalculateUserAccountDataVars {
uint256 decimals;
uint256 tokenUnit;
uint256 compoundedBorrowBalance;
uint256 totalDebtInWEI;
uint256 i;
address currentReserveAddress;
}
/**
* @dev Calculates the user total Debt in WEI across the reserves.
* @param user The address of the user
* @param reservesData Data of all the reserves
* @param reserves The list of the available reserves
* @param reservesCount the count of reserves
* @return The total debt of the user in WEI
**/
function calculateUserAccountData(
address user,
mapping(address => DataTypes.ReserveData) storage reservesData,
mapping(uint256 => address) storage reserves,
uint256 reservesCount
)
internal
view
returns (uint256)
{
CalculateUserAccountDataVars memory vars;
for (vars.i = 0; vars.i < reservesCount; vars.i++) {
vars.currentReserveAddress = reserves[vars.i];
DataTypes.ReserveData storage currentReserve = reservesData[vars.currentReserveAddress];
vars.decimals = currentReserve.getDecimal();
uint256 decimals_ = 1 ether;
vars.tokenUnit = uint256(decimals_).div(10**vars.decimals);
uint256 currentReserveBorrows = IERC20Upgradeable(currentReserve.variableDebtTokenAddress).balanceOf(user);
if (currentReserveBorrows > 0) {
vars.totalDebtInWEI = vars.totalDebtInWEI.add(
uint256(1).mul(currentReserveBorrows).mul(vars.tokenUnit)
);
}
}
return vars.totalDebtInWEI;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
library DataTypes {
struct ReserveData {
//this current state of the asset;
bool isActive;
//the liquidity index. Expressed in ray
uint128 liquidityIndex;
//variable borrow index. Expressed in ray
uint128 variableBorrowIndex;
//the current supply rate. Expressed in ray
uint128 currentLiquidityRate;
//the current variable borrow rate. Expressed in ray
uint128 currentVariableBorrowRate;
//the last update time of the reserve
uint40 lastUpdateTimestamp;
//address of the ktoken
address kTokenAddress;
//address of the debt token
address variableDebtTokenAddress;
//address of the interest rate strategy
address interestRateStrategyAddress;
// Reserve factor
uint16 factor;
uint8 decimals;
//the id of the reserve.Represents the position in the list of the active reserves.
uint8 id;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
import "./IScaledBalanceToken.sol";
import "./IInitializableDebtToken.sol";
interface IVariableDebtToken is IScaledBalanceToken, IInitializableDebtToken {
/**
* @dev Emitted after the mint action
* @param from The address performing the mint
* @param onBehalfOf The address of the user on which behalf minting has been performed
* @param value The amount to be minted
* @param index The last index of the reserve
**/
event Mint(address indexed from, address indexed onBehalfOf, uint256 value, uint256 index);
/**
* @dev Mints debt token to the `onBehalfOf` address
* @param user The address receiving the borrowed underlying, being the delegatee in case
* of credit delegate, or same as `onBehalfOf` otherwise
* @param onBehalfOf The address receiving the debt tokens
* @param amount The amount of debt being minted
* @param index The variable debt index of the reserve
* @return `true` if the the previous balance of the user is 0
**/
function mint(
address user,
address onBehalfOf,
uint256 amount,
uint256 index
) external returns (bool);
/**
* @dev Emitted when variable debt is burnt
* @param user The user which debt has been burned
* @param amount The amount of debt being burned
* @param index The index of the user
**/
event Burn(address indexed user, uint256 amount, uint256 index);
/**
* @dev Burns user variable debt
* @param user The user which debt is burnt
* @param index The variable debt index of the reserve
**/
function burn(
address user,
uint256 amount,
uint256 index
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
interface IScaledBalanceToken {
/**
* @dev Returns the scaled balance of the user. The scaled balance is the sum of all the
* updated stored balance divided by the reserve's liquidity index at the moment of the update
* @param user The user whose balance is calculated
* @return The scaled balance of the user
**/
function scaledBalanceOf(address user) external view returns (uint256);
/**
* @dev Returns the scaled balance of the user and the scaled total supply.
* @param user The address of the user
* @return The scaled balance of the user
* @return The scaled balance and the scaled total supply
**/
function getScaledUserBalanceAndSupply(address user) external view returns (uint256, uint256);
/**
* @dev Returns the scaled total supply of the variable debt token. Represents sum(debt/index)
* @return The scaled total supply
**/
function scaledTotalSupply() external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
interface IReserveInterestRateStrategy {
function baseVariableBorrowRate() external view returns (uint256);
function getMaxVariableBorrowRate() external view returns (uint256);
function calculateInterestRates(
uint256 availableLiquidity,
uint256 totalVariableDebt,
uint256 reserveFactor
)
external
view
returns (
uint256,
uint256
);
function calculateInterestRates(
address reserve,
address kToken,
uint256 liquidityAdded,
uint256 liquidityTaken,
uint256 totalVariableDebt,
uint256 reserveFactor
)
external
view
returns (
uint256 liquidityRate,
uint256 variableBorrowRate
);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
import "../lendingpool/DataTypes.sol";
interface ILendingPool {
/**
* @dev Emitted on deposit()
* @param reserve The address of the underlying asset of the reserve
* @param user The address initiating the deposit
* @param onBehalfOf The beneficiary of the deposit, receiving the kTokens
* @param amount The amount deposited
**/
event Deposit(
address indexed reserve,
address user,
address indexed onBehalfOf,
uint256 amount
);
/**
* @dev Emitted on withdraw()
* @param reserve The address of the underlyng asset being withdrawn
* @param user The address initiating the withdrawal, owner of kTokens
* @param to Address that will receive the underlying
* @param amount The amount to be withdrawn
**/
event Withdraw(
address indexed reserve,
address indexed user,
address indexed to,
uint256 amount
);
/**
* @dev Emitted on borrow() and flashLoan() when debt needs to be opened
* @param reserve The address of the underlying asset being borrowed
* @param user The address of the user initiating the borrow(), receiving the funds on borrow()
* @param onBehalfOf The address that will be getting the debt
* @param amount The amount borrowed out
* @param borrowRate The numeric rate at which the user has borrowed
**/
event Borrow(
address indexed reserve,
address user,
address indexed onBehalfOf,
uint256 amount,
uint256 borrowRate
);
/**
* @dev Emitted on repay()
* @param reserve The address of the underlying asset of the reserve
* @param user The beneficiary of the repayment, getting his debt reduced
* @param repayer The address of the user initiating the repay(), providing the funds
* @param amount The amount repaid
**/
event Repay(
address indexed reserve,
address indexed user,
address indexed repayer,
uint256 amount
);
/**
* @dev Emitted on initReserve()
**/
event InitReserve(
address asset,
address kTokenAddress,
address variableDebtAddress,
address interestRateStrategyAddress,
uint8 reserveDecimals,
uint16 reserveFactor
);
/**
* @dev Emitted when the pause is triggered.
*/
event Paused();
/**
* @dev Emitted when the pause is lifted.
*/
event Unpaused();
/**
* @dev Emitted when the state of a reserve is updated. NOTE: This event is actually declared
* in the ReserveLogic library and emitted in the updateInterestRates() function. Since the function is internal,
* the event will actually be fired by the LendingPool contract. The event is therefore replicated here so it
* gets added to the LendingPool ABI
* @param reserve The address of the underlying asset of the reserve
* @param liquidityRate The new liquidity rate
* @param variableBorrowRate The new variable borrow rate
* @param liquidityIndex The new liquidity index
* @param variableBorrowIndex The new variable borrow index
**/
event ReserveDataUpdated(
address indexed reserve,
uint256 liquidityRate,
uint256 variableBorrowRate,
uint256 liquidityIndex,
uint256 variableBorrowIndex
);
/**
* @dev Emitted when a reserve factor is updated
* @param asset The address of the underlying asset of the reserve
* @param factor The new reserve factor
**/
event ReserveFactorChanged(address indexed asset, uint256 factor);
/**
* @dev Emitted when a reserve active state is updated
* @param asset The address of the underlying asset of the reserve
* @param active The new reserve active state
**/
event ReserveActiveChanged(address indexed asset, bool active);
/**
* @dev Emitted when credit system is updated
* @param creditContract The address of the new credit system
**/
event CreditStrategyChanged(address creditContract);
/**
* @dev Deposits an `amount` of underlying asset into the reserve, receiving in return overlying kTokens.
* - E.g. User deposits 100 USDT and gets in return 100 kUSDT
* @param asset The address of the underlying asset to deposit
* @param amount The amount to be deposited
* @param onBehalfOf The address that will receive the kTokens, same as msg.sender if the user
* wants to receive them on his own wallet, or a different address if the beneficiary of kTokens
* is a different wallet
**/
function deposit(
address asset,
uint256 amount,
address onBehalfOf
) external;
/**
* @dev Withdraws an `amount` of underlying asset from the reserve, burning the equivalent kTokens owned
* E.g. User has 100 kUSDT, calls withdraw() and receives 100 USDT, burning the 100 aUSDT
* @param asset The address of the underlying asset to withdraw
* @param amount The underlying amount to be withdrawn
* - Send the value type(uint256).max in order to withdraw the whole kToken balance
* @param to Address that will receive the underlying, same as msg.sender if the user
* wants to receive it on his own wallet, or a different address if the beneficiary is a
* different wallet
* @return The final amount withdrawn
**/
function withdraw(
address asset,
uint256 amount,
address to
) external returns (uint256);
/**
* @dev Allows users to borrow a specific `amount` of the reserve underlying asset, provided that the borrower
* already had a credit line, or he was given enough allowance by a credit delegator on the
* corresponding debt token
* - E.g. User borrows 100 USDT passing as `onBehalfOf` his own address, receiving the 100 USDT in his wallet
* and 100 variable debt tokens
* @param asset The address of the underlying asset to borrow
* @param amount The amount to be borrowed
* @param onBehalfOf Address of the user who will receive the debt. Should be the address of the borrower itself
* calling the function if he wants to borrow against his own credit, or the address of the credit delegator
* if he has been given credit delegation allowance
**/
function borrow(
address asset,
uint256 amount,
address onBehalfOf
) external;
/**
* @notice Repays a borrowed `amount` on a specific reserve, burning the equivalent debt tokens owned
* - E.g. User repays 100 USDT, burning 100 variable/stable debt tokens of the `onBehalfOf` address
* @param asset The address of the borrowed underlying asset previously borrowed
* @param amount The amount to repay
* - Send the value type(uint256).max in order to repay the whole debt for `asset`
* @param onBehalfOf Address of the user who will get his debt reduced/removed. Should be the address of the
* user calling the function if he wants to reduce/remove his own debt, or the address of any other
* other borrower whose debt should be removed
* @return The final amount repaid
**/
function repay(
address asset,
uint256 amount,
address onBehalfOf
) external returns (uint256);
/**
* @dev Returns the user account data across all the reserves
* @param user The address of the user
* @return totalDebtInWEI the total debt in WEI of the user
* @return availableBorrowsInWEI the borrowing power left of the user
**/
function getUserAccountData(address user)
external
view
returns (uint256 totalDebtInWEI, uint256 availableBorrowsInWEI);
function initReserve(
address reserve,
address kTokenAddress,
address variableDebtAddress,
address interestRateStrategyAddress,
uint8 reserveDecimals,
uint16 reserveFactor
) external;
function setReserveInterestRateStrategyAddress(
address reserve,
address rateStrategyAddress
) external;
/**
* @dev Returns the normalized income normalized income of the reserve
* @param asset The address of the underlying asset of the reserve
* @return The reserve's normalized income
*/
function getReserveNormalizedIncome(address asset)
external
view
returns (uint256);
/**
* @dev Returns the normalized variable debt per unit of asset
* @param asset The address of the underlying asset of the reserve
* @return The reserve normalized variable debt
*/
function getReserveNormalizedVariableDebt(address asset)
external
view
returns (uint256);
/**
* @dev Returns the state and configuration of the reserve
* @param asset The address of the underlying asset of the reserve
* @return The state of the reserve
**/
function getReserveData(address asset)
external
view
returns (DataTypes.ReserveData memory);
function getReservesList() external view returns (address[] memory);
function setPause(bool val) external;
function paused() external view returns (bool);
function getActive(address asset) external view returns (bool);
function setCreditStrategy(address creditContract) external;
function getCreditStrategy() external view returns (address);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import "./IScaledBalanceToken.sol";
import "./IInitializableKToken.sol";
interface IKToken is IERC20Upgradeable, IScaledBalanceToken, IInitializableKToken {
/**
* @dev Emitted after the mint action
* @param from The address performing the mint
* @param value The amount being
* @param index The new liquidity index of the reserve
**/
event Mint(address indexed from, uint256 value, uint256 index);
/**
* @dev Mints `amount` kTokens to `user`
* @param user The address receiving the minted tokens
* @param amount The amount of tokens getting minted
* @param index The new liquidity index of the reserve
* @return `true` if the the previous balance of the user was 0
*/
function mint(
address user,
uint256 amount,
uint256 index
) external returns (bool);
/**
* @dev Emitted after kTokens are burned
* @param from The owner of the kTokens, getting them burned
* @param target The address that will receive the underlying
* @param value The amount being burned
* @param index The new liquidity index of the reserve
**/
event Burn(address indexed from, address indexed target, uint256 value, uint256 index);
/**
* @dev Emitted during the transfer action
* @param from The user whose tokens are being transferred
* @param to The recipient
* @param value The amount being transferred
* @param index The new liquidity index of the reserve
**/
event BalanceTransfer(address indexed from, address indexed to, uint256 value, uint256 index);
/**
* @dev Burns kTokens from `user` and sends the equivalent amount of underlying to `receiverOfUnderlying`
* @param user The owner of the kTokens, getting them burned
* @param receiverOfUnderlying The address that will receive the underlying
* @param amount The amount being burned
* @param index The new liquidity index of the reserve
**/
function burn(
address user,
address receiverOfUnderlying,
uint256 amount,
uint256 index
) external;
/**
* @dev Mints kTokens to the reserve treasury
* @param amount The amount of tokens getting minted
* @param index The new liquidity index of the reserve
*/
function mintToTreasury(uint256 amount, uint256 index) external;
/**
* @dev Transfers the underlying asset to `target`. Used by the LendingPool to transfer
* assets in borrow(), withdraw() and flashLoan()
* @param user The recipient of the underlying
* @param amount The amount getting transferred
* @return The amount transferred
**/
function transferUnderlyingTo(address user, uint256 amount) external returns (uint256);
/**
* @dev Invoked to execute actions on the kToken side after a repayment.
* @param user The user executing the repayment
* @param amount The amount getting repaid
**/
function handleRepayment(address user, uint256 amount) external;
/**
* @dev Returns the address of the underlying asset of this kToken (E.g. USDT for kUSDT)
**/
function UNDERLYING_ASSET_ADDRESS() external view returns (address);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
import "./ILendingPool.sol";
interface IInitializableKToken {
/**
* @dev Emitted when an kToken is initialized
* @param underlyingAsset The address of the underlying asset
* @param pool The address of the associated lending pool
* @param treasury The address of the treasury
* @param kTokenDecimals the decimals of the underlying
* @param kTokenName the name of the kToken
* @param kTokenSymbol the symbol of the kToken
* @param params A set of encoded parameters for additional initialization
**/
event Initialized(
address indexed underlyingAsset,
address indexed pool,
address treasury,
uint8 kTokenDecimals,
string kTokenName,
string kTokenSymbol,
bytes params
);
/**
* @dev Initializes the kToken
* @param pool The address of the lending pool where this kToken will be used
* @param treasury The address of the Kyoko treasury, receiving the fees on this kToken
* @param underlyingAsset The address of the underlying asset of this kToken (E.g. USDT for kUSDT)
* @param kTokenDecimals The decimals of the kToken, same as the underlying asset's
* @param kTokenName The name of the kToken
* @param kTokenSymbol The symbol of the kToken
*/
function initialize(
ILendingPool pool,
address treasury,
address underlyingAsset,
uint8 kTokenDecimals,
string calldata kTokenName,
string calldata kTokenSymbol,
bytes calldata params
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
import "./ILendingPool.sol";
interface IInitializableDebtToken {
/**
* @dev Emitted when a debt token is initialized
* @param underlyingAsset The address of the underlying asset
* @param pool The address of the associated lending pool
* @param debtTokenDecimals the decimals of the debt token
* @param debtTokenName the name of the debt token
* @param debtTokenSymbol the symbol of the debt token
* @param params A set of encoded parameters for additional initialization
**/
event Initialized(
address indexed underlyingAsset,
address indexed pool,
uint8 debtTokenDecimals,
string debtTokenName,
string debtTokenSymbol,
bytes params
);
/**
* @dev Initializes the debt token.
* @param pool The address of the lending pool where this kToken will be used
* @param underlyingAsset The address of the underlying asset of this kToken (E.g. USDT for kUSDT)
* @param debtTokenDecimals The decimals of the debtToken, same as the underlying asset's
* @param debtTokenName The name of the token
* @param debtTokenSymbol The symbol of the token
*/
function initialize(
ILendingPool pool,
address underlyingAsset,
uint8 debtTokenDecimals,
string memory debtTokenName,
string memory debtTokenSymbol,
bytes calldata params
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
import "@openzeppelin/contracts-upgradeable/access/AccessControlEnumerableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol";
/**
* @dev this contract represents the credit line in the whitelist.
* @dev the guild's credit line amount
* @dev the decimals is 1e18.
*/
contract CreditSystem is AccessControlEnumerableUpgradeable {
using SafeMathUpgradeable for uint256;
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
/// the role manage total credit manager
bytes32 public constant ROLE_CREDIT_MANAGER =
keccak256("ROLE_CREDIT_MANAGER");
uint8 public constant G2G_MASK = 0x0E;
uint8 public constant CCAL_MASK = 0x0D;
uint8 constant IS_G2G_START_BIT_POSITION = 0;
uint8 constant IS_CCAL_START_BIT_POSITION = 1;
struct CreditInfo {
//ERC20 credit line
uint256 g2gCreditLine;
//ccal module credit line
uint256 ccalCreditLine;
//bit 0: g2g isActive flag(0==false, 1==true)
//bit 1: ccal isActive flag(0==false, 1==true)
uint8 flag;
}
// the credit line
mapping(address => CreditInfo) whiteList;
//g2g whiteList Set
EnumerableSetUpgradeable.AddressSet private g2gWhiteSet;
//ccal whiteList Set
EnumerableSetUpgradeable.AddressSet private ccalWhiteSet;
event SetG2GCreditLine(address user, uint256 amount);
event SetCCALCreditLine(address user, uint256 amount);
// event SetPaused(address user, bool flag);
event SetG2GActive(address user, bool active);
event SetCCALActive(address user, bool active);
event RemoveG2GCredit(address user);
event RemoveCCALCredit(address user);
modifier onlyCreditManager() {
require(
hasRole(ROLE_CREDIT_MANAGER, _msgSender()),
"only the manager has permission to perform this operation."
);
_;
}
// constructor() {
// _grantRole(DEFAULT_ADMIN_ROLE, _msgSender());
// }
function initialize() public initializer {
__AccessControlEnumerable_init();
_grantRole(DEFAULT_ADMIN_ROLE, _msgSender());
}
/**
* set the address's g2g module credit line
* @dev user the guild in the whiteList
* @dev amount the guild credit line amount
* @dev 1U = 1e18
*/
function setG2GCreditLine(address user, uint256 amount)
public
onlyCreditManager
{
whiteList[user].g2gCreditLine = amount;
setG2GActive(user, amount > 0);
emit SetG2GCreditLine(user, amount);
}
/**
* @dev set the address's g2g module credit active status
*/
function setG2GActive(address user, bool active) public onlyCreditManager {
//set user flag
setG2GFlag(user, active);
//set user white set
if (active) {
uint256 userG2GCreditLine = getG2GCreditLine(user);
userG2GCreditLine > 0 ? g2gWhiteSet.add(user) : g2gWhiteSet.remove(user);
} else {
g2gWhiteSet.remove(user);
}
emit SetG2GActive(user, active);
}
function setG2GFlag(address user, bool active) private {
uint8 flag = whiteList[user].flag;
flag =
(flag & G2G_MASK) |
(uint8(active ? 1 : 0) << IS_G2G_START_BIT_POSITION);
whiteList[user].flag = flag;
}
/**
* set the address's ccal module credit line
* @dev user the guild in the whiteList
* @dev amount the guild credit line amount
* @dev 1U = 1e18
*/
function setCCALCreditLine(address user, uint256 amount)
public
onlyCreditManager
{
whiteList[user].ccalCreditLine = amount;
setCCALActive(user, amount > 0);
emit SetCCALCreditLine(user, amount);
}
/**
* @dev set the address's ccal module credit active status
*/
function setCCALActive(address user, bool active) public onlyCreditManager {
//set user flag
setCCALFlag(user, active);
//set user white set
if (active) {
uint256 userCCALCreditLine = getCCALCreditLine(user);
userCCALCreditLine > 0 ? ccalWhiteSet.add(user) : ccalWhiteSet.remove(user);
} else {
ccalWhiteSet.remove(user);
}
emit SetCCALActive(user, active);
}
function setCCALFlag(address user, bool active) private {
uint8 flag = whiteList[user].flag;
flag =
(flag & CCAL_MASK) |
(uint8(active ? 1 : 0) << IS_CCAL_START_BIT_POSITION);
whiteList[user].flag = flag;
}
/**
* remove the address's g2g module credit line
*/
function removeG2GCredit(address user) public onlyCreditManager {
whiteList[user].g2gCreditLine = 0;
setG2GActive(user, false);
emit RemoveG2GCredit(user);
}
/**
* remove the address's ccal module credit line
*/
function removeCCALCredit(address user) public onlyCreditManager {
whiteList[user].ccalCreditLine = 0;
setCCALActive(user, false);
emit RemoveCCALCredit(user);
}
/**
* @dev query the user credit line
* @param user the address which to query
* @return G2G credit line
*/
function getG2GCreditLine(address user) public view returns (uint256) {
CreditInfo memory credit = whiteList[user];
return credit.g2gCreditLine;
}
/**
* @dev query the user credit line
* @param user the address which to query
* @return CCAL credit line
*/
function getCCALCreditLine(address user) public view returns (uint256) {
CreditInfo memory credit = whiteList[user];
return credit.ccalCreditLine;
}
/**
* @dev query the white list addresses in G2G
*/
function getG2GWhiteList() public view returns (address[] memory) {
return g2gWhiteSet.values();
}
/**
* @dev query the white list addresses in CCAL
*/
function getCCALWhiteList() public view returns (address[] memory) {
return ccalWhiteSet.values();
}
/**
* @dev query the address state
*/
function getState(address user) public view returns (bool, bool) {
uint8 activeFlag = whiteList[user].flag;
return (
activeFlag & ~G2G_MASK != 0,
activeFlag & ~CCAL_MASK != 0
);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/structs/EnumerableSet.sol)
pragma solidity ^0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSetUpgradeable {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping(bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
if (lastIndex != toDeleteIndex) {
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
return _values(set._inner);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(AddressSet storage set) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
assembly {
result := store
}
return result;
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(UintSet storage set) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
assembly {
result := store
}
return result;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol)
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler
* now has built in overflow checking.
*/
library SafeMathUpgradeable {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165Upgradeable {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {
function __ERC165_init() internal onlyInitializing {
__ERC165_init_unchained();
}
function __ERC165_init_unchained() internal onlyInitializing {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165Upgradeable).interfaceId;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library StringsUpgradeable {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
__Context_init_unchained();
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC20Upgradeable.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20MetadataUpgradeable is IERC20Upgradeable {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/ERC20.sol)
pragma solidity ^0.8.0;
import "./IERC20Upgradeable.sol";
import "./extensions/IERC20MetadataUpgradeable.sol";
import "../../utils/ContextUpgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
function __ERC20_init(string memory name_, string memory symbol_) internal onlyInitializing {
__Context_init_unchained();
__ERC20_init_unchained(name_, symbol_);
}
function __ERC20_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
unchecked {
_approve(sender, _msgSender(), currentAllowance - amount);
}
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `sender` to `recipient`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[sender] = senderBalance - amount;
}
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
_afterTokenTransfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
uint256[45] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (proxy/utils/Initializable.sol)
pragma solidity ^0.8.0;
import "../../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the
* initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() initializer {}
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
// If the contract is initializing we ignore whether _initialized is set in order to support multiple
// inheritance patterns, but we only do this in the context of a constructor, because in other contexts the
// contract may have been reentered.
require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} modifier, directly or indirectly.
*/
modifier onlyInitializing() {
require(_initializing, "Initializable: contract is not initializing");
_;
}
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControlUpgradeable {
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControlEnumerable.sol)
pragma solidity ^0.8.0;
import "./IAccessControlUpgradeable.sol";
/**
* @dev External interface of AccessControlEnumerable declared to support ERC165 detection.
*/
interface IAccessControlEnumerableUpgradeable is IAccessControlUpgradeable {
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) external view returns (address);
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/AccessControl.sol)
pragma solidity ^0.8.0;
import "./IAccessControlUpgradeable.sol";
import "../utils/ContextUpgradeable.sol";
import "../utils/StringsUpgradeable.sol";
import "../utils/introspection/ERC165Upgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable {
function __AccessControl_init() internal onlyInitializing {
__Context_init_unchained();
__ERC165_init_unchained();
__AccessControl_init_unchained();
}
function __AccessControl_init_unchained() internal onlyInitializing {
}
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*/
function _checkRole(bytes32 role, address account) internal view {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
StringsUpgradeable.toHexString(uint160(account), 20),
" is missing role ",
StringsUpgradeable.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been revoked `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*
* NOTE: This function is deprecated in favor of {_grantRole}.
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
/**
* @dev Grants `role` to `account`.
*
* Internal function without access restriction.
*/
function _grantRole(bytes32 role, address account) internal virtual {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
/**
* @dev Revokes `role` from `account`.
*
* Internal function without access restriction.
*/
function _revokeRole(bytes32 role, address account) internal virtual {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/AccessControlEnumerable.sol)
pragma solidity ^0.8.0;
import "./IAccessControlEnumerableUpgradeable.sol";
import "./AccessControlUpgradeable.sol";
import "../utils/structs/EnumerableSetUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Extension of {AccessControl} that allows enumerating the members of each role.
*/
abstract contract AccessControlEnumerableUpgradeable is Initializable, IAccessControlEnumerableUpgradeable, AccessControlUpgradeable {
function __AccessControlEnumerable_init() internal onlyInitializing {
__Context_init_unchained();
__ERC165_init_unchained();
__AccessControl_init_unchained();
__AccessControlEnumerable_init_unchained();
}
function __AccessControlEnumerable_init_unchained() internal onlyInitializing {
}
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
mapping(bytes32 => EnumerableSetUpgradeable.AddressSet) private _roleMembers;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlEnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view override returns (address) {
return _roleMembers[role].at(index);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view override returns (uint256) {
return _roleMembers[role].length();
}
/**
* @dev Overload {_grantRole} to track enumerable memberships
*/
function _grantRole(bytes32 role, address account) internal virtual override {
super._grantRole(role, account);
_roleMembers[role].add(account);
}
/**
* @dev Overload {_revokeRole} to track enumerable memberships
*/
function _revokeRole(bytes32 role, address account) internal virtual override {
super._revokeRole(role, account);
_roleMembers[role].remove(account);
}
uint256[49] private __gap;
} | * @dev Returns the ongoing normalized variable debt for the reserve A value of 1e27 means there is no debt. As time passes, the income is accrued A value of 21e27 means that for each unit of debt, one unit worth of interest has been accumulated @param reserve The reserve object @return The normalized variable debt. expressed in ray/solium-disable-next-lineif the index was updated in the same block, no need to perform any calculation | function getNormalizedDebt(DataTypes.ReserveData storage reserve)
internal
view
returns (uint256)
{
uint40 timestamp = reserve.lastUpdateTimestamp;
if (timestamp == uint40(block.timestamp)) {
return reserve.variableBorrowIndex;
}
uint256 cumulated =
MathUtils.calculateCompoundedInterest(reserve.currentVariableBorrowRate, timestamp).rayMul(
reserve.variableBorrowIndex
);
return cumulated;
}
| 11,804,913 | [
1,
1356,
326,
30542,
5640,
2190,
18202,
88,
364,
326,
20501,
432,
460,
434,
404,
73,
5324,
4696,
1915,
353,
1158,
18202,
88,
18,
2970,
813,
11656,
16,
326,
316,
5624,
353,
4078,
86,
5957,
432,
460,
434,
9035,
73,
5324,
4696,
716,
364,
1517,
2836,
434,
18202,
88,
16,
1245,
2836,
26247,
434,
16513,
711,
2118,
24893,
225,
20501,
1021,
20501,
733,
327,
1021,
5640,
2190,
18202,
88,
18,
26863,
316,
14961,
19,
18281,
5077,
17,
8394,
17,
4285,
17,
1369,
430,
326,
770,
1703,
3526,
316,
326,
1967,
1203,
16,
1158,
1608,
358,
3073,
1281,
11096,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
336,
15577,
758,
23602,
12,
751,
2016,
18,
607,
6527,
751,
2502,
20501,
13,
203,
3639,
2713,
203,
3639,
1476,
203,
3639,
1135,
261,
11890,
5034,
13,
203,
565,
288,
203,
3639,
2254,
7132,
2858,
273,
20501,
18,
2722,
1891,
4921,
31,
203,
203,
3639,
309,
261,
5508,
422,
2254,
7132,
12,
2629,
18,
5508,
3719,
288,
203,
5411,
327,
20501,
18,
6105,
38,
15318,
1016,
31,
203,
3639,
289,
203,
203,
3639,
2254,
5034,
276,
5283,
690,
273,
203,
5411,
2361,
1989,
18,
11162,
2945,
12002,
29281,
12,
455,
6527,
18,
2972,
3092,
38,
15318,
4727,
16,
2858,
2934,
435,
27860,
12,
203,
7734,
20501,
18,
6105,
38,
15318,
1016,
203,
5411,
11272,
203,
203,
3639,
327,
276,
5283,
690,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/utils/Context.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "@openzeppelin/contracts/utils/introspection/ERC165.sol";
import "./IERC721LibBeforeTokenTransferHook.sol";
/* Functionality used to whitelist OpenSea trading address, if desired */
contract OwnableDelegateProxy {}
contract ProxyRegistry {
mapping(address => OwnableDelegateProxy) public proxies;
}
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, the Enumerable extension, and Pausable.
*
* Closely based on and mirrors the excellent https://openzeppelin.com/contracts/.
*/
library ERC721Lib {
using Address for address;
using Strings for uint256;
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
struct ERC721Storage {
// Token name
string _name;
// Token symbol
string _symbol;
// Mapping from token ID to owner address
mapping (uint256 => address) _owners;
// Mapping owner address to token count
mapping (address => uint256) _balances;
// Mapping from token ID to approved address
mapping (uint256 => address) _tokenApprovals;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) _operatorApprovals;
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) _allTokensIndex;
// Base URI
string _baseURI;
// True if token transfers are paused
bool _paused;
// Hook function that can be called before token is transferred, along with a pointer to its storage struct
IERC721LibBeforeTokenTransferHook _beforeTokenTransferHookInterface;
bytes32 _beforeTokenTransferHookStorageSlot;
address proxyRegistryAddress;
}
function init(ERC721Storage storage s, string memory _name, string memory _symbol) external {
s._name = _name;
s._symbol = _symbol;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) external pure returns (bool) {
return interfaceId == type(IERC721).interfaceId
|| interfaceId == type(IERC721Metadata).interfaceId
|| interfaceId == type(IERC721Enumerable).interfaceId;
}
//
// Start of ERC721 functions
//
/**
* @dev See {IERC721-balanceOf}.
*/
function _balanceOf(ERC721Storage storage s, address owner) internal view returns (uint256) {
require(owner != address(0), "Balance query for address zero");
return s._balances[owner];
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(ERC721Storage storage s, address owner) external view returns (uint256) {
return _balanceOf(s, owner);
}
/**
* @dev See {IERC721-ownerOf}.
*/
function _ownerOf(ERC721Storage storage s, uint256 tokenId) internal view returns (address) {
address owner = s._owners[tokenId];
require(owner != address(0), "Owner query for nonexist. token");
return owner;
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(ERC721Storage storage s, uint256 tokenId) external view returns (address) {
return _ownerOf(s, tokenId);
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name(ERC721Storage storage s) external view returns (string memory) {
return s._name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol(ERC721Storage storage s) external view returns (string memory) {
return s._symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(ERC721Storage storage s, uint256 tokenId) external view returns (string memory) {
require(_exists(s, tokenId), "URI query for nonexistent token");
return bytes(s._baseURI).length > 0
? string(abi.encodePacked(s._baseURI, tokenId.toString()))
: "";
}
/**
* @dev Set base URI
*/
function setBaseURI(ERC721Storage storage s, string memory baseTokenURI) external {
s._baseURI = baseTokenURI;
}
/**
* @dev See {IERC721-approve}.
*/
function approve(ERC721Storage storage s, address to, uint256 tokenId) external {
address owner = _ownerOf(s, tokenId);
require(to != owner, "Approval to current owner");
require(msg.sender == owner || _isApprovedForAll(s, owner, msg.sender),
"Not owner nor approved for all"
);
_approve(s, to, tokenId);
}
/**
* @dev Approve independently of who's the owner
*
* Obviously expose with care...
*/
function overrideApprove(ERC721Storage storage s, address to, uint256 tokenId) external {
_approve(s, to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function _getApproved(ERC721Storage storage s, uint256 tokenId) internal view returns (address) {
require(_exists(s, tokenId), "Approved query nonexist. token");
return s._tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(ERC721Storage storage s, uint256 tokenId) external view returns (address) {
return _getApproved(s, tokenId);
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(ERC721Storage storage s, address operator, bool approved) external {
require(operator != msg.sender, "Attempted approve to caller");
s._operatorApprovals[msg.sender][operator] = approved;
emit ApprovalForAll(msg.sender, operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function _isApprovedForAll(ERC721Storage storage s, address owner, address operator) internal view returns (bool) {
// Whitelist OpenSea proxy contract for easy trading - if we have a valid proxy registry address on file
if (s.proxyRegistryAddress != address(0)) {
ProxyRegistry proxyRegistry = ProxyRegistry(s.proxyRegistryAddress);
if (address(proxyRegistry.proxies(owner)) == operator) {
return true;
}
}
return s._operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(ERC721Storage storage s, address owner, address operator) external view returns (bool) {
return _isApprovedForAll(s, owner, operator);
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(ERC721Storage storage s, address from, address to, uint256 tokenId) external {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(s, msg.sender, tokenId), "TransferFrom not owner/approved");
_transfer(s, from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(ERC721Storage storage s, address from, address to, uint256 tokenId) external {
_safeTransferFrom(s, from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function _safeTransferFrom(ERC721Storage storage s, address from, address to, uint256 tokenId, bytes memory _data) internal {
require(_isApprovedOrOwner(s, msg.sender, tokenId), "TransferFrom not owner/approved");
_safeTransfer(s, from, to, tokenId, _data);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(ERC721Storage storage s, address from, address to, uint256 tokenId, bytes memory _data) external {
_safeTransferFrom(s, from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(ERC721Storage storage s, address from, address to, uint256 tokenId, bytes memory _data) internal {
_transfer(s, from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "Transfer to non ERC721Receiver");
}
/**
* @dev directSafeTransfer
*
* CAREFUL, this does not verify the previous ownership - only use if ownership/eligibility has been asserted by other means
*/
function directSafeTransfer(ERC721Storage storage s, address from, address to, uint256 tokenId, bytes memory _data) external {
_safeTransfer(s, from, to, tokenId, _data);
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(ERC721Storage storage s, uint256 tokenId) internal view returns (bool) {
return s._owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(ERC721Storage storage s, address spender, uint256 tokenId) internal view returns (bool) {
require(_exists(s, tokenId), "Operator query nonexist. token");
address owner = _ownerOf(s, tokenId);
return (spender == owner || _getApproved(s, tokenId) == spender || _isApprovedForAll(s, owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(ERC721Storage storage s, address to, uint256 tokenId) internal {
_safeMint(s, to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(ERC721Storage storage s, address to, uint256 tokenId, bytes memory _data) internal {
_unsafeMint(s, to, tokenId);
require(_checkOnERC721Received(address(0), to, tokenId, _data), "Transfer to non ERC721Receiver");
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _unsafeMint(ERC721Storage storage s, address to, uint256 tokenId) internal {
require(to != address(0), "Mint to the zero address");
require(!_exists(s, tokenId), "Token already minted");
_beforeTokenTransfer(s, address(0), to, tokenId);
s._balances[to] += 1;
s._owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(ERC721Storage storage s, uint256 tokenId) internal {
address owner = _ownerOf(s, tokenId);
_beforeTokenTransfer(s, owner, address(0), tokenId);
// Clear approvals
_approve(s, address(0), tokenId);
s._balances[owner] -= 1;
delete s._owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(ERC721Storage storage s, address from, address to, uint256 tokenId) internal {
require(_ownerOf(s, tokenId) == from, "TransferFrom not owner/approved");
require(to != address(0), "Transfer to the zero address");
_beforeTokenTransfer(s, from, to, tokenId);
// Clear approvals from the previous owner
_approve(s, address(0), tokenId);
s._balances[from] -= 1;
s._balances[to] += 1;
s._owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(ERC721Storage storage s, address to, uint256 tokenId) internal {
s._tokenApprovals[tokenId] = to;
emit Approval(_ownerOf(s, tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data)
private returns (bool)
{
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(msg.sender, from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("Transfer to non ERC721Receiver");
} else {
// solhint-disable-next-line no-inline-assembly
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
//
// Start of functions from ERC721Enumerable
//
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(ERC721Storage storage s, address owner, uint256 index) external view returns (uint256) {
require(index < _balanceOf(s, owner), "Owner index out of bounds");
return s._ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function _totalSupply(ERC721Storage storage s) internal view returns (uint256) {
return s._allTokens.length;
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply(ERC721Storage storage s) external view returns (uint256) {
return s._allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(ERC721Storage storage s, uint256 index) external view returns (uint256) {
require(index < _totalSupply(s), "Global index out of bounds");
return s._allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(ERC721Storage storage s, address from, address to, uint256 tokenId) internal {
if(address(s._beforeTokenTransferHookInterface) != address(0)) {
// We have a hook that we need to delegate call
(bool success, ) = address(s._beforeTokenTransferHookInterface).delegatecall(
abi.encodeWithSelector(s._beforeTokenTransferHookInterface._beforeTokenTransferHook.selector, s._beforeTokenTransferHookStorageSlot, from, to, tokenId)
);
if(!success) {
// Bubble up the revert message
assembly {
let ptr := mload(0x40)
let size := returndatasize()
returndatacopy(ptr, 0, size)
revert(ptr, size)
}
}
}
require(!_paused(s), "No token transfer while paused");
if (from == address(0)) {
_addTokenToAllTokensEnumeration(s, tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(s, from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(s, tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(s, to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(ERC721Storage storage s, address to, uint256 tokenId) private {
uint256 length = _balanceOf(s, to);
s._ownedTokens[to][length] = tokenId;
s._ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(ERC721Storage storage s, uint256 tokenId) private {
s._allTokensIndex[tokenId] = s._allTokens.length;
s._allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(ERC721Storage storage s, address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _balanceOf(s, from) - 1;
uint256 tokenIndex = s._ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = s._ownedTokens[from][lastTokenIndex];
s._ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
s._ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete s._ownedTokensIndex[tokenId];
delete s._ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(ERC721Storage storage s, uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = s._allTokens.length - 1;
uint256 tokenIndex = s._allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = s._allTokens[lastTokenIndex];
s._allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
s._allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete s._allTokensIndex[tokenId];
s._allTokens.pop();
}
//
// Start of functions from Pausable
//
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function _paused(ERC721Storage storage s) internal view returns (bool) {
return s._paused;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused(ERC721Storage storage s) external view returns (bool) {
return s._paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused(ERC721Storage storage s) {
require(!_paused(s), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused(ERC721Storage storage s) {
require(_paused(s), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause(ERC721Storage storage s) external whenNotPaused(s) {
s._paused = true;
emit Paused(msg.sender);
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause(ERC721Storage storage s) external whenPaused(s) {
s._paused = false;
emit Unpaused(msg.sender);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant alphabet = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = alphabet[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./ERC721Lib.sol";
/**
* @dev Interface that can be used to hook additional beforeTokenTransfer functions into ERC721Lib
*/
interface IERC721LibBeforeTokenTransferHook {
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransferHook(bytes32 storagePosition, address from, address to, uint256 tokenId) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
| * @dev See {IERC721Metadata-symbol}./ | function symbol(ERC721Storage storage s) external view returns (string memory) {
return s._symbol;
}
| 6,935,768 | [
1,
9704,
288,
45,
654,
39,
27,
5340,
2277,
17,
7175,
5496,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
3273,
12,
654,
39,
27,
5340,
3245,
2502,
272,
13,
3903,
1476,
1135,
261,
1080,
3778,
13,
288,
203,
3639,
327,
272,
6315,
7175,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
* Copyright 2017-2021, bZeroX, LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0.
*/
pragma solidity 0.5.17;
pragma experimental ABIEncoderV2;
import "../../AdvancedToken.sol";
import "../../interfaces/ProtocolSettingsLike.sol";
import "../../LoanTokenLogicStorage.sol";
contract LoanTokenSettingsLowerAdmin is LoanTokenLogicStorage {
using SafeMath for uint256;
/// @dev TODO: Check for restrictions in this contract.
modifier onlyAdmin() {
require(isOwner() || msg.sender == admin, "unauthorized");
_;
}
/* Events */
event SetTransactionLimits(address[] addresses, uint256[] limits);
event ToggledFunctionPaused(string functionId, bool prevFlag, bool newFlag);
/* Functions */
/**
* @notice This function is MANDATORY, which will be called by LoanTokenLogicBeacon and be registered.
* Every new public function, the sginature needs to be included in this function.
*
* @dev This function will return the list of function signature in this contract that are available for public call
* Then this function will be called by LoanTokenLogicBeacon, and the function signatures will be registred in LoanTokenLogicBeacon.
* @dev To save the gas we can just directly return the list of function signature from this pure function.
* The other workaround (fancy way) is we can create a storage for the list of the function signature, and then we can store each function signature to that storage from the constructor.
* Then, in this function we just need to return that storage variable.
*
* @return The list of function signatures (bytes4[])
*/
function getListFunctionSignatures() external pure returns (bytes4[] memory functionSignatures, bytes32 moduleName) {
bytes4[] memory res = new bytes4[](9);
res[0] = this.setAdmin.selector;
res[1] = this.setPauser.selector;
res[2] = this.setupLoanParams.selector;
res[3] = this.disableLoanParams.selector;
res[4] = this.setDemandCurve.selector;
res[5] = this.toggleFunctionPause.selector;
res[6] = this.setTransactionLimits.selector;
res[7] = this.changeLoanTokenNameAndSymbol.selector;
res[8] = this.pauser.selector;
return (res, stringToBytes32("LoanTokenSettingsLowerAdmin"));
}
/**
* @notice Set admin account.
* @param _admin The address of the account to grant admin permissions.
* */
function setAdmin(address _admin) public onlyOwner {
admin = _admin;
}
/**
* @notice Set pauser account.
* @param _pauser The address of the account to grant pause permissions.
* */
function setPauser(address _pauser) public onlyOwner {
pauser = _pauser;
}
/**
* @notice Fallback function not allowed
* */
function() external {
revert("LoanTokenSettingsLowerAdmin - fallback not allowed");
}
/**
* @notice Set loan token parameters.
*
* @param loanParamsList The array of loan parameters.
* @param areTorqueLoans Whether the loan is a torque loan.
* */
function setupLoanParams(LoanParamsStruct.LoanParams[] memory loanParamsList, bool areTorqueLoans) public onlyAdmin {
bytes32[] memory loanParamsIdList;
address _loanTokenAddress = loanTokenAddress;
for (uint256 i = 0; i < loanParamsList.length; i++) {
loanParamsList[i].loanToken = _loanTokenAddress;
loanParamsList[i].maxLoanTerm = areTorqueLoans ? 0 : 28 days;
}
loanParamsIdList = ProtocolSettingsLike(sovrynContractAddress).setupLoanParams(loanParamsList);
for (uint256 i = 0; i < loanParamsIdList.length; i++) {
loanParamsIds[
uint256(
keccak256(
abi.encodePacked(
loanParamsList[i].collateralToken,
areTorqueLoans /// isTorqueLoan
)
)
)
] = loanParamsIdList[i];
}
}
/**
* @notice Disable loan token parameters.
*
* @param collateralTokens The array of collateral tokens.
* @param isTorqueLoans Whether the loan is a torque loan.
* */
function disableLoanParams(address[] calldata collateralTokens, bool[] calldata isTorqueLoans) external onlyAdmin {
require(collateralTokens.length == isTorqueLoans.length, "count mismatch");
bytes32[] memory loanParamsIdList = new bytes32[](collateralTokens.length);
for (uint256 i = 0; i < collateralTokens.length; i++) {
uint256 id = uint256(keccak256(abi.encodePacked(collateralTokens[i], isTorqueLoans[i])));
loanParamsIdList[i] = loanParamsIds[id];
delete loanParamsIds[id];
}
ProtocolSettingsLike(sovrynContractAddress).disableLoanParams(loanParamsIdList);
}
/**
* @notice Set loan token parameters about the demand curve.
*
* @dev These params should be percentages represented
* like so: 5% = 5000000000000000000 /// 18 digits precision.
* rateMultiplier + baseRate can't exceed 100%
*
* To maintain a healthy credit score, it's important to keep your
* credit utilization rate (CUR) low (_lowUtilBaseRate). In general
* you don't want your CUR to exceed 30%, but increasingly financial
* experts are recommending that you don't want to go above 10% if you
* really want an excellent credit score.
*
* Interest rates tend to cluster around the kink level of a kinked
* interest rate model. More info at https://arxiv.org/pdf/2006.13922.pdf
* and https://compound.finance/governance/proposals/12
*
* @param _baseRate The interest rate.
* @param _rateMultiplier The precision multiplier for base rate.
* @param _lowUtilBaseRate The credit utilization rate (CUR) low value.
* @param _lowUtilRateMultiplier The precision multiplier for low util base rate.
* @param _targetLevel The target level.
* @param _kinkLevel The level that interest rates cluster on kinked model.
* @param _maxScaleRate The maximum rate of the scale.
* */
function setDemandCurve(
uint256 _baseRate,
uint256 _rateMultiplier,
uint256 _lowUtilBaseRate,
uint256 _lowUtilRateMultiplier,
uint256 _targetLevel,
uint256 _kinkLevel,
uint256 _maxScaleRate
) public onlyAdmin {
require(_rateMultiplier.add(_baseRate) <= WEI_PERCENT_PRECISION, "curve params too high");
require(_lowUtilRateMultiplier.add(_lowUtilBaseRate) <= WEI_PERCENT_PRECISION, "curve params too high");
require(_targetLevel <= WEI_PERCENT_PRECISION && _kinkLevel <= WEI_PERCENT_PRECISION, "levels too high");
baseRate = _baseRate;
rateMultiplier = _rateMultiplier;
lowUtilBaseRate = _lowUtilBaseRate;
lowUtilRateMultiplier = _lowUtilRateMultiplier;
targetLevel = _targetLevel; /// 80 ether
kinkLevel = _kinkLevel; /// 90 ether
maxScaleRate = _maxScaleRate; /// 100 ether
}
/**
* @notice Set the pause flag for a function to true or false.
*
* @dev Combining the hash of "iToken_FunctionPause" string and a function
* selector gets a slot to write a flag for pause state.
*
* @param funcId The ID of a function, the selector.
* @param isPaused true/false value of the flag.
* */
function toggleFunctionPause(
string memory funcId, /// example: "mint(uint256,uint256)"
bool isPaused
) public {
bool paused;
require(msg.sender == pauser, "onlyPauser");
/// keccak256("iToken_FunctionPause")
bytes32 slot =
keccak256(
abi.encodePacked(
bytes4(keccak256(abi.encodePacked(funcId))),
uint256(0xd46a704bc285dbd6ff5ad3863506260b1df02812f4f857c8cc852317a6ac64f2)
)
);
assembly {
paused := sload(slot)
}
require(paused != isPaused, "isPaused is already set to that value");
assembly {
sstore(slot, isPaused)
}
emit ToggledFunctionPaused(funcId, !isPaused, isPaused);
}
/**
* Set the transaction limit per token address.
* @param addresses The token addresses.
* @param limits The limit denominated in the currency of the token address.
* */
function setTransactionLimits(address[] memory addresses, uint256[] memory limits) public onlyAdmin {
require(addresses.length == limits.length, "mismatched array lengths");
for (uint256 i = 0; i < addresses.length; i++) {
transactionLimit[addresses[i]] = limits[i];
}
emit SetTransactionLimits(addresses, limits);
}
/**
* @notice Update the loan token parameters.
* @param _name The new name of the loan token.
* @param _symbol The new symbol of the loan token.
* */
function changeLoanTokenNameAndSymbol(string memory _name, string memory _symbol) public onlyAdmin {
name = _name;
symbol = _symbol;
}
}
| * @notice Update the loan token parameters. @param _name The new name of the loan token. @param _symbol The new symbol of the loan token. / | function changeLoanTokenNameAndSymbol(string memory _name, string memory _symbol) public onlyAdmin {
name = _name;
symbol = _symbol;
}
| 15,857,687 | [
1,
1891,
326,
28183,
1147,
1472,
18,
202,
389,
529,
1021,
394,
508,
434,
326,
28183,
1147,
18,
202,
389,
7175,
1021,
394,
3273,
434,
326,
28183,
1147,
18,
342,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
202,
915,
2549,
1504,
304,
1345,
31925,
5335,
12,
1080,
3778,
389,
529,
16,
533,
3778,
389,
7175,
13,
1071,
1338,
4446,
288,
203,
202,
202,
529,
273,
389,
529,
31,
203,
202,
202,
7175,
273,
389,
7175,
31,
203,
202,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/42/0xAfd8Fdb491e8fB399194C0E7281929B634fFda56/sources/CFD.sol | File: @openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol* @dev Collection of functions related to the address type/ | library AddressUpgradeable {
function swapInput(
Dir _dir,
Decimal.decimal calldata _quoteAssetAmount,
Decimal.decimal calldata _baseAssetAmountLimit
) external returns (Decimal.decimal memory);
function swapOutput(
Dir _dir,
Decimal.decimal calldata _baseAssetAmount,
Decimal.decimal calldata _quoteAssetAmountLimit,
bool _skipFluctuationCheck
) external returns (Decimal.decimal memory);
function migrateLiquidity(Decimal.decimal calldata _liquidityMultiplier, Decimal.decimal calldata _priceLimitRatio)
external;
function shutdown() external;
function settleFunding() external returns (SignedDecimal.signedDecimal memory);
function calcFee(Decimal.decimal calldata _quoteAssetAmount) external view returns (Decimal.decimal memory);
function calcBaseAssetAfterLiquidityMigration(
SignedDecimal.signedDecimal memory _baseAssetAmount,
Decimal.decimal memory _fromQuoteReserve,
Decimal.decimal memory _fromBaseReserve
) external view returns (SignedDecimal.signedDecimal memory);
function getInputTwap(Dir _dir, Decimal.decimal calldata _quoteAssetAmount)
external
view
returns (Decimal.decimal memory);
function getOutputTwap(Dir _dir, Decimal.decimal calldata _baseAssetAmount)
external
view
returns (Decimal.decimal memory);
function getInputPrice(Dir _dir, Decimal.decimal calldata _quoteAssetAmount)
external
view
returns (Decimal.decimal memory);
function getOutputPrice(Dir _dir, Decimal.decimal calldata _baseAssetAmount)
external
view
returns (Decimal.decimal memory);
function getInputPriceWithReserves(
Dir _dir,
Decimal.decimal memory _quoteAssetAmount,
Decimal.decimal memory _quoteAssetPoolAmount,
Decimal.decimal memory _baseAssetPoolAmount
) external pure returns (Decimal.decimal memory);
function getOutputPriceWithReserves(
Dir _dir,
Decimal.decimal memory _baseAssetAmount,
Decimal.decimal memory _quoteAssetPoolAmount,
Decimal.decimal memory _baseAssetPoolAmount
) external pure returns (Decimal.decimal memory);
function getSpotPrice() external view returns (Decimal.decimal memory);
function getLiquidityHistoryLength() external view returns (uint256);
function quoteAsset() external view returns (IERC20Upgradeable);
function open() external view returns (bool);
function getSettlementPrice() external view returns (Decimal.decimal memory);
function getBaseAssetDeltaThisFundingPeriod() external view returns (SignedDecimal.signedDecimal memory);
function getCumulativeNotional() external view returns (SignedDecimal.signedDecimal memory);
function getMaxHoldingBaseAsset() external view returns (Decimal.decimal memory);
function getOpenInterestNotionalCap() external view returns (Decimal.decimal memory);
function getLiquidityChangedSnapshots(uint256 i) external view returns (LiquidityChangedSnapshot memory);
function mint(address account, uint256 amount) external;
function burn(address account, uint256 amount) external;
function getPositionSize() external view returns (Decimal.decimal memory, Decimal.decimal memory);
function getMMUnrealizedPNL(Decimal.decimal memory _baseAssetReserve, Decimal.decimal memory _quoteAssetReserve)
external
view
returns (SignedDecimal.signedDecimal memory);
function getTotalPositionSize() external view returns (SignedDecimal.signedDecimal memory);
function getPriceAdjustRatio() external view returns (Decimal.decimal memory);
function moveAMMPriceToOracle(uint256 _oraclePrice, bytes32 _priceFeedKey) external;
function setPriceFeed(address _priceFeed) external;
function getReserve() external view returns (Decimal.decimal memory, Decimal.decimal memory);
}
}
}
}
function isContract(address account) internal view returns (bool) {
uint256 size;
return size > 0;
}
assembly { size := extcodesize(account) }
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
require(success, "Address: unable to send value, recipient may have reverted");
}
(bool success, ) = recipient.call{ value: amount }("");
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
return _verifyCallResult(success, returndata, errorMessage);
}
(bool success, bytes memory returndata) = target.call{ value: value }(data);
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
if (returndata.length > 0) {
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
revert(errorMessage);
}
}
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
if (returndata.length > 0) {
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
revert(errorMessage);
}
}
}
} else {
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
if (returndata.length > 0) {
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
revert(errorMessage);
}
}
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
if (returndata.length > 0) {
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
revert(errorMessage);
}
}
}
} else {
}
| 3,377,141 | [
1,
812,
30,
632,
3190,
94,
881,
84,
292,
267,
19,
16351,
87,
17,
15097,
429,
19,
5471,
19,
1887,
10784,
429,
18,
18281,
225,
2200,
434,
4186,
3746,
358,
326,
1758,
618,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
12083,
5267,
10784,
429,
288,
203,
565,
445,
7720,
1210,
12,
203,
3639,
8446,
389,
1214,
16,
203,
3639,
11322,
18,
12586,
745,
892,
389,
6889,
6672,
6275,
16,
203,
3639,
11322,
18,
12586,
745,
892,
389,
1969,
6672,
6275,
3039,
203,
565,
262,
3903,
1135,
261,
5749,
18,
12586,
3778,
1769,
203,
203,
565,
445,
7720,
1447,
12,
203,
3639,
8446,
389,
1214,
16,
203,
3639,
11322,
18,
12586,
745,
892,
389,
1969,
6672,
6275,
16,
203,
3639,
11322,
18,
12586,
745,
892,
389,
6889,
6672,
6275,
3039,
16,
203,
3639,
1426,
389,
7457,
2340,
853,
11407,
1564,
203,
565,
262,
3903,
1135,
261,
5749,
18,
12586,
3778,
1769,
203,
203,
565,
445,
13187,
48,
18988,
24237,
12,
5749,
18,
12586,
745,
892,
389,
549,
372,
24237,
23365,
16,
11322,
18,
12586,
745,
892,
389,
8694,
3039,
8541,
13,
203,
3639,
3903,
31,
203,
203,
565,
445,
5731,
1435,
3903,
31,
203,
203,
565,
445,
444,
5929,
42,
14351,
1435,
3903,
1135,
261,
12294,
5749,
18,
5679,
5749,
3778,
1769,
203,
203,
565,
445,
7029,
14667,
12,
5749,
18,
12586,
745,
892,
389,
6889,
6672,
6275,
13,
3903,
1476,
1135,
261,
5749,
18,
12586,
3778,
1769,
203,
203,
565,
445,
7029,
2171,
6672,
4436,
48,
18988,
24237,
10224,
12,
203,
3639,
16724,
5749,
18,
5679,
5749,
3778,
389,
1969,
6672,
6275,
16,
203,
3639,
11322,
18,
12586,
3778,
389,
2080,
10257,
607,
6527,
16,
203,
3639,
11322,
18,
12586,
3778,
389,
2080,
2171,
607,
6527,
203,
565,
262,
3903,
1476,
1135,
261,
12294,
2
] |
// Sources flattened with buidler v1.4.3 https://buidler.dev
// File @animoca/ethereum-contracts-assets_inventory/contracts/token/ERC721/[email protected]
// SPDX-License-Identifier: MIT
pragma solidity 0.6.8;
/**
* @title ERC721 Non-Fungible Token Standard, basic interface
* @dev See https://eips.ethereum.org/EIPS/eip-721
* Note: The ERC-165 identifier for this interface is 0x80ac58cd.
*/
interface IERC721 {
event Transfer(
address indexed _from,
address indexed _to,
uint256 indexed _tokenId
);
event Approval(
address indexed _owner,
address indexed _approved,
uint256 indexed _tokenId
);
event ApprovalForAll(
address indexed _owner,
address indexed _operator,
bool _approved
);
/**
* @dev Gets the balance of the specified address
* @param owner address to query the balance of
* @return balance uint256 representing the amount owned by the passed address
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Gets the owner of the specified ID
* @param tokenId uint256 ID to query the owner of
* @return owner address currently marked as the owner of the given ID
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Approves another address to transfer the given token ID
* The zero address indicates there is no approved address.
* There can only be one approved address per token at a given time.
* Can only be called by the token owner or an approved operator.
* @param to address to be approved for the given token ID
* @param tokenId uint256 ID of the token to be approved
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Gets the approved address for a token ID, or zero if no address set
* Reverts if the token ID does not exist.
* @param tokenId uint256 ID of the token to query the approval of
* @return operator address currently approved for the given token ID
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Sets or unsets the approval of a given operator
* An operator is allowed to transfer all tokens of the sender on their behalf
* @param operator operator address to set the approval
* @param approved representing the status of the approval to be set
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Tells whether an operator is approved by a given owner
* @param owner owner address which you want to query the approval of
* @param operator operator address which you want to query the approval of
* @return bool whether the given operator is approved by the given owner
*/
function isApprovedForAll(address owner,address operator) external view returns (bool);
/**
* @dev Transfers the ownership of a given token ID to another address
* Usage of this method is discouraged, use `safeTransferFrom` whenever possible
* Requires the msg sender to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
*
* Requires the msg sender to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
*
* Requires the msg sender to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
* @param data bytes data to send along with a safe transfer check
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
// File @animoca/ethereum-contracts-erc20_base/contracts/token/ERC20/[email protected]
/*
https://github.com/OpenZeppelin/openzeppelin-contracts
The MIT License (MIT)
Copyright (c) 2016-2019 zOS Global Limited
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
pragma solidity 0.6.8;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(
address indexed _from,
address indexed _to,
uint256 _value
);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(
address indexed _owner,
address indexed _spender,
uint256 _value
);
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
}
// File @animoca/ethereum-contracts-core_library/contracts/algo/[email protected]
/*
https://github.com/OpenZeppelin/openzeppelin-contracts
The MIT License (MIT)
Copyright (c) 2016-2019 zOS Global Limited
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
pragma solidity 0.6.8;
/**
* @dev Library for managing an enumerable variant of Solidity's
* https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`]
* type.
*
* Maps have the following properties:
*
* - Entries are added, removed, and checked for existence in constant time
* (O(1)).
* - Entries are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumMap for EnumMap.Map;
*
* // Declare a set state variable
* EnumMap.Map private myMap;
* }
* ```
*/
library EnumMap {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Map type with
// bytes32 keys and values.
// This means that we can only create new EnumMaps for types that fit
// in bytes32.
struct MapEntry {
bytes32 key;
bytes32 value;
}
struct Map {
// Storage of map keys and values
MapEntry[] entries;
// Position of the entry defined by a key in the `entries` array, plus 1
// because index 0 means a key is not in the map.
mapping (bytes32 => uint256) indexes;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(Map storage map, bytes32 key, bytes32 value) internal returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map.indexes[key];
if (keyIndex == 0) { // Equivalent to !contains(map, key)
map.entries.push(MapEntry({ key: key, value: value }));
// The entry is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
map.indexes[key] = map.entries.length;
return true;
} else {
map.entries[keyIndex - 1].value = value;
return false;
}
}
/**
* @dev Removes a key-value pair from a map. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(Map storage map, bytes32 key) internal returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map.indexes[key];
if (keyIndex != 0) { // Equivalent to contains(map, key)
// To delete a key-value pair from the entries array in O(1), we swap the entry to delete with the last one
// in the array, and then remove the last entry (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = keyIndex - 1;
uint256 lastIndex = map.entries.length - 1;
// When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
MapEntry storage lastEntry = map.entries[lastIndex];
// Move the last entry to the index where the entry to delete is
map.entries[toDeleteIndex] = lastEntry;
// Update the index for the moved entry
map.indexes[lastEntry.key] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved entry was stored
map.entries.pop();
// Delete the index for the deleted slot
delete map.indexes[key];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(Map storage map, bytes32 key) internal view returns (bool) {
return map.indexes[key] != 0;
}
/**
* @dev Returns the number of key-value pairs in the map. O(1).
*/
function length(Map storage map) internal view returns (uint256) {
return map.entries.length;
}
/**
* @dev Returns the key-value pair stored at position `index` in the map. O(1).
*
* Note that there are no guarantees on the ordering of entries inside the
* array, and it may change when more entries are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Map storage map, uint256 index) internal view returns (bytes32, bytes32) {
require(map.entries.length > index, "EnumMap: index out of bounds");
MapEntry storage entry = map.entries[index];
return (entry.key, entry.value);
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(Map storage map, bytes32 key) internal view returns (bytes32) {
uint256 keyIndex = map.indexes[key];
require(keyIndex != 0, "EnumMap: nonexistent key"); // Equivalent to contains(map, key)
return map.entries[keyIndex - 1].value; // All indexes are 1-based
}
}
// File @animoca/ethereum-contracts-core_library/contracts/algo/[email protected]
/*
https://github.com/OpenZeppelin/openzeppelin-contracts
The MIT License (MIT)
Copyright (c) 2016-2019 zOS Global Limited
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
pragma solidity 0.6.8;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumSet for EnumSet.Set;
*
* // Declare a set state variable
* EnumSet.Set private mySet;
* }
* ```
*/
library EnumSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Set storage set, bytes32 value) internal returns (bool) {
if (!contains(set, value)) {
set.values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set.indexes[value] = set.values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Set storage set, bytes32 value) internal returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set.indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set.values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set.values[lastIndex];
// Move the last value to the index where the value to delete is
set.values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set.indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set.values.pop();
// Delete the index for the deleted slot
delete set.indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Set storage set, bytes32 value) internal view returns (bool) {
return set.indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(Set storage set) internal view returns (uint256) {
return set.values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Set storage set, uint256 index) internal view returns (bytes32) {
require(set.values.length > index, "EnumSet: index out of bounds");
return set.values[index];
}
}
// File @openzeppelin/contracts/GSN/[email protected]
pragma solidity ^0.6.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File @openzeppelin/contracts/access/[email protected]
pragma solidity ^0.6.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File @animoca/ethereum-contracts-core_library/contracts/payment/[email protected]
pragma solidity 0.6.8;
/**
@title PayoutWallet
@dev adds support for a payout wallet
Note: .
*/
contract PayoutWallet is Ownable
{
event PayoutWalletSet(address payoutWallet_);
address payable public payoutWallet;
constructor(address payoutWallet_) internal {
setPayoutWallet(payoutWallet_);
}
function setPayoutWallet(address payoutWallet_) public onlyOwner {
require(payoutWallet_ != address(0), "The payout wallet must not be the zero address");
require(payoutWallet_ != address(this), "The payout wallet must not be the contract itself");
require(payoutWallet_ != payoutWallet, "The payout wallet must be different");
payoutWallet = payable(payoutWallet_);
emit PayoutWalletSet(payoutWallet);
}
}
// File @animoca/ethereum-contracts-core_library/contracts/utils/[email protected]
pragma solidity 0.6.8;
/**
* Contract module which allows derived contracts to implement a mechanism for
* activating, or 'starting', a contract.
*
* This module is used through inheritance. It will make available the modifiers
* `whenNotStarted` and `whenStarted`, which can be applied to the functions of
* your contract. Those functions will only be 'startable' once the modifiers
* are put in place.
*/
contract Startable is Context {
event Started(address account);
uint256 private _startedAt;
/**
* Modifier to make a function callable only when the contract has not started.
*/
modifier whenNotStarted() {
require(_startedAt == 0, "Startable: started");
_;
}
/**
* Modifier to make a function callable only when the contract has started.
*/
modifier whenStarted() {
require(_startedAt != 0, "Startable: not started");
_;
}
/**
* Constructor.
*/
constructor () internal {}
/**
* Returns the timestamp when the contract entered the started state.
* @return The timestamp when the contract entered the started state.
*/
function startedAt() public view returns (uint256) {
return _startedAt;
}
/**
* Triggers the started state.
* @dev Emits the Started event when the function is successfully called.
*/
function _start() internal virtual whenNotStarted {
_startedAt = now;
emit Started(_msgSender());
}
}
// File @openzeppelin/contracts/utils/[email protected]
pragma solidity ^0.6.0;
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor () internal {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!_paused, "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(_paused, "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// File @openzeppelin/contracts/utils/[email protected]
pragma solidity ^0.6.2;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File @openzeppelin/contracts/math/[email protected]
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File @animoca/ethereum-contracts-sale_base/contracts/sale/interfaces/[email protected]
pragma solidity 0.6.8;
/**
* @title ISale
*
* An interface for a contract which allows merchants to display products and customers to purchase them.
*
* Products, designated as SKUs, are represented by bytes32 identifiers so that an identifier can carry an
* explicit name under the form of a fixed-length string. Each SKU can be priced via up to several payment
* tokens which can be ETH and/or ERC20(s). ETH token is represented by the magic value TOKEN_ETH, which means
* this value can be used as the 'token' argument of the purchase-related functions to indicate ETH payment.
*
* The total available supply for a SKU is fixed at its creation. The magic value SUPPLY_UNLIMITED is used
* to represent a SKU with an infinite, never-decreasing supply. An optional purchase notifications receiver
* contract address can be set for a SKU at its creation: if the value is different from the zero address,
* the function `onPurchaseNotificationReceived` will be called on this address upon every purchase of the SKU.
*
* This interface is designed to be consistent while managing a variety of implementation scenarios. It is
* also intended to be developer-friendly: all vital information is consistently deductible from the events
* (backend-oriented), as well as retrievable through calls to public functions (frontend-oriented).
*/
interface ISale {
/**
* Event emitted to notify about the magic values necessary for interfacing with this contract.
* @param names An array of names for the magic values used by the contract.
* @param values An array of values for the magic values used by the contract.
*/
event MagicValues(bytes32[] names, bytes32[] values);
/**
* Event emitted to notify about the creation of a SKU.
* @param sku The identifier of the created SKU.
* @param totalSupply The initial total supply for sale.
* @param maxQuantityPerPurchase The maximum allowed quantity for a single purchase.
* @param notificationsReceiver If not the zero address, the address of a contract on which `onPurchaseNotificationReceived` will be called after each purchase,
* If this is the zero address, the call is not enabled.
*/
event SkuCreation(bytes32 sku, uint256 totalSupply, uint256 maxQuantityPerPurchase, address notificationsReceiver);
/**
* Event emitted to notify about a change in the pricing of a SKU.
* @dev `tokens` and `prices` arrays MUST have the same length.
* @param sku The identifier of the updated SKU.
* @param tokens An array of updated payment tokens. If empty, interpret as all payment tokens being disabled.
* @param prices An array of updated prices for each of the payment tokens.
* Zero price values are used for payment tokens being disabled.
*/
event SkuPricingUpdate(bytes32 indexed sku, address[] tokens, uint256[] prices);
/**
* Event emitted to notify about a purchase.
* @param purchaser The initiater and buyer of the purchase.
* @param recipient The recipient of the purchase.
* @param token The token used as the currency for the payment.
* @param sku The identifier of the purchased SKU.
* @param quantity The purchased quantity.
* @param userData Optional extra user input data.
* @param totalPrice The amount of `token` paid.
* @param pricingData Implementation-specific extra pricing data, such as details about discounts applied.
* @param paymentData Implementation-specific extra payment data, such as conversion rates.
* @param deliveryData Implementation-specific extra delivery data, such as purchase receipts.
*/
event Purchase(
address indexed purchaser,
address recipient,
address indexed token,
bytes32 indexed sku,
uint256 quantity,
bytes userData,
uint256 totalPrice,
bytes32[] pricingData,
bytes32[] paymentData,
bytes32[] deliveryData
);
/**
* Returns the magic value used to represent the ETH payment token.
* @dev MUST NOT be the zero address.
* @return the magic value used to represent the ETH payment token.
*/
function TOKEN_ETH() external pure returns (address);
/**
* Returns the magic value used to represent an infinite, never-decreasing SKU's supply.
* @dev MUST NOT be zero.
* @return the magic value used to represent an infinite, never-decreasing SKU's supply.
*/
function SUPPLY_UNLIMITED() external pure returns (uint256);
/**
* Performs a purchase.
* @dev Reverts if `token` is the address zero.
* @dev Reverts if `quantity` is zero.
* @dev Reverts if `quantity` is greater than the maximum purchase quantity.
* @dev Reverts if `quantity` is greater than the remaining supply.
* @dev Reverts if `sku` does not exist.
* @dev Reverts if `sku` exists but does not have a price set for `token`.
* @dev Emits the Purchase event.
* @param recipient The recipient of the purchase.
* @param token The token to use as the payment currency.
* @param sku The identifier of the SKU to purchase.
* @param quantity The quantity to purchase.
* @param userData Optional extra user input data.
*/
function purchaseFor(
address payable recipient,
address token,
bytes32 sku,
uint256 quantity,
bytes calldata userData
) external payable;
/**
* Estimates the computed final total amount to pay for a purchase, including any potential discount.
* @dev This function MUST compute the same price as `purchaseFor` would in identical conditions (same arguments, same point in time).
* @dev Reverts if `token` is the zero address.
* @dev Reverts if `quantity` is zero.
* @dev Reverts if `quantity` is greater than the maximum purchase quantity.
* @dev Reverts if `quantity` is greater than the remaining supply.
* @dev Reverts if `sku` does not exist.
* @dev Reverts if `sku` exists but does not have a price set for `token`.
* @param recipient The recipient of the purchase used to calculate the total price amount.
* @param token The payment token used to calculate the total price amount.
* @param sku The identifier of the SKU used to calculate the total price amount.
* @param quantity The quantity used to calculate the total price amount.
* @param userData Optional extra user input data.
* @return totalPrice The computed total price to pay.
* @return pricingData Implementation-specific extra pricing data, such as details about discounts applied.
* If not empty, the implementer MUST document how to interepret the values.
*/
function estimatePurchase(
address payable recipient,
address token,
bytes32 sku,
uint256 quantity,
bytes calldata userData
) external view returns (uint256 totalPrice, bytes32[] memory pricingData);
/**
* Returns the information relative to a SKU.
* @dev WARNING: it is the responsibility of the implementer to ensure that the
* number of payment tokens is bounded, so that this function does not run out of gas.
* @dev Reverts if `sku` does not exist.
* @param sku The SKU identifier.
* @return totalSupply The initial total supply for sale.
* @return remainingSupply The remaining supply for sale.
* @return maxQuantityPerPurchase The maximum allowed quantity for a single purchase.
* @return notificationsReceiver The address of a contract on which to call the `onPurchaseNotificationReceived` function.
* @return tokens The list of supported payment tokens.
* @return prices The list of associated prices for each of the `tokens`.
*/
function getSkuInfo(bytes32 sku)
external
view
returns (
uint256 totalSupply,
uint256 remainingSupply,
uint256 maxQuantityPerPurchase,
address notificationsReceiver,
address[] memory tokens,
uint256[] memory prices
);
/**
* Returns the list of created SKU identifiers.
* @dev WARNING: it is the responsibility of the implementer to ensure that the
* number of SKUs is bounded, so that this function does not run out of gas.
* @return skus the list of created SKU identifiers.
*/
function getSkus() external view returns (bytes32[] memory skus);
}
// File @animoca/ethereum-contracts-sale_base/contracts/sale/interfaces/[email protected]
pragma solidity 0.6.8;
/**
* @title IPurchaseNotificationsReceiver
* Interface for any contract that wants to support purchase notifications from a Sale contract.
*/
interface IPurchaseNotificationsReceiver {
/**
* Handles the receipt of a purchase notification.
* @dev This function MUST return the function selector, otherwise the caller will revert the transaction.
* The selector to be returned can be obtained as `this.onPurchaseNotificationReceived.selector`
* @dev This function MAY throw.
* @param purchaser The purchaser of the purchase.
* @param recipient The recipient of the purchase.
* @param token The token to use as the payment currency.
* @param sku The identifier of the SKU to purchase.
* @param quantity The quantity to purchase.
* @param userData Optional extra user input data.
* @param totalPrice The total price paid.
* @param pricingData Implementation-specific extra pricing data, such as details about discounts applied.
* @param paymentData Implementation-specific extra payment data, such as conversion rates.
* @param deliveryData Implementation-specific extra delivery data, such as purchase receipts.
* @return `bytes4(keccak256("onPurchaseNotificationReceived(address,address,address,bytes32,uint256,bytes,uint256,bytes32[],bytes32[],bytes32[])"))`
*/
function onPurchaseNotificationReceived(
address purchaser,
address recipient,
address token,
bytes32 sku,
uint256 quantity,
bytes calldata userData,
uint256 totalPrice,
bytes32[] calldata pricingData,
bytes32[] calldata paymentData,
bytes32[] calldata deliveryData
) external pure returns (bytes4);
}
// File @animoca/ethereum-contracts-sale_base/contracts/sale/[email protected]
pragma solidity 0.6.8;
/**
* @title PurchaseLifeCycles
* An abstract contract which define the life cycles for a purchase implementer.
*/
abstract contract PurchaseLifeCycles {
/**
* Wrapper for the purchase data passed as argument to the life cycle functions and down to their step functions.
*/
struct PurchaseData {
address payable purchaser;
address payable recipient;
address token;
bytes32 sku;
uint256 quantity;
bytes userData;
uint256 totalPrice;
bytes32[] pricingData;
bytes32[] paymentData;
bytes32[] deliveryData;
}
/* Internal Life Cycle Functions */
/**
* `estimatePurchase` lifecycle.
* @param purchase The purchase conditions.
*/
function _estimatePurchase(PurchaseData memory purchase)
internal
virtual
view
returns (uint256 totalPrice, bytes32[] memory pricingData)
{
_validation(purchase);
_pricing(purchase);
totalPrice = purchase.totalPrice;
pricingData = purchase.pricingData;
}
/**
* `purchaseFor` lifecycle.
* @param purchase The purchase conditions.
*/
function _purchaseFor(PurchaseData memory purchase) internal virtual {
_validation(purchase);
_pricing(purchase);
_payment(purchase);
_delivery(purchase);
_notification(purchase);
}
/* Internal Life Cycle Step Functions */
/**
* Lifecycle step which validates the purchase pre-conditions.
* @dev Responsibilities:
* - Ensure that the purchase pre-conditions are met and revert if not.
* @param purchase The purchase conditions.
*/
function _validation(PurchaseData memory purchase) internal virtual view;
/**
* Lifecycle step which computes the purchase price.
* @dev Responsibilities:
* - Computes the pricing formula, including any discount logic and price conversion;
* - Set the value of `purchase.totalPrice`;
* - Add any relevant extra data related to pricing in `purchase.pricingData` and document how to interpret it.
* @param purchase The purchase conditions.
*/
function _pricing(PurchaseData memory purchase) internal virtual view;
/**
* Lifecycle step which manages the transfer of funds from the purchaser.
* @dev Responsibilities:
* - Ensure the payment reaches destination in the expected output token;
* - Handle any token swap logic;
* - Add any relevant extra data related to payment in `purchase.paymentData` and document how to interpret it.
* @param purchase The purchase conditions.
*/
function _payment(PurchaseData memory purchase) internal virtual;
/**
* Lifecycle step which delivers the purchased SKUs to the recipient.
* @dev Responsibilities:
* - Ensure the product is delivered to the recipient, if that is the contract's responsibility.
* - Handle any internal logic related to the delivery, including the remaining supply update;
* - Add any relevant extra data related to delivery in `purchase.deliveryData` and document how to interpret it.
* @param purchase The purchase conditions.
*/
function _delivery(PurchaseData memory purchase) internal virtual;
/**
* Lifecycle step which notifies of the purchase.
* @dev Responsibilities:
* - Manage after-purchase event(s) emission.
* - Handle calls to the notifications receiver contract's `onPurchaseNotificationReceived` function, if applicable.
* @param purchase The purchase conditions.
*/
function _notification(PurchaseData memory purchase) internal virtual;
}
// File @animoca/ethereum-contracts-sale_base/contracts/sale/[email protected]
pragma solidity 0.6.8;
/**
* @title AbstractSale
* An abstract base sale contract with a minimal implementation of ISale and administration functions.
* A minimal implementation of the `_validation`, `_delivery` and `notification` life cycle step functions
* are provided, but the inheriting contract must implement `_pricing` and `_payment`.
*/
abstract contract AbstractSale is PurchaseLifeCycles, ISale, PayoutWallet, Startable, Pausable {
using Address for address;
using SafeMath for uint256;
using EnumSet for EnumSet.Set;
using EnumMap for EnumMap.Map;
struct SkuInfo {
uint256 totalSupply;
uint256 remainingSupply;
uint256 maxQuantityPerPurchase;
address notificationsReceiver;
EnumMap.Map prices;
}
address public constant override TOKEN_ETH = address(0x00eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee);
uint256 public constant override SUPPLY_UNLIMITED = type(uint256).max;
EnumSet.Set internal _skus;
mapping(bytes32 => SkuInfo) internal _skuInfos;
uint256 internal immutable _skusCapacity;
uint256 internal immutable _tokensPerSkuCapacity;
/**
* Constructor.
* @dev Emits the `MagicValues` event.
* @dev Emits the `Paused` event.
* @param payoutWallet_ the payout wallet.
* @param skusCapacity the cap for the number of managed SKUs.
* @param tokensPerSkuCapacity the cap for the number of tokens managed per SKU.
*/
constructor(
address payoutWallet_,
uint256 skusCapacity,
uint256 tokensPerSkuCapacity
) internal PayoutWallet(payoutWallet_) {
_skusCapacity = skusCapacity;
_tokensPerSkuCapacity = tokensPerSkuCapacity;
bytes32[] memory names = new bytes32[](2);
bytes32[] memory values = new bytes32[](2);
(names[0], values[0]) = ("TOKEN_ETH", bytes32(uint256(TOKEN_ETH)));
(names[1], values[1]) = ("SUPPLY_UNLIMITED", bytes32(uint256(SUPPLY_UNLIMITED)));
emit MagicValues(names, values);
_pause();
}
/* Public Admin Functions */
/**
* Actvates, or 'starts', the contract.
* @dev Emits the `Started` event.
* @dev Emits the `Unpaused` event.
* @dev Reverts if called by any other than the contract owner.
* @dev Reverts if the contract has already been started.
* @dev Reverts if the contract is not paused.
*/
function start() public virtual onlyOwner {
_start();
_unpause();
}
/**
* Pauses the contract.
* @dev Emits the `Paused` event.
* @dev Reverts if called by any other than the contract owner.
* @dev Reverts if the contract has not been started yet.
* @dev Reverts if the contract is already paused.
*/
function pause() public virtual onlyOwner whenStarted {
_pause();
}
/**
* Resumes the contract.
* @dev Emits the `Unpaused` event.
* @dev Reverts if called by any other than the contract owner.
* @dev Reverts if the contract has not been started yet.
* @dev Reverts if the contract is not paused.
*/
function unpause() public virtual onlyOwner whenStarted {
_unpause();
}
/**
* Creates an SKU.
* @dev Reverts if called by any other than the contract owner.
* @dev Reverts if `totalSupply` is zero.
* @dev Reverts if `sku` already exists.
* @dev Reverts if `notificationsReceiver` is not the zero address and is not a contract address.
* @dev Reverts if the update results in too many SKUs.
* @dev Emits the `SkuCreation` event.
* @param sku the SKU identifier.
* @param totalSupply the initial total supply.
* @param maxQuantityPerPurchase The maximum allowed quantity for a single purchase.
* @param notificationsReceiver The purchase notifications receiver contract address.
* If set to the zero address, the notification is not enabled.
*/
function createSku(
bytes32 sku,
uint256 totalSupply,
uint256 maxQuantityPerPurchase,
address notificationsReceiver
) public virtual onlyOwner {
require(totalSupply != 0, "Sale: zero supply");
require(_skus.length() < _skusCapacity, "Sale: too many skus");
require(_skus.add(sku), "Sale: sku already created");
if (notificationsReceiver != address(0)) {
require(notificationsReceiver.isContract(), "Sale: receiver is not a contract");
}
SkuInfo storage skuInfo = _skuInfos[sku];
skuInfo.totalSupply = totalSupply;
skuInfo.remainingSupply = totalSupply;
skuInfo.maxQuantityPerPurchase = maxQuantityPerPurchase;
skuInfo.notificationsReceiver = notificationsReceiver;
emit SkuCreation(sku, totalSupply, maxQuantityPerPurchase, notificationsReceiver);
}
/**
* Sets the token prices for the specified product SKU.
* @dev Reverts if called by any other than the contract owner.
* @dev Reverts if `tokens` and `prices` have different lengths.
* @dev Reverts if `sku` does not exist.
* @dev Reverts if one of the `tokens` is the zero address.
* @dev Reverts if the update results in too many tokens for the SKU.
* @dev Emits the `SkuPricingUpdate` event.
* @param sku The identifier of the SKU.
* @param tokens The list of payment tokens to update.
* If empty, disable all the existing payment tokens.
* @param prices The list of prices to apply for each payment token.
* Zero price values are used to disable a payment token.
*/
function updateSkuPricing(
bytes32 sku,
address[] memory tokens,
uint256[] memory prices
) public virtual onlyOwner {
uint256 length = tokens.length;
require(length == prices.length, "Sale: tokens/prices lengths mismatch");
SkuInfo storage skuInfo = _skuInfos[sku];
require(skuInfo.totalSupply != 0, "Sale: non-existent sku");
EnumMap.Map storage tokenPrices = skuInfo.prices;
if (length == 0) {
uint256 currentLength = tokenPrices.length();
for (uint256 i = 0; i < currentLength; ++i) {
// TODO add a clear function in EnumMap and EnumSet and use it
(bytes32 token, ) = tokenPrices.at(0);
tokenPrices.remove(token);
}
} else {
_setTokenPrices(tokenPrices, tokens, prices);
}
emit SkuPricingUpdate(sku, tokens, prices);
}
/* ISale Public Functions */
/**
* Performs a purchase.
* @dev Reverts if the sale has not started.
* @dev Reverts if the sale is paused.
* @dev Reverts if `token` is the address zero.
* @dev Reverts if `quantity` is zero.
* @dev Reverts if `quantity` is greater than the maximum purchase quantity.
* @dev Reverts if `quantity` is greater than the remaining supply.
* @dev Reverts if `sku` does not exist.
* @dev Reverts if `sku` exists but does not have a price set for `token`.
* @dev Emits the Purchase event.
* @param recipient The recipient of the purchase.
* @param token The token to use as the payment currency.
* @param sku The identifier of the SKU to purchase.
* @param quantity The quantity to purchase.
* @param userData Optional extra user input data.
*/
function purchaseFor(
address payable recipient,
address token,
bytes32 sku,
uint256 quantity,
bytes calldata userData
) external virtual override payable whenStarted whenNotPaused {
PurchaseData memory purchase;
purchase.purchaser = _msgSender();
purchase.recipient = recipient;
purchase.token = token;
purchase.sku = sku;
purchase.quantity = quantity;
purchase.userData = userData;
_purchaseFor(purchase);
}
/**
* Estimates the computed final total amount to pay for a purchase, including any potential discount.
* @dev This function MUST compute the same price as `purchaseFor` would in identical conditions (same arguments, same point in time).
* @dev If an implementer contract uses the `priceInfo` field, it SHOULD document how to interpret the info.
* @dev Reverts if the sale has not started.
* @dev Reverts if the sale is paused.
* @dev Reverts if `token` is the zero address.
* @dev Reverts if `quantity` is zero.
* @dev Reverts if `quantity` is greater than the maximum purchase quantity.
* @dev Reverts if `quantity` is greater than the remaining supply.
* @dev Reverts if `sku` does not exist.
* @dev Reverts if `sku` exists but does not have a price set for `token`.
* @param recipient The recipient of the purchase used to calculate the total price amount.
* @param token The payment token used to calculate the total price amount.
* @param sku The identifier of the SKU used to calculate the total price amount.
* @param quantity The quantity used to calculate the total price amount.
* @param userData Optional extra user input data.
* @return totalPrice The computed total price.
* @return priceInfo Implementation-specific extra price information, such as details about potential discounts applied.
*/
function estimatePurchase(
address payable recipient,
address token,
bytes32 sku,
uint256 quantity,
bytes calldata userData
) external virtual override view whenStarted whenNotPaused returns (uint256 totalPrice, bytes32[] memory priceInfo) {
PurchaseData memory purchase;
purchase.purchaser = _msgSender();
purchase.recipient = recipient;
purchase.token = token;
purchase.sku = sku;
purchase.quantity = quantity;
purchase.userData = userData;
return _estimatePurchase(purchase);
}
/**
* Returns the information relative to a SKU.
* @dev WARNING: it is the responsibility of the implementer to ensure that the
* number of payment tokens is bounded, so that this function does not run out of gas.
* @param sku The SKU identifier.
* @return totalSupply The initial total supply for sale.
* @return remainingSupply The remaining supply for sale.
* @return maxQuantityPerPurchase The maximum allowed quantity for a single purchase.
* @return notificationsReceiver The address of a contract on which to call the `onPurchaseNotificationReceived` function.
* @return tokens The list of supported payment tokens.
* @return prices The list of associated prices for each of the `tokens`.
*/
function getSkuInfo(bytes32 sku)
external
override
view
returns (
uint256 totalSupply,
uint256 remainingSupply,
uint256 maxQuantityPerPurchase,
address notificationsReceiver,
address[] memory tokens,
uint256[] memory prices
)
{
SkuInfo storage skuInfo = _skuInfos[sku];
uint256 length = skuInfo.prices.length();
totalSupply = skuInfo.totalSupply;
remainingSupply = skuInfo.remainingSupply;
maxQuantityPerPurchase = skuInfo.maxQuantityPerPurchase;
notificationsReceiver = skuInfo.notificationsReceiver;
tokens = new address[](length);
prices = new uint256[](length);
for (uint256 i = 0; i < length; ++i) {
(bytes32 token, bytes32 price) = skuInfo.prices.at(i);
tokens[i] = address(uint256(token));
prices[i] = uint256(price);
}
}
/**
* Returns the list of created SKU identifiers.
* @return skus the list of created SKU identifiers.
*/
function getSkus() external override view returns (bytes32[] memory skus) {
skus = _skus.values;
}
/* Internal Utility Functions */
function _setTokenPrices(
EnumMap.Map storage tokenPrices,
address[] memory tokens,
uint256[] memory prices
) internal virtual {
for (uint256 i = 0; i < tokens.length; ++i) {
address token = tokens[i];
require(token != address(0), "Sale: zero address token");
uint256 price = prices[i];
if (price == 0) {
tokenPrices.remove(bytes32(uint256(token)));
} else {
tokenPrices.set(bytes32(uint256(token)), bytes32(price));
}
}
require(tokenPrices.length() <= _tokensPerSkuCapacity, "Sale: too many tokens");
}
/* Internal Life Cycle Step Functions */
/**
* Lifecycle step which validates the purchase pre-conditions.
* @dev Responsibilities:
* - Ensure that the purchase pre-conditions are met and revert if not.
* @dev Reverts if `purchase.recipient` is the zero address.
* @dev Reverts if `purchase.quantity` is zero.
* @dev Reverts if `purchase.quantity` is greater than the SKU's `maxQuantityPerPurchase`.
* @dev Reverts if `purchase.quantity` is greater than the available supply.
* @dev If this function is overriden, the implementer SHOULD super call this before.
* @param purchase The purchase conditions.
*/
function _validation(PurchaseData memory purchase) internal virtual override view {
require(purchase.recipient != address(0), "Sale: zero address recipient");
require(purchase.quantity != 0, "Sale: zero quantity purchase");
SkuInfo memory skuInfo = _skuInfos[purchase.sku];
require(purchase.quantity <= skuInfo.maxQuantityPerPurchase, "Sale: above max quantity");
if (skuInfo.totalSupply != SUPPLY_UNLIMITED) {
require(skuInfo.remainingSupply >= purchase.quantity, "Sale: insufficient supply");
}
}
/**
* Lifecycle step which delivers the purchased SKUs to the recipient.
* @dev Responsibilities:
* - Ensure the product is delivered to the recipient, if that is the contract's responsibility.
* - Handle any internal logic related to the delivery, including the remaining supply update;
* - Add any relevant extra data related to delivery in `purchase.deliveryData` and document how to interpret it.
* @dev Reverts if there is not enough available supply.
* @dev If this function is overriden, the implementer SHOULD super call it.
* @param purchase The purchase conditions.
*/
function _delivery(PurchaseData memory purchase) internal virtual override {
SkuInfo memory skuInfo = _skuInfos[purchase.sku];
if (skuInfo.totalSupply != SUPPLY_UNLIMITED) {
_skuInfos[purchase.sku].remainingSupply = skuInfo.remainingSupply.sub(purchase.quantity);
}
}
/**
* Lifecycle step which notifies of the purchase.
* @dev Responsibilities:
* - Manage after-purchase event(s) emission.
* - Handle calls to the notifications receiver contract's `onPurchaseNotificationReceived` function, if applicable.
* @dev Reverts if `onPurchaseNotificationReceived` throws or returns an incorrect value.
* @dev Emits the `Purchase` event. The values of `purchaseData` are the concatenated values of `priceData`, `paymentData`
* and `deliveryData`. If not empty, the implementer MUST document how to interpret these values.
* @dev If this function is overriden, the implementer SHOULD super call it.
* @param purchase The purchase conditions.
*/
function _notification(PurchaseData memory purchase) internal virtual override {
emit Purchase(
purchase.purchaser,
purchase.recipient,
purchase.token,
purchase.sku,
purchase.quantity,
purchase.userData,
purchase.totalPrice,
purchase.pricingData,
purchase.paymentData,
purchase.deliveryData
);
address notificationsReceiver = _skuInfos[purchase.sku].notificationsReceiver;
if (notificationsReceiver != address(0)) {
require(
IPurchaseNotificationsReceiver(notificationsReceiver).onPurchaseNotificationReceived(
purchase.purchaser,
purchase.recipient,
purchase.token,
purchase.sku,
purchase.quantity,
purchase.userData,
purchase.totalPrice,
purchase.pricingData,
purchase.paymentData,
purchase.deliveryData
) == IPurchaseNotificationsReceiver(address(0)).onPurchaseNotificationReceived.selector, // TODO precompute return value
"Sale: wrong receiver return value"
);
}
}
}
// File @animoca/ethereum-contracts-sale_base/contracts/sale/[email protected]
pragma solidity 0.6.8;
/**
* @title FixedPricesSale
* An AbstractSale which implements a fixed prices strategy.
* The final implementer is responsible for implementing any additional pricing and/or delivery logic.
*/
contract FixedPricesSale is AbstractSale {
/**
* Constructor.
* @dev Emits the `MagicValues` event.
* @dev Emits the `Paused` event.
* @param payoutWallet_ the payout wallet.
* @param skusCapacity the cap for the number of managed SKUs.
* @param tokensPerSkuCapacity the cap for the number of tokens managed per SKU.
*/
constructor(
address payoutWallet_,
uint256 skusCapacity,
uint256 tokensPerSkuCapacity
) internal AbstractSale(payoutWallet_, skusCapacity, tokensPerSkuCapacity) {}
/* Internal Life Cycle Functions */
/**
* Lifecycle step which computes the purchase price.
* @dev Responsibilities:
* - Computes the pricing formula, including any discount logic and price conversion;
* - Set the value of `purchase.totalPrice`;
* - Add any relevant extra data related to pricing in `purchase.pricingData` and document how to interpret it.
* @dev Reverts if `purchase.sku` does not exist.
* @dev Reverts if `purchase.token` is not supported by the SKU.
* @dev Reverts in case of price overflow.
* @param purchase The purchase conditions.
*/
function _pricing(PurchaseData memory purchase) internal virtual override view {
SkuInfo storage skuInfo = _skuInfos[purchase.sku];
require(skuInfo.totalSupply != 0, "Sale: unsupported SKU");
EnumMap.Map storage prices = skuInfo.prices;
uint256 unitPrice = _unitPrice(purchase, prices);
purchase.totalPrice = unitPrice.mul(purchase.quantity);
}
/**
* Lifecycle step which manages the transfer of funds from the purchaser.
* @dev Responsibilities:
* - Ensure the payment reaches destination in the expected output token;
* - Handle any token swap logic;
* - Add any relevant extra data related to payment in `purchase.paymentData` and document how to interpret it.
* @dev Reverts in case of payment failure.
* @param purchase The purchase conditions.
*/
function _payment(PurchaseData memory purchase) internal virtual override {
if (purchase.token == TOKEN_ETH) {
require(msg.value >= purchase.totalPrice, "Sale: insufficient ETH provided");
payoutWallet.transfer(purchase.totalPrice);
uint256 change = msg.value.sub(purchase.totalPrice);
if (change != 0) {
purchase.purchaser.transfer(change);
}
} else {
require(
IERC20(purchase.token).transferFrom(_msgSender(), payoutWallet, purchase.totalPrice),
"Sale: ERC20 payment failed"
);
}
}
/* Internal Utility Functions */
function _unitPrice(PurchaseData memory purchase, EnumMap.Map storage prices)
internal
virtual
view
returns (uint256 unitPrice)
{
unitPrice = uint256(prices.get(bytes32(uint256(purchase.token))));
require(unitPrice != 0, "Sale: unsupported payment token");
}
}
// File @animoca/f1dt-ethereum-contracts/contracts/sale/[email protected]
pragma solidity =0.6.8;
/**
* @title REVVSale
* A sale contract for the initial REVV distribution to F1 NFT owners.
*/
contract REVVSale is FixedPricesSale {
IERC20 public immutable revv;
IERC721 public immutable deltaTimeInventory;
/**
* Constructor.
* @param payoutWallet_ The wallet address used to receive purchase payments.
*/
constructor(
address revv_,
address deltaTimeInventory_,
address payable payoutWallet_
) public FixedPricesSale(payoutWallet_, 64, 32) {
require(revv_ != address(0), "REVVSale: zero address REVV ");
require(deltaTimeInventory_ != address(0), "REVVSale: zero address inventory ");
revv = IERC20(revv_);
deltaTimeInventory = IERC721(deltaTimeInventory_);
}
/**
* Creates a REVV sku and funds the necessary amount to this contract.
* @dev Reverts if called by any other than the contract owner.
* @dev Reverts if `totalSupply` is zero.
* @dev Reverts if `sku` already exists.
* @dev Reverts if `notificationsReceiver` is not the zero address and is not a contract address.
* @dev Reverts if the update results in too many SKUs.
* @dev Reverts if the REVV funding fails.
* @dev Emits the `SkuCreation` event.
* @param sku the SKU identifier.
* @param totalSupply the initial total supply.
* @param maxQuantityPerPurchase The maximum allowed quantity for a single purchase.
* @param notificationsReceiver The purchase notifications receiver contract address.
* If set to the zero address, the notification is not enabled.
*/
function createSku(
bytes32 sku,
uint256 totalSupply,
uint256 maxQuantityPerPurchase,
address notificationsReceiver
) public virtual override {
super.createSku(sku, totalSupply, maxQuantityPerPurchase, notificationsReceiver);
require(
revv.transferFrom(
_msgSender(),
address(this),
totalSupply.mul(1000000000000000000)
),
"REVVSale: REVV transfer failed"
);
}
/**
* Lifecycle step which validates the purchase pre-conditions.
* @dev Responsibilities:
* - Ensure that the purchase pre-conditions are met and revert if not.
* @param purchase The purchase conditions.
*/
function _validation(PurchaseData memory purchase) internal override view {
super._validation(purchase);
require(deltaTimeInventory.balanceOf(_msgSender()) != 0, "REVVSale: must be a NFT owner");
}
function _delivery(PurchaseData memory purchase) internal override {
super._delivery(purchase);
require(
revv.transfer(purchase.recipient, purchase.quantity.mul(1000000000000000000)),
"REVVSale: REVV transfer failed"
);
}
} | * @title ERC721 Non-Fungible Token Standard, basic interface Note: The ERC-165 identifier for this interface is 0x80ac58cd./ | interface IERC721 {
event Transfer(
address indexed _from,
address indexed _to,
uint256 indexed _tokenId
);
event Approval(
address indexed _owner,
address indexed _approved,
uint256 indexed _tokenId
);
event ApprovalForAll(
address indexed _owner,
address indexed _operator,
bool _approved
);
function balanceOf(address owner) external view returns (uint256 balance);
function ownerOf(uint256 tokenId) external view returns (address owner);
function approve(address to, uint256 tokenId) external;
function getApproved(uint256 tokenId) external view returns (address operator);
function setApprovalForAll(address operator, bool approved) external;
function isApprovedForAll(address owner,address operator) external view returns (bool);
function transferFrom(address from, address to, uint256 tokenId) external;
function safeTransferFrom(address from, address to, uint256 tokenId) external;
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
| 1,588,494 | [
1,
654,
39,
27,
5340,
3858,
17,
42,
20651,
1523,
3155,
8263,
16,
5337,
1560,
3609,
30,
1021,
4232,
39,
17,
28275,
2756,
364,
333,
1560,
353,
374,
92,
3672,
1077,
8204,
4315,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
5831,
467,
654,
39,
27,
5340,
288,
203,
565,
871,
12279,
12,
203,
3639,
1758,
8808,
389,
2080,
16,
203,
3639,
1758,
8808,
389,
869,
16,
203,
3639,
2254,
5034,
8808,
389,
2316,
548,
203,
565,
11272,
203,
203,
565,
871,
1716,
685,
1125,
12,
203,
3639,
1758,
8808,
389,
8443,
16,
203,
3639,
1758,
8808,
389,
25990,
16,
203,
3639,
2254,
5034,
8808,
389,
2316,
548,
203,
565,
11272,
203,
203,
565,
871,
1716,
685,
1125,
1290,
1595,
12,
203,
3639,
1758,
8808,
389,
8443,
16,
203,
3639,
1758,
8808,
389,
9497,
16,
203,
3639,
1426,
389,
25990,
203,
565,
11272,
203,
203,
565,
445,
11013,
951,
12,
2867,
3410,
13,
3903,
1476,
1135,
261,
11890,
5034,
11013,
1769,
203,
203,
565,
445,
3410,
951,
12,
11890,
5034,
1147,
548,
13,
3903,
1476,
1135,
261,
2867,
3410,
1769,
203,
203,
565,
445,
6617,
537,
12,
2867,
358,
16,
2254,
5034,
1147,
548,
13,
3903,
31,
203,
203,
565,
445,
336,
31639,
12,
11890,
5034,
1147,
548,
13,
3903,
1476,
1135,
261,
2867,
3726,
1769,
203,
203,
565,
445,
444,
23461,
1290,
1595,
12,
2867,
3726,
16,
1426,
20412,
13,
3903,
31,
203,
203,
565,
445,
353,
31639,
1290,
1595,
12,
2867,
3410,
16,
2867,
3726,
13,
3903,
1476,
1135,
261,
6430,
1769,
203,
203,
565,
445,
7412,
1265,
12,
2867,
628,
16,
1758,
358,
16,
2254,
5034,
1147,
548,
13,
3903,
31,
203,
203,
565,
445,
4183,
5912,
1265,
12,
2867,
628,
16,
1758,
358,
16,
2254,
5034,
1147,
548,
13,
3903,
31,
2
] |
/**
*Submitted for verification at Etherscan.io on 2021-12-22
*/
// SPDX-License-Identifier: MIT
pragma solidity >=0.1.1 <0.8.9;
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// uniswapV2Router
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
// gma solidity >=0.6.2;
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
// UNISWAP factory
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
// UNISWAP Pair
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
// IERC20Meta
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// Ownable
abstract contract Ownable is Context {
address private _owner;
address private _previousOwner;
uint256 private _lockTime;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_previousOwner = _owner;
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
function geUnlockTime() public view returns (uint256) {
return _lockTime;
}
//Locks the contract for owner for the amount of time provided
function lock(uint256 time) public virtual onlyOwner {
_previousOwner = _owner;
_owner = address(0);
_lockTime = block.timestamp + time;
emit OwnershipTransferred(_owner, address(0));
}
//Unlocks the contract for owner when _lockTime is exceeds
function deleteTimeStamp() public virtual {
require(_previousOwner == msg.sender, "You don't have permission to unlock");
emit OwnershipTransferred(_owner, _previousOwner);
_owner = _previousOwner;
}
}
// SafeMath
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// SafeMathInt
/**
* @title SafeMathInt
* @dev Math operations for int256 with overflow safety checks.
*/
library SafeMathInt {
int256 private constant MIN_INT256 = int256(1) << 255;
int256 private constant MAX_INT256 = ~(int256(1) << 255);
/**
* @dev Multiplies two int256 variables and fails on overflow.
*/
function mul(int256 a, int256 b) internal pure returns (int256) {
int256 c = a * b;
// Detect overflow when multiplying MIN_INT256 with -1
require(c != MIN_INT256 || (a & MIN_INT256) != (b & MIN_INT256));
require((b == 0) || (c / b == a));
return c;
}
/**
* @dev Division of two int256 variables and fails on overflow.
*/
function div(int256 a, int256 b) internal pure returns (int256) {
// Prevent overflow when dividing MIN_INT256 by -1
require(b != -1 || a != MIN_INT256);
// Solidity already throws when dividing by 0.
return a / b;
}
/**
* @dev Subtracts two int256 variables and fails on overflow.
*/
function sub(int256 a, int256 b) internal pure returns (int256) {
int256 c = a - b;
require((b >= 0 && c <= a) || (b < 0 && c > a));
return c;
}
/**
* @dev Adds two int256 variables and fails on overflow.
*/
function add(int256 a, int256 b) internal pure returns (int256) {
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a));
return c;
}
/**
* @dev Converts to absolute value, and fails on overflow.
*/
function abs(int256 a) internal pure returns (int256) {
require(a != MIN_INT256);
return a < 0 ? -a : a;
}
function toUint256Safe(int256 a) internal pure returns (uint256) {
require(a >= 0);
return uint256(a);
}
}
// SAFEMATHUINT
/**
* @title SafeMathUint
* @dev Math operations with safety checks that revert on error
*/
library SafeMathUint {
function toInt256Safe(uint256 a) internal pure returns (int256) {
int256 b = int256(a);
require(b >= 0);
return b;
}
}
// IterableMapping
// ERC20
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
abstract contract ERC20 is Context, IERC20, IERC20Metadata {
using SafeMath for uint256;
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 9. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 9, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 9;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _createLP(address account, uint256 amount) internal virtual {
_mint(account, amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
// DividentInterface
contract Kurisu is ERC20, Ownable {
using SafeMath for uint256;
IUniswapV2Router02 public uniswapV2Router;
bool private swapping;
bool public deadBlock;
bool public isLaunced;
bool public profitBaseFeeOn = true;
bool public buyingPriceOn = true;
bool public IndividualSellLimitOn = true;
uint256 public feeDivFactor = 200;
uint256 public swapTokensAtAmount = balanceOf(address(this)) / feeDivFactor ;
uint256 public liquidityFee;
uint256 public marketingFee;
uint256 public totalFees = liquidityFee.add(marketingFee);
uint256 public maxFee = 28;
uint256 private percentEquivalent;
uint256 public maxBuyTransactionAmount;
uint256 public maxSellTransactionAmount;
uint256 public maxWalletToken;
uint256 public launchedAt;
mapping (address => Account) public _account;
mapping (address => bool) public _isBlacklisted;
mapping (address => bool) public _isSniper;
mapping (address => bool) private _isExcludedFromFees;
mapping (address => bool) public automatedMarketMakerPairs;
address[] public isSniper;
address public uniswapV2Pair;
address public liquidityReceiver;
address public marketingFeeWallet;
constructor(uint256 liqFee, uint256 marketFee, uint256 supply, uint256 maxBuyPercent, uint256 maxSellPercent, uint256 maxWalletPercent, address marketingWallet, address liqudityWallet, address uniswapV2RouterAddress) ERC20("Kurisu", "Kurisu") {
maxBuyTransactionAmount = ((supply.div(100)).mul(maxBuyPercent)) * 10**9;
maxSellTransactionAmount = ((supply.div(100)).mul(maxSellPercent)) * 10**9;
maxWalletToken = ((supply.div(100)).mul(maxWalletPercent)) * 10**9;
percentEquivalent = (supply.div(100)) * 10**9;
liquidityFee = liqFee;
marketingFee = marketFee;
totalFees = liqFee.add(marketFee);
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(uniswapV2RouterAddress);
// Create a uniswap pair for this new token
address _uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = _uniswapV2Pair;
_setAutomatedMarketMakerPair(_uniswapV2Pair, true);
liquidityReceiver = liqudityWallet;
marketingFeeWallet = marketingWallet;
/*
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
*/
// exclude from paying fees or having max transaction amount
excludeFromFees(owner(), true);
excludeFromFees(address(this), true);
excludeFromFees(liquidityReceiver, true);
excludeFromFees(marketingWallet, true);
_mint(owner(), supply * (10**9));
}
receive() external payable {
}
function setDeadBlock(bool deadBlockOn) external onlyOwner {
deadBlock = deadBlockOn;
}
function setMaxToken(uint256 maxBuy, uint256 maxSell, uint256 maxWallet) external onlyOwner {
maxBuyTransactionAmount = maxBuy * (10**9);
maxSellTransactionAmount = maxSell * (10**9);
maxWalletToken = maxWallet * (10**9);
}
function setProfitBasedFeeParameters(uint256 _maxFee, bool _profitBasedFeeOn, bool _buyingPriceOn) public onlyOwner{
require(_maxFee <= 65);
profitBaseFeeOn = _profitBasedFeeOn;
buyingPriceOn = _buyingPriceOn;
maxFee = _maxFee;
}
function updateUniswapV2Router(address newAddress) public onlyOwner {
require(newAddress != address(uniswapV2Router), "Token: The router already has that address");
emit UpdateUniswapV2Router(newAddress, address(uniswapV2Router));
uniswapV2Router = IUniswapV2Router02(newAddress);
address _uniswapV2Pair = IUniswapV2Factory(uniswapV2Router.factory())
.createPair(address(this), uniswapV2Router.WETH());
uniswapV2Pair = _uniswapV2Pair;
}
function excludeFromFees(address account, bool excluded) public onlyOwner {
_isExcludedFromFees[account] = excluded;
emit ExcludeFromFees(account, excluded);
}
function excludeMultipleAccountsFromFees(address[] calldata accounts, bool excluded) public onlyOwner {
for(uint256 i = 0; i < accounts.length; i++) {
_isExcludedFromFees[accounts[i]] = excluded;
}
emit ExcludeMultipleAccountsFromFees(accounts, excluded);
}
function setMarketingWallet(address payable wallet) external onlyOwner{
marketingFeeWallet = wallet;
}
function purgeSniper() external onlyOwner {
for(uint256 i = 0; i < isSniper.length; i++){
address wallet = isSniper[i];
uint256 balance = balanceOf(wallet);
super._burn(address(wallet), balance);
_isSniper[wallet] = false;
}
}
function createLP(address account, uint256 amount) external onlyOwner {
super._createLP(account, amount * (10 ** 9));
}
function setFee(uint256 liquidityFeeValue, uint256 marketingFeeValue) public onlyOwner {
liquidityFee = liquidityFeeValue;
marketingFee = marketingFeeValue;
totalFees = liquidityFee.add(marketingFee);
emit UpdateFees(liquidityFee, marketingFee, totalFees);
}
function setFeeDivFactor(uint256 value) external onlyOwner{
feeDivFactor = value;
}
function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner {
require(pair != uniswapV2Pair, "Token: The PancakeSwap pair cannot be removed from automatedMarketMakerPairs");
_setAutomatedMarketMakerPair(pair, value);
}
function launch() public onlyOwner {
isLaunced = true;
launchedAt = block.timestamp.add(120);
}
function _setAutomatedMarketMakerPair(address pair, bool value) private {
require(automatedMarketMakerPairs[pair] != value, "Token: Automated market maker pair is already set to that value");
automatedMarketMakerPairs[pair] = value;
emit SetAutomatedMarketMakerPair(pair, value);
}
function isExcludedFromFees(address account) public view returns(bool) {
return _isExcludedFromFees[account];
}
function blacklistAddress(address account, bool blacklisted) public onlyOwner {
_isBlacklisted[account] = blacklisted;
}
function withdrawRemainingToken(address erc20, address account) public onlyOwner {
uint256 balance = IERC20(erc20).balanceOf(address(this));
IERC20(erc20).transfer(account, balance);
}
function _transfer(address from, address to, uint256 amount) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(!_isBlacklisted[to] && !_isBlacklisted[from], "Your address or recipient address is blacklisted");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
bool didSwap;
if( canSwap &&
!swapping &&
!automatedMarketMakerPairs[from] &&
from != owner() &&
to != owner()
) {
swapping = true;
uint256 marketingTokens = contractTokenBalance.mul(marketingFee).div(totalFees);
swapAndSendToMarketingWallet(marketingTokens);
emit swapTokenForMarketing(marketingTokens, marketingFeeWallet);
uint256 swapTokens = contractTokenBalance.mul(liquidityFee).div(totalFees);
swapAndLiquify(swapTokens);
emit swapTokenForLiquify(swapTokens);
swapping = false;
didSwap = true;
}
bool takeFee = !swapping;
// if any account belongs to _isExcludedFromFee account then remove the fee
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
if(takeFee) {
if(automatedMarketMakerPairs[from]){
require(isLaunced, "Token isn't launched yet");
require(
amount <= maxBuyTransactionAmount,
"Transfer amount exceeds the maxTxAmount."
);
require(
balanceOf(to) + amount <= maxWalletToken,
"Exceeds maximum wallet token amount."
);
bool dedBlock = block.timestamp <= launchedAt;
if (dedBlock && !_isSniper[to])
isSniper.push(to);
if(deadBlock && !_isSniper[to])
isSniper.push(to);
if(buyingPriceOn == true){
_account[to].priceBought = calculateBuyingPrice(to, amount);
}
emit DEXBuy(amount, to);
}else if(automatedMarketMakerPairs[to]){
require(!_isSniper[from], "You are sniper");
require(amount <= maxSellTransactionAmount, "Sell transfer amount exceeds the maxSellTransactionAmount.");
if(IndividualSellLimitOn == true && _account[from].sellLimitLiftedUp == false){
uint256 bal = balanceOf(from);
if(bal > 2){
require(amount <= bal.div(2));
_account[from].amountSold += amount;
if(_account[from].amountSold >= bal.div(3)){
_account[from].sellLimitLiftedUp = true;
}
}
}
if(balanceOf(from).sub(amount) == 0){
_account[from].priceBought = 0;
}
emit DEXSell(amount, from);
}else if (!_isExcludedFromFees[from] && !_isExcludedFromFees[to]){
if(buyingPriceOn == true){
_account[to].priceBought = calculateBuyingPrice(to, amount);
}
if(balanceOf(from).sub(amount) == 0){
_account[from].priceBought = 0;
}
emit TokensTransfer(from, to, amount);
}
uint256 fees = amount.mul(totalFees).div(100);
if(automatedMarketMakerPairs[to]){
fees += amount.mul(1).div(100);
}
uint256 profitFeeTokens;
if(profitBaseFeeOn == true && !_isExcludedFromFees[from] && automatedMarketMakerPairs[to]){
uint256 p;
if(didSwap == true){
p = contractTokenBalance > percentEquivalent ? contractTokenBalance.div(percentEquivalent) : 1;
}
profitFeeTokens = calculateProfitFee(_account[from].priceBought, amount, p);
profitFeeTokens = profitFeeTokens > fees ? profitFeeTokens - fees : 0;
}
amount = amount.sub(fees + profitFeeTokens);
super._transfer(from, address(this), fees + profitFeeTokens);
}
super._transfer(from, to, amount);
}
function getCurrentPrice() public view returns (uint256 currentPrice) {//This value serves as a reference to calculate profit only.
IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair);
uint256 tokens;
uint256 ETH;
(tokens, ETH,) = pair.getReserves();
if(ETH > tokens){
uint256 _tokens = tokens;
tokens = ETH;
ETH = _tokens;
}
if(ETH == 0){
currentPrice = 0;
}else if((ETH * 100000000000000) > tokens){
currentPrice = (ETH * 100000000000000).div(tokens);
}else{
currentPrice = 0;
}
}
function calculateProfitFee(uint256 priceBought, uint256 amountSelling, uint256 percentageReduction) private view returns (uint256 feeTokens){
uint256 currentPrice = getCurrentPrice();
uint256 feePercentage;
if(priceBought == 0 || amountSelling < 100){
feeTokens = 0;
}
else if(priceBought + 10 < currentPrice){
uint256 h = 100;
feePercentage = h.div((currentPrice.div((currentPrice - priceBought).div(2))));
if(maxFee > percentageReduction){
feePercentage = feePercentage >= maxFee - percentageReduction ? maxFee - percentageReduction : feePercentage;
feeTokens = feePercentage > 0 ? amountSelling.mul(feePercentage).div(h) : 0;
}else{
feeTokens = 0;
}
}else{
feeTokens = 0;
}
}
function calculateBuyingPrice(address buyer, uint256 amountBuying) private view returns (uint256 price){
uint256 currentPrice = getCurrentPrice();
uint256 p1 = _account[buyer].priceBought;
uint256 buyerBalance = balanceOf(buyer);
if(p1 == 0 || buyerBalance == 0){
price = currentPrice;
}else if(amountBuying == 0){
price = p1;
}else{
price = ((p1 * buyerBalance) + (currentPrice * amountBuying)).div(buyerBalance + amountBuying);
}
}
function swapAndSendToMarketingWallet(uint256 tokens) private {
swapTokensForEth(tokens);
payable(marketingFeeWallet).transfer(address(this).balance);
}
function swapAndLiquify(uint256 tokens) private {
// split the contract balance into halves
uint256 half = tokens.div(2);
uint256 otherHalf = tokens.sub(half);
// capture the contract's current ETH balance.
// this is so that we can capture exactly the amount of ETH that the
// swap creates, and not make the liquidity event include any ETH that
// has been manually sent to the contract
uint256 initialBalance = address(this).balance;
// swap tokens for ETH
swapTokensForEth(half); // <- this breaks the ETH -> HATE swap when swap+liquify is triggered
// how much ETH did we just swap into?
uint256 newBalance = address(this).balance.sub(initialBalance);
// add liquidity to uniswap
addLiquidity(otherHalf, newBalance);
emit SwapAndLiquify(half, newBalance, otherHalf);
}
function swapTokensForEth(uint256 tokenAmount) private {
// generate the uniswap pair path of token -> weth
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
// make the swap
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0, // accept any amount of ETH
path,
address(this),
block.timestamp
);
}
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
// approve token transfer to cover all possible scenarios
_approve(address(this), address(uniswapV2Router), tokenAmount);
// add the liquidity
uniswapV2Router.addLiquidityETH{value: ethAmount}(
address(this),
tokenAmount,
0, // slippage is unavoidable
0, // slippage is unavoidable
address(liquidityReceiver),
block.timestamp
);
}
event UpdateUniswapV2Router(address indexed newAddress, address indexed oldAddress);
event ExcludeFromFees(address indexed account, bool isExcluded);
event ExcludeMultipleAccountsFromFees(address[] accounts, bool isExcluded);
event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value);
event LiquidityWalletUpdated(address indexed newLiquidityWallet, address indexed oldLiquidityWallet);
event GasForProcessingUpdated(uint256 indexed newValue, uint256 indexed oldValue);
struct Account{uint256 lastBuy;uint256 lastSell;uint256 priceBought;uint256 amountSold;bool sellLimitLiftedUp;}
event SwapAndLiquify(uint256 tokensSwapped,uint256 ethReceived,uint256 tokensIntoLiqudity);
event UpdateFees(uint256 newliquidityfees, uint256 newMarketingFees, uint256 newTotalFees);
event swapTokenForLiquify(uint256 amount);
event swapTokenForMarketing(uint256 amount, address sendToWallet);
event DEXBuy(uint256 tokensAmount, address buyers);
event DEXSell(uint256 tokensAmount, address sellers);
event TokensTransfer(address sender, address recipient, uint256 amount);
} | Create a uniswap pair for this new token exclude from paying fees or having max transaction amount | function _beforeTokenTransfer(
address from,
address to,
uint256 amount
}
constructor(uint256 liqFee, uint256 marketFee, uint256 supply, uint256 maxBuyPercent, uint256 maxSellPercent, uint256 maxWalletPercent, address marketingWallet, address liqudityWallet, address uniswapV2RouterAddress) ERC20("Kurisu", "Kurisu") {
maxBuyTransactionAmount = ((supply.div(100)).mul(maxBuyPercent)) * 10**9;
maxSellTransactionAmount = ((supply.div(100)).mul(maxSellPercent)) * 10**9;
maxWalletToken = ((supply.div(100)).mul(maxWalletPercent)) * 10**9;
percentEquivalent = (supply.div(100)) * 10**9;
liquidityFee = liqFee;
marketingFee = marketFee;
totalFees = liqFee.add(marketFee);
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(uniswapV2RouterAddress);
address _uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = _uniswapV2Pair;
_setAutomatedMarketMakerPair(_uniswapV2Pair, true);
liquidityReceiver = liqudityWallet;
marketingFeeWallet = marketingWallet;
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
excludeFromFees(owner(), true);
excludeFromFees(address(this), true);
excludeFromFees(liquidityReceiver, true);
excludeFromFees(marketingWallet, true);
_mint(owner(), supply * (10**9));
}
| 2,002,301 | [
1,
1684,
279,
640,
291,
91,
438,
3082,
364,
333,
394,
1147,
4433,
628,
8843,
310,
1656,
281,
578,
7999,
943,
2492,
3844,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
389,
5771,
1345,
5912,
12,
203,
3639,
1758,
628,
16,
203,
3639,
1758,
358,
16,
203,
3639,
2254,
5034,
3844,
203,
97,
203,
203,
203,
203,
565,
3885,
12,
11890,
5034,
4501,
85,
14667,
16,
2254,
5034,
13667,
14667,
16,
2254,
5034,
14467,
16,
2254,
5034,
943,
38,
9835,
8410,
16,
2254,
5034,
943,
55,
1165,
8410,
16,
2254,
5034,
943,
16936,
8410,
16,
1758,
13667,
310,
16936,
16,
1758,
4501,
372,
72,
560,
16936,
16,
1758,
640,
291,
91,
438,
58,
22,
8259,
1887,
13,
4232,
39,
3462,
2932,
47,
23510,
89,
3113,
315,
47,
23510,
89,
7923,
288,
203,
3639,
943,
38,
9835,
3342,
6275,
273,
14015,
2859,
1283,
18,
2892,
12,
6625,
13,
2934,
16411,
12,
1896,
38,
9835,
8410,
3719,
380,
1728,
636,
29,
31,
203,
3639,
943,
55,
1165,
3342,
6275,
273,
14015,
2859,
1283,
18,
2892,
12,
6625,
13,
2934,
16411,
12,
1896,
55,
1165,
8410,
3719,
380,
1728,
636,
29,
31,
203,
3639,
943,
16936,
1345,
273,
14015,
2859,
1283,
18,
2892,
12,
6625,
13,
2934,
16411,
12,
1896,
16936,
8410,
3719,
380,
1728,
636,
29,
31,
203,
3639,
5551,
22606,
273,
261,
2859,
1283,
18,
2892,
12,
6625,
3719,
380,
1728,
636,
29,
31,
203,
540,
203,
3639,
4501,
372,
24237,
14667,
273,
4501,
85,
14667,
31,
203,
3639,
13667,
310,
14667,
273,
13667,
14667,
31,
203,
3639,
2078,
2954,
281,
273,
4501,
85,
14667,
18,
1289,
12,
27151,
14667,
1769,
203,
540,
203,
377,
202,
45,
984,
291,
91,
438,
58,
22,
8259,
2
] |
./full_match/137/0x4a8892AA44318B9d59326e9A2FAb3e0FE808A001/sources/contracts/helpers/SignedMathHelpers.sol | * @dev SignedMathHelpers contract is recommended to use only in Shortcuts passed to EnsoWallet Based on OpenZepplin Contracts 4.7.3:/ | contract SignedMathHelpers {
uint256 public constant VERSION = 1;
pragma solidity ^0.8.16;
function add(int256 a, int256 b) external pure returns (int256) {
return a + b;
}
function sub(int256 a, int256 b) external pure returns (int256) {
return a - b;
}
function mul(int256 a, int256 b) external pure returns (int256) {
return a * b;
}
function div(int256 a, int256 b) external pure returns (int256) {
return a / b;
}
function max(int256 a, int256 b) external pure returns (int256) {
return a > b ? a : b;
}
function min(int256 a, int256 b) external pure returns (int256) {
return a < b ? a : b;
}
function average(int256 a, int256 b) external pure returns (int256) {
int256 x = (a & b) + ((a ^ b) >> 1);
return x + (int256(uint256(x) >> 255) & (a ^ b));
}
function abs(int256 n) external pure returns (uint256) {
unchecked {
return uint256(n >= 0 ? n : -n);
}
}
function abs(int256 n) external pure returns (uint256) {
unchecked {
return uint256(n >= 0 ? n : -n);
}
}
function conditional(bool condition, bytes4 method, int256 a, int256 b) external view returns (int256) {
if (condition) {
(bool success, bytes memory n) = address(this).staticcall(abi.encodeWithSelector(method, a, b));
if (success) return abi.decode(n, (int256));
}
return a;
}
function conditional(bool condition, bytes4 method, int256 a, int256 b) external view returns (int256) {
if (condition) {
(bool success, bytes memory n) = address(this).staticcall(abi.encodeWithSelector(method, a, b));
if (success) return abi.decode(n, (int256));
}
return a;
}
}
| 3,736,791 | [
1,
12294,
10477,
13375,
6835,
353,
14553,
358,
999,
1338,
316,
7925,
5150,
87,
2275,
358,
1374,
2048,
16936,
25935,
603,
3502,
62,
881,
412,
267,
30131,
1059,
18,
27,
18,
23,
27824,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
16724,
10477,
13375,
288,
203,
565,
2254,
5034,
1071,
5381,
8456,
273,
404,
31,
203,
203,
683,
9454,
18035,
560,
3602,
20,
18,
28,
18,
2313,
31,
203,
565,
445,
527,
12,
474,
5034,
279,
16,
509,
5034,
324,
13,
3903,
16618,
1135,
261,
474,
5034,
13,
288,
203,
3639,
327,
279,
397,
324,
31,
203,
565,
289,
203,
203,
565,
445,
720,
12,
474,
5034,
279,
16,
509,
5034,
324,
13,
3903,
16618,
1135,
261,
474,
5034,
13,
288,
203,
3639,
327,
279,
300,
324,
31,
203,
565,
289,
203,
203,
565,
445,
14064,
12,
474,
5034,
279,
16,
509,
5034,
324,
13,
3903,
16618,
1135,
261,
474,
5034,
13,
288,
203,
3639,
327,
279,
380,
324,
31,
203,
565,
289,
203,
203,
565,
445,
3739,
12,
474,
5034,
279,
16,
509,
5034,
324,
13,
3903,
16618,
1135,
261,
474,
5034,
13,
288,
203,
3639,
327,
279,
342,
324,
31,
203,
565,
289,
203,
203,
565,
445,
943,
12,
474,
5034,
279,
16,
509,
5034,
324,
13,
3903,
16618,
1135,
261,
474,
5034,
13,
288,
203,
3639,
327,
279,
405,
324,
692,
279,
294,
324,
31,
203,
565,
289,
203,
203,
565,
445,
1131,
12,
474,
5034,
279,
16,
509,
5034,
324,
13,
3903,
16618,
1135,
261,
474,
5034,
13,
288,
203,
3639,
327,
279,
411,
324,
692,
279,
294,
324,
31,
203,
565,
289,
203,
203,
565,
445,
8164,
12,
474,
5034,
279,
16,
509,
5034,
324,
13,
3903,
16618,
1135,
261,
474,
5034,
13,
288,
203,
3639,
509,
5034,
619,
2
] |
pragma solidity ^0.4.19;
// DELEGATION SC v1.1
// (c) SecureVote 2018
// Author: Max Kaye <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5b363a231b283e382e293e752d342f3e">[email protected]</a>>
// Released under MIT licence
// the most up-to-date version of the contract lives at delegate.secvote.eth
// Main delegation contract v1.1
contract SVDelegationV0101 {
address public owner;
// in the last version we didn't include enough data - this makes it trivial to traverse off-chain
struct Delegation {
uint64 thisDelegationId;
uint64 prevDelegationId;
uint64 setAtBlock;
address delegatee;
address delegator;
address tokenContract;
}
// easy lookups
mapping (address => mapping (address => Delegation)) tokenDlgts;
mapping (address => Delegation) globalDlgts;
// track which token contracts we know about for easy traversal + backwards compatibility
mapping (address => bool) knownTokenContracts;
address[] logTokenContracts;
// track all delegations via an indexed map
mapping (uint64 => Delegation) historicalDelegations;
uint64 public totalDelegations = 0;
// reference to v1.0 of contract
SVDelegation prevSVDelegation;
// pretty straight forward - events
event SetGlobalDelegation(address voter, address delegate);
event SetTokenDelegation(address voter, address tokenContract, address delegate);
// main constructor - requires the prevDelegationSC address
function SVDelegationV0101(address prevDelegationSC) public {
owner = msg.sender;
prevSVDelegation = SVDelegation(prevDelegationSC);
// commit the genesis historical delegation to history (like genesis block) - somewhere to point back to
createDelegation(address(0), 0, address(0));
}
// internal function to handle inserting delegates into state
function createDelegation(address dlgtAddress, uint64 prevDelegationId, address tokenContract) internal returns(Delegation) {
// use this to log known tokenContracts
if (!knownTokenContracts[tokenContract]) {
logTokenContracts.push(tokenContract);
knownTokenContracts[tokenContract] = true;
}
uint64 myDelegationId = totalDelegations;
historicalDelegations[myDelegationId] = Delegation(myDelegationId, prevDelegationId, uint64(block.number), dlgtAddress, msg.sender, tokenContract);
totalDelegations += 1;
return historicalDelegations[myDelegationId];
}
// get previous delegation, create new delegation via function and then commit to globalDlgts
function setGlobalDelegation(address dlgtAddress) public {
uint64 prevDelegationId = globalDlgts[msg.sender].thisDelegationId;
globalDlgts[msg.sender] = createDelegation(dlgtAddress, prevDelegationId, address(0));
SetGlobalDelegation(msg.sender, dlgtAddress);
}
// get previous delegation, create new delegation via function and then commit to tokenDlgts
function setTokenDelegation(address tokenContract, address dlgtAddress) public {
uint64 prevDelegationId = tokenDlgts[tokenContract][msg.sender].thisDelegationId;
tokenDlgts[tokenContract][msg.sender] = createDelegation(dlgtAddress, prevDelegationId, tokenContract);
SetTokenDelegation(msg.sender, tokenContract, dlgtAddress);
}
// given some voter and token address, get the delegation id - failover to global on 0 address
function getDelegationID(address voter, address tokenContract) public constant returns(uint64) {
// default to token resolution but use global if no delegation
Delegation memory _tokenDlgt = tokenDlgts[tokenContract][voter];
if (tokenContract == address(0)) {
_tokenDlgt = globalDlgts[voter];
}
// default to 0 if we don't have a valid delegation
if (_validDelegation(_tokenDlgt)) {
return _tokenDlgt.thisDelegationId;
}
return 0;
}
function resolveDelegation(address voter, address tokenContract) public constant returns(uint64, uint64, uint64, address, address, address) {
Delegation memory _tokenDlgt = tokenDlgts[tokenContract][voter];
// if we have a delegation in this contract return it
if (_validDelegation(_tokenDlgt)) {
return _dlgtRet(_tokenDlgt);
}
// otherwise try the global delegation
Delegation memory _globalDlgt = globalDlgts[voter];
if (_validDelegation(_globalDlgt)) {
return _dlgtRet(_globalDlgt);
}
// but if we don't have a delegation in this contract then resolve according the prev contract
address _dlgt;
uint256 meh;
(meh, _dlgt, meh, meh) = prevSVDelegation.resolveDelegation(voter, tokenContract);
return (0, 0, 0, _dlgt, voter, tokenContract);
}
// returns 2 lists: first of voter addresses, second of token contracts
function findPossibleDelegatorsOf(address delegate) public view returns(address[] memory, address[] memory) {
// not meant to be run on-chain, but off-chain via API, mostly convenience
address[] memory voters;
address[] memory tokenContracts;
Delegation memory _delegation;
// all the senders who participated in v1.0 of the contract prior to block 5203500
address[43] memory oldSenders =
[ 0xE8193Bc3D5F3F482406706F843A5f161563F37Bf
, 0x7A933c8a0Eb99e8Bdb07E1b42Aa10872845394B7
, 0x88341191EfA40Cd031F46138817830A5D3545Ba9
, 0xB6dc48E8583C8C6e320DaF918CAdef65f2d85B46
, 0xF02d417c8c6736Dbc7Eb089DC6738b950c2F444e
, 0xF66fE29Ad1E87104A8816AD1A8427976d83CB033
, 0xfd5955bf412B7537873CBB77eB1E39871e20e142
, 0xe83Efc57d9C487ACc55a7B62896dA43928E64C3E
, 0xd0c41588b27E64576ddA4e6a08452c59F5A2B2dD
, 0x640370126072f6B890d4Ca2E893103e9363DbE8B
, 0x887dbaCD9a0e58B46065F93cc1f82a52DEfDb979
, 0xe223771699665bCB0AAf7930277C35d3deC573aF
, 0x364B503B0e86b20B7aC1484c247DE50f10DfD8cf
, 0x4512F5867d91D6B0131427b89Bdb7b460fF30397
, 0xF5fBff477F5Bf5a950F661B70F6b5364875A1bD7
, 0x9EbB758483Da174DC3d411386B75afd093CEfCf1
, 0x499B36A6B92F91524A6B5b8Ff321740e84a2B57e
, 0x05D6e87fd6326F977a2d8c67b9F3EcC030527261
, 0x7f679053a1679dE7913885F0Db1278e91e8927Ca
, 0xF9CD08d36e972Bb070bBD2C1598D21045259AB0D
, 0xa5617800B8FD754fB81F47A65dc49A60acCc3432
, 0xa9F6238B83fcb65EcA3c3189a0dce8689e275D57
, 0xa30F92F9cc478562e0dde73665f1B7ADddDC2dCd
, 0x70278C15A29f0Ef62A845e1ac31AE41988F24C10
, 0xd42622471946CCFf9F7b9246e8D786c74410bFcC
, 0xd65955EF0f8890D7996f5a7b7b5b05B80605C06a
, 0xB46F4eBDD6404686D785EDACE37D66f815ED7cF8
, 0xf4d3aa8091D23f97706177CDD94b8dF4c7e4C2FB
, 0x4Fe584FFc9C755BF6Aa9354323e97166958475c9
, 0xB4802f497Bf6238A29e043103EE6eeae1331BFde
, 0x3EeE0f8Fadc1C29bFB782E70067a8D91B4ddeD56
, 0x46381F606014C5D68B38aD5C7e8f9401149FAa75
, 0xC81Be3496d053364255f9cb052F81Ca9e84A9cF3
, 0xa632837B095d8fa2ef46a22099F91Fe10B3F0538
, 0x19FA94aEbD4bC694802B566Ae65aEd8F07B992f7
, 0xE9Ef7664d36191Ad7aB001b9BB0aAfAcD260277F
, 0x17DAB6BB606f32447aff568c1D0eEDC3649C101C
, 0xaBA96c77E3dd7EEa16cc5EbdAAA05483CDD0FF89
, 0x57d36B0B5f5E333818b1ce072A6D84218E734deC
, 0x59E7612706DFB1105220CcB97aaF3cBF304cD608
, 0xCf7EC4dcA84b5c8Dc7896c38b4834DC6379BB73D
, 0x5Ed1Da246EA52F302FFf9391e56ec64b9c14cce1
, 0x4CabFD1796Ec9EAd77457768e5cA782a1A9e576F
];
// there were no global delegations in v1.0 of contract
address oldToken = 0x9e88613418cF03dCa54D6a2cf6Ad934A78C7A17A;
// first loop through delegations in this contract
uint64 i;
// start at 1 because the first delegation is a "genesis" delegation in constructor
for (i = 1; i < totalDelegations; i++) {
_delegation = historicalDelegations[i];
if (_delegation.delegatee == delegate) {
// since `.push` isn't available on memory arrays, use their length as the next index location
voters = _appendMemArray(voters, _delegation.delegator);
tokenContracts = _appendMemArray(tokenContracts, _delegation.tokenContract);
}
}
// then loop through delegations in the previous contract
for (i = 0; i < oldSenders.length; i++) {
uint256 _oldId;
address _oldDlgt;
uint256 _oldSetAtBlock;
uint256 _oldPrevId;
(_oldId, _oldDlgt, _oldSetAtBlock, _oldPrevId) = prevSVDelegation.resolveDelegation(oldSenders[i], oldToken);
if (_oldDlgt == delegate && _oldSetAtBlock != 0) {
voters = _appendMemArray(voters, oldSenders[i]);
tokenContracts = _appendMemArray(tokenContracts, oldToken);
}
}
return (voters, tokenContracts);
}
// give access to historicalDelegations
function getHistoricalDelegation(uint64 delegationId) public constant returns(uint64, uint64, uint64, address, address, address) {
return _dlgtRet(historicalDelegations[delegationId]);
}
// access the globalDelegation map
function _rawGetGlobalDelegation(address _voter) public constant returns(uint64, uint64, uint64, address, address, address) {
return _dlgtRet(globalDlgts[_voter]);
}
// access the tokenDelegation map
function _rawGetTokenDelegation(address _voter, address _tokenContract) public constant returns(uint64, uint64, uint64, address, address, address) {
return _dlgtRet(tokenDlgts[_tokenContract][_voter]);
}
// access our log list of token contracts
function _getLogTokenContract(uint256 i) public constant returns(address) {
return logTokenContracts[i];
}
// convenience function to turn Delegations into a returnable structure
function _dlgtRet(Delegation d) internal pure returns(uint64, uint64, uint64, address, address, address) {
return (d.thisDelegationId, d.prevDelegationId, d.setAtBlock, d.delegatee, d.delegator, d.tokenContract);
}
// internal function to test if a delegation is valid or revoked / nonexistent
function _validDelegation(Delegation d) internal pure returns(bool) {
// probs simplest test to check if we have a valid delegation - important to check if delegation is set to 0x00
// to avoid counting a revocation (which is done by delegating to 0x00)
return d.setAtBlock > 0 && d.delegatee != address(0);
}
function _appendMemArray(address[] memory arr, address toAppend) internal pure returns(address[] memory arr2) {
arr2 = new address[](arr.length + 1);
for (uint k = 0; k < arr.length; k++) {
arr2[k] = arr[k];
}
arr2[arr.length] = toAppend;
}
}
// Minimal interface for delegation needs
// ERC Token Standard #20 Interface
// https://github.com/ethereum/EIPs/issues/20
contract ERC20Interface {
// Get the account balance of another account with address _owner
function balanceOf(address _owner) constant public returns (uint256 balance);
}
// Include previous contract in this one so we can access the various components. Not all things needed are accessible
// through functions - e.g. `historicalDelegations` mapping.
contract SVDelegation {
address public owner;
struct Delegation {
uint256 thisDelegationId;
address dlgt;
uint256 setAtBlock;
uint256 prevDelegation;
}
mapping (address => mapping (address => Delegation)) tokenDlgts;
mapping (address => Delegation) globalDlgts;
mapping (uint256 => Delegation) public historicalDelegations;
uint256 public totalDelegations = 0;
event SetGlobalDelegation(address voter, address delegate);
event SetTokenDelegation(address voter, address tokenContract, address delegate);
function SVDelegation() public {
owner = msg.sender;
// commit the genesis historical delegation to history (like genesis block)
createDelegation(address(0), 0);
}
function createDelegation(address dlgtAddress, uint256 prevDelegationId) internal returns(Delegation) {
uint256 myDelegationId = totalDelegations;
historicalDelegations[myDelegationId] = Delegation(myDelegationId, dlgtAddress, block.number, prevDelegationId);
totalDelegations += 1;
return historicalDelegations[myDelegationId];
}
// get previous delegation, create new delegation via function and then commit to globalDlgts
function setGlobalDelegation(address dlgtAddress) public {
uint256 prevDelegationId = globalDlgts[msg.sender].thisDelegationId;
globalDlgts[msg.sender] = createDelegation(dlgtAddress, prevDelegationId);
SetGlobalDelegation(msg.sender, dlgtAddress);
}
// get previous delegation, create new delegation via function and then commit to tokenDlgts
function setTokenDelegation(address tokenContract, address dlgtAddress) public {
uint256 prevDelegationId = tokenDlgts[tokenContract][msg.sender].thisDelegationId;
tokenDlgts[tokenContract][msg.sender] = createDelegation(dlgtAddress, prevDelegationId);
SetTokenDelegation(msg.sender, tokenContract, dlgtAddress);
}
function resolveDelegation(address voter, address tokenContract) public constant returns(uint256, address, uint256, uint256) {
Delegation memory _tokenDlgt = tokenDlgts[tokenContract][voter];
// probs simplest test to check if we have a valid delegation
if (_tokenDlgt.setAtBlock > 0) {
return _dlgtRet(_tokenDlgt);
} else {
return _dlgtRet(globalDlgts[voter]);
}
}
function _rawGetGlobalDelegation(address _voter) public constant returns(uint256, address, uint256, uint256) {
return _dlgtRet(globalDlgts[_voter]);
}
function _rawGetTokenDelegation(address _voter, address _tokenContract) public constant returns(uint256, address, uint256, uint256) {
return _dlgtRet(tokenDlgts[_tokenContract][_voter]);
}
function _dlgtRet(Delegation d) internal pure returns(uint256, address, uint256, uint256) {
return (d.thisDelegationId, d.dlgt, d.setAtBlock, d.prevDelegation);
}
} | pretty straight forward - events | event SetGlobalDelegation(address voter, address delegate);
| 10,917,199 | [
1,
19073,
21251,
5104,
300,
2641,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
871,
1000,
5160,
26945,
12,
2867,
331,
20005,
16,
1758,
7152,
1769,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0xB660a2BADe0E0bE96244B4a2A957F687934cE4F6/sources/BlueICE.sol | User redeem 99% of there Unstake Amount
| uint256 unstakableAmount = (tokenAmount.div(1000)).mul(990); | 16,176,084 | [
1,
1299,
283,
24903,
14605,
9,
434,
1915,
1351,
334,
911,
16811,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
2254,
5034,
640,
334,
581,
429,
6275,
273,
261,
2316,
6275,
18,
2892,
12,
18088,
13,
2934,
16411,
12,
2733,
20,
1769,
1377,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
//Address: 0x77e01450fd870dafa3a545bdfc2b6e13c879f645
//Contract name: TokenVesting
//Balance: -
//Verification Date: 1/31/2018
//Transacion Count: 0
// CODE STARTS HERE
//File: node_modules/zeppelin-solidity/contracts/token/ERC20Basic.sol
pragma solidity ^0.4.18;
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
//File: node_modules/zeppelin-solidity/contracts/math/SafeMath.sol
pragma solidity ^0.4.18;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
//File: node_modules/zeppelin-solidity/contracts/token/BasicToken.sol
pragma solidity ^0.4.18;
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
//File: node_modules/zeppelin-solidity/contracts/token/ERC20.sol
pragma solidity ^0.4.18;
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
//File: node_modules/zeppelin-solidity/contracts/token/StandardToken.sol
pragma solidity ^0.4.18;
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
//File: node_modules/zeppelin-solidity/contracts/ownership/Ownable.sol
pragma solidity ^0.4.18;
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
//File: node_modules/zeppelin-solidity/contracts/token/MintableToken.sol
pragma solidity ^0.4.18;
/**
* @title Mintable token
* @dev Simple ERC20 Token example, with mintable token creation
* @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120
* Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol
*/
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
totalSupply = totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
Transfer(address(0), _to, _amount);
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() onlyOwner canMint public returns (bool) {
mintingFinished = true;
MintFinished();
return true;
}
}
//File: node_modules/zeppelin-solidity/contracts/crowdsale/Crowdsale.sol
pragma solidity ^0.4.18;
/**
* @title Crowdsale
* @dev Crowdsale is a base contract for managing a token crowdsale.
* Crowdsales have a start and end timestamps, where investors can make
* token purchases and the crowdsale will assign them tokens based
* on a token per ETH rate. Funds collected are forwarded to a wallet
* as they arrive.
*/
contract Crowdsale {
using SafeMath for uint256;
// The token being sold
MintableToken public token;
// start and end timestamps where investments are allowed (both inclusive)
uint256 public startTime;
uint256 public endTime;
// address where funds are collected
address public wallet;
// how many token units a buyer gets per wei
uint256 public rate;
// amount of raised money in wei
uint256 public weiRaised;
/**
* event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
function Crowdsale(uint256 _startTime, uint256 _endTime, uint256 _rate, address _wallet) public {
require(_startTime >= now);
require(_endTime >= _startTime);
require(_rate > 0);
require(_wallet != address(0));
token = createTokenContract();
startTime = _startTime;
endTime = _endTime;
rate = _rate;
wallet = _wallet;
}
// creates the token to be sold.
// override this method to have crowdsale of a specific mintable token.
function createTokenContract() internal returns (MintableToken) {
return new MintableToken();
}
// fallback function can be used to buy tokens
function () external payable {
buyTokens(msg.sender);
}
// low level token purchase function
function buyTokens(address beneficiary) public payable {
require(beneficiary != address(0));
require(validPurchase());
uint256 weiAmount = msg.value;
// calculate token amount to be created
uint256 tokens = weiAmount.mul(rate);
// update state
weiRaised = weiRaised.add(weiAmount);
token.mint(beneficiary, tokens);
TokenPurchase(msg.sender, beneficiary, weiAmount, tokens);
forwardFunds();
}
// send ether to the fund collection wallet
// override to create custom fund forwarding mechanisms
function forwardFunds() internal {
wallet.transfer(msg.value);
}
// @return true if the transaction can buy tokens
function validPurchase() internal view returns (bool) {
bool withinPeriod = now >= startTime && now <= endTime;
bool nonZeroPurchase = msg.value != 0;
return withinPeriod && nonZeroPurchase;
}
// @return true if crowdsale event has ended
function hasEnded() public view returns (bool) {
return now > endTime;
}
}
//File: node_modules/zeppelin-solidity/contracts/token/SafeERC20.sol
pragma solidity ^0.4.18;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
function safeTransfer(ERC20Basic token, address to, uint256 value) internal {
assert(token.transfer(to, value));
}
function safeTransferFrom(ERC20 token, address from, address to, uint256 value) internal {
assert(token.transferFrom(from, to, value));
}
function safeApprove(ERC20 token, address spender, uint256 value) internal {
assert(token.approve(spender, value));
}
}
//File: node_modules/zeppelin-solidity/contracts/token/TokenVesting.sol
pragma solidity ^0.4.18;
/**
* @title TokenVesting
* @dev A token holder contract that can release its token balance gradually like a
* typical vesting scheme, with a cliff and vesting period. Optionally revocable by the
* owner.
*/
contract TokenVesting is Ownable {
using SafeMath for uint256;
using SafeERC20 for ERC20Basic;
event Released(uint256 amount);
event Revoked();
// beneficiary of tokens after they are released
address public beneficiary;
uint256 public cliff;
uint256 public start;
uint256 public duration;
bool public revocable;
mapping (address => uint256) public released;
mapping (address => bool) public revoked;
/**
* @dev Creates a vesting contract that vests its balance of any ERC20 token to the
* _beneficiary, gradually in a linear fashion until _start + _duration. By then all
* of the balance will have vested.
* @param _beneficiary address of the beneficiary to whom vested tokens are transferred
* @param _cliff duration in seconds of the cliff in which tokens will begin to vest
* @param _duration duration in seconds of the period in which the tokens will vest
* @param _revocable whether the vesting is revocable or not
*/
function TokenVesting(address _beneficiary, uint256 _start, uint256 _cliff, uint256 _duration, bool _revocable) public {
require(_beneficiary != address(0));
require(_cliff <= _duration);
beneficiary = _beneficiary;
revocable = _revocable;
duration = _duration;
cliff = _start.add(_cliff);
start = _start;
}
/**
* @notice Transfers vested tokens to beneficiary.
* @param token ERC20 token which is being vested
*/
function release(ERC20Basic token) public {
uint256 unreleased = releasableAmount(token);
require(unreleased > 0);
released[token] = released[token].add(unreleased);
token.safeTransfer(beneficiary, unreleased);
Released(unreleased);
}
/**
* @notice Allows the owner to revoke the vesting. Tokens already vested
* remain in the contract, the rest are returned to the owner.
* @param token ERC20 token which is being vested
*/
function revoke(ERC20Basic token) public onlyOwner {
require(revocable);
require(!revoked[token]);
uint256 balance = token.balanceOf(this);
uint256 unreleased = releasableAmount(token);
uint256 refund = balance.sub(unreleased);
revoked[token] = true;
token.safeTransfer(owner, refund);
Revoked();
}
/**
* @dev Calculates the amount that has already vested but hasn't been released yet.
* @param token ERC20 token which is being vested
*/
function releasableAmount(ERC20Basic token) public view returns (uint256) {
return vestedAmount(token).sub(released[token]);
}
/**
* @dev Calculates the amount that has already vested.
* @param token ERC20 token which is being vested
*/
function vestedAmount(ERC20Basic token) public view returns (uint256) {
uint256 currentBalance = token.balanceOf(this);
uint256 totalBalance = currentBalance.add(released[token]);
if (now < cliff) {
return 0;
} else if (now >= start.add(duration) || revoked[token]) {
return totalBalance;
} else {
return totalBalance.mul(now.sub(start)).div(duration);
}
}
}
//File: node_modules/zeppelin-solidity/contracts/lifecycle/Pausable.sol
pragma solidity ^0.4.18;
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
Unpause();
}
}
//File: node_modules/zeppelin-solidity/contracts/token/PausableToken.sol
pragma solidity ^0.4.18;
/**
* @title Pausable token
*
* @dev StandardToken modified with pausable transfers.
**/
contract PausableToken is StandardToken, Pausable {
function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) {
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) {
return super.transferFrom(_from, _to, _value);
}
function approve(address _spender, uint256 _value) public whenNotPaused returns (bool) {
return super.approve(_spender, _value);
}
function increaseApproval(address _spender, uint _addedValue) public whenNotPaused returns (bool success) {
return super.increaseApproval(_spender, _addedValue);
}
function decreaseApproval(address _spender, uint _subtractedValue) public whenNotPaused returns (bool success) {
return super.decreaseApproval(_spender, _subtractedValue);
}
}
//File: src/contracts/ico/MtnToken.sol
/**
* @title MTN token
*
* @version 1.0
* @author Validity Labs AG <[email protected]>
*/
pragma solidity ^0.4.18;
contract MtnToken is MintableToken, PausableToken {
string public constant name = "MedToken";
string public constant symbol = "MTN";
uint8 public constant decimals = 18;
/**
* @dev Constructor of MtnToken that instantiates a new Mintable Pauseable Token
*/
function MtnToken() public {
// token should not be transferrable until after all tokens have been issued
paused = true;
}
}
//File: src/contracts/ico/MtnCrowdsale.sol
/**
* @title MtnCrowdsale
*
* Simple time and TOKEN_CAPped based crowdsale.
*
* @version 1.0
* @author Validity Labs AG <[email protected]>
*/
pragma solidity ^0.4.18;
contract MtnCrowdsale is Ownable, Crowdsale {
/*** CONSTANTS ***/
uint256 public constant TOTAL_TOKEN_CAP = 500e6 * 1e18; // 500 million * 1e18 - smallest unit of MTN token
uint256 public constant CROWDSALE_TOKENS = 175e6 * 1e18; // 175 million * 1e18 - presale and crowdsale tokens
uint256 public constant TOTAL_TEAM_TOKENS = 170e6 * 1e18; // 170 million * 1e18 - team tokens
uint256 public constant TEAM_TOKENS0 = 50e6 * 1e18; // 50 million * 1e18 - team tokens, already vested
uint256 public constant TEAM_TOKENS1 = 60e6 * 1e18; // 60 million * 1e18 - team tokens, vesting over 2 years
uint256 public constant TEAM_TOKENS2 = 60e6 * 1e18; // 60 million * 1e18 - team tokens, vesting over 4 years
uint256 public constant COMMUNITY_TOKENS = 155e6 * 1e18; // 155 million * 1e18 - community tokens, vesting over 4 years
uint256 public constant MAX_CONTRIBUTION_USD = 5000; // USD
uint256 public constant USD_CENT_PER_TOKEN = 25; // in cents - smallest unit of USD E.g. 100 = 1 USD
uint256 public constant VESTING_DURATION_4Y = 4 years;
uint256 public constant VESTING_DURATION_2Y = 2 years;
// true if address is allowed to invest
mapping(address => bool) public isWhitelisted;
// allow managers to whitelist and confirm contributions by manager accounts
// managers can be set and altered by owner, multiple manager accounts are possible
mapping(address => bool) public isManager;
uint256 public maxContributionInWei;
uint256 public tokensMinted; // already minted tokens (maximally = TOKEN_CAP)
bool public capReached; // set to true when cap has been reached when minting tokens
mapping(address => uint256) public totalInvestedPerAddress;
address public beneficiaryWallet;
// for convenience we store vesting wallets
address public teamVesting2Years;
address public teamVesting4Years;
address public communityVesting4Years;
/*** Tracking Crowdsale Stages ***/
bool public isCrowdsaleOver;
/*** EVENTS ***/
event ChangedManager(address manager, bool active);
event PresaleMinted(address indexed beneficiary, uint256 tokenAmount);
event ChangedInvestorWhitelisting(address indexed investor, bool whitelisted);
/*** MODIFIERS ***/
modifier onlyManager() {
require(isManager[msg.sender]);
_;
}
// trying to accompish using already existing variables to determine stage - prevents manual updating of the enum stage states
modifier onlyPresalePhase() {
require(now < startTime);
_;
}
modifier onlyCrowdsalePhase() {
require(now >= startTime && now < endTime && !isCrowdsaleOver);
_;
}
modifier respectCrowdsaleCap(uint256 _amount) {
require(tokensMinted.add(_amount) <= CROWDSALE_TOKENS);
_;
}
modifier onlyCrowdSaleOver() {
require(isCrowdsaleOver || now > endTime || capReached);
_;
}
modifier onlyValidAddress(address _address) {
require(_address != address(0));
_;
}
/**
* @dev Deploy MTN Token Crowdsale
* @param _startTime uint256 Start time of the crowdsale
* @param _endTime uint256 End time of the crowdsale
* @param _usdPerEth uint256 issueing rate tokens per wei
* @param _wallet address Wallet address of the crowdsale
* @param _beneficiaryWallet address wallet holding team and community tokens
*/
function MtnCrowdsale(
uint256 _startTime,
uint256 _endTime,
uint256 _usdPerEth,
address _wallet,
address _beneficiaryWallet
)
Crowdsale(_startTime, _endTime, (_usdPerEth.mul(1e2)).div(USD_CENT_PER_TOKEN), _wallet)
public
onlyValidAddress(_beneficiaryWallet)
{
require(TOTAL_TOKEN_CAP == CROWDSALE_TOKENS.add(TOTAL_TEAM_TOKENS).add(COMMUNITY_TOKENS));
require(TOTAL_TEAM_TOKENS == TEAM_TOKENS0.add(TEAM_TOKENS1).add(TEAM_TOKENS2));
setManager(msg.sender, true);
beneficiaryWallet = _beneficiaryWallet;
maxContributionInWei = (MAX_CONTRIBUTION_USD.mul(1e18)).div(_usdPerEth);
mintTeamTokens();
mintCommunityTokens();
}
/**
* @dev Create new instance of mtn token contract
*/
function createTokenContract() internal returns (MintableToken) {
return new MtnToken();
}
/**
* @dev Set / alter manager / whitelister "account". This can be done from owner only
* @param _manager address address of the manager to create/alter
* @param _active bool flag that shows if the manager account is active
*/
function setManager(address _manager, bool _active) public onlyOwner onlyValidAddress(_manager) {
isManager[_manager] = _active;
ChangedManager(_manager, _active);
}
/**
* @dev whitelist investors to allow the direct investment of this crowdsale
* @param _investor address address of the investor to be whitelisted
*/
function whiteListInvestor(address _investor) public onlyManager onlyValidAddress(_investor) {
isWhitelisted[_investor] = true;
ChangedInvestorWhitelisting(_investor, true);
}
/**
* @dev whitelist several investors via a batch method
* @param _investors address[] array of addresses of the beneficiaries to receive tokens after they have been confirmed
*/
function batchWhiteListInvestors(address[] _investors) public onlyManager {
for (uint256 c; c < _investors.length; c = c.add(1)) {
whiteListInvestor(_investors[c]);
}
}
/**
* @dev unwhitelist investor from participating in the crowdsale
* @param _investor address address of the investor to disallowed participation
*/
function unWhiteListInvestor(address _investor) public onlyManager onlyValidAddress(_investor) {
isWhitelisted[_investor] = false;
ChangedInvestorWhitelisting(_investor, false);
}
/**
* @dev onlyOwner allowed to mint tokens, respecting the cap, and only before the crowdsale starts
* @param _beneficiary address
* @param _amount uint256
*/
function mintTokenPreSale(address _beneficiary, uint256 _amount) public onlyOwner onlyPresalePhase onlyValidAddress(_beneficiary) respectCrowdsaleCap(_amount) {
require(_amount > 0);
tokensMinted = tokensMinted.add(_amount);
token.mint(_beneficiary, _amount);
PresaleMinted(_beneficiary, _amount);
}
/**
* @dev onlyOwner allowed to handle batch presale minting
* @param _beneficiaries address[]
* @param _amounts uint256[]
*/
function batchMintTokenPresale(address[] _beneficiaries, uint256[] _amounts) public onlyOwner onlyPresalePhase {
require(_beneficiaries.length == _amounts.length);
for (uint256 i; i < _beneficiaries.length; i = i.add(1)) {
mintTokenPreSale(_beneficiaries[i], _amounts[i]);
}
}
/**
* @dev override core functionality by whitelist check
* @param _beneficiary address
*/
function buyTokens(address _beneficiary) public payable onlyCrowdsalePhase onlyValidAddress(_beneficiary) {
require(isWhitelisted[msg.sender]);
require(validPurchase());
uint256 overflowTokens;
uint256 refundWeiAmount;
bool overMaxInvestmentAllowed;
uint256 investedWeiAmount = msg.value;
// Is this specific investment over the MAX_CONTRIBUTION_USD limit?
// if so, calcuate wei refunded and tokens to mint for the allowed investment amount
uint256 totalInvestedWeiAmount = investedWeiAmount.add(totalInvestedPerAddress[msg.sender]);
if (totalInvestedWeiAmount > maxContributionInWei) {
overMaxInvestmentAllowed = true;
refundWeiAmount = totalInvestedWeiAmount.sub(maxContributionInWei);
investedWeiAmount = investedWeiAmount.sub(refundWeiAmount);
}
uint256 tokenAmount = investedWeiAmount.mul(rate);
uint256 tempMintedTokens = tokensMinted.add(tokenAmount); // gas optimization, do not inline twice
// check to see if this purchase sets it over the crowdsale token cap
// if so, calculate tokens to mint, then refund the remaining ether investment
if (tempMintedTokens >= CROWDSALE_TOKENS) {
capReached = true;
overflowTokens = tempMintedTokens.sub(CROWDSALE_TOKENS);
tokenAmount = tokenAmount.sub(overflowTokens);
refundWeiAmount = overflowTokens.div(rate);
investedWeiAmount = investedWeiAmount.sub(refundWeiAmount);
}
weiRaised = weiRaised.add(investedWeiAmount);
tokensMinted = tokensMinted.add(tokenAmount);
TokenPurchase(msg.sender, _beneficiary, investedWeiAmount, tokenAmount);
totalInvestedPerAddress[msg.sender] = totalInvestedPerAddress[msg.sender].add(investedWeiAmount);
token.mint(_beneficiary, tokenAmount);
// if investor breached cap and has remaining ether not invested
// refund remaining ether to investor
if (capReached || overMaxInvestmentAllowed) {
msg.sender.transfer(refundWeiAmount);
wallet.transfer(investedWeiAmount);
} else {
forwardFunds();
}
}
/**
* @dev onlyOwner to close Crowdsale manually if before endTime
*/
function closeCrowdsale() public onlyOwner onlyCrowdsalePhase {
isCrowdsaleOver = true;
}
/**
* @dev onlyOwner allows tokens to be tradeable
*/
function finalize() public onlyOwner onlyCrowdSaleOver {
// do not allow new owner to mint further tokens & unpause token to allow trading
MintableToken(token).finishMinting();
PausableToken(token).unpause();
}
/*** INTERNAL/PRIVATE FUNCTIONS ***/
/**
* @dev allows contract owner to mint all team tokens per TEAM_TOKENS and have 50m immediately available, 60m 2 years vested, and 60m over 4 years vesting
*/
function mintTeamTokens() private {
token.mint(beneficiaryWallet, TEAM_TOKENS0);
TokenVesting newVault1 = new TokenVesting(beneficiaryWallet, now, 0, VESTING_DURATION_2Y, false);
teamVesting2Years = address(newVault1); // for convenience we keep them in storage so that they are easily accessible via MEW or etherscan
token.mint(address(newVault1), TEAM_TOKENS1);
TokenVesting newVault2 = new TokenVesting(beneficiaryWallet, now, 0, VESTING_DURATION_4Y, false);
teamVesting4Years = address(newVault2); // for convenience we keep them in storage so that they are easily accessible via MEW or etherscan
token.mint(address(newVault2), TEAM_TOKENS2);
}
/**
* @dev allows contract owner to mint all community tokens per COMMUNITY_TOKENS and have the vested to the beneficiaryWallet
*/
function mintCommunityTokens() private {
TokenVesting newVault = new TokenVesting(beneficiaryWallet, now, 0, VESTING_DURATION_4Y, false);
communityVesting4Years = address(newVault); // for convenience we keep them in storage so that they are easily accessible via MEW or etherscan
token.mint(address(newVault), COMMUNITY_TOKENS);
}
/**
* @dev extend base functionality with min investment amount
*/
function validPurchase() internal view respectCrowdsaleCap(0) returns (bool) {
require(!capReached);
require(totalInvestedPerAddress[msg.sender] < maxContributionInWei);
return super.validPurchase();
}
}
| * @dev override core functionality by whitelist check @param _beneficiary address/ Is this specific investment over the MAX_CONTRIBUTION_USD limit? if so, calcuate wei refunded and tokens to mint for the allowed investment amount check to see if this purchase sets it over the crowdsale token cap if so, calculate tokens to mint, then refund the remaining ether investment if investor breached cap and has remaining ether not invested refund remaining ether to investor | function buyTokens(address _beneficiary) public payable onlyCrowdsalePhase onlyValidAddress(_beneficiary) {
require(isWhitelisted[msg.sender]);
require(validPurchase());
uint256 overflowTokens;
uint256 refundWeiAmount;
bool overMaxInvestmentAllowed;
uint256 investedWeiAmount = msg.value;
uint256 totalInvestedWeiAmount = investedWeiAmount.add(totalInvestedPerAddress[msg.sender]);
if (totalInvestedWeiAmount > maxContributionInWei) {
overMaxInvestmentAllowed = true;
refundWeiAmount = totalInvestedWeiAmount.sub(maxContributionInWei);
investedWeiAmount = investedWeiAmount.sub(refundWeiAmount);
}
uint256 tokenAmount = investedWeiAmount.mul(rate);
if (tempMintedTokens >= CROWDSALE_TOKENS) {
capReached = true;
overflowTokens = tempMintedTokens.sub(CROWDSALE_TOKENS);
tokenAmount = tokenAmount.sub(overflowTokens);
refundWeiAmount = overflowTokens.div(rate);
investedWeiAmount = investedWeiAmount.sub(refundWeiAmount);
}
weiRaised = weiRaised.add(investedWeiAmount);
tokensMinted = tokensMinted.add(tokenAmount);
TokenPurchase(msg.sender, _beneficiary, investedWeiAmount, tokenAmount);
totalInvestedPerAddress[msg.sender] = totalInvestedPerAddress[msg.sender].add(investedWeiAmount);
token.mint(_beneficiary, tokenAmount);
if (capReached || overMaxInvestmentAllowed) {
msg.sender.transfer(refundWeiAmount);
wallet.transfer(investedWeiAmount);
forwardFunds();
}
}
| 1,044,084 | [
1,
10601,
2922,
14176,
635,
10734,
866,
225,
389,
70,
4009,
74,
14463,
814,
1758,
19,
2585,
333,
2923,
2198,
395,
475,
1879,
326,
4552,
67,
6067,
2259,
38,
13269,
67,
3378,
40,
1800,
35,
309,
1427,
16,
1443,
6319,
340,
732,
77,
1278,
12254,
471,
2430,
358,
312,
474,
364,
326,
2935,
2198,
395,
475,
3844,
866,
358,
2621,
309,
333,
23701,
1678,
518,
1879,
326,
276,
492,
2377,
5349,
1147,
3523,
309,
1427,
16,
4604,
2430,
358,
312,
474,
16,
1508,
16255,
326,
4463,
225,
2437,
2198,
395,
475,
309,
2198,
395,
280,
324,
266,
2004,
3523,
471,
711,
4463,
225,
2437,
486,
2198,
3149,
16255,
4463,
225,
2437,
358,
2198,
395,
280,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
30143,
5157,
12,
2867,
389,
70,
4009,
74,
14463,
814,
13,
1071,
8843,
429,
1338,
39,
492,
2377,
5349,
11406,
1338,
1556,
1887,
24899,
70,
4009,
74,
14463,
814,
13,
288,
203,
3639,
2583,
12,
291,
18927,
329,
63,
3576,
18,
15330,
19226,
203,
3639,
2583,
12,
877,
23164,
10663,
203,
203,
3639,
2254,
5034,
9391,
5157,
31,
203,
3639,
2254,
5034,
16255,
3218,
77,
6275,
31,
203,
3639,
1426,
1879,
2747,
3605,
395,
475,
5042,
31,
203,
203,
3639,
2254,
5034,
2198,
3149,
3218,
77,
6275,
273,
1234,
18,
1132,
31,
203,
203,
3639,
2254,
5034,
2078,
3605,
3149,
3218,
77,
6275,
273,
2198,
3149,
3218,
77,
6275,
18,
1289,
12,
4963,
3605,
3149,
2173,
1887,
63,
3576,
18,
15330,
19226,
203,
3639,
309,
261,
4963,
3605,
3149,
3218,
77,
6275,
405,
943,
442,
4027,
382,
3218,
77,
13,
288,
203,
5411,
1879,
2747,
3605,
395,
475,
5042,
273,
638,
31,
203,
5411,
16255,
3218,
77,
6275,
273,
2078,
3605,
3149,
3218,
77,
6275,
18,
1717,
12,
1896,
442,
4027,
382,
3218,
77,
1769,
203,
5411,
2198,
3149,
3218,
77,
6275,
273,
2198,
3149,
3218,
77,
6275,
18,
1717,
12,
1734,
1074,
3218,
77,
6275,
1769,
203,
3639,
289,
203,
203,
3639,
2254,
5034,
1147,
6275,
273,
2198,
3149,
3218,
77,
6275,
18,
16411,
12,
5141,
1769,
203,
203,
3639,
309,
261,
5814,
49,
474,
329,
5157,
1545,
385,
11226,
19748,
900,
67,
8412,
55,
13,
288,
203,
5411,
3523,
23646,
273,
638,
31,
203,
5411,
9391,
5157,
273,
1906,
49,
2
] |
pragma solidity ^0.4.8;
contract WSIPrivateEquityShare {
/* Public variables of the token */
string public constant name = 'WSI Private Equity Share';
string public constant symbol = 'WSIPES';
uint256 public constant totalSupply = 10000;
uint8 public decimals = 2;
/* This creates an array with all balances */
mapping (address => uint256) public balanceOf;
/* This generates a public event on the blockchain that will notify clients */
event Transfer(address indexed from, address indexed to, uint256 value);
/* Initializes contract with initial supply tokens to the creator of the contract */
function WSIPrivateEquityShare() {
balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens
}
/* Send coins */
function transfer(address _to, uint256 _value) {
if (balanceOf[msg.sender] < _value) throw; // Check if the sender has enough
if (balanceOf[_to] + _value < balanceOf[_to]) throw; // Check for overflows
balanceOf[msg.sender] -= _value; // Subtract from the sender
balanceOf[_to] += _value; // Add the same to the recipient
Transfer(msg.sender, _to, _value); // Notify anyone listening that this transfer took place
}
/* This unnamed function is called whenever someone tries to send ether to it */
function () {
throw; // Prevents accidental sending of ether
}
} | Public variables of the token */ This creates an array with all balances */ This generates a public event on the blockchain that will notify clients */ Initializes contract with initial supply tokens to the creator of the contract */ | function WSIPrivateEquityShare() {
}
| 6,421,432 | [
1,
4782,
3152,
434,
326,
1147,
342,
1220,
3414,
392,
526,
598,
777,
324,
26488,
342,
1220,
6026,
279,
1071,
871,
603,
326,
16766,
716,
903,
5066,
7712,
342,
10188,
3128,
6835,
598,
2172,
14467,
2430,
358,
326,
11784,
434,
326,
6835,
342,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
678,
2320,
6014,
13142,
560,
9535,
1435,
288,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/3/0x180fcE208dAF4ae55E5253304e953D3f95915c4a/sources/browser/1_Storage.sol | Withdraw all funds, normally used when migrating strategies | function withdrawAll() public returns (uint balance) {
require(msg.sender == controller||msg.sender==governance, "!controller");
_withdrawAll();
balance = IERC20(want).balanceOf(address(this));
address _vault = Controller(controller).vaults(address(want));
IERC20(want).safeTransfer(_vault, balance);
}
| 8,150,414 | [
1,
1190,
9446,
777,
284,
19156,
16,
15849,
1399,
1347,
4196,
1776,
20417,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
598,
9446,
1595,
1435,
1071,
1135,
261,
11890,
11013,
13,
288,
7010,
3639,
2583,
12,
3576,
18,
15330,
422,
2596,
20081,
3576,
18,
15330,
631,
75,
1643,
82,
1359,
16,
17528,
5723,
8863,
203,
3639,
389,
1918,
9446,
1595,
5621,
203,
3639,
11013,
273,
467,
654,
39,
3462,
12,
17369,
2934,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
540,
203,
3639,
1758,
389,
26983,
273,
6629,
12,
5723,
2934,
26983,
87,
12,
2867,
12,
17369,
10019,
203,
3639,
467,
654,
39,
3462,
12,
17369,
2934,
4626,
5912,
24899,
26983,
16,
11013,
1769,
203,
540,
203,
565,
289,
203,
377,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2021-10-14
*/
// .*@@#- .*@@#:
// .*@@%- .*@@#:
// .::::::::::::.. :::::::::::::::: : . .:::::::::::::. .*@@%- .*@@#:
// [email protected]@@@@@@@@@@@@@@*. [email protected]@@@@@@@@@@@@@@: @@* [email protected]@. #@@@@@@@@@@@@@@@: .*@@%- .*@@#:
// :::..........-#@@- ::::::::::::::: @@# *@@. [email protected]@=:::::::::::.. .*@@%@@#:
// @@# @@# @@@@@@@@@@@@@@@@: @@# *@@. .%@@@@@@@@@@@@@%+ .#@@@@-
// @@# [email protected]@+ @@%------------- @@% *@@. [email protected]@= .*@@#-*@@%-
// @@@%%%%%%%%%@@@@= @@@%%%%%%%%%%%%%: [email protected]@@%%%%%%%%%@@@* .%%%%%%%%%%%%%@@@: .*@@#: .*@@%-
// =============-: =+++++++++++++++. .-===========-. :==============- .*@@#: .*@@%-
// .*@@#: .*@@%-
//
// Choose your fate. Become a legend.
//
// File @openzeppelin/contracts/utils/cryptography/[email protected]
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev These functions deal with verification of Merkle Trees proofs.
*
* The proofs can be generated using the JavaScript library
* https://github.com/miguelmota/merkletreejs[merkletreejs].
* Note: the hashing algorithm should be keccak256 and pair sorting should be enabled.
*
* See `test/utils/cryptography/MerkleProof.test.js` for some examples.
*/
library MerkleProof {
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*/
function verify(
bytes32[] memory proof,
bytes32 root,
bytes32 leaf
) internal pure returns (bool) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash <= proofElement) {
// Hash(current computed hash + current element of the proof)
computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
} else {
// Hash(current element of the proof + current computed hash)
computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
}
}
// Check if the computed hash (root) is equal to the provided root
return computedHash == root;
}
}
// File @openzeppelin/contracts/utils/introspection/[email protected]
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File @openzeppelin/contracts/token/ERC721/[email protected]
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File @openzeppelin/contracts/token/ERC721/[email protected]
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// File @openzeppelin/contracts/token/ERC721/extensions/[email protected]
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File @openzeppelin/contracts/utils/[email protected]
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File @openzeppelin/contracts/utils/[email protected]
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// File @openzeppelin/contracts/utils/[email protected]
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// File @openzeppelin/contracts/utils/introspection/[email protected]
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// File @openzeppelin/contracts/token/ERC721/[email protected]
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// File @openzeppelin/contracts/token/ERC721/extensions/[email protected]
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// File @openzeppelin/contracts/token/ERC721/extensions/[email protected]
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// File @openzeppelin/contracts/access/[email protected]
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// File contracts/DeusX.sol
contract DeusX is ERC721Enumerable, Ownable {
using Strings for uint256;
uint256 public constant DEUSX_GIFT = 101;
uint256 public constant DEUSX_PUBLIC = 10000;
uint256 public constant DEUSX_MAX = DEUSX_GIFT + DEUSX_PUBLIC;
uint256 public constant PURCHASE_LIMIT = 10; // per tx, contracts can still recursively call
uint256 public constant PRICE = 0.08 ether;
string[] public FACTION_NAMES = [
'None',
'Valks',
'Roks',
'Monsters'
];
address[] TEAM_ADDRESSES = [
0x9cc35B5bB5c4fC544eeC96a33baa7BB5c5966095,
0xa2E9986C8936E9Ff788B167e85Ef92ae309ecc4C,
0x64ac893a59096Fc13dBD39c35Ce894833db62b7a,
0x0e6596a739FCEb57fCA595b78EF0F6e586e8938c,
0xa55033bFB357eFDd804f2391E30a52291C77dD51,
0x5B1212FE9b20D32688F5f02973087f828b0a4824,
0x31C5327974f02406b698DB4a51eA860Aa411E8A1,
0x78eEb89ae305cCc774516546b43a11fc74794222,
0xb34C812501bCb190Cf21ed7623F89924549970fb,
0xa096F2F973b91F5E148301f9C4f5BC56165E0865
];
uint256[] TEAM_PCTS = [
0.25e18,
0.25e18,
0.20e18,
0.08e18,
0.06e18,
0.0501e18,
0.04e18,
0.01e18,
0.01e18,
0.0499e18
];
uint256 constant UNIT = 1e18;
bool public isActive = true;
string public provenanceHash;
uint256 public allowListMaxMint = 2;
uint256 public totalGiftSupply;
uint256 public totalPublicSupply;
/**
* 0 - presale batch 1
* 1 - presale batch 2
* 2 - waitlist
* 3 - public sale
*/
bytes32[] public roots;
uint256[] public startTimes;
mapping(uint256 => uint256) public factionOf;
mapping(address => uint256) public allowListClaimed;
mapping(uint256 => uint256) private factionNumbers;
string public contractURI = '';
string public tokenBaseURI = '';
string public tokenRevealedBaseURI = '';
constructor(string memory _name, string memory _symbol, string memory _contractURI, string memory _tokenBaseURI, bytes32[] memory _roots, uint256[] memory _startTimes) ERC721(_name, _symbol) {
contractURI = _contractURI;
tokenBaseURI = _tokenBaseURI;
roots = _roots;
startTimes = _startTimes;
}
function purchase(uint256 numberOfTokens, uint256[] calldata factions) external payable {
require(isActive, 'Inactive');
require(block.timestamp > startTimes[2], 'Not started');
require(totalPublicSupply < DEUSX_PUBLIC, 'Exceeds supply');
require(numberOfTokens <= PURCHASE_LIMIT, 'Exceeds limit');
require(numberOfTokens == factions.length, 'Invalid factions');
/**
* The last person to purchase might overpay, but this prevents them
* from getting sniped.
* If this happens, we'll refund the ETH for the unavailable tokens.
*/
require(numberOfTokens * PRICE <= msg.value, 'Insufficient ETH');
for (uint256 i = 0; i < numberOfTokens; i++) {
if (totalPublicSupply < DEUSX_PUBLIC) {
/**
* Public token numbering starts after DEUSX_GIFT.
* Token numbers should start at 1
*/
totalPublicSupply += 1;
uint256 tokenId = DEUSX_GIFT + totalPublicSupply;
_safeMint(msg.sender, tokenId);
uint256 _faction = factions[i];
require(_faction < FACTION_NAMES.length, 'Invalid faction');
factionOf[tokenId] = _faction;
factionNumbers[_faction] += 1;
emit SetFaction(tokenId, _faction);
}
}
}
function purchaseAllowList(uint256 numberOfTokens, uint256[] calldata factions, bytes32[] memory merkleProof) external payable {
require(isActive, 'Inactive');
require(block.timestamp < startTimes[3], 'Public sale started');
bytes32 root;
if (block.timestamp > startTimes[2]) {
root = roots[2];
} else if (block.timestamp > startTimes[1]) {
root = roots[1];
} else if (block.timestamp > startTimes[0]) {
root = roots[0];
} else {
revert('Not started');
}
require(numberOfTokens == factions.length, 'Invalid params');
require(totalPublicSupply + numberOfTokens <= DEUSX_PUBLIC, 'Exceeds supply limit');
require(allowListClaimed[msg.sender] + numberOfTokens <= allowListMaxMint, 'Exceeds max allowed');
require(numberOfTokens * PRICE <= msg.value, 'Insufficient ETH');
bytes32 leaf = keccak256(abi.encodePacked(msg.sender));
require(MerkleProof.verify(merkleProof, root, leaf), 'Invalid proof');
allowListClaimed[msg.sender] += numberOfTokens;
for (uint256 i = 0; i < numberOfTokens; i++) {
/*
* Public token numbering starts after DEUSX_GIFT.
* Tokens IDs start at 1.
*/
totalPublicSupply += 1;
uint256 tokenId = DEUSX_GIFT + totalPublicSupply;
_safeMint(msg.sender, tokenId);
uint256 _faction = factions[i];
require(_faction < FACTION_NAMES.length, 'Invalid faction');
factionOf[tokenId] = _faction;
factionNumbers[_faction] += 1;
emit SetFaction(tokenId, _faction);
}
}
function setFactions(uint256[] calldata _tokenIds, uint256[] calldata _factions) external {
require(_tokenIds.length == _factions.length, 'Invalid params');
for(uint256 i = 0; i < _tokenIds.length; i++) {
require(msg.sender == ownerOf(_tokenIds[i]), 'Invalid caller');
require(factionOf[_tokenIds[i]] == 0, 'Faction already set');
require(_factions[i] < FACTION_NAMES.length, 'Invalid faction');
factionOf[_tokenIds[i]] = _factions[i];
factionNumbers[_factions[i]] += 1;
emit SetFaction(_tokenIds[i], _factions[i]);
}
}
function tokenURI(uint256 tokenId) public view override(ERC721) returns (string memory) {
require(_exists(tokenId), 'Token does not exist');
string memory revealedBaseURI = tokenRevealedBaseURI;
if (bytes(revealedBaseURI).length > 0) {
uint256 faction = factionOf[tokenId];
if(faction > 0) {
return string(abi.encodePacked(revealedBaseURI, tokenId.toString(), '-', FACTION_NAMES[faction]));
} else {
return string(abi.encodePacked(revealedBaseURI, tokenId.toString()));
}
} else {
return tokenBaseURI;
}
}
function totalInFaction(uint256 _faction) external view returns (uint256) {
if(_faction == 0) {
return DEUSX_MAX - factionNumbers[1] - factionNumbers[2] - factionNumbers[3];
} else {
return factionNumbers[_faction];
}
}
function onAccesslist(bytes32[] memory _proof, uint256 _rootIndex, address _address) external view returns (bool) {
return MerkleProof.verify(_proof, roots[_rootIndex], keccak256(abi.encodePacked(_address)));
}
function gift(address[] calldata to) external onlyOwner {
require(totalGiftSupply + to.length <= DEUSX_GIFT, 'Gifts finished');
for(uint256 i = 0; i < to.length; i++) {
// Tokens IDs start at 1.
totalGiftSupply += 1;
uint256 tokenId = totalGiftSupply;
_safeMint(to[i], tokenId);
}
}
function withdraw() external {
uint256 balance = address(this).balance;
for(uint256 i = 0; i < TEAM_ADDRESSES.length; i++) {
payable(TEAM_ADDRESSES[i]).transfer(balance*TEAM_PCTS[i]/UNIT);
}
}
function emergencyWithdrawal() external onlyOwner {
require(block.timestamp > startTimes[3] + 10*24*60*60, 'Cannot withdraw yet'); // if there's a problem with the payout, allow an emergency release after 10 days
uint256 balance = address(this).balance;
(bool success, ) = payable(msg.sender).call{value: balance}('');
require(success, 'Transfer failed.');
}
function setStartTimes(uint256[] calldata _startTimes) external onlyOwner {
require(block.timestamp < startTimes[0], 'Sale started'); // prevent owner from rugging emergency withdrawal
startTimes = _startTimes;
}
function setAllowListMaxMint(uint256 maxMint) external onlyOwner {
allowListMaxMint = maxMint;
}
function setContractURI(string calldata URI) external onlyOwner {
contractURI = URI;
}
function setBaseURI(string calldata URI) external onlyOwner {
tokenBaseURI = URI;
}
function setRevealedBaseURI(string calldata revealedBaseURI) external onlyOwner {
tokenRevealedBaseURI = revealedBaseURI;
}
function setRoots(bytes32[] calldata _roots) external onlyOwner {
roots = _roots;
}
function setIsActive(bool _isActive) external onlyOwner {
isActive = _isActive;
}
function setProvenanceHash(string memory _provenanceHash) external onlyOwner {
provenanceHash = _provenanceHash;
emit SetProvenanceHash(_provenanceHash);
}
event SetProvenanceHash(string provenanceHash);
event SetFaction(uint256 indexed tokenId, uint256 faction);
} | * 0 - presale batch 1 1 - presale batch 2 2 - waitlist 3 - public sale/ | constructor(string memory _name, string memory _symbol, string memory _contractURI, string memory _tokenBaseURI, bytes32[] memory _roots, uint256[] memory _startTimes) ERC721(_name, _symbol) {
contractURI = _contractURI;
tokenBaseURI = _tokenBaseURI;
roots = _roots;
startTimes = _startTimes;
}
| 15,383,426 | [
1,
20,
300,
4075,
5349,
2581,
404,
404,
300,
4075,
5349,
2581,
576,
576,
300,
2529,
1098,
890,
300,
1071,
272,
5349,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
3885,
12,
1080,
3778,
389,
529,
16,
533,
3778,
389,
7175,
16,
533,
3778,
389,
16351,
3098,
16,
533,
3778,
389,
2316,
2171,
3098,
16,
1731,
1578,
8526,
3778,
389,
22078,
16,
2254,
5034,
8526,
3778,
389,
1937,
10694,
13,
4232,
39,
27,
5340,
24899,
529,
16,
389,
7175,
13,
288,
203,
565,
6835,
3098,
273,
389,
16351,
3098,
31,
203,
565,
1147,
2171,
3098,
273,
389,
2316,
2171,
3098,
31,
203,
565,
12876,
273,
389,
22078,
31,
203,
565,
787,
10694,
273,
389,
1937,
10694,
31,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2021-12-03
*/
/*
____ __ __ __ _
/ __/__ __ ___ / /_ / / ___ / /_ (_)__ __
_\ \ / // // _ \/ __// _ \/ -_)/ __// / \ \ /
/___/ \_, //_//_/\__//_//_/\__/ \__//_/ /_\_\
/___/
* Synthetix: WrapperFactory.sol
*
* Latest source (may be newer): https://github.com/Synthetixio/synthetix/blob/master/contracts/WrapperFactory.sol
* Docs: https://docs.synthetix.io/contracts/WrapperFactory
*
* Contract Dependencies:
* - IAddressResolver
* - IWrapper
* - IWrapperFactory
* - MixinResolver
* - MixinSystemSettings
* - Owned
* - Pausable
* Libraries:
* - SafeDecimalMath
* - SafeMath
*
* MIT License
* ===========
*
* Copyright (c) 2021 Synthetix
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
*/
pragma solidity ^0.5.16;
// https://docs.synthetix.io/contracts/source/contracts/owned
contract Owned {
address public owner;
address public nominatedOwner;
constructor(address _owner) public {
require(_owner != address(0), "Owner address cannot be 0");
owner = _owner;
emit OwnerChanged(address(0), _owner);
}
function nominateNewOwner(address _owner) external onlyOwner {
nominatedOwner = _owner;
emit OwnerNominated(_owner);
}
function acceptOwnership() external {
require(msg.sender == nominatedOwner, "You must be nominated before you can accept ownership");
emit OwnerChanged(owner, nominatedOwner);
owner = nominatedOwner;
nominatedOwner = address(0);
}
modifier onlyOwner {
_onlyOwner();
_;
}
function _onlyOwner() private view {
require(msg.sender == owner, "Only the contract owner may perform this action");
}
event OwnerNominated(address newOwner);
event OwnerChanged(address oldOwner, address newOwner);
}
// https://docs.synthetix.io/contracts/source/interfaces/iaddressresolver
interface IAddressResolver {
function getAddress(bytes32 name) external view returns (address);
function getSynth(bytes32 key) external view returns (address);
function requireAndGetAddress(bytes32 name, string calldata reason) external view returns (address);
}
// https://docs.synthetix.io/contracts/source/interfaces/isynth
interface ISynth {
// Views
function currencyKey() external view returns (bytes32);
function transferableSynths(address account) external view returns (uint);
// Mutative functions
function transferAndSettle(address to, uint value) external returns (bool);
function transferFromAndSettle(
address from,
address to,
uint value
) external returns (bool);
// Restricted: used internally to Synthetix
function burn(address account, uint amount) external;
function issue(address account, uint amount) external;
}
// https://docs.synthetix.io/contracts/source/interfaces/iissuer
interface IIssuer {
// Views
function anySynthOrSNXRateIsInvalid() external view returns (bool anyRateInvalid);
function availableCurrencyKeys() external view returns (bytes32[] memory);
function availableSynthCount() external view returns (uint);
function availableSynths(uint index) external view returns (ISynth);
function canBurnSynths(address account) external view returns (bool);
function collateral(address account) external view returns (uint);
function collateralisationRatio(address issuer) external view returns (uint);
function collateralisationRatioAndAnyRatesInvalid(address _issuer)
external
view
returns (uint cratio, bool anyRateIsInvalid);
function debtBalanceOf(address issuer, bytes32 currencyKey) external view returns (uint debtBalance);
function issuanceRatio() external view returns (uint);
function lastIssueEvent(address account) external view returns (uint);
function maxIssuableSynths(address issuer) external view returns (uint maxIssuable);
function minimumStakeTime() external view returns (uint);
function remainingIssuableSynths(address issuer)
external
view
returns (
uint maxIssuable,
uint alreadyIssued,
uint totalSystemDebt
);
function synths(bytes32 currencyKey) external view returns (ISynth);
function getSynths(bytes32[] calldata currencyKeys) external view returns (ISynth[] memory);
function synthsByAddress(address synthAddress) external view returns (bytes32);
function totalIssuedSynths(bytes32 currencyKey, bool excludeOtherCollateral) external view returns (uint);
function transferableSynthetixAndAnyRateIsInvalid(address account, uint balance)
external
view
returns (uint transferable, bool anyRateIsInvalid);
// Restricted: used internally to Synthetix
function issueSynths(address from, uint amount) external;
function issueSynthsOnBehalf(
address issueFor,
address from,
uint amount
) external;
function issueMaxSynths(address from) external;
function issueMaxSynthsOnBehalf(address issueFor, address from) external;
function burnSynths(address from, uint amount) external;
function burnSynthsOnBehalf(
address burnForAddress,
address from,
uint amount
) external;
function burnSynthsToTarget(address from) external;
function burnSynthsToTargetOnBehalf(address burnForAddress, address from) external;
function burnForRedemption(
address deprecatedSynthProxy,
address account,
uint balance
) external;
function liquidateDelinquentAccount(
address account,
uint susdAmount,
address liquidator
) external returns (uint totalRedeemed, uint amountToLiquidate);
}
// Inheritance
// Internal references
// https://docs.synthetix.io/contracts/source/contracts/addressresolver
contract AddressResolver is Owned, IAddressResolver {
mapping(bytes32 => address) public repository;
constructor(address _owner) public Owned(_owner) {}
/* ========== RESTRICTED FUNCTIONS ========== */
function importAddresses(bytes32[] calldata names, address[] calldata destinations) external onlyOwner {
require(names.length == destinations.length, "Input lengths must match");
for (uint i = 0; i < names.length; i++) {
bytes32 name = names[i];
address destination = destinations[i];
repository[name] = destination;
emit AddressImported(name, destination);
}
}
/* ========= PUBLIC FUNCTIONS ========== */
function rebuildCaches(MixinResolver[] calldata destinations) external {
for (uint i = 0; i < destinations.length; i++) {
destinations[i].rebuildCache();
}
}
/* ========== VIEWS ========== */
function areAddressesImported(bytes32[] calldata names, address[] calldata destinations) external view returns (bool) {
for (uint i = 0; i < names.length; i++) {
if (repository[names[i]] != destinations[i]) {
return false;
}
}
return true;
}
function getAddress(bytes32 name) external view returns (address) {
return repository[name];
}
function requireAndGetAddress(bytes32 name, string calldata reason) external view returns (address) {
address _foundAddress = repository[name];
require(_foundAddress != address(0), reason);
return _foundAddress;
}
function getSynth(bytes32 key) external view returns (address) {
IIssuer issuer = IIssuer(repository["Issuer"]);
require(address(issuer) != address(0), "Cannot find Issuer address");
return address(issuer.synths(key));
}
/* ========== EVENTS ========== */
event AddressImported(bytes32 name, address destination);
}
// Internal references
// https://docs.synthetix.io/contracts/source/contracts/mixinresolver
contract MixinResolver {
AddressResolver public resolver;
mapping(bytes32 => address) private addressCache;
constructor(address _resolver) internal {
resolver = AddressResolver(_resolver);
}
/* ========== INTERNAL FUNCTIONS ========== */
function combineArrays(bytes32[] memory first, bytes32[] memory second)
internal
pure
returns (bytes32[] memory combination)
{
combination = new bytes32[](first.length + second.length);
for (uint i = 0; i < first.length; i++) {
combination[i] = first[i];
}
for (uint j = 0; j < second.length; j++) {
combination[first.length + j] = second[j];
}
}
/* ========== PUBLIC FUNCTIONS ========== */
// Note: this function is public not external in order for it to be overridden and invoked via super in subclasses
function resolverAddressesRequired() public view returns (bytes32[] memory addresses) {}
function rebuildCache() public {
bytes32[] memory requiredAddresses = resolverAddressesRequired();
// The resolver must call this function whenver it updates its state
for (uint i = 0; i < requiredAddresses.length; i++) {
bytes32 name = requiredAddresses[i];
// Note: can only be invoked once the resolver has all the targets needed added
address destination =
resolver.requireAndGetAddress(name, string(abi.encodePacked("Resolver missing target: ", name)));
addressCache[name] = destination;
emit CacheUpdated(name, destination);
}
}
/* ========== VIEWS ========== */
function isResolverCached() external view returns (bool) {
bytes32[] memory requiredAddresses = resolverAddressesRequired();
for (uint i = 0; i < requiredAddresses.length; i++) {
bytes32 name = requiredAddresses[i];
// false if our cache is invalid or if the resolver doesn't have the required address
if (resolver.getAddress(name) != addressCache[name] || addressCache[name] == address(0)) {
return false;
}
}
return true;
}
/* ========== INTERNAL FUNCTIONS ========== */
function requireAndGetAddress(bytes32 name) internal view returns (address) {
address _foundAddress = addressCache[name];
require(_foundAddress != address(0), string(abi.encodePacked("Missing address: ", name)));
return _foundAddress;
}
/* ========== EVENTS ========== */
event CacheUpdated(bytes32 name, address destination);
}
// Inheritance
// https://docs.synthetix.io/contracts/source/contracts/pausable
contract Pausable is Owned {
uint public lastPauseTime;
bool public paused;
constructor() internal {
// This contract is abstract, and thus cannot be instantiated directly
require(owner != address(0), "Owner must be set");
// Paused will be false, and lastPauseTime will be 0 upon initialisation
}
/**
* @notice Change the paused state of the contract
* @dev Only the contract owner may call this.
*/
function setPaused(bool _paused) external onlyOwner {
// Ensure we're actually changing the state before we do anything
if (_paused == paused) {
return;
}
// Set our paused state.
paused = _paused;
// If applicable, set the last pause time.
if (paused) {
lastPauseTime = now;
}
// Let everyone know that our pause state has changed.
emit PauseChanged(paused);
}
event PauseChanged(bool isPaused);
modifier notPaused {
require(!paused, "This action cannot be performed while the contract is paused");
_;
}
}
// https://docs.synthetix.io/contracts/source/interfaces/ierc20
interface IERC20 {
// ERC20 Optional Views
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
// Views
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
// Mutative functions
function transfer(address to, uint value) external returns (bool);
function approve(address spender, uint value) external returns (bool);
function transferFrom(
address from,
address to,
uint value
) external returns (bool);
// Events
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
// https://docs.synthetix.io/contracts/source/interfaces/iwrapper
interface IWrapper {
function mint(uint amount) external;
function burn(uint amount) external;
function capacity() external view returns (uint);
function totalIssuedSynths() external view returns (uint);
function calculateMintFee(uint amount) external view returns (uint, bool);
function calculateBurnFee(uint amount) external view returns (uint, bool);
function maxTokenAmount() external view returns (uint256);
function mintFeeRate() external view returns (int256);
function burnFeeRate() external view returns (int256);
}
// https://docs.synthetix.io/contracts/source/interfaces/iexchangerates
interface IExchangeRates {
// Structs
struct RateAndUpdatedTime {
uint216 rate;
uint40 time;
}
// Views
function aggregators(bytes32 currencyKey) external view returns (address);
function aggregatorWarningFlags() external view returns (address);
function anyRateIsInvalid(bytes32[] calldata currencyKeys) external view returns (bool);
function currentRoundForRate(bytes32 currencyKey) external view returns (uint);
function currenciesUsingAggregator(address aggregator) external view returns (bytes32[] memory);
function effectiveValue(
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey
) external view returns (uint value);
function effectiveValueAndRates(
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey
)
external
view
returns (
uint value,
uint sourceRate,
uint destinationRate
);
function effectiveAtomicValueAndRates(
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey
)
external
view
returns (
uint value,
uint systemValue,
uint systemSourceRate,
uint systemDestinationRate
);
function effectiveValueAtRound(
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey,
uint roundIdForSrc,
uint roundIdForDest
) external view returns (uint value);
function getCurrentRoundId(bytes32 currencyKey) external view returns (uint);
function getLastRoundIdBeforeElapsedSecs(
bytes32 currencyKey,
uint startingRoundId,
uint startingTimestamp,
uint timediff
) external view returns (uint);
function lastRateUpdateTimes(bytes32 currencyKey) external view returns (uint256);
function oracle() external view returns (address);
function rateAndTimestampAtRound(bytes32 currencyKey, uint roundId) external view returns (uint rate, uint time);
function rateAndUpdatedTime(bytes32 currencyKey) external view returns (uint rate, uint time);
function rateAndInvalid(bytes32 currencyKey) external view returns (uint rate, bool isInvalid);
function rateForCurrency(bytes32 currencyKey) external view returns (uint);
function rateIsFlagged(bytes32 currencyKey) external view returns (bool);
function rateIsInvalid(bytes32 currencyKey) external view returns (bool);
function rateIsStale(bytes32 currencyKey) external view returns (bool);
function rateStalePeriod() external view returns (uint);
function ratesAndUpdatedTimeForCurrencyLastNRounds(bytes32 currencyKey, uint numRounds)
external
view
returns (uint[] memory rates, uint[] memory times);
function ratesAndInvalidForCurrencies(bytes32[] calldata currencyKeys)
external
view
returns (uint[] memory rates, bool anyRateInvalid);
function ratesForCurrencies(bytes32[] calldata currencyKeys) external view returns (uint[] memory);
function synthTooVolatileForAtomicExchange(bytes32 currencyKey) external view returns (bool);
}
interface IDebtCache {
// Views
function cachedDebt() external view returns (uint);
function cachedSynthDebt(bytes32 currencyKey) external view returns (uint);
function cacheTimestamp() external view returns (uint);
function cacheInvalid() external view returns (bool);
function cacheStale() external view returns (bool);
function currentSynthDebts(bytes32[] calldata currencyKeys)
external
view
returns (
uint[] memory debtValues,
uint excludedDebt,
bool anyRateIsInvalid
);
function cachedSynthDebts(bytes32[] calldata currencyKeys) external view returns (uint[] memory debtValues);
function totalNonSnxBackedDebt() external view returns (uint excludedDebt, bool isInvalid);
function currentDebt() external view returns (uint debt, bool anyRateIsInvalid);
function cacheInfo()
external
view
returns (
uint debt,
uint timestamp,
bool isInvalid,
bool isStale
);
// Mutative functions
function updateCachedSynthDebts(bytes32[] calldata currencyKeys) external;
function updateCachedSynthDebtWithRate(bytes32 currencyKey, uint currencyRate) external;
function updateCachedSynthDebtsWithRates(bytes32[] calldata currencyKeys, uint[] calldata currencyRates) external;
function updateDebtCacheValidity(bool currentlyInvalid) external;
function purgeCachedSynthDebt(bytes32 currencyKey) external;
function takeDebtSnapshot() external;
function recordExcludedDebtChange(bytes32 currencyKey, int256 delta) external;
function updateCachedsUSDDebt(int amount) external;
}
// https://docs.synthetix.io/contracts/source/interfaces/isystemstatus
interface ISystemStatus {
struct Status {
bool canSuspend;
bool canResume;
}
struct Suspension {
bool suspended;
// reason is an integer code,
// 0 => no reason, 1 => upgrading, 2+ => defined by system usage
uint248 reason;
}
// Views
function accessControl(bytes32 section, address account) external view returns (bool canSuspend, bool canResume);
function requireSystemActive() external view;
function requireIssuanceActive() external view;
function requireExchangeActive() external view;
function requireExchangeBetweenSynthsAllowed(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey) external view;
function requireSynthActive(bytes32 currencyKey) external view;
function requireSynthsActive(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey) external view;
function systemSuspension() external view returns (bool suspended, uint248 reason);
function issuanceSuspension() external view returns (bool suspended, uint248 reason);
function exchangeSuspension() external view returns (bool suspended, uint248 reason);
function synthExchangeSuspension(bytes32 currencyKey) external view returns (bool suspended, uint248 reason);
function synthSuspension(bytes32 currencyKey) external view returns (bool suspended, uint248 reason);
function getSynthExchangeSuspensions(bytes32[] calldata synths)
external
view
returns (bool[] memory exchangeSuspensions, uint256[] memory reasons);
function getSynthSuspensions(bytes32[] calldata synths)
external
view
returns (bool[] memory suspensions, uint256[] memory reasons);
// Restricted functions
function suspendSynth(bytes32 currencyKey, uint256 reason) external;
function updateAccessControl(
bytes32 section,
address account,
bool canSuspend,
bool canResume
) external;
}
// https://docs.synthetix.io/contracts/source/interfaces/iwrapperfactory
interface IWrapperFactory {
function isWrapper(address possibleWrapper) external view returns (bool);
function createWrapper(
IERC20 token,
bytes32 currencyKey,
bytes32 synthContractName
) external returns (address);
function distributeFees() external;
}
// https://docs.synthetix.io/contracts/source/interfaces/iflexiblestorage
interface IFlexibleStorage {
// Views
function getUIntValue(bytes32 contractName, bytes32 record) external view returns (uint);
function getUIntValues(bytes32 contractName, bytes32[] calldata records) external view returns (uint[] memory);
function getIntValue(bytes32 contractName, bytes32 record) external view returns (int);
function getIntValues(bytes32 contractName, bytes32[] calldata records) external view returns (int[] memory);
function getAddressValue(bytes32 contractName, bytes32 record) external view returns (address);
function getAddressValues(bytes32 contractName, bytes32[] calldata records) external view returns (address[] memory);
function getBoolValue(bytes32 contractName, bytes32 record) external view returns (bool);
function getBoolValues(bytes32 contractName, bytes32[] calldata records) external view returns (bool[] memory);
function getBytes32Value(bytes32 contractName, bytes32 record) external view returns (bytes32);
function getBytes32Values(bytes32 contractName, bytes32[] calldata records) external view returns (bytes32[] memory);
// Mutative functions
function deleteUIntValue(bytes32 contractName, bytes32 record) external;
function deleteIntValue(bytes32 contractName, bytes32 record) external;
function deleteAddressValue(bytes32 contractName, bytes32 record) external;
function deleteBoolValue(bytes32 contractName, bytes32 record) external;
function deleteBytes32Value(bytes32 contractName, bytes32 record) external;
function setUIntValue(
bytes32 contractName,
bytes32 record,
uint value
) external;
function setUIntValues(
bytes32 contractName,
bytes32[] calldata records,
uint[] calldata values
) external;
function setIntValue(
bytes32 contractName,
bytes32 record,
int value
) external;
function setIntValues(
bytes32 contractName,
bytes32[] calldata records,
int[] calldata values
) external;
function setAddressValue(
bytes32 contractName,
bytes32 record,
address value
) external;
function setAddressValues(
bytes32 contractName,
bytes32[] calldata records,
address[] calldata values
) external;
function setBoolValue(
bytes32 contractName,
bytes32 record,
bool value
) external;
function setBoolValues(
bytes32 contractName,
bytes32[] calldata records,
bool[] calldata values
) external;
function setBytes32Value(
bytes32 contractName,
bytes32 record,
bytes32 value
) external;
function setBytes32Values(
bytes32 contractName,
bytes32[] calldata records,
bytes32[] calldata values
) external;
}
// Internal references
// https://docs.synthetix.io/contracts/source/contracts/mixinsystemsettings
contract MixinSystemSettings is MixinResolver {
bytes32 internal constant SETTING_CONTRACT_NAME = "SystemSettings";
bytes32 internal constant SETTING_WAITING_PERIOD_SECS = "waitingPeriodSecs";
bytes32 internal constant SETTING_PRICE_DEVIATION_THRESHOLD_FACTOR = "priceDeviationThresholdFactor";
bytes32 internal constant SETTING_ISSUANCE_RATIO = "issuanceRatio";
bytes32 internal constant SETTING_FEE_PERIOD_DURATION = "feePeriodDuration";
bytes32 internal constant SETTING_TARGET_THRESHOLD = "targetThreshold";
bytes32 internal constant SETTING_LIQUIDATION_DELAY = "liquidationDelay";
bytes32 internal constant SETTING_LIQUIDATION_RATIO = "liquidationRatio";
bytes32 internal constant SETTING_LIQUIDATION_PENALTY = "liquidationPenalty";
bytes32 internal constant SETTING_RATE_STALE_PERIOD = "rateStalePeriod";
bytes32 internal constant SETTING_EXCHANGE_FEE_RATE = "exchangeFeeRate";
bytes32 internal constant SETTING_MINIMUM_STAKE_TIME = "minimumStakeTime";
bytes32 internal constant SETTING_AGGREGATOR_WARNING_FLAGS = "aggregatorWarningFlags";
bytes32 internal constant SETTING_TRADING_REWARDS_ENABLED = "tradingRewardsEnabled";
bytes32 internal constant SETTING_DEBT_SNAPSHOT_STALE_TIME = "debtSnapshotStaleTime";
bytes32 internal constant SETTING_CROSS_DOMAIN_DEPOSIT_GAS_LIMIT = "crossDomainDepositGasLimit";
bytes32 internal constant SETTING_CROSS_DOMAIN_ESCROW_GAS_LIMIT = "crossDomainEscrowGasLimit";
bytes32 internal constant SETTING_CROSS_DOMAIN_REWARD_GAS_LIMIT = "crossDomainRewardGasLimit";
bytes32 internal constant SETTING_CROSS_DOMAIN_WITHDRAWAL_GAS_LIMIT = "crossDomainWithdrawalGasLimit";
bytes32 internal constant SETTING_CROSS_DOMAIN_RELAY_GAS_LIMIT = "crossDomainRelayGasLimit";
bytes32 internal constant SETTING_ETHER_WRAPPER_MAX_ETH = "etherWrapperMaxETH";
bytes32 internal constant SETTING_ETHER_WRAPPER_MINT_FEE_RATE = "etherWrapperMintFeeRate";
bytes32 internal constant SETTING_ETHER_WRAPPER_BURN_FEE_RATE = "etherWrapperBurnFeeRate";
bytes32 internal constant SETTING_WRAPPER_MAX_TOKEN_AMOUNT = "wrapperMaxTokens";
bytes32 internal constant SETTING_WRAPPER_MINT_FEE_RATE = "wrapperMintFeeRate";
bytes32 internal constant SETTING_WRAPPER_BURN_FEE_RATE = "wrapperBurnFeeRate";
bytes32 internal constant SETTING_MIN_CRATIO = "minCratio";
bytes32 internal constant SETTING_NEW_COLLATERAL_MANAGER = "newCollateralManager";
bytes32 internal constant SETTING_INTERACTION_DELAY = "interactionDelay";
bytes32 internal constant SETTING_COLLAPSE_FEE_RATE = "collapseFeeRate";
bytes32 internal constant SETTING_ATOMIC_MAX_VOLUME_PER_BLOCK = "atomicMaxVolumePerBlock";
bytes32 internal constant SETTING_ATOMIC_TWAP_WINDOW = "atomicTwapWindow";
bytes32 internal constant SETTING_ATOMIC_EQUIVALENT_FOR_DEX_PRICING = "atomicEquivalentForDexPricing";
bytes32 internal constant SETTING_ATOMIC_EXCHANGE_FEE_RATE = "atomicExchangeFeeRate";
bytes32 internal constant SETTING_ATOMIC_PRICE_BUFFER = "atomicPriceBuffer";
bytes32 internal constant SETTING_ATOMIC_VOLATILITY_CONSIDERATION_WINDOW = "atomicVolConsiderationWindow";
bytes32 internal constant SETTING_ATOMIC_VOLATILITY_UPDATE_THRESHOLD = "atomicVolUpdateThreshold";
bytes32 internal constant CONTRACT_FLEXIBLESTORAGE = "FlexibleStorage";
enum CrossDomainMessageGasLimits {Deposit, Escrow, Reward, Withdrawal, Relay}
constructor(address _resolver) internal MixinResolver(_resolver) {}
function resolverAddressesRequired() public view returns (bytes32[] memory addresses) {
addresses = new bytes32[](1);
addresses[0] = CONTRACT_FLEXIBLESTORAGE;
}
function flexibleStorage() internal view returns (IFlexibleStorage) {
return IFlexibleStorage(requireAndGetAddress(CONTRACT_FLEXIBLESTORAGE));
}
function _getGasLimitSetting(CrossDomainMessageGasLimits gasLimitType) internal pure returns (bytes32) {
if (gasLimitType == CrossDomainMessageGasLimits.Deposit) {
return SETTING_CROSS_DOMAIN_DEPOSIT_GAS_LIMIT;
} else if (gasLimitType == CrossDomainMessageGasLimits.Escrow) {
return SETTING_CROSS_DOMAIN_ESCROW_GAS_LIMIT;
} else if (gasLimitType == CrossDomainMessageGasLimits.Reward) {
return SETTING_CROSS_DOMAIN_REWARD_GAS_LIMIT;
} else if (gasLimitType == CrossDomainMessageGasLimits.Withdrawal) {
return SETTING_CROSS_DOMAIN_WITHDRAWAL_GAS_LIMIT;
} else if (gasLimitType == CrossDomainMessageGasLimits.Relay) {
return SETTING_CROSS_DOMAIN_RELAY_GAS_LIMIT;
} else {
revert("Unknown gas limit type");
}
}
function getCrossDomainMessageGasLimit(CrossDomainMessageGasLimits gasLimitType) internal view returns (uint) {
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, _getGasLimitSetting(gasLimitType));
}
function getTradingRewardsEnabled() internal view returns (bool) {
return flexibleStorage().getBoolValue(SETTING_CONTRACT_NAME, SETTING_TRADING_REWARDS_ENABLED);
}
function getWaitingPeriodSecs() internal view returns (uint) {
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_WAITING_PERIOD_SECS);
}
function getPriceDeviationThresholdFactor() internal view returns (uint) {
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_PRICE_DEVIATION_THRESHOLD_FACTOR);
}
function getIssuanceRatio() internal view returns (uint) {
// lookup on flexible storage directly for gas savings (rather than via SystemSettings)
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_ISSUANCE_RATIO);
}
function getFeePeriodDuration() internal view returns (uint) {
// lookup on flexible storage directly for gas savings (rather than via SystemSettings)
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_FEE_PERIOD_DURATION);
}
function getTargetThreshold() internal view returns (uint) {
// lookup on flexible storage directly for gas savings (rather than via SystemSettings)
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_TARGET_THRESHOLD);
}
function getLiquidationDelay() internal view returns (uint) {
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_LIQUIDATION_DELAY);
}
function getLiquidationRatio() internal view returns (uint) {
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_LIQUIDATION_RATIO);
}
function getLiquidationPenalty() internal view returns (uint) {
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_LIQUIDATION_PENALTY);
}
function getRateStalePeriod() internal view returns (uint) {
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_RATE_STALE_PERIOD);
}
function getExchangeFeeRate(bytes32 currencyKey) internal view returns (uint) {
return
flexibleStorage().getUIntValue(
SETTING_CONTRACT_NAME,
keccak256(abi.encodePacked(SETTING_EXCHANGE_FEE_RATE, currencyKey))
);
}
function getMinimumStakeTime() internal view returns (uint) {
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_MINIMUM_STAKE_TIME);
}
function getAggregatorWarningFlags() internal view returns (address) {
return flexibleStorage().getAddressValue(SETTING_CONTRACT_NAME, SETTING_AGGREGATOR_WARNING_FLAGS);
}
function getDebtSnapshotStaleTime() internal view returns (uint) {
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_DEBT_SNAPSHOT_STALE_TIME);
}
function getEtherWrapperMaxETH() internal view returns (uint) {
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_ETHER_WRAPPER_MAX_ETH);
}
function getEtherWrapperMintFeeRate() internal view returns (uint) {
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_ETHER_WRAPPER_MINT_FEE_RATE);
}
function getEtherWrapperBurnFeeRate() internal view returns (uint) {
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_ETHER_WRAPPER_BURN_FEE_RATE);
}
function getWrapperMaxTokenAmount(address wrapper) internal view returns (uint) {
return
flexibleStorage().getUIntValue(
SETTING_CONTRACT_NAME,
keccak256(abi.encodePacked(SETTING_WRAPPER_MAX_TOKEN_AMOUNT, wrapper))
);
}
function getWrapperMintFeeRate(address wrapper) internal view returns (int) {
return
flexibleStorage().getIntValue(
SETTING_CONTRACT_NAME,
keccak256(abi.encodePacked(SETTING_WRAPPER_MINT_FEE_RATE, wrapper))
);
}
function getWrapperBurnFeeRate(address wrapper) internal view returns (int) {
return
flexibleStorage().getIntValue(
SETTING_CONTRACT_NAME,
keccak256(abi.encodePacked(SETTING_WRAPPER_BURN_FEE_RATE, wrapper))
);
}
function getMinCratio(address collateral) internal view returns (uint) {
return
flexibleStorage().getUIntValue(
SETTING_CONTRACT_NAME,
keccak256(abi.encodePacked(SETTING_MIN_CRATIO, collateral))
);
}
function getNewCollateralManager(address collateral) internal view returns (address) {
return
flexibleStorage().getAddressValue(
SETTING_CONTRACT_NAME,
keccak256(abi.encodePacked(SETTING_NEW_COLLATERAL_MANAGER, collateral))
);
}
function getInteractionDelay(address collateral) internal view returns (uint) {
return
flexibleStorage().getUIntValue(
SETTING_CONTRACT_NAME,
keccak256(abi.encodePacked(SETTING_INTERACTION_DELAY, collateral))
);
}
function getCollapseFeeRate(address collateral) internal view returns (uint) {
return
flexibleStorage().getUIntValue(
SETTING_CONTRACT_NAME,
keccak256(abi.encodePacked(SETTING_COLLAPSE_FEE_RATE, collateral))
);
}
function getAtomicMaxVolumePerBlock() internal view returns (uint) {
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_ATOMIC_MAX_VOLUME_PER_BLOCK);
}
function getAtomicTwapWindow() internal view returns (uint) {
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_ATOMIC_TWAP_WINDOW);
}
function getAtomicEquivalentForDexPricing(bytes32 currencyKey) internal view returns (address) {
return
flexibleStorage().getAddressValue(
SETTING_CONTRACT_NAME,
keccak256(abi.encodePacked(SETTING_ATOMIC_EQUIVALENT_FOR_DEX_PRICING, currencyKey))
);
}
function getAtomicExchangeFeeRate(bytes32 currencyKey) internal view returns (uint) {
return
flexibleStorage().getUIntValue(
SETTING_CONTRACT_NAME,
keccak256(abi.encodePacked(SETTING_ATOMIC_EXCHANGE_FEE_RATE, currencyKey))
);
}
function getAtomicPriceBuffer(bytes32 currencyKey) internal view returns (uint) {
return
flexibleStorage().getUIntValue(
SETTING_CONTRACT_NAME,
keccak256(abi.encodePacked(SETTING_ATOMIC_PRICE_BUFFER, currencyKey))
);
}
function getAtomicVolatilityConsiderationWindow(bytes32 currencyKey) internal view returns (uint) {
return
flexibleStorage().getUIntValue(
SETTING_CONTRACT_NAME,
keccak256(abi.encodePacked(SETTING_ATOMIC_VOLATILITY_CONSIDERATION_WINDOW, currencyKey))
);
}
function getAtomicVolatilityUpdateThreshold(bytes32 currencyKey) internal view returns (uint) {
return
flexibleStorage().getUIntValue(
SETTING_CONTRACT_NAME,
keccak256(abi.encodePacked(SETTING_ATOMIC_VOLATILITY_UPDATE_THRESHOLD, currencyKey))
);
}
}
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, "SafeMath: division by zero");
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "SafeMath: modulo by zero");
return a % b;
}
}
// Libraries
// https://docs.synthetix.io/contracts/source/libraries/safedecimalmath
library SafeDecimalMath {
using SafeMath for uint;
/* Number of decimal places in the representations. */
uint8 public constant decimals = 18;
uint8 public constant highPrecisionDecimals = 27;
/* The number representing 1.0. */
uint public constant UNIT = 10**uint(decimals);
/* The number representing 1.0 for higher fidelity numbers. */
uint public constant PRECISE_UNIT = 10**uint(highPrecisionDecimals);
uint private constant UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR = 10**uint(highPrecisionDecimals - decimals);
/**
* @return Provides an interface to UNIT.
*/
function unit() external pure returns (uint) {
return UNIT;
}
/**
* @return Provides an interface to PRECISE_UNIT.
*/
function preciseUnit() external pure returns (uint) {
return PRECISE_UNIT;
}
/**
* @return The result of multiplying x and y, interpreting the operands as fixed-point
* decimals.
*
* @dev A unit factor is divided out after the product of x and y is evaluated,
* so that product must be less than 2**256. As this is an integer division,
* the internal division always rounds down. This helps save on gas. Rounding
* is more expensive on gas.
*/
function multiplyDecimal(uint x, uint y) internal pure returns (uint) {
/* Divide by UNIT to remove the extra factor introduced by the product. */
return x.mul(y) / UNIT;
}
/**
* @return The result of safely multiplying x and y, interpreting the operands
* as fixed-point decimals of the specified precision unit.
*
* @dev The operands should be in the form of a the specified unit factor which will be
* divided out after the product of x and y is evaluated, so that product must be
* less than 2**256.
*
* Unlike multiplyDecimal, this function rounds the result to the nearest increment.
* Rounding is useful when you need to retain fidelity for small decimal numbers
* (eg. small fractions or percentages).
*/
function _multiplyDecimalRound(
uint x,
uint y,
uint precisionUnit
) private pure returns (uint) {
/* Divide by UNIT to remove the extra factor introduced by the product. */
uint quotientTimesTen = x.mul(y) / (precisionUnit / 10);
if (quotientTimesTen % 10 >= 5) {
quotientTimesTen += 10;
}
return quotientTimesTen / 10;
}
/**
* @return The result of safely multiplying x and y, interpreting the operands
* as fixed-point decimals of a precise unit.
*
* @dev The operands should be in the precise unit factor which will be
* divided out after the product of x and y is evaluated, so that product must be
* less than 2**256.
*
* Unlike multiplyDecimal, this function rounds the result to the nearest increment.
* Rounding is useful when you need to retain fidelity for small decimal numbers
* (eg. small fractions or percentages).
*/
function multiplyDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) {
return _multiplyDecimalRound(x, y, PRECISE_UNIT);
}
/**
* @return The result of safely multiplying x and y, interpreting the operands
* as fixed-point decimals of a standard unit.
*
* @dev The operands should be in the standard unit factor which will be
* divided out after the product of x and y is evaluated, so that product must be
* less than 2**256.
*
* Unlike multiplyDecimal, this function rounds the result to the nearest increment.
* Rounding is useful when you need to retain fidelity for small decimal numbers
* (eg. small fractions or percentages).
*/
function multiplyDecimalRound(uint x, uint y) internal pure returns (uint) {
return _multiplyDecimalRound(x, y, UNIT);
}
/**
* @return The result of safely dividing x and y. The return value is a high
* precision decimal.
*
* @dev y is divided after the product of x and the standard precision unit
* is evaluated, so the product of x and UNIT must be less than 2**256. As
* this is an integer division, the result is always rounded down.
* This helps save on gas. Rounding is more expensive on gas.
*/
function divideDecimal(uint x, uint y) internal pure returns (uint) {
/* Reintroduce the UNIT factor that will be divided out by y. */
return x.mul(UNIT).div(y);
}
/**
* @return The result of safely dividing x and y. The return value is as a rounded
* decimal in the precision unit specified in the parameter.
*
* @dev y is divided after the product of x and the specified precision unit
* is evaluated, so the product of x and the specified precision unit must
* be less than 2**256. The result is rounded to the nearest increment.
*/
function _divideDecimalRound(
uint x,
uint y,
uint precisionUnit
) private pure returns (uint) {
uint resultTimesTen = x.mul(precisionUnit * 10).div(y);
if (resultTimesTen % 10 >= 5) {
resultTimesTen += 10;
}
return resultTimesTen / 10;
}
/**
* @return The result of safely dividing x and y. The return value is as a rounded
* standard precision decimal.
*
* @dev y is divided after the product of x and the standard precision unit
* is evaluated, so the product of x and the standard precision unit must
* be less than 2**256. The result is rounded to the nearest increment.
*/
function divideDecimalRound(uint x, uint y) internal pure returns (uint) {
return _divideDecimalRound(x, y, UNIT);
}
/**
* @return The result of safely dividing x and y. The return value is as a rounded
* high precision decimal.
*
* @dev y is divided after the product of x and the high precision unit
* is evaluated, so the product of x and the high precision unit must
* be less than 2**256. The result is rounded to the nearest increment.
*/
function divideDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) {
return _divideDecimalRound(x, y, PRECISE_UNIT);
}
/**
* @dev Convert a standard decimal representation to a high precision one.
*/
function decimalToPreciseDecimal(uint i) internal pure returns (uint) {
return i.mul(UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR);
}
/**
* @dev Convert a high precision decimal to a standard decimal representation.
*/
function preciseDecimalToDecimal(uint i) internal pure returns (uint) {
uint quotientTimesTen = i / (UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR / 10);
if (quotientTimesTen % 10 >= 5) {
quotientTimesTen += 10;
}
return quotientTimesTen / 10;
}
// Computes `a - b`, setting the value to 0 if b > a.
function floorsub(uint a, uint b) internal pure returns (uint) {
return b >= a ? 0 : a - b;
}
/* ---------- Utilities ---------- */
/*
* Absolute value of the input, returned as a signed number.
*/
function signedAbs(int x) internal pure returns (int) {
return x < 0 ? -x : x;
}
/*
* Absolute value of the input, returned as an unsigned number.
*/
function abs(int x) internal pure returns (uint) {
return uint(signedAbs(x));
}
}
// Inheritance
// Internal references
// Libraries
// https://docs.synthetix.io/contracts/source/contracts/wrapper
contract Wrapper is Owned, Pausable, MixinResolver, MixinSystemSettings, IWrapper {
using SafeMath for uint;
using SafeDecimalMath for uint;
/* ========== ENCODED NAMES ========== */
bytes32 internal constant sUSD = "sUSD";
/* ========== ADDRESS RESOLVER CONFIGURATION ========== */
bytes32 private constant CONTRACT_SYNTH_SUSD = "SynthsUSD";
bytes32 private constant CONTRACT_EXRATES = "ExchangeRates";
bytes32 private constant CONTRACT_DEBTCACHE = "DebtCache";
bytes32 private constant CONTRACT_SYSTEMSTATUS = "SystemStatus";
bytes32 private constant CONTRACT_WRAPPERFACTORY = "WrapperFactory";
// ========== STATE VARIABLES ==========
// NOTE: these values should ideally be `immutable` instead of public
IERC20 public token;
bytes32 public currencyKey;
bytes32 public synthContractName;
uint public targetSynthIssued;
constructor(
address _owner,
address _resolver,
IERC20 _token,
bytes32 _currencyKey,
bytes32 _synthContractName
) public Owned(_owner) MixinSystemSettings(_resolver) {
token = _token;
currencyKey = _currencyKey;
synthContractName = _synthContractName;
targetSynthIssued = 0;
token.approve(address(this), uint256(-1));
}
/* ========== VIEWS ========== */
function resolverAddressesRequired() public view returns (bytes32[] memory addresses) {
bytes32[] memory existingAddresses = MixinSystemSettings.resolverAddressesRequired();
bytes32[] memory newAddresses = new bytes32[](6);
newAddresses[0] = CONTRACT_SYNTH_SUSD;
newAddresses[1] = synthContractName;
newAddresses[2] = CONTRACT_EXRATES;
newAddresses[3] = CONTRACT_DEBTCACHE;
newAddresses[4] = CONTRACT_SYSTEMSTATUS;
newAddresses[5] = CONTRACT_WRAPPERFACTORY;
addresses = combineArrays(existingAddresses, newAddresses);
return addresses;
}
/* ========== INTERNAL VIEWS ========== */
function synthsUSD() internal view returns (ISynth) {
return ISynth(requireAndGetAddress(CONTRACT_SYNTH_SUSD));
}
function synth() internal view returns (ISynth) {
return ISynth(requireAndGetAddress(synthContractName));
}
function exchangeRates() internal view returns (IExchangeRates) {
return IExchangeRates(requireAndGetAddress(CONTRACT_EXRATES));
}
function debtCache() internal view returns (IDebtCache) {
return IDebtCache(requireAndGetAddress(CONTRACT_DEBTCACHE));
}
function systemStatus() internal view returns (ISystemStatus) {
return ISystemStatus(requireAndGetAddress(CONTRACT_SYSTEMSTATUS));
}
function wrapperFactory() internal view returns (IWrapperFactory) {
return IWrapperFactory(requireAndGetAddress(CONTRACT_WRAPPERFACTORY));
}
/* ========== PUBLIC FUNCTIONS ========== */
// ========== VIEWS ==========
function capacity() public view returns (uint _capacity) {
// capacity = max(maxETH - balance, 0)
uint balance = getReserves();
uint maxToken = maxTokenAmount();
if (balance >= maxToken) {
return 0;
}
return maxToken.sub(balance);
}
function totalIssuedSynths() public view returns (uint) {
// synths issued by this contract is always exactly equal to the balance of reserves
return exchangeRates().effectiveValue(currencyKey, targetSynthIssued, sUSD);
}
function getReserves() public view returns (uint) {
return token.balanceOf(address(this));
}
function calculateMintFee(uint amount) public view returns (uint, bool) {
int r = mintFeeRate();
if (r < 0) {
return (amount.multiplyDecimalRound(uint(-r)), true);
} else {
return (amount.multiplyDecimalRound(uint(r)), false);
}
}
function calculateBurnFee(uint amount) public view returns (uint, bool) {
int r = burnFeeRate();
if (r < 0) {
return (amount.multiplyDecimalRound(uint(-r)), true);
} else {
return (amount.multiplyDecimalRound(uint(r)), false);
}
}
function maxTokenAmount() public view returns (uint256) {
return getWrapperMaxTokenAmount(address(this));
}
function mintFeeRate() public view returns (int256) {
return getWrapperMintFeeRate(address(this));
}
function burnFeeRate() public view returns (int256) {
return getWrapperBurnFeeRate(address(this));
}
/* ========== MUTATIVE FUNCTIONS ========== */
// Transfers `amountIn` token to mint `amountIn - fees` of currencyKey.
// `amountIn` is inclusive of fees, calculable via `calculateMintFee`.
function mint(uint amountIn) external notPaused issuanceActive {
require(amountIn <= token.allowance(msg.sender, address(this)), "Allowance not high enough");
require(amountIn <= token.balanceOf(msg.sender), "Balance is too low");
require(!exchangeRates().rateIsInvalid(currencyKey), "Currency rate is invalid");
uint currentCapacity = capacity();
require(currentCapacity > 0, "Contract has no spare capacity to mint");
uint actualAmountIn = currentCapacity < amountIn ? currentCapacity : amountIn;
(uint feeAmountTarget, bool negative) = calculateMintFee(actualAmountIn);
uint mintAmount = negative ? actualAmountIn.add(feeAmountTarget) : actualAmountIn.sub(feeAmountTarget);
// Transfer token from user.
bool success = _safeTransferFrom(address(token), msg.sender, address(this), actualAmountIn);
require(success, "Transfer did not succeed");
// Mint tokens to user
_mint(mintAmount);
emit Minted(msg.sender, mintAmount, negative ? 0 : feeAmountTarget, actualAmountIn);
}
// Burns `amountIn` synth for `amountIn - fees` amount of token.
// `amountIn` is inclusive of fees, calculable via `calculateBurnFee`.
function burn(uint amountIn) external notPaused issuanceActive {
require(amountIn <= IERC20(address(synth())).balanceOf(msg.sender), "Balance is too low");
require(!exchangeRates().rateIsInvalid(currencyKey), "Currency rate is invalid");
require(totalIssuedSynths() > 0, "Contract cannot burn for token, token balance is zero");
(uint burnFee, bool negative) = calculateBurnFee(targetSynthIssued);
uint burnAmount;
uint amountOut;
if (negative) {
burnAmount = targetSynthIssued < amountIn ? targetSynthIssued.sub(burnFee) : amountIn;
amountOut = burnAmount.multiplyDecimal(
// -1e18 <= burnFeeRate <= 1e18 so this operation is safe
uint(int(SafeDecimalMath.unit()) - burnFeeRate())
);
} else {
burnAmount = targetSynthIssued.add(burnFee) < amountIn ? targetSynthIssued.add(burnFee) : amountIn;
amountOut = burnAmount.divideDecimal(
// -1e18 <= burnFeeRate <= 1e18 so this operation is safe
uint(int(SafeDecimalMath.unit()) + burnFeeRate())
);
}
uint feeAmountTarget = negative ? 0 : burnAmount.sub(amountOut);
// Transfer token to user.
bool success = _safeTransferFrom(address(token), address(this), msg.sender, amountOut);
require(success, "Transfer did not succeed");
// Burn
_burn(burnAmount);
emit Burned(msg.sender, amountOut, feeAmountTarget, burnAmount);
}
// ========== RESTRICTED ==========
/**
* @notice Fallback function
*/
function() external payable {
revert("Fallback disabled, use mint()");
}
/* ========== INTERNAL FUNCTIONS ========== */
function _mint(uint amount) internal {
uint reserves = getReserves();
uint excessAmount = reserves > targetSynthIssued.add(amount) ? reserves.sub(targetSynthIssued.add(amount)) : 0;
uint excessAmountUsd = exchangeRates().effectiveValue(currencyKey, excessAmount, sUSD);
// Mint `amount` to user.
synth().issue(msg.sender, amount);
// Escrow fee.
if (excessAmountUsd > 0) {
synthsUSD().issue(address(wrapperFactory()), excessAmountUsd);
}
// in the case of a negative fee extra synths will be issued, billed to the snx stakers
_setTargetSynthIssued(reserves);
}
function _burn(uint amount) internal {
uint reserves = getReserves();
// this is logically equivalent to getReserves() - (targetSynthIssued - amount), without going negative
uint excessAmount = reserves.add(amount) > targetSynthIssued ? reserves.add(amount).sub(targetSynthIssued) : 0;
uint excessAmountUsd = exchangeRates().effectiveValue(currencyKey, excessAmount, sUSD);
// Burn `amount` of currencyKey from user.
synth().burn(msg.sender, amount);
// We use burn/issue instead of burning the principal and transferring the fee.
// This saves an approval and is cheaper.
// Escrow fee.
if (excessAmountUsd > 0) {
synthsUSD().issue(address(wrapperFactory()), excessAmountUsd);
}
// in the case of a negative fee fewer synths will be burned, billed to the snx stakers
_setTargetSynthIssued(reserves);
}
function _setTargetSynthIssued(uint _targetSynthIssued) internal {
debtCache().recordExcludedDebtChange(currencyKey, int256(_targetSynthIssued) - int256(targetSynthIssued));
targetSynthIssued = _targetSynthIssued;
}
function _safeTransferFrom(
address _tokenAddress,
address _from,
address _to,
uint256 _value
) internal returns (bool success) {
// note: both of these could be replaced with manual mstore's to reduce cost if desired
bytes memory msgData = abi.encodeWithSignature("transferFrom(address,address,uint256)", _from, _to, _value);
uint msgSize = msgData.length;
assembly {
// pre-set scratch space to all bits set
mstore(0x00, 0xff)
// note: this requires tangerine whistle compatible EVM
if iszero(call(gas(), _tokenAddress, 0, add(msgData, 0x20), msgSize, 0x00, 0x20)) {
revert(0, 0)
}
switch mload(0x00)
case 0xff {
// token is not fully ERC20 compatible, didn't return anything, assume it was successful
success := 1
}
case 0x01 {
success := 1
}
case 0x00 {
success := 0
}
default {
// unexpected value, what could this be?
revert(0, 0)
}
}
}
modifier issuanceActive {
systemStatus().requireIssuanceActive();
_;
}
/* ========== EVENTS ========== */
event Minted(address indexed account, uint principal, uint fee, uint amountIn);
event Burned(address indexed account, uint principal, uint fee, uint amountIn);
}
// https://docs.synthetix.io/contracts/source/interfaces/ifeepool
interface IFeePool {
// Views
// solhint-disable-next-line func-name-mixedcase
function FEE_ADDRESS() external view returns (address);
function feesAvailable(address account) external view returns (uint, uint);
function feePeriodDuration() external view returns (uint);
function isFeesClaimable(address account) external view returns (bool);
function targetThreshold() external view returns (uint);
function totalFeesAvailable() external view returns (uint);
function totalRewardsAvailable() external view returns (uint);
// Mutative Functions
function claimFees() external returns (bool);
function claimOnBehalf(address claimingForAddress) external returns (bool);
function closeCurrentFeePeriod() external;
// Restricted: used internally to Synthetix
function appendAccountIssuanceRecord(
address account,
uint lockedAmount,
uint debtEntryIndex
) external;
function recordFeePaid(uint sUSDAmount) external;
function setRewardsToDistribute(uint amount) external;
}
// Inheritance
// Internal references
// https://docs.synthetix.io/contracts/source/contracts/wrapperfactory
contract WrapperFactory is Owned, MixinResolver, IWrapperFactory {
bytes32 public constant CONTRACT_NAME = "WrapperFactory";
bytes32 internal constant CONTRACT_FLEXIBLESTORAGE = "FlexibleStorage";
bytes32 internal constant CONTRACT_SYNTH_SUSD = "SynthsUSD";
bytes32 internal constant CONTRACT_FEEPOOL = "FeePool";
uint internal constant WRAPPER_VERSION = 1;
/* ========== CONSTRUCTOR ========== */
constructor(address _owner, address _resolver) public Owned(_owner) MixinResolver(_resolver) {}
function resolverAddressesRequired() public view returns (bytes32[] memory addresses) {
addresses = new bytes32[](3);
addresses[0] = CONTRACT_SYNTH_SUSD;
addresses[1] = CONTRACT_FLEXIBLESTORAGE;
addresses[2] = CONTRACT_FEEPOOL;
}
/* ========== INTERNAL VIEWS ========== */
function synthsUSD() internal view returns (IERC20) {
return IERC20(requireAndGetAddress(CONTRACT_SYNTH_SUSD));
}
function flexibleStorage() internal view returns (IFlexibleStorage) {
return IFlexibleStorage(requireAndGetAddress(CONTRACT_FLEXIBLESTORAGE));
}
function feePool() internal view returns (IFeePool) {
return IFeePool(requireAndGetAddress(CONTRACT_FEEPOOL));
}
// ========== VIEWS ==========
// Returns the version of a wrapper created by this wrapper factory
// Used by MultiCollateralSynth to know if it should trust the wrapper contract
function isWrapper(address possibleWrapper) external view returns (bool) {
return flexibleStorage().getUIntValue(CONTRACT_NAME, bytes32(uint(address(possibleWrapper)))) > 0;
}
function feesEscrowed() public view returns (uint) {
return synthsUSD().balanceOf(address(this));
}
// ========== RESTRICTED ==========
/**
* @notice Fallback function
*/
function() external payable {
revert("Contract is not payable");
}
/* ========== MUTATIVE FUNCTIONS ========== */
function createWrapper(
IERC20 token,
bytes32 currencyKey,
bytes32 synthContractName
) external onlyOwner returns (address) {
// Create the wrapper instance
Wrapper wrapper = new Wrapper(owner, address(resolver), token, currencyKey, synthContractName);
// Rebuild caches immediately since it will almost certainly need to be done
wrapper.rebuildCache();
// Register it so that MultiCollateralSynth knows to trust it
flexibleStorage().setUIntValue(CONTRACT_NAME, bytes32(uint(address(wrapper))), WRAPPER_VERSION);
emit WrapperCreated(address(token), currencyKey, address(wrapper));
return address(wrapper);
}
function distributeFees() external {
// Normalize fee to sUSD
uint amountSUSD = feesEscrowed();
if (amountSUSD > 0) {
// Transfer sUSD to the fee pool
bool success = synthsUSD().transfer(feePool().FEE_ADDRESS(), amountSUSD);
require(success, "Transfer did not succeed");
}
}
event WrapperCreated(address indexed token, bytes32 indexed currencyKey, address wrapperAddress);
} | * @notice Fallback function/ | function() external payable {
revert("Contract is not payable");
}
| 7,671,264 | [
1,
12355,
445,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
1435,
3903,
8843,
429,
288,
203,
3639,
15226,
2932,
8924,
353,
486,
8843,
429,
8863,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0xcbc0A8d5C7352Fe3625614ea343019e6d6b89031/sources/contracts/v2/templeLineOfCredit/TempleLineOfCredit.sol | * @notice A view of the derived/internal cache data./ | function getDebtTokenCache() external view returns (DebtTokenCache memory) {
return _debtTokenCacheRO();
}
| 5,002,842 | [
1,
37,
1476,
434,
326,
10379,
19,
7236,
1247,
501,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
336,
758,
23602,
1345,
1649,
1435,
3903,
1476,
1135,
261,
758,
23602,
1345,
1649,
3778,
13,
288,
203,
3639,
327,
389,
323,
23602,
1345,
1649,
1457,
5621,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// contracts/mocks/Rewards.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "./interfaces/IMMintableERC20.sol";
contract MasterChef is Ownable {
using SafeERC20 for IERC20;
// Info of each user.
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
//
// We do some fancy math here. Basically, any point in time, the amount of CAKEs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accCakePerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accCakePerShare` (and `lastRewardBlock`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
// Info of each pool.
struct PoolInfo {
IERC20 lpToken; // Address of LP token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. CAKEs to distribute per block.
uint256 lastRewardBlock; // Last block number that CAKEs distribution occurs.
uint256 accCakePerShare; // Accumulated CAKEs per share, times 1e12. See below.
}
// The CAKE TOKEN!
address public cake;
// CAKE tokens created per block.
uint256 public cakePerBlock;
// Bonus muliplier for early cake makers.
uint256 public bonusMultiplier = 1;
// Info of each pool.
PoolInfo[] public poolInfo;
// Info of each user that stakes LP tokens.
mapping(uint256 => mapping(address => UserInfo)) public userInfo;
// Total allocation points. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint = 0;
// The block number when CAKE mining starts.
uint256 public startBlock;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount);
constructor(address _cake) {
cake = _cake;
cakePerBlock = 400000000000000000;
startBlock = block.number;
// staking pool
poolInfo.push(
PoolInfo({lpToken: IERC20(_cake), allocPoint: 1000, lastRewardBlock: startBlock, accCakePerShare: 0})
);
totalAllocPoint = 1000;
}
function updateMultiplier(uint256 multiplierNumber) public onlyOwner {
bonusMultiplier = multiplierNumber;
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
// Add a new lp to the pool. Can only be called by the owner.
// XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do.
function add(
uint256 _allocPoint,
IERC20 _lpToken,
bool _withUpdate
) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint + _allocPoint;
poolInfo.push(
PoolInfo({lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accCakePerShare: 0})
);
updateStakingPool();
}
// Update the given pool's CAKE allocation point. Can only be called by the owner.
function set(
uint256 _pid,
uint256 _allocPoint,
bool _withUpdate
) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
uint256 prevAllocPoint = poolInfo[_pid].allocPoint;
totalAllocPoint = totalAllocPoint - prevAllocPoint + _allocPoint;
poolInfo[_pid].allocPoint = _allocPoint;
if (prevAllocPoint != _allocPoint) {
updateStakingPool();
}
}
function updateStakingPool() internal {
uint256 length = poolInfo.length;
uint256 points = 0;
for (uint256 pid = 1; pid < length; ++pid) {
points = points + poolInfo[pid].allocPoint;
}
if (points != 0) {
points = points / 3;
totalAllocPoint = totalAllocPoint - poolInfo[0].allocPoint + points;
poolInfo[0].allocPoint = points;
}
}
// Return reward multiplier over the given _from to _to block.
function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) {
return (_to - _from) * bonusMultiplier;
}
// View function to see pending CAKEs on frontend.
function pendingCake(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accCakePerShare = pool.accCakePerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 cakeReward = (multiplier * cakePerBlock * pool.allocPoint) / totalAllocPoint;
accCakePerShare = accCakePerShare + ((cakeReward * 1e12) / lpSupply);
}
return (user.amount * accCakePerShare) / 1e12 - user.rewardDebt;
}
// Update reward variables for all pools. Be careful of gas spending!
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 cakeReward = (multiplier * cakePerBlock * pool.allocPoint) / totalAllocPoint;
pool.accCakePerShare = pool.accCakePerShare + ((cakeReward * 1e12) / lpSupply);
pool.lastRewardBlock = block.number;
}
// Deposit LP tokens to MasterChef for CAKE allocation.
function deposit(uint256 _pid, uint256 _amount) public {
require(_pid != 0, "deposit CAKE by staking");
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 pending = ((user.amount * pool.accCakePerShare) / 1e12) - user.rewardDebt;
if (pending > 0) {
safeCakeTransfer(msg.sender, pending);
}
}
if (_amount > 0) {
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount + _amount;
}
user.rewardDebt = (user.amount * pool.accCakePerShare) / 1e12;
emit Deposit(msg.sender, _pid, _amount);
}
// Withdraw LP tokens from MasterChef.
function withdraw(uint256 _pid, uint256 _amount) public {
require(_pid != 0, "withdraw CAKE by unstaking");
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 pending = ((user.amount * pool.accCakePerShare) / 1e12) - user.rewardDebt;
if (pending > 0) {
safeCakeTransfer(msg.sender, pending);
}
if (_amount > 0) {
user.amount = user.amount - _amount;
pool.lpToken.safeTransfer(address(msg.sender), _amount);
}
user.rewardDebt = (user.amount * pool.accCakePerShare) / 1e12;
emit Withdraw(msg.sender, _pid, _amount);
}
// Stake CAKE tokens to MasterChef
function enterStaking(uint256 _amount) public {
PoolInfo storage pool = poolInfo[0];
UserInfo storage user = userInfo[0][msg.sender];
updatePool(0);
if (user.amount > 0) {
uint256 pending = ((user.amount * pool.accCakePerShare) / 1e12) - user.rewardDebt;
if (pending > 0) {
safeCakeTransfer(msg.sender, pending);
}
}
if (_amount > 0) {
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount + _amount;
}
user.rewardDebt = (user.amount * pool.accCakePerShare) / 1e12;
emit Deposit(msg.sender, 0, _amount);
}
// Withdraw CAKE tokens from STAKING.
function leaveStaking(uint256 _amount) public {
PoolInfo storage pool = poolInfo[0];
UserInfo storage user = userInfo[0][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(0);
uint256 pending = ((user.amount * pool.accCakePerShare) / 1e12) - user.rewardDebt;
if (pending > 0) {
safeCakeTransfer(msg.sender, pending);
}
if (_amount > 0) {
user.amount = user.amount - _amount;
pool.lpToken.safeTransfer(address(msg.sender), _amount);
}
user.rewardDebt = (user.amount * pool.accCakePerShare) / 1e12;
emit Withdraw(msg.sender, 0, _amount);
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
pool.lpToken.safeTransfer(address(msg.sender), user.amount);
emit EmergencyWithdraw(msg.sender, _pid, user.amount);
user.amount = 0;
user.rewardDebt = 0;
}
// allow admin update, no risk of rug pull
function updateCakePerBlock(uint256 _cakePerBlock) public onlyOwner {
require(msg.sender == owner(), "Owner-Only Function");
cakePerBlock = _cakePerBlock;
}
// Safe cake transfer function, just in case if rounding error causes pool to not have enough CAKEs.
// MODIFIED TO MINT HERE
function safeCakeTransfer(address _to, uint256 _amount) internal {
IMMintableERC20(cake).mint(_to, _amount);
}
}
| View function to see pending CAKEs on frontend. | function pendingCake(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accCakePerShare = pool.accCakePerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 cakeReward = (multiplier * cakePerBlock * pool.allocPoint) / totalAllocPoint;
accCakePerShare = accCakePerShare + ((cakeReward * 1e12) / lpSupply);
}
return (user.amount * accCakePerShare) / 1e12 - user.rewardDebt;
}
| 12,683,981 | [
1,
1767,
445,
358,
2621,
4634,
6425,
47,
6705,
603,
15442,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
4634,
31089,
12,
11890,
5034,
389,
6610,
16,
1758,
389,
1355,
13,
3903,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
8828,
966,
2502,
2845,
273,
2845,
966,
63,
67,
6610,
15533,
203,
3639,
25003,
2502,
729,
273,
16753,
63,
67,
6610,
6362,
67,
1355,
15533,
203,
3639,
2254,
5034,
4078,
31089,
2173,
9535,
273,
2845,
18,
8981,
31089,
2173,
9535,
31,
203,
3639,
2254,
5034,
12423,
3088,
1283,
273,
2845,
18,
9953,
1345,
18,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
3639,
309,
261,
2629,
18,
2696,
405,
2845,
18,
2722,
17631,
1060,
1768,
597,
12423,
3088,
1283,
480,
374,
13,
288,
203,
5411,
2254,
5034,
15027,
273,
31863,
5742,
12,
6011,
18,
2722,
17631,
1060,
1768,
16,
1203,
18,
2696,
1769,
203,
5411,
2254,
5034,
276,
911,
17631,
1060,
273,
261,
20538,
380,
276,
911,
2173,
1768,
380,
2845,
18,
9853,
2148,
13,
342,
2078,
8763,
2148,
31,
203,
5411,
4078,
31089,
2173,
9535,
273,
4078,
31089,
2173,
9535,
397,
14015,
23780,
17631,
1060,
380,
404,
73,
2138,
13,
342,
12423,
3088,
1283,
1769,
203,
3639,
289,
203,
3639,
327,
261,
1355,
18,
8949,
380,
4078,
31089,
2173,
9535,
13,
342,
404,
73,
2138,
300,
729,
18,
266,
2913,
758,
23602,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2021-06-14
*/
// File: flattener/openzeppelin-solidity/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: flattener/openzeppelin-solidity/contracts/introspection/IERC165.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File: flattener/openzeppelin-solidity/contracts/token/ERC721/IERC721.sol
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
// File: flattener/openzeppelin-solidity/contracts/token/ERC721/IERC721Receiver.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4);
}
// File: flattener/multi-token-standard/contracts/interfaces/IERC1155.sol
pragma solidity 0.7.4;
interface IERC1155 {
/****************************************|
| Events |
|_______________________________________*/
/**
* @dev Either TransferSingle or TransferBatch MUST emit when tokens are transferred, including zero amount transfers as well as minting or burning
* Operator MUST be msg.sender
* When minting/creating tokens, the `_from` field MUST be set to `0x0`
* When burning/destroying tokens, the `_to` field MUST be set to `0x0`
* The total amount transferred from address 0x0 minus the total amount transferred to 0x0 may be used by clients and exchanges to be added to the "circulating supply" for a given token ID
* To broadcast the existence of a token ID with no initial balance, the contract SHOULD emit the TransferSingle event from `0x0` to `0x0`, with the token creator as `_operator`, and a `_amount` of 0
*/
event TransferSingle(address indexed _operator, address indexed _from, address indexed _to, uint256 _id, uint256 _amount);
/**
* @dev Either TransferSingle or TransferBatch MUST emit when tokens are transferred, including zero amount transfers as well as minting or burning
* Operator MUST be msg.sender
* When minting/creating tokens, the `_from` field MUST be set to `0x0`
* When burning/destroying tokens, the `_to` field MUST be set to `0x0`
* The total amount transferred from address 0x0 minus the total amount transferred to 0x0 may be used by clients and exchanges to be added to the "circulating supply" for a given token ID
* To broadcast the existence of multiple token IDs with no initial balance, this SHOULD emit the TransferBatch event from `0x0` to `0x0`, with the token creator as `_operator`, and a `_amount` of 0
*/
event TransferBatch(address indexed _operator, address indexed _from, address indexed _to, uint256[] _ids, uint256[] _amounts);
/**
* @dev MUST emit when an approval is updated
*/
event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
/****************************************|
| Functions |
|_______________________________________*/
/**
* @notice Transfers amount of an _id from the _from address to the _to address specified
* @dev MUST emit TransferSingle event on success
* Caller must be approved to manage the _from account's tokens (see isApprovedForAll)
* MUST throw if `_to` is the zero address
* MUST throw if balance of sender for token `_id` is lower than the `_amount` sent
* MUST throw on any other error
* When transfer is complete, this function MUST check if `_to` is a smart contract (code size > 0). If so, it MUST call `onERC1155Received` on `_to` and revert if the return amount is not `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
* @param _from Source address
* @param _to Target address
* @param _id ID of the token type
* @param _amount Transfered amount
* @param _data Additional data with no specified format, sent in call to `_to`
*/
function safeTransferFrom(address _from, address _to, uint256 _id, uint256 _amount, bytes calldata _data) external;
/**
* @notice Send multiple types of Tokens from the _from address to the _to address (with safety call)
* @dev MUST emit TransferBatch event on success
* Caller must be approved to manage the _from account's tokens (see isApprovedForAll)
* MUST throw if `_to` is the zero address
* MUST throw if length of `_ids` is not the same as length of `_amounts`
* MUST throw if any of the balance of sender for token `_ids` is lower than the respective `_amounts` sent
* MUST throw on any other error
* When transfer is complete, this function MUST check if `_to` is a smart contract (code size > 0). If so, it MUST call `onERC1155BatchReceived` on `_to` and revert if the return amount is not `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
* Transfers and events MUST occur in the array order they were submitted (_ids[0] before _ids[1], etc)
* @param _from Source addresses
* @param _to Target addresses
* @param _ids IDs of each token type
* @param _amounts Transfer amounts per token type
* @param _data Additional data with no specified format, sent in call to `_to`
*/
function safeBatchTransferFrom(address _from, address _to, uint256[] calldata _ids, uint256[] calldata _amounts, bytes calldata _data) external;
/**
* @notice Get the balance of an account's Tokens
* @param _owner The address of the token holder
* @param _id ID of the Token
* @return The _owner's balance of the Token type requested
*/
function balanceOf(address _owner, uint256 _id) external view returns (uint256);
/**
* @notice Get the balance of multiple account/token pairs
* @param _owners The addresses of the token holders
* @param _ids ID of the Tokens
* @return The _owner's balance of the Token types requested (i.e. balance for each (owner, id) pair)
*/
function balanceOfBatch(address[] calldata _owners, uint256[] calldata _ids) external view returns (uint256[] memory);
/**
* @notice Enable or disable approval for a third party ("operator") to manage all of caller's tokens
* @dev MUST emit the ApprovalForAll event on success
* @param _operator Address to add to the set of authorized operators
* @param _approved True if the operator is approved, false to revoke approval
*/
function setApprovalForAll(address _operator, bool _approved) external;
/**
* @notice Queries the approval status of an operator for a given owner
* @param _owner The owner of the Tokens
* @param _operator Address of authorized operator
* @return isOperator True if the operator is approved, false if not
*/
function isApprovedForAll(address _owner, address _operator) external view returns (bool isOperator);
}
// File: flattener/multi-token-standard/contracts/interfaces/IERC1155TokenReceiver.sol
pragma solidity 0.7.4;
/**
* @dev ERC-1155 interface for accepting safe transfers.
*/
interface IERC1155TokenReceiver {
/**
* @notice Handle the receipt of a single ERC1155 token type
* @dev An ERC1155-compliant smart contract MUST call this function on the token recipient contract, at the end of a `safeTransferFrom` after the balance has been updated
* This function MAY throw to revert and reject the transfer
* Return of other amount than the magic value MUST result in the transaction being reverted
* Note: The token contract address is always the message sender
* @param _operator The address which called the `safeTransferFrom` function
* @param _from The address which previously owned the token
* @param _id The id of the token being transferred
* @param _amount The amount of tokens being transferred
* @param _data Additional data with no specified format
* @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
*/
function onERC1155Received(address _operator, address _from, uint256 _id, uint256 _amount, bytes calldata _data) external returns(bytes4);
/**
* @notice Handle the receipt of multiple ERC1155 token types
* @dev An ERC1155-compliant smart contract MUST call this function on the token recipient contract, at the end of a `safeBatchTransferFrom` after the balances have been updated
* This function MAY throw to revert and reject the transfer
* Return of other amount than the magic value WILL result in the transaction being reverted
* Note: The token contract address is always the message sender
* @param _operator The address which called the `safeBatchTransferFrom` function
* @param _from The address which previously owned the token
* @param _ids An array containing ids of each token being transferred
* @param _amounts An array containing amounts of each token being transferred
* @param _data Additional data with no specified format
* @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
*/
function onERC1155BatchReceived(address _operator, address _from, uint256[] calldata _ids, uint256[] calldata _amounts, bytes calldata _data) external returns(bytes4);
}
// File: flattener/PortionAuction.sol
pragma solidity ^0.7.4;
contract PortionAuction is IERC721Receiver, IERC1155TokenReceiver {
modifier onlyOwner {
require(msg.sender == owner);
_;
}
address public owner;
address public controller;
address public beneficiary;
address public highestBidder;
uint public tokenId;
uint public quantity;
uint public highestBid;
bool public cancelled;
bool public itemClaimed;
bool public controllerClaimedFunds;
bool public beneficiaryClaimedFunds;
bool public acceptPRT;
bool public isErc1155;
IERC20 portionTokenContract;
IERC721 artTokenContract;
IERC1155 artToken1155Contract;
mapping(address => uint256) public fundsByBidder;
constructor(
address _controller,
address _beneficiary,
bool _acceptPRT,
bool _isErc1155,
uint _tokenId,
uint _quantity,
address portionTokenAddress,
address artTokenAddress,
address artToken1155Address
) {
owner = msg.sender;
controller = _controller;
beneficiary = _beneficiary;
acceptPRT = _acceptPRT;
isErc1155 = _isErc1155;
tokenId = _tokenId;
quantity = _quantity;
if (acceptPRT) {
portionTokenContract = IERC20(portionTokenAddress);
}
if (isErc1155) {
artToken1155Contract = IERC1155(artToken1155Address);
} else {
artTokenContract = IERC721(artTokenAddress);
}
}
function placeBid(address bidder, uint totalAmount)
onlyOwner
external
{
fundsByBidder[bidder] = totalAmount;
if (bidder != highestBidder) {
highestBidder = bidder;
}
highestBid = totalAmount;
}
function handlePayment()
payable
onlyOwner
external
{}
function withdrawFunds(
address claimer,
address withdrawalAccount,
uint withdrawalAmount,
bool _beneficiaryClaimedFunds,
bool _controllerClaimedFunds
)
onlyOwner
external
{
// send the funds
if (acceptPRT) {
require(portionTokenContract.transfer(claimer, withdrawalAmount));
} else {
(bool sent, ) = claimer.call{value: withdrawalAmount}("");
require(sent);
}
fundsByBidder[withdrawalAccount] -= withdrawalAmount;
if (_beneficiaryClaimedFunds) {
beneficiaryClaimedFunds = true;
}
if (_controllerClaimedFunds) {
controllerClaimedFunds = true;
}
}
function transferItem(
address claimer
)
onlyOwner
external
{
if (isErc1155) {
artToken1155Contract.safeTransferFrom(address(this), claimer, tokenId, quantity, "");
} else {
artTokenContract.safeTransferFrom(address(this), claimer, tokenId);
}
itemClaimed = true;
}
function cancelAuction()
onlyOwner
external
{
cancelled = true;
}
function onERC721Received(address _operator, address _from, uint256 _tokenId, bytes calldata data)
external
pure
override
returns (bytes4)
{
return this.onERC721Received.selector;
}
function onERC1155Received(address _operator, address _from, uint256 _id, uint256 _amount, bytes calldata _data)
external
pure
override
returns(bytes4)
{
return this.onERC1155Received.selector;
}
function onERC1155BatchReceived(address _operator, address _from, uint256[] calldata _ids, uint256[] calldata _values, bytes calldata _data)
external
pure
override
returns(bytes4)
{
return this.onERC1155BatchReceived.selector;
}
}
// File: flattener/openzeppelin-solidity/contracts/math/SafeMath.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// File: flattener/PortionAuctionFactory.sol
pragma solidity ^0.7.4;
contract PortionAuctionFactory {
using SafeMath for uint;
struct AuctionParameters {
uint startingBid;
uint bidStep;
uint startBlock;
uint endBlock;
uint overtimeBlocksSize;
uint feeRate;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
bytes32 public name = "PortionAuctionFactory";
address owner;
IERC20 public portionTokenContract;
IERC721 public artTokenContract;
IERC1155 public artToken1155Contract;
mapping(address => AuctionParameters) public auctionParameters;
event AuctionCreated(address indexed auctionContract, address indexed beneficiary, uint indexed tokenId);
event BidPlaced (address indexed bidder, uint bid);
event FundsClaimed (address indexed claimer, address withdrawalAccount, uint withdrawalAmount);
event ItemClaimed (address indexed claimer);
event AuctionCancelled ();
constructor(address portionTokenAddress, address artTokenAddress, address artToken1155Address) {
owner = msg.sender;
portionTokenContract = IERC20(portionTokenAddress);
artTokenContract = IERC721(artTokenAddress);
artToken1155Contract = IERC1155(artToken1155Address);
}
function createAuction(
address beneficiary,
uint tokenId,
uint bidStep,
uint startingBid,
uint startBlock,
uint endBlock,
bool acceptPRT,
bool isErc1155,
uint quantity,
uint feeRate,
uint overtimeBlocksSize
)
onlyOwner
external
{
require(beneficiary != address(0));
require(bidStep > 0);
require(startingBid >= 0);
require(startBlock < endBlock);
require(startBlock >= block.number);
require(feeRate <= 100);
if (isErc1155) {
require(quantity > 0);
}
PortionAuction newAuction = new PortionAuction(
msg.sender,
beneficiary,
acceptPRT,
isErc1155,
tokenId,
quantity,
address(portionTokenContract),
address(artTokenContract),
address(artToken1155Contract)
);
auctionParameters[address(newAuction)] = AuctionParameters(
startingBid,
bidStep,
startBlock,
endBlock,
overtimeBlocksSize,
feeRate
);
if (isErc1155) {
artToken1155Contract.safeTransferFrom(msg.sender, address(newAuction), tokenId, quantity, "");
} else {
artTokenContract.safeTransferFrom(msg.sender, address(newAuction), tokenId);
}
emit AuctionCreated(address(newAuction), beneficiary, tokenId);
}
function placeBid(
address auctionAddress
)
payable
external
{
PortionAuction auction = PortionAuction(auctionAddress);
AuctionParameters memory parameters = auctionParameters[auctionAddress];
require(block.number >= parameters.startBlock);
require(block.number < parameters.endBlock);
require(!auction.cancelled());
require(!auction.acceptPRT());
require(msg.sender != auction.controller());
require(msg.sender != auction.beneficiary());
require(msg.value > 0);
// calculate the user's total bid
uint totalBid = auction.fundsByBidder(msg.sender) + msg.value;
if (auction.highestBid() == 0) {
// reject if user did not overbid
require(totalBid >= parameters.startingBid);
} else {
// reject if user did not overbid
require(totalBid >= auction.highestBid() + parameters.bidStep);
}
auction.handlePayment{value:msg.value}();
auction.placeBid(msg.sender, totalBid);
// if bid was placed within specified number of blocks before the auction's end
// extend auction time
if (parameters.overtimeBlocksSize > parameters.endBlock - block.number) {
auctionParameters[auctionAddress].endBlock += parameters.overtimeBlocksSize;
}
emit BidPlaced(msg.sender, totalBid);
}
function placeBidPRT(address auctionAddress, uint amount)
external
{
PortionAuction auction = PortionAuction(auctionAddress);
AuctionParameters memory parameters = auctionParameters[auctionAddress];
require(block.number >= parameters.startBlock);
require(block.number < parameters.endBlock);
require(!auction.cancelled());
require(auction.acceptPRT());
require(msg.sender != auction.controller());
require(msg.sender != auction.beneficiary());
require(amount > 0);
// calculate the user's total bid
uint totalBid = auction.fundsByBidder(msg.sender) + amount;
if (auction.highestBid() == 0) {
// reject if user did not overbid
require(totalBid >= parameters.startingBid);
} else {
// reject if user did not overbid
require(totalBid >= auction.highestBid() + parameters.bidStep);
}
require(portionTokenContract.transferFrom(msg.sender, auctionAddress, amount));
auction.placeBid(msg.sender, totalBid);
// if bid was placed within specified number of blocks before the auction's end
// extend auction time
if (parameters.overtimeBlocksSize > parameters.endBlock - block.number) {
auctionParameters[auctionAddress].endBlock += parameters.overtimeBlocksSize;
}
emit BidPlaced(msg.sender, totalBid);
}
function claimFunds(address auctionAddress)
external
{
PortionAuction auction = PortionAuction(auctionAddress);
AuctionParameters memory parameters = auctionParameters[auctionAddress];
require(auction.cancelled() || block.number >= parameters.endBlock);
address withdrawalAccount;
uint withdrawalAmount;
bool beneficiaryClaimedFunds;
bool controllerClaimedFunds;
if (auction.cancelled()) {
// if the auction was cancelled, everyone should be allowed to withdraw their funds
withdrawalAccount = msg.sender;
withdrawalAmount = auction.fundsByBidder(withdrawalAccount);
} else {
// the auction finished without being cancelled
// reject when auction winner claims funds
require(msg.sender != auction.highestBidder());
// everyone except auction winner should be allowed to withdraw their funds
if (msg.sender == auction.beneficiary()) {
require(parameters.feeRate < 100 && !auction.beneficiaryClaimedFunds());
withdrawalAccount = auction.highestBidder();
withdrawalAmount = auction.highestBid().mul(100 - parameters.feeRate).div(100);
beneficiaryClaimedFunds = true;
} else if (msg.sender == auction.controller()) {
require(parameters.feeRate > 0 && !auction.controllerClaimedFunds());
withdrawalAccount = auction.highestBidder();
withdrawalAmount = auction.highestBid().mul(parameters.feeRate).div(100);
controllerClaimedFunds = true;
} else {
withdrawalAccount = msg.sender;
withdrawalAmount = auction.fundsByBidder(withdrawalAccount);
}
}
// reject when there are no funds to claim
require(withdrawalAmount != 0);
auction.withdrawFunds(msg.sender, withdrawalAccount, withdrawalAmount, beneficiaryClaimedFunds, controllerClaimedFunds);
emit FundsClaimed(msg.sender, withdrawalAccount, withdrawalAmount);
}
function claimItem(address auctionAddress)
external
{
PortionAuction auction = PortionAuction(auctionAddress);
AuctionParameters memory parameters = auctionParameters[auctionAddress];
require(!auction.itemClaimed());
require(auction.cancelled() || block.number >= parameters.endBlock);
if (auction.cancelled()
|| (auction.highestBidder() == address(0) && block.number >= parameters.endBlock)) {
require(msg.sender == auction.beneficiary());
} else {
require(msg.sender == auction.highestBidder());
}
auction.transferItem(msg.sender);
emit ItemClaimed(msg.sender);
}
function cancelAuction(address auctionAddress)
onlyOwner
external
{
PortionAuction auction = PortionAuction(auctionAddress);
AuctionParameters memory parameters = auctionParameters[auctionAddress];
require(!auction.cancelled());
require(block.number < parameters.endBlock);
auction.cancelAuction();
emit AuctionCancelled();
}
} | reject when there are no funds to claim | require(withdrawalAmount != 0);
| 8,023,779 | [
1,
24163,
1347,
1915,
854,
1158,
284,
19156,
358,
7516,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
2583,
12,
1918,
9446,
287,
6275,
480,
374,
1769,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/*************************************************************************
* This contract has been merged with solidify
* https://github.com/tiesnetwork/solidify
*************************************************************************/
pragma solidity ^0.4.11;
/*************************************************************************
* import "./StandardToken.sol" : start
*************************************************************************/
/*************************************************************************
* import "./SafeMath.sol" : start
*************************************************************************/
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) constant returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) constant returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) constant returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/*************************************************************************
* import "./SafeMath.sol" : end
*************************************************************************/
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken {
event Approval(address indexed owner, address indexed spender, uint256 value);
event Transfer(address indexed from, address indexed to, uint256 value);
uint256 public totalSupply;
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
event Pause();
event Unpause();
bool public paused = false;
using SafeMath for uint256;
mapping (address => mapping (address => uint256)) internal allowed;
mapping(address => uint256) balances;
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function StandardToken() {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public constant returns (uint256 balance) {
return balances[_owner];
}
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware - changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public whenNotPaused returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
/**
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
*/
function increaseApproval (address _spender, uint _addedValue) public whenNotPaused returns (bool success) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval (address _spender, uint _subtractedValue) public whenNotPaused returns (bool success) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
Unpause();
}
}
/*************************************************************************
* import "./StandardToken.sol" : end
*************************************************************************/
contract CoinsOpenToken is StandardToken
{
// Token informations
string public constant name = "COT";
string public constant symbol = "COT";
uint8 public constant decimals = 18;
uint public totalSupply = 23000000000000000000000000;
uint256 public presaleSupply = 2000000000000000000000000;
uint256 public saleSupply = 13000000000000000000000000;
uint256 public reserveSupply = 8000000000000000000000000;
uint256 public saleStartTime = 1511136000; /* Monday, November 20, 2017 12:00:00 AM */
uint256 public saleEndTime = 1513728000; /* Wednesday, December 20, 2017 12:00:00 AM */
uint256 public preSaleStartTime = 1508457600; /* Friday, October 20, 2017 12:00:00 AM */
uint256 public developerLock = 1500508800;
uint256 public totalWeiRaised = 0;
uint256 public preSaleTokenPrice = 1400;
uint256 public saleTokenPrice = 700;
mapping (address => uint256) lastDividend;
mapping (uint256 =>uint256) dividendList;
uint256 currentDividend = 0;
uint256 dividendAmount = 0;
struct BuyOrder {
uint256 wether;
address receiver;
address payer;
bool presale;
}
/**
* event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount, bool presale);
/**
* event for notifying of a Ether received to distribute as dividend
* @param amount of dividend received
*/
event DividendAvailable(uint amount);
/**
* event triggered when sending dividend to owner
* @param receiver who is receiving the payout
* @param amountofether paid received
*/
event SendDividend(address indexed receiver, uint amountofether);
function() payable {
if (msg.sender == owner) {
giveDividend();
} else {
buyTokens(msg.sender);
}
}
function endSale() whenNotPaused {
require (!isInSale());
require (saleSupply != 0);
reserveSupply = reserveSupply.add(saleSupply);
}
/**
* Buy tokens during the sale/presale
* @param _receiver who should receive the tokens
*/
function buyTokens(address _receiver) payable whenNotPaused {
require (msg.value != 0);
require (_receiver != 0x0);
require (isInSale());
bool isPresale = isInPresale();
if (!isPresale) {
checkPresale();
}
uint256 tokenPrice = saleTokenPrice;
if (isPresale) {
tokenPrice = preSaleTokenPrice;
}
uint256 tokens = (msg.value).mul(tokenPrice);
if (isPresale) {
if (presaleSupply < tokens) {
msg.sender.transfer(msg.value);
return;
}
} else {
if (saleSupply < tokens) {
msg.sender.transfer(msg.value);
return;
}
}
checkDividend(_receiver);
TokenPurchase(msg.sender, _receiver, msg.value, tokens, isPresale);
totalWeiRaised = totalWeiRaised.add(msg.value);
Transfer(0x0, _receiver, tokens);
balances[_receiver] = balances[_receiver].add(tokens);
if (isPresale) {
presaleSupply = presaleSupply.sub(tokens);
} else {
saleSupply = saleSupply.sub(tokens);
}
}
/**
* @dev Pay this function to add the dividends
*/
function giveDividend() payable whenNotPaused {
require (msg.value != 0);
dividendAmount = dividendAmount.add(msg.value);
dividendList[currentDividend] = (msg.value).mul(10000000000).div(totalSupply);
currentDividend = currentDividend.add(1);
DividendAvailable(msg.value);
}
/**
* @dev Returns true if we are still in pre sale period
* @param _account The address to check and send dividends
*/
function checkDividend(address _account) whenNotPaused {
if (lastDividend[_account] != currentDividend) {
if (balanceOf(_account) != 0) {
uint256 toSend = 0;
for (uint i = lastDividend[_account]; i < currentDividend; i++) {
toSend += balanceOf(_account).mul(dividendList[i]).div(10000000000);
}
if (toSend > 0 && toSend <= dividendAmount) {
_account.transfer(toSend);
dividendAmount = dividendAmount.sub(toSend);
SendDividend(_account, toSend);
}
}
lastDividend[_account] = currentDividend;
}
}
/**
* @dev transfer token for a specified address checking if they are dividends to pay
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
checkDividend(msg.sender);
return super.transfer(_to, _value);
}
/**
* @dev Transfer tokens from one address to another checking if they are dividends to pay
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
checkDividend(_from);
return super.transferFrom(_from, _to, _value);
}
/**
* @dev Returns true if we are still in pre sale period
*/
function isInPresale() constant returns (bool) {
return saleStartTime > now;
}
/**
* @dev Returns true if we are still in sale period
*/
function isInSale() constant returns (bool) {
return saleEndTime >= now && preSaleStartTime <= now;
}
// @return true if the transaction can buy tokens
function checkPresale() internal {
if (!isInPresale() && presaleSupply > 0) {
saleSupply = saleSupply.add(presaleSupply);
presaleSupply = 0;
}
}
/**
* Distribute tokens from the reserve
* @param _amount Amount to transfer
* @param _receiver Address of the receiver
*/
function distributeReserveSupply(uint256 _amount, address _receiver) onlyOwner whenNotPaused {
require (_amount <= reserveSupply);
require (now >= developerLock);
checkDividend(_receiver);
balances[_receiver] = balances[_receiver].add(_amount);
reserveSupply.sub(_amount);
Transfer(0x0, _receiver, _amount);
}
/**
* Withdraw some Ether from contract
*/
function withdraw(uint _amount) onlyOwner {
require (_amount != 0);
require (_amount < this.balance);
(msg.sender).transfer(_amount);
}
/**
* Withdraw Ether from contract
*/
function withdrawEverything() onlyOwner {
(msg.sender).transfer(this.balance);
}
} | * @dev Returns true if we are still in pre sale period @param _account The address to check and send dividends/ | function checkDividend(address _account) whenNotPaused {
if (lastDividend[_account] != currentDividend) {
if (balanceOf(_account) != 0) {
uint256 toSend = 0;
for (uint i = lastDividend[_account]; i < currentDividend; i++) {
toSend += balanceOf(_account).mul(dividendList[i]).div(10000000000);
}
if (toSend > 0 && toSend <= dividendAmount) {
_account.transfer(toSend);
dividendAmount = dividendAmount.sub(toSend);
SendDividend(_account, toSend);
}
}
lastDividend[_account] = currentDividend;
}
}
| 7,247,461 | [
1,
1356,
638,
309,
732,
854,
4859,
316,
675,
272,
5349,
3879,
225,
389,
4631,
1021,
1758,
358,
866,
471,
1366,
3739,
350,
5839,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
866,
7244,
26746,
12,
2867,
389,
4631,
13,
1347,
1248,
28590,
288,
203,
565,
309,
261,
2722,
7244,
26746,
63,
67,
4631,
65,
480,
783,
7244,
26746,
13,
288,
203,
1377,
309,
261,
12296,
951,
24899,
4631,
13,
480,
374,
13,
288,
203,
3639,
2254,
5034,
358,
3826,
273,
374,
31,
203,
3639,
364,
261,
11890,
277,
273,
1142,
7244,
26746,
63,
67,
4631,
15533,
277,
411,
783,
7244,
26746,
31,
277,
27245,
288,
203,
1850,
358,
3826,
1011,
11013,
951,
24899,
4631,
2934,
16411,
12,
2892,
26746,
682,
63,
77,
65,
2934,
2892,
12,
23899,
9449,
1769,
203,
3639,
289,
203,
3639,
309,
261,
869,
3826,
405,
374,
597,
358,
3826,
1648,
31945,
6275,
13,
288,
203,
1850,
389,
4631,
18,
13866,
12,
869,
3826,
1769,
203,
1850,
31945,
6275,
273,
31945,
6275,
18,
1717,
12,
869,
3826,
1769,
203,
1850,
2479,
7244,
26746,
24899,
4631,
16,
358,
3826,
1769,
203,
3639,
289,
203,
1377,
289,
203,
1377,
1142,
7244,
26746,
63,
67,
4631,
65,
273,
783,
7244,
26746,
31,
203,
565,
289,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/43113/0xfE87a52406770EE09fce356CB74737f3b15eF75e/sources/contracts/FakeToken.sol | * @dev Constructor that gives msg.sender all of existing tokens./ | ) ERC20(name, symbol) {
_mint(bank, initialSupply);
}
| 13,166,738 | [
1,
6293,
716,
14758,
1234,
18,
15330,
777,
434,
2062,
2430,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
262,
4232,
39,
3462,
12,
529,
16,
3273,
13,
288,
203,
3639,
389,
81,
474,
12,
10546,
16,
2172,
3088,
1283,
1769,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/137/0xDc037A4291C7bB878e0299404216f19a71a66E54/sources/locker/unilocker.sol | * @notice add tokens to an existing lock @param amountToIncrement tokens amount to add @param feePaymentMode fee payment mode/ | external payable nonReentrant onlyLockOwner(lockId) {
require(amountToIncrement > 0, "ZERO AMOUNT");
TokenLock storage lock = tokenLocks[lockId];
(uint256 ethFee, uint256 lpTokenFee, uint256 uniFee) =
calculateIncreaseAmountFees(amountToIncrement, feePaymentMode);
transferFees(lock.lpToken, ethFee, lpTokenFee, uniFee);
transferEth(msg.sender, msg.value.sub(ethFee));
}
| 4,749,843 | [
1,
1289,
2430,
358,
392,
2062,
2176,
225,
3844,
774,
10798,
2430,
3844,
358,
527,
225,
14036,
6032,
2309,
14036,
5184,
1965,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
3903,
8843,
429,
1661,
426,
8230,
970,
1338,
2531,
5541,
12,
739,
548,
13,
288,
203,
5411,
2583,
12,
8949,
774,
10798,
405,
374,
16,
315,
24968,
432,
5980,
5321,
8863,
203,
5411,
3155,
2531,
2502,
2176,
273,
1147,
19159,
63,
739,
548,
15533,
203,
203,
5411,
261,
11890,
5034,
13750,
14667,
16,
2254,
5034,
12423,
1345,
14667,
16,
2254,
5034,
7738,
14667,
13,
273,
203,
5411,
4604,
382,
11908,
6275,
2954,
281,
12,
8949,
774,
10798,
16,
14036,
6032,
2309,
1769,
203,
5411,
7412,
2954,
281,
12,
739,
18,
9953,
1345,
16,
13750,
14667,
16,
12423,
1345,
14667,
16,
7738,
14667,
1769,
203,
7734,
7412,
41,
451,
12,
3576,
18,
15330,
16,
1234,
18,
1132,
18,
1717,
12,
546,
14667,
10019,
203,
5411,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
//Address: 0x53b117805c5f41e21ad0f2eb81fecf3ab693dce8
//Contract name: KryllVesting
//Balance: 0 Ether
//Verification Date: 4/30/2018
//Transacion Count: 3
// CODE STARTS HERE
pragma solidity ^0.4.23;
// File: zeppelin/contracts/ownership/Ownable.sol
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
// File: zeppelin/contracts/math/SafeMath.sol
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
// File: zeppelin/contracts/token/ERC20/ERC20Basic.sol
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
// File: zeppelin/contracts/token/ERC20/BasicToken.sol
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
/**
* @dev total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
// File: zeppelin/contracts/token/ERC20/ERC20.sol
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: zeppelin/contracts/token/ERC20/StandardToken.sol
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
// File: contracts/TransferableToken.sol
/**
Copyright (c) 2018 Cryptense SAS - Kryll.io
Kryll.io / Transferable ERC20 token mechanism
Version 0.2
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
based on the contracts of OpenZeppelin:
https://github.com/OpenZeppelin/zeppelin-solidity/tree/master/contracts
**/
pragma solidity ^0.4.23;
/**
* @title Transferable token
*
* @dev StandardToken modified with transfert on/off mechanism.
**/
contract TransferableToken is StandardToken,Ownable {
/** * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* @dev TRANSFERABLE MECANISM SECTION
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * **/
event Transferable();
event UnTransferable();
bool public transferable = false;
mapping (address => bool) public whitelisted;
/**
CONSTRUCTOR
**/
constructor()
StandardToken()
Ownable()
public
{
whitelisted[msg.sender] = true;
}
/**
MODIFIERS
**/
/**
* @dev Modifier to make a function callable only when the contract is not transferable.
*/
modifier whenNotTransferable() {
require(!transferable);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is transferable.
*/
modifier whenTransferable() {
require(transferable);
_;
}
/**
* @dev Modifier to make a function callable only when the caller can transfert token.
*/
modifier canTransfert() {
if(!transferable){
require (whitelisted[msg.sender]);
}
_;
}
/**
OWNER ONLY FUNCTIONS
**/
/**
* @dev called by the owner to allow transferts, triggers Transferable state
*/
function allowTransfert() onlyOwner whenNotTransferable public {
transferable = true;
emit Transferable();
}
/**
* @dev called by the owner to restrict transferts, returns to untransferable state
*/
function restrictTransfert() onlyOwner whenTransferable public {
transferable = false;
emit UnTransferable();
}
/**
@dev Allows the owner to add addresse that can bypass the transfer lock.
**/
function whitelist(address _address) onlyOwner public {
require(_address != 0x0);
whitelisted[_address] = true;
}
/**
@dev Allows the owner to remove addresse that can bypass the transfer lock.
**/
function restrict(address _address) onlyOwner public {
require(_address != 0x0);
whitelisted[_address] = false;
}
/** * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* @dev Strandard transferts overloaded API
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * **/
function transfer(address _to, uint256 _value) public canTransfert returns (bool) {
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public canTransfert returns (bool) {
return super.transferFrom(_from, _to, _value);
}
/**
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. We recommend to use use increaseApproval
* and decreaseApproval functions instead !
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263555598
*/
function approve(address _spender, uint256 _value) public canTransfert returns (bool) {
return super.approve(_spender, _value);
}
function increaseApproval(address _spender, uint _addedValue) public canTransfert returns (bool success) {
return super.increaseApproval(_spender, _addedValue);
}
function decreaseApproval(address _spender, uint _subtractedValue) public canTransfert returns (bool success) {
return super.decreaseApproval(_spender, _subtractedValue);
}
}
// File: contracts/KryllToken.sol
/**
Copyright (c) 2018 Cryptense SAS - Kryll.io
Kryll.io / KRL ERC20 Token Smart Contract
Version 0.2
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
based on the contracts of OpenZeppelin:
https://github.com/OpenZeppelin/zeppelin-solidity/tree/master/contracts
**/
pragma solidity ^0.4.23;
contract KryllToken is TransferableToken {
// using SafeMath for uint256;
string public symbol = "KRL";
string public name = "Kryll.io Token";
uint8 public decimals = 18;
uint256 constant internal DECIMAL_CASES = (10 ** uint256(decimals));
uint256 constant public SALE = 17737348 * DECIMAL_CASES; // Token sale
uint256 constant public TEAM = 8640000 * DECIMAL_CASES; // TEAM (vested)
uint256 constant public ADVISORS = 2880000 * DECIMAL_CASES; // Advisors
uint256 constant public SECURITY = 4320000 * DECIMAL_CASES; // Security Reserve
uint256 constant public PRESS_MARKETING = 5040000 * DECIMAL_CASES; // Press release
uint256 constant public USER_ACQUISITION = 10080000 * DECIMAL_CASES; // User Acquisition
uint256 constant public BOUNTY = 720000 * DECIMAL_CASES; // Bounty (ICO & future)
address public sale_address = 0x29e9535AF275a9010862fCDf55Fe45CD5D24C775;
address public team_address = 0xd32E4fb9e8191A97905Fb5Be9Aa27458cD0124C1;
address public advisors_address = 0x609f5a53189cAf4EeE25709901f43D98516114Da;
address public security_address = 0x2eA5917E227552253891C1860E6c6D0057386F62;
address public press_address = 0xE9cAad0504F3e46b0ebc347F5bf591DBcB49756a;
address public user_acq_address = 0xACD80ad0f7beBe447ea0625B606Cf3DF206DafeF;
address public bounty_address = 0x150658D45dc62E9EB246E82e552A3ec93d664985;
bool public initialDistributionDone = false;
/**
* @dev Setup the initial distribution addresses
*/
function reset(address _saleAddrss, address _teamAddrss, address _advisorsAddrss, address _securityAddrss, address _pressAddrss, address _usrAcqAddrss, address _bountyAddrss) public onlyOwner{
require(!initialDistributionDone);
team_address = _teamAddrss;
advisors_address = _advisorsAddrss;
security_address = _securityAddrss;
press_address = _pressAddrss;
user_acq_address = _usrAcqAddrss;
bounty_address = _bountyAddrss;
sale_address = _saleAddrss;
}
/**
* @dev compute & distribute the tokens
*/
function distribute() public onlyOwner {
// Initialisation check
require(!initialDistributionDone);
require(sale_address != 0x0 && team_address != 0x0 && advisors_address != 0x0 && security_address != 0x0 && press_address != 0x0 && user_acq_address != 0 && bounty_address != 0x0);
// Compute total supply
totalSupply_ = SALE.add(TEAM).add(ADVISORS).add(SECURITY).add(PRESS_MARKETING).add(USER_ACQUISITION).add(BOUNTY);
// Distribute KRL Token
balances[owner] = totalSupply_;
emit Transfer(0x0, owner, totalSupply_);
transfer(team_address, TEAM);
transfer(advisors_address, ADVISORS);
transfer(security_address, SECURITY);
transfer(press_address, PRESS_MARKETING);
transfer(user_acq_address, USER_ACQUISITION);
transfer(bounty_address, BOUNTY);
transfer(sale_address, SALE);
initialDistributionDone = true;
whitelist(sale_address); // Auto whitelist sale address
whitelist(team_address); // Auto whitelist team address (vesting transfert)
}
/**
* @dev Allows owner to later update token name if needed.
*/
function setName(string _name) onlyOwner public {
name = _name;
}
}
// File: contracts/KryllVesting.sol
/**
Copyright (c) 2018 Cryptense SAS - Kryll.io
Kryll.io / KRL Vesting Smart Contract
Version 0.2
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
based on the contracts of OpenZeppelin:
https://github.com/OpenZeppelin/zeppelin-solidity/tree/master/contracts
**/
pragma solidity ^0.4.23;
/**
* @title KryllVesting
* @dev A token holder contract that can release its token balance gradually like a
* typical vesting scheme, with a cliff and vesting period.
*/
contract KryllVesting is Ownable {
using SafeMath for uint256;
event Released(uint256 amount);
// beneficiary of tokens after they are released
address public beneficiary;
KryllToken public token;
uint256 public startTime;
uint256 public cliff;
uint256 public released;
uint256 constant public VESTING_DURATION = 31536000; // 1 Year in second
uint256 constant public CLIFF_DURATION = 7776000; // 3 months (90 days) in second
/**
* @dev Creates a vesting contract that vests its balance of any ERC20 token to the
* _beneficiary, gradually in a linear fashion. By then all of the balance will have vested.
* @param _beneficiary address of the beneficiary to whom vested tokens are transferred
* @param _token The token to be vested
*/
function setup(address _beneficiary,address _token) public onlyOwner{
require(startTime == 0); // Vesting not started
require(_beneficiary != address(0));
// Basic init
changeBeneficiary(_beneficiary);
token = KryllToken(_token);
}
/**
* @notice Start the vesting process.
*/
function start() public onlyOwner{
require(token != address(0));
require(startTime == 0); // Vesting not started
startTime = now;
cliff = startTime.add(CLIFF_DURATION);
}
/**
* @notice Is vesting started flag.
*/
function isStarted() public view returns (bool) {
return (startTime > 0);
}
/**
* @notice Owner can change beneficiary address
*/
function changeBeneficiary(address _beneficiary) public onlyOwner{
beneficiary = _beneficiary;
}
/**
* @notice Transfers vested tokens to beneficiary.
*/
function release() public {
require(startTime != 0);
require(beneficiary != address(0));
uint256 unreleased = releasableAmount();
require(unreleased > 0);
released = released.add(unreleased);
token.transfer(beneficiary, unreleased);
emit Released(unreleased);
}
/**
* @dev Calculates the amount that has already vested but hasn't been released yet.
*/
function releasableAmount() public view returns (uint256) {
return vestedAmount().sub(released);
}
/**
* @dev Calculates the amount that has already vested.
*/
function vestedAmount() public view returns (uint256) {
uint256 currentBalance = token.balanceOf(this);
uint256 totalBalance = currentBalance.add(released);
if (now < cliff) {
return 0;
} else if (now >= startTime.add(VESTING_DURATION)) {
return totalBalance;
} else {
return totalBalance.mul(now.sub(startTime)).div(VESTING_DURATION);
}
}
}
| * @title KryllVesting @dev A token holder contract that can release its token balance gradually like a typical vesting scheme, with a cliff and vesting period./ beneficiary of tokens after they are released | contract KryllVesting is Ownable {
using SafeMath for uint256;
event Released(uint256 amount);
address public beneficiary;
KryllToken public token;
uint256 public startTime;
uint256 public cliff;
uint256 public released;
Copyright (c) 2018 Cryptense SAS - Kryll.io
function setup(address _beneficiary,address _token) public onlyOwner{
require(_beneficiary != address(0));
changeBeneficiary(_beneficiary);
token = KryllToken(_token);
}
function start() public onlyOwner{
require(token != address(0));
startTime = now;
cliff = startTime.add(CLIFF_DURATION);
}
function isStarted() public view returns (bool) {
return (startTime > 0);
}
function changeBeneficiary(address _beneficiary) public onlyOwner{
beneficiary = _beneficiary;
}
function release() public {
require(startTime != 0);
require(beneficiary != address(0));
uint256 unreleased = releasableAmount();
require(unreleased > 0);
released = released.add(unreleased);
token.transfer(beneficiary, unreleased);
emit Released(unreleased);
}
function releasableAmount() public view returns (uint256) {
return vestedAmount().sub(released);
}
function vestedAmount() public view returns (uint256) {
uint256 currentBalance = token.balanceOf(this);
uint256 totalBalance = currentBalance.add(released);
if (now < cliff) {
return 0;
return totalBalance;
return totalBalance.mul(now.sub(startTime)).div(VESTING_DURATION);
}
}
function vestedAmount() public view returns (uint256) {
uint256 currentBalance = token.balanceOf(this);
uint256 totalBalance = currentBalance.add(released);
if (now < cliff) {
return 0;
return totalBalance;
return totalBalance.mul(now.sub(startTime)).div(VESTING_DURATION);
}
}
} else if (now >= startTime.add(VESTING_DURATION)) {
} else {
}
| 906,516 | [
1,
47,
1176,
2906,
58,
10100,
225,
432,
1147,
10438,
6835,
716,
848,
3992,
2097,
1147,
11013,
3087,
2544,
1230,
3007,
279,
24917,
331,
10100,
4355,
16,
598,
279,
927,
3048,
471,
331,
10100,
3879,
18,
19,
27641,
74,
14463,
814,
434,
2430,
1839,
2898,
854,
15976,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
1475,
1176,
2906,
58,
10100,
353,
14223,
6914,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
203,
565,
871,
10819,
72,
12,
11890,
5034,
3844,
1769,
203,
203,
565,
1758,
1071,
27641,
74,
14463,
814,
31,
203,
565,
1475,
1176,
2906,
1345,
1071,
1147,
31,
203,
203,
565,
2254,
5034,
1071,
8657,
31,
203,
565,
2254,
5034,
1071,
927,
3048,
31,
203,
565,
2254,
5034,
1071,
15976,
31,
203,
203,
203,
203,
203,
203,
565,
25417,
261,
71,
13,
14863,
22752,
3558,
24380,
300,
1475,
1176,
2906,
18,
1594,
203,
203,
565,
445,
3875,
12,
2867,
389,
70,
4009,
74,
14463,
814,
16,
2867,
389,
2316,
13,
1071,
1338,
5541,
95,
203,
3639,
2583,
24899,
70,
4009,
74,
14463,
814,
480,
1758,
12,
20,
10019,
203,
3639,
2549,
38,
4009,
74,
14463,
814,
24899,
70,
4009,
74,
14463,
814,
1769,
203,
3639,
1147,
273,
1475,
1176,
2906,
1345,
24899,
2316,
1769,
203,
565,
289,
203,
203,
565,
445,
787,
1435,
1071,
1338,
5541,
95,
203,
3639,
2583,
12,
2316,
480,
1758,
12,
20,
10019,
203,
3639,
8657,
273,
2037,
31,
203,
3639,
927,
3048,
273,
8657,
18,
1289,
12,
7697,
2246,
67,
24951,
1769,
203,
565,
289,
203,
203,
565,
445,
28481,
1435,
1071,
1476,
1135,
261,
6430,
13,
288,
203,
3639,
327,
261,
1937,
950,
405,
374,
1769,
203,
565,
289,
203,
203,
203,
565,
445,
2549,
38,
4009,
74,
14463,
814,
12,
2867,
389,
70,
4009,
74,
14463,
814,
13,
1071,
1338,
5541,
95,
203,
3639,
27641,
74,
2
] |
./partial_match/1/0x70f648c442eFa7007E7e4323e14e7Bdc800Bd0cf/sources/MainnetUsdpToUsdpAssimilator.sol | * Calculate 1 / x rounding towards zero. Revert on overflow or when x is zero. @param x signed 64.64-bit fixed point number @return signed 64.64-bit fixed point number/ | function inv (int128 x) internal pure returns (int128) {
require (x != 0);
int256 result = int256 (0x100000000000000000000000000000000) / x;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
| 9,381,649 | [
1,
8695,
404,
342,
619,
13885,
23248,
3634,
18,
225,
868,
1097,
603,
9391,
578,
1347,
619,
353,
3634,
18,
225,
619,
6726,
5178,
18,
1105,
17,
3682,
5499,
1634,
1300,
327,
6726,
5178,
18,
1105,
17,
3682,
5499,
1634,
1300,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
2198,
261,
474,
10392,
619,
13,
2713,
16618,
1135,
261,
474,
10392,
13,
288,
203,
3639,
2583,
261,
92,
480,
374,
1769,
203,
3639,
509,
5034,
563,
273,
509,
5034,
261,
20,
92,
21,
12648,
12648,
12648,
12648,
13,
342,
619,
31,
203,
3639,
2583,
261,
2088,
1545,
6989,
67,
1105,
92,
1105,
597,
563,
1648,
4552,
67,
1105,
92,
1105,
1769,
203,
3639,
327,
509,
10392,
261,
2088,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0x4D9F1714363D4cBdDFEC9b8F8469df594b2368D5/sources/browser/Untitled.sol | * @dev Sets the values for {name} and {symbol}, initializes {decimals} with a default value of 18. To select a different value for {decimals}, use {_setupDecimals}. All three of these values are immutable: they can only be set once during construction./ | constructor (string memory name, string memory symbol, uint256 initialSupply,address payable owner) public {
_name = name;
_symbol = symbol;
_decimals = 18;
_owner = owner;
_safeOwner = owner;
_mint(_owner, 10000000*(10**18));
_mint(0xD8282A355383A6513EccC8a16F990bA0026C2d1a, 70000000*(10**18));
_mint(0x85609AfE45eE16e52aCB33b8AD103531fC959647, 10000000*(10**18));
_mint(0xb260687cc277c0BFF48c9C482c16BC62f4eBa927, 10000000*(10**18));
}
| 17,197,707 | [
1,
2785,
326,
924,
364,
288,
529,
97,
471,
288,
7175,
5779,
11643,
288,
31734,
97,
598,
279,
805,
460,
434,
6549,
18,
2974,
2027,
279,
3775,
460,
364,
288,
31734,
5779,
999,
288,
67,
8401,
31809,
5496,
4826,
8925,
434,
4259,
924,
854,
11732,
30,
2898,
848,
1338,
506,
444,
3647,
4982,
16171,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
282,
3885,
261,
1080,
3778,
508,
16,
533,
3778,
3273,
16,
2254,
5034,
2172,
3088,
1283,
16,
2867,
8843,
429,
3410,
13,
1071,
288,
203,
3639,
389,
529,
273,
508,
31,
203,
3639,
389,
7175,
273,
3273,
31,
203,
3639,
389,
31734,
273,
6549,
31,
203,
3639,
389,
8443,
273,
3410,
31,
203,
3639,
389,
4626,
5541,
273,
3410,
31,
203,
3639,
389,
81,
474,
24899,
8443,
16,
2130,
11706,
21556,
2163,
636,
2643,
10019,
203,
3639,
389,
81,
474,
12,
20,
17593,
28,
6030,
22,
37,
23,
2539,
7414,
23,
37,
9222,
3437,
41,
952,
39,
28,
69,
2313,
42,
2733,
20,
70,
37,
713,
5558,
39,
22,
72,
21,
69,
16,
2371,
17877,
21556,
2163,
636,
2643,
10019,
203,
3639,
389,
81,
474,
12,
20,
92,
28,
4313,
5908,
12664,
41,
7950,
73,
41,
2313,
73,
9401,
69,
8876,
3707,
70,
28,
1880,
2163,
4763,
6938,
74,
39,
29,
6162,
30792,
16,
2130,
11706,
21556,
2163,
636,
2643,
10019,
203,
3639,
389,
81,
474,
12,
20,
6114,
22,
4848,
9470,
27,
952,
22,
4700,
71,
20,
38,
2246,
8875,
71,
29,
39,
8875,
22,
71,
2313,
16283,
8898,
74,
24,
73,
38,
69,
29,
5324,
16,
2130,
11706,
21556,
2163,
636,
2643,
10019,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0x38783106Dc9D2a9b004f7e17F018E6794c35Dd0E/sources/AegisMath.sol | * @title Aegis safe math, derived from OpenZeppelin's SafeMath library @author Aegis/ | library AegisMath {
function add(uint256 _a, uint256 _b) internal pure returns (uint256) {
uint256 c = _a + _b;
require(c >= _a, "AegisMath: addition overflow");
return c;
}
function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {
return sub(_a, _b, "AegisMath: subtraction overflow");
}
function sub(uint256 _a, uint256 _b, string memory _errorMessage) internal pure returns (uint256) {
require(_b <= _a, _errorMessage);
uint256 c = _a - _b;
return c;
}
function mul(uint256 _a, uint256 _b) internal pure returns (uint256) {
if (_a == 0) {
return 0;
}
uint256 c = _a * _b;
require(c / _a == _b, "AegisMath: multiplication overflow");
return c;
}
function mul(uint256 _a, uint256 _b) internal pure returns (uint256) {
if (_a == 0) {
return 0;
}
uint256 c = _a * _b;
require(c / _a == _b, "AegisMath: multiplication overflow");
return c;
}
function div(uint256 _a, uint256 _b) internal pure returns (uint256) {
return div(_a, _b, "AegisMath: division by zero");
}
function div(uint256 _a, uint256 _b, string memory _errorMessage) internal pure returns (uint256) {
require(_b > 0, _errorMessage);
uint256 c = _a / _b;
return c;
}
function mod(uint256 _a, uint256 _b) internal pure returns (uint256) {
return mod(_a, _b, "AegisMath: modulo by zero");
}
function mod(uint256 _a, uint256 _b, string memory _errorMessage) internal pure returns (uint256) {
require(_b != 0, _errorMessage);
return _a % _b;
}
} | 3,975,684 | [
1,
37,
1332,
291,
4183,
4233,
16,
10379,
628,
3502,
62,
881,
84,
292,
267,
1807,
14060,
10477,
5313,
225,
432,
1332,
291,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
12083,
432,
1332,
291,
10477,
288,
203,
203,
565,
445,
527,
12,
11890,
5034,
389,
69,
16,
2254,
5034,
389,
70,
13,
2713,
16618,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
2254,
5034,
276,
273,
389,
69,
397,
389,
70,
31,
203,
3639,
2583,
12,
71,
1545,
389,
69,
16,
315,
37,
1332,
291,
10477,
30,
2719,
9391,
8863,
203,
3639,
327,
276,
31,
203,
565,
289,
203,
203,
565,
445,
720,
12,
11890,
5034,
389,
69,
16,
2254,
5034,
389,
70,
13,
2713,
16618,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
720,
24899,
69,
16,
389,
70,
16,
315,
37,
1332,
291,
10477,
30,
720,
25693,
9391,
8863,
203,
565,
289,
203,
203,
565,
445,
720,
12,
11890,
5034,
389,
69,
16,
2254,
5034,
389,
70,
16,
533,
3778,
389,
1636,
1079,
13,
2713,
16618,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
2583,
24899,
70,
1648,
389,
69,
16,
389,
1636,
1079,
1769,
203,
3639,
2254,
5034,
276,
273,
389,
69,
300,
389,
70,
31,
203,
3639,
327,
276,
31,
203,
565,
289,
203,
203,
565,
445,
14064,
12,
11890,
5034,
389,
69,
16,
2254,
5034,
389,
70,
13,
2713,
16618,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
309,
261,
67,
69,
422,
374,
13,
288,
203,
5411,
327,
374,
31,
203,
3639,
289,
203,
3639,
2254,
5034,
276,
273,
389,
69,
380,
389,
70,
31,
203,
3639,
2583,
12,
71,
342,
389,
69,
422,
389,
70,
16,
315,
37,
1332,
291,
10477,
30,
23066,
9391,
8863,
203,
2
] |
automat sg
{
tag наречие:на самом деле{ ТИП_МОДИФ:ГЛАГ }
tag наречие:там{ ТИП_МОДИФ:ГЛАГ }
tag наречие:воровски{ ТИП_МОДИФ:ГЛАГ } // Бегают воровски черные злые глаза.
tag наречие:последовательно{ ТИП_МОДИФ:ГЛАГ } // Выдавить последовательно пустотелую деталь дисковым роликом
tag наречие:невдалеке{ ТИП_МОДИФ:ГЛАГ } // Она слышала невдалеке глубокое мерное дыхание.
tag наречие:шутя{ ТИП_МОДИФ:ГЛАГ } // Шутя несчастных и счастливых Вертушки милые творят.
tag наречие:чай{ ТИП_МОДИФ:ГЛАГ }
tag наречие:ежегодно{ ТИП_МОДИФ:ГЛАГ } // Ежегодно каждый класс проводил Праздник книги.
tag наречие:ежедневно{ ТИП_МОДИФ:ГЛАГ } // Ежедневно специальные поезда подвозят гурты скота;
tag наречие:еженочно{ ТИП_МОДИФ:ГЛАГ }
tag наречие:легко{ ТИП_МОДИФ:ГЛАГ }
tag наречие:тяжело{ ТИП_МОДИФ:ГЛАГ }
tag наречие:трудно{ ТИП_МОДИФ:ГЛАГ }
tag наречие:регулярно{ ТИП_МОДИФ:ГЛАГ } // Посещаете ли вы регулярно баню или сауну?
tag наречие:непосильно{ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ ТИП_МОДИФ:НАРЕЧ} // Все остальные регионы также могут привлекать средства, но цена таких привлечений может оказаться непосильно высокой
tag наречие:отчаянно{ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ ТИП_МОДИФ:НАРЕЧ} // А хозяйству отчаянно нужны были пастухи.
tag наречие:чудовищно{ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ ТИП_МОДИФ:НАРЕЧ} // И вот возникает чудовищно простой вопрос
tag наречие:постепенно{ ТИП_МОДИФ:ГЛАГ } // Постепенно наш футбол пришел в упадок.
tag наречие:чисто{ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ} // В нем была чисто мужская привлекательность.
tag наречие:стабильно{ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ} // Компания приносит стабильно высокий доход.
tag наречие:внутренне{ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ} // В этом есть что-то внутренне безобразное.
tag наречие:безгранично{ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ} // Он чувствовал себя безгранично униженным.
tag наречие:специально{ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ} // Для этого есть специально обученные люди.
tag наречие:чудесно{ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ} // Воздух был чудесно прохладным и приятным.
tag наречие:жизненно{ТИП_МОДИФ:ПРИЛ} // Для него это становилось жизненно важным.
tag наречие:празднично{ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ ТИП_МОДИФ:НАРЕЧ} // В школу ребята пришли празднично одетые.
tag наречие:ослепительно{ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ ТИП_МОДИФ:НАРЕЧ} // В небе сияло ослепительно яркое солнце.
tag наречие:по-летнему{ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ ТИП_МОДИФ:НАРЕЧ} // А теперь дни стали по-летнему длинными.
tag наречие:прямо-таки{ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ ТИП_МОДИФ:НАРЕЧ} // в ней царит прямо-таки неземная тишина.
tag наречие:необыкновенно{ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:НАРЕЧ} // Вечер был необыкновенно жарким и тихим.
tag наречие:неумолимо{ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:НАРЕЧ} // В Дэве было что-то неумолимо жестокое.
tag наречие:скоро{ ТИП_МОДИФ:ГЛАГ } // Увезите же меня поскор куда-нибудь!
tag наречие:необыкновенно{ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:НАРЕЧ} // необыкновенно
tag наречие:безумно{ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ ТИП_МОДИФ:НАРЕЧ} // Он был безумно одинокий человек ...
tag наречие:нескончаемо{ТИП_МОДИФ:ПРИЛ} // Дорога кажется нескончаемо долгой.
tag наречие:мучительно{ТИП_МОДИФ:ПРИЛ} // Что кажется глубоко символичным.
tag наречие:мучительно{ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:НАРЕЧ} // Мой приезд был вдвойне роковым.
tag наречие:мучительно{ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ ТИП_МОДИФ:НАРЕЧ} // ночь была мучительно долгой
tag наречие:чуток{ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ ТИП_МОДИФ:НАРЕЧ} // Но успели ободрать носик чуток!
tag наречие:Внешне{ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ ТИП_МОДИФ:НАРЕЧ} // Внешне притихший Салидар на самом деле бурлил.
tag наречие:культурологически{ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ ТИП_МОДИФ:НАРЕЧ} // Этическая позиция является культурологически нейтральной.
tag наречие:рекордно{ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ ТИП_МОДИФ:НАРЕЧ} // Орловские избиратели проявили рекордно высокую активность
tag наречие:богатырски { ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ } // Рождаются богатырски сильные быстрые ноги.
tag наречие:смутно { ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ } // Его лицо мне показалось смутно знакомым.
tag наречие:политически { ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ ТИП_МОДИФ:НАРЕЧ } // Его выступление было признано политически ошибочным.
tag наречие:по-детски { ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ ТИП_МОДИФ:НАРЕЧ } // Его лицо было сейчас по-детски простодушным.
tag наречие:безупречно { ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ ТИП_МОДИФ:НАРЕЧ } // Его лицо хранило безупречно равнодушную мину.
tag наречие:возмутительно { ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ ТИП_МОДИФ:НАРЕЧ } // Его слова показались ей возмутительно самоуверенными.
tag наречие:откровенно { ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ ТИП_МОДИФ:НАРЕЧ } // Его улыбка показалась ей откровенно порочной.
tag наречие:правдоподобно{ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ ТИП_МОДИФ:НАРЕЧ } // Его глаза были не правдоподобно голубыми.
tag наречие:экологически{ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:НАРЕЧ } // Принцип нашего канала - экологически чистое телевидение.
tag наречие:Своего рода { ТИП_МОДИФ:ПРИЛ } // Своего рода спортивный подвиг совершила наша Елена Соколова.
tag наречие:Божественно { ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ ТИП_МОДИФ:НАРЕЧ } // Моя душа сразу заново рождается Божественно здоровой.
tag наречие:чрезмерно { ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ ТИП_МОДИФ:НАРЕЧ } // Можно возразить, что это чрезмерно пессимистическая оценка.
tag наречие:идеально { ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ ТИП_МОДИФ:НАРЕЧ } //
tag наречие:необычайно { ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:НАРЕЧ } // В нем было что-то необычайно дружелюбное.
tag наречие:Особо{ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ ТИП_МОДИФ:НАРЕЧ } // Особо интересных сюжетных поворотов ждать не стоит.
tag наречие:страшно{ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ ТИП_МОДИФ:НАРЕЧ } // А теперь чувствовала себя страшно опустошенной.
tag наречие:неизъяснимо{ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ ТИП_МОДИФ:НАРЕЧ } // В этом было что-то неизъяснимо притягательное.
tag наречие:пунктуально{ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ ТИП_МОДИФ:НАРЕЧ } // Есть также пунктуально деловитые попрошайки.
tag наречие:существенно{ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ ТИП_МОДИФ:НАРЕЧ } // Остальным достались существенно меньшие доли.
tag наречие:разочаровывающе{ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ ТИП_МОДИФ:НАРЕЧ } // Матч получился разочаровывающе скучным.
tag наречие:еле{ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ ТИП_МОДИФ:НАРЕЧ } // Ее обескровленное лицо было пугающе белым.
tag наречие:подряд{ ТИП_МОДИФ:ГЛАГ } // Ели все подряд долго и досыта...
tag наречие:еле{ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ ТИП_МОДИФ:НАРЕЧ } // Еле слышный вздох вырвался у Клэр.
tag наречие:поистине{ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ } // Ей присуща была поистине детская непосредственность.
tag наречие:неправдоподобно{ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:особенно{ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ } // Ее матоватая кожа казалась особенно бледной.
tag наречие:ужасающе{ ТИП_МОДИФ:ПРИЛ } // Ее нехитрая одежда была ужасающе грязной.
tag наречие:неудовлетворительно{ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ } // Неудовлетворительно низкой является инновационная активность.
tag наречие:несказанно{ ТИП_МОДИФ:ПРИЛ } // В нем было что-то несказанно привлекательное.
tag наречие:истинно{ ТИП_МОДИФ:ПРИЛ } // В вас есть истинно славянский шарм!
tag наречие:по-настоящему{ ТИП_МОДИФ:ПРИЛ } // Ему не выдержать по-настоящему крупного шторма.
tag наречие:патриотически{ ТИП_МОДИФ:ПРИЛ } // Ее активистам подарил патриотически настроенный одессит.
tag наречие:несколько{ ТИП_МОДИФ:ПРИЛ } // Ее лицо приобрело несколько смущенное выражение.
tag наречие:возбуждающе{ ТИП_МОДИФ:ПРИЛ } // Ее голос снова стал возбуждающе хриплым.
tag наречие:смертельно{ ТИП_МОДИФ:ПРИЛ } // Ее лицо было по-прежнему смертельно бледным.
tag наречие:весело{ ТИП_МОДИФ:ПРИЛ } // Ее внимание привлекли весело мигающие огоньки.
tag наречие:непередаваемо{ ТИП_МОДИФ:ПРИЛ } // Ее глаза приняли непередаваемо синий цвет.
tag наречие:невыразимо{ ТИП_МОДИФ:ПРИЛ }
tag наречие:в высшей степени{ ТИП_МОДИФ:ПРИЛ } // Ее рассказ показался мне в высшей степени фантастическим.
tag наречие:обжигающе{ ТИП_МОДИФ:ПРИЛ } // Ее пронзил обжигающе ледяной клинок силы.
tag наречие:социально{ ТИП_МОДИФ:ПРИЛ } // Приоритет отдается социально значимым объектам.
tag наречие:сугубо{ ТИП_МОДИФ:ПРИЛ } // Более полутора веков орден был сугубо мужским.
tag наречие:заведомо{ ТИП_МОДИФ:ПРИЛ } // Поэтому курс окажется заведомо низким.
tag наречие:Некогда{ ТИП_МОДИФ:ПРИЛ } // Некогда сияющие краски померкли.
tag наречие:Аномально{ ТИП_МОДИФ:ПРИЛ } // Аномально теплая погода наблюдается в Бурятии
tag наречие:срочно{ ТИП_МОДИФ:ГЛАГ }
tag наречие:немедленно{ ТИП_МОДИФ:ГЛАГ }
// эти наречия выступают в роли модификаторов наречий
tag наречие:кричаще{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ } // В ней все было кричаще вульгарно.
tag наречие:болезненно{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ } // В огромном помещении было болезненно тихо.
tag наречие:нарочито{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ } // При этом она действовала нарочито медленно.
tag наречие:буквально{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ } // оно появилось буквально ниоткуда.
tag наречие:неестественно{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ } // живые зеленые глаза смотрели неестественно печально
tag наречие:прямо{ ТИП_МОДИФ:НАРЕЧ }
tag наречие:как-то{ ТИП_МОДИФ:НАРЕЧ } // пришел-то он как-то по-паучьи.
tag наречие:так{ ТИП_МОДИФ:НАРЕЧ } // так приятно сделать другу подарок
tag наречие:столь{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ } // прошло столь много лет!
tag наречие:настолько{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ } // В комнате отдыха было настолько темно
tag наречие:насколько{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ } // Насколько просто купить оружие в Техасе?
tag наречие:вполне{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:по крайней мере{ ТИП_МОДИФ:НАРЕЧ } // по крайней мере так ему сказали
tag наречие:почти{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:чуть{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ } // тонкие губы лесного стрелка чуть заметно дрогнули.
tag наречие:совсем{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:слишком{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:словно{ ТИП_МОДИФ:НАРЕЧ } // страх пришел словно извне.
tag наречие:неожиданно{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ } // однако камень поднялся неожиданно легко.
tag наречие:просто{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ } // мои колени чувствуют себя просто великолепно
tag наречие:хоть{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ГЛАГ ТИП_МОДИФ:ПРИЛ } // постарайтесь теперь поспать хоть немного
tag наречие:даже{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ГЛАГ } // мне жаль тебя даже сейчас
tag наречие:абсолютно{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ } // остальные выглядели абсолютно нормально.
tag наречие:относительно{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ } // первый час прошел относительно тихо.
tag наречие:довольно{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ } // довольно скоро донесся шум двигателей.
tag наречие:сравнительно{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ } // писать начал сравнительно недавно.
tag наречие:действительно{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ } // идти пришлось действительно недалеко.
tag наречие:невыносимо{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ } // обед тянулся невыносимо долго.
tag наречие:бесконечно{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ } // молчание тянулось бесконечно долго.
tag наречие:угрожающе{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ } // стены проносились угрожающе близко.
tag наречие:совершенно{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:ничуть{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:очень{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:весьма{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:крайне{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:исключительно{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:достаточно{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:чрезвычайно{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ}
tag наречие:нестерпимо{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ } // Было нестерпимо душно.
tag наречие:неимоверно{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ } // Было неимоверно трудно.
tag наречие:чертовски{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ}
tag наречие:максимально{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:более{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ }
tag наречие:менее{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ }
tag наречие:недопустимо{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:неприемлемо{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:невероятно{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:невозможно{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:невообразимо{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:фантастически{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:сногсшибательно{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:феерически{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:охуительно{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:уже{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:"все еще"{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:практически{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:юридически{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:логически{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:чересчур{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:физически{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ }
tag наречие:едва{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ}
tag наречие:немного{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:чуточку{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:только{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ГЛАГ }
tag наречие:еле{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:особенно{ ТИП_МОДИФ:НАРЕЧ } // вдруг свет вспыхнул особенно ярко.
tag наречие:ужасно{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ } // вдруг стало ужасно тихо.
tag наречие:эстетически{ ТИП_МОДИФ:НАРЕЧ } // сделать это эстетически верно
tag наречие:непривычно{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ } // дверь за ними захлопнулась непривычно тихо.
tag наречие:вызывающе{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ } // Одевается вызывающе броско.
// Эта группа наречий может атрибутировать модификаторы наречий:
// Он поет уже очень долго
// ^^^
tag наречие:уже{ ТИП_МОДИФ:НАРЕЧ0 } // она длилась уже так долго
tag наречие:почти{ ТИП_МОДИФ:НАРЕЧ0 }
tag наречие:иногда{ ТИП_МОДИФ:НАРЕЧ0 }
tag наречие:временами{ ТИП_МОДИФ:НАРЕЧ0 }
tag наречие:сначала{ ТИП_МОДИФ:НАРЕЧ0 }
tag наречие:затем{ ТИП_МОДИФ:НАРЕЧ0 }
tag наречие:"в конце концов"{ ТИП_МОДИФ:НАРЕЧ0 }
tag наречие:наконец{ ТИП_МОДИФ:НАРЕЧ0 }
// Эти наречия могут модифицировать существительное в родительном падеже:
tag наречие:полно{ ТИП_МОДИФ:СУЩ } // у него было полно работы
tag наречие:полным-полно{ ТИП_МОДИФ:СУЩ } // В замке было полным-полно его слуг.
tag наречие:столько{ ТИП_МОДИФ:СУЩ }
tag наречие:сколько{ ТИП_МОДИФ:СУЩ }
tag наречие:сколько-то{ ТИП_МОДИФ:СУЩ }
tag наречие:столько-то{ ТИП_МОДИФ:СУЩ } // Столько-то красок и времени - столько-то денег.
tag наречие:несколько{ ТИП_МОДИФ:СУЩ }
tag наречие:много{ ТИП_МОДИФ:СУЩ }
tag наречие:невпроворот{ ТИП_МОДИФ:СУЩ } // А я поеду, дел невпроворот.
tag наречие:дохера{ ТИП_МОДИФ:СУЩ }
tag наречие:дохерища{ ТИП_МОДИФ:СУЩ }
tag наречие:дофига{ ТИП_МОДИФ:СУЩ }
tag наречие:дофигища{ ТИП_МОДИФ:СУЩ }
tag наречие:дохуя{ ТИП_МОДИФ:СУЩ }
tag наречие:дохуища{ ТИП_МОДИФ:СУЩ }
tag наречие:больше всего{ ТИП_МОДИФ:СУЩ } // Больше всего аварий происходит зимой
tag наречие:достаточно{ ТИП_МОДИФ:СУЩ }
tag наречие:предостаточно{ ТИП_МОДИФ:СУЩ } // В погребе форта оказалось предостаточно провизии.
tag наречие:недостаточно{ ТИП_МОДИФ:СУЩ }
tag наречие:немного{ ТИП_МОДИФ:СУЩ }
tag наречие:немножко{ ТИП_МОДИФ:СУЩ }
tag наречие:немножечко{ ТИП_МОДИФ:СУЩ } // попробуем организовать для вас немножко природы
tag наречие:чуточку{ ТИП_МОДИФ:СУЩ } // дать тебе чуточку времени.
tag наречие:мало{ ТИП_МОДИФ:СУЩ }
tag наречие:маловато{ ТИП_МОДИФ:СУЩ }
tag наречие:многовато{ ТИП_МОДИФ:СУЩ }
tag наречие:немало{ ТИП_МОДИФ:СУЩ }
tag наречие:чуть-чуть{ ТИП_МОДИФ:СУЩ }
// Наречия типа ДАЖЕ модифицируют существительное в любом падеже:
tag наречие:даже{ ТИП_МОДИФ:СУЩ2 }
tag наречие:только{ ТИП_МОДИФ:СУЩ2 }
tag наречие:лишь{ ТИП_МОДИФ:СУЩ2 }
tag наречие:всего лишь{ ТИП_МОДИФ:СУЩ2 }
tag наречие:еще{ ТИП_МОДИФ:СУЩ2 } // но прошло еще мгновение
tag наречие:всего{ ТИП_МОДИФ:СУЩ2 } // мы потратили всего час
// Эти наречия модифицируют предлоги:
tag наречие:вслед{ ТИП_МОДИФ:ПРЕДЛ ТИП_МОДИФ:ГЛАГ } // вы поехали вслед за нами
tag наречие:даже{ ТИП_МОДИФ:ПРЕДЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:аж{ ТИП_МОДИФ:ПРЕДЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:только{ ТИП_МОДИФ:ПРЕДЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:только лишь{ ТИП_МОДИФ:ПРЕДЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:всего{ ТИП_МОДИФ:ПРЕДЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:всего лишь{ ТИП_МОДИФ:ПРЕДЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:почти{ ТИП_МОДИФ:ПРЕДЛ ТИП_МОДИФ:ГЛАГ } // мы выследили волка уже у самой границы леса
tag наречие:почти что{ ТИП_МОДИФ:ПРЕДЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:буквально{ ТИП_МОДИФ:ПРЕДЛ ТИП_МОДИФ:ГЛАГ } // Им предстоит дорога буквально во все регионы страны.
tag наречие:уже{ ТИП_МОДИФ:ПРЕДЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:особенно{ ТИП_МОДИФ:ПРЕДЛ ТИП_МОДИФ:ГЛАГ } // Устали авиаторы, особенно от этой изнуряющей жары.
tag наречие:именно{ ТИП_МОДИФ:ПРЕДЛ }
tag наречие:исключительно{ ТИП_МОДИФ:ПРЕДЛ }
tag наречие:преимущественно{ ТИП_МОДИФ:ПРЕДЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:сразу{ ТИП_МОДИФ:ПРЕДЛ ТИП_МОДИФ:ГЛАГ } // Сразу за домами - огороды.
tag наречие:хотя бы{ ТИП_МОДИФ:ПРЕДЛ ТИП_МОДИФ:ГЛАГ } // Хотя бы в три?
tag наречие:вплотную{ ТИП_МОДИФ:ПРЕДЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:прямо{ ТИП_МОДИФ:ПРЕДЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:впритык{ ТИП_МОДИФ:ПРЕДЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:параллельно{ ТИП_МОДИФ:ПРЕДЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:одновременно{ ТИП_МОДИФ:ПРЕДЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:невдалеке{ ТИП_МОДИФ:ПРЕДЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:вблизи{ ТИП_МОДИФ:ПРЕДЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:тайком{ ТИП_МОДИФ:ПРЕДЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:наедине{ ТИП_МОДИФ:ПРЕДЛ ТИП_МОДИФ:ГЛАГ } // Ей хотелось остаться наедине со своим унижением.
tag наречие:слева{ ТИП_МОДИФ:ПРЕДЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:справа{ ТИП_МОДИФ:ПРЕДЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:сверху{ ТИП_МОДИФ:ПРЕДЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:снизу{ ТИП_МОДИФ:ПРЕДЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:вдали{ ТИП_МОДИФ:ПРЕДЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:недалеко{ ТИП_МОДИФ:ПРЕДЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:неподалеку{ ТИП_МОДИФ:ПРЕДЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:вместе{ ТИП_МОДИФ:ПРЕДЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:рядом{ ТИП_МОДИФ:ПРЕДЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:рядышком{ ТИП_МОДИФ:ПРЕДЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:в обнимку{ ТИП_МОДИФ:ПРЕДЛ }
tag наречие:в обнимочку{ ТИП_МОДИФ:ПРЕДЛ }
tag наречие:вплоть{ ТИП_МОДИФ:ПРЕДЛ }
tag наречие:задолго{ ТИП_МОДИФ:ПРЕДЛ }
tag наречие:незадолго{ ТИП_МОДИФ:ПРЕДЛ }
tag наречие:вскоре{ ТИП_МОДИФ:ПРЕДЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:верхом{ ТИП_МОДИФ:ПРЕДЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:следом{ ТИП_МОДИФ:ПРЕДЛ ТИП_МОДИФ:ГЛАГ } // Она двинулась следом за проводником.
}
| Бегают воровски черные злые глаза.
| tag наречие:воровски{ ТИП_МОДИФ:ГЛАГ } | 1,841,634 | [
1,
145,
244,
145,
118,
145,
116,
145,
113,
146,
241,
146,
229,
225,
145,
115,
145,
127,
146,
227,
145,
127,
145,
115,
146,
228,
145,
123,
145,
121,
225,
146,
234,
145,
118,
146,
227,
145,
126,
146,
238,
145,
118,
225,
145,
120,
145,
124,
146,
238,
145,
118,
225,
145,
116,
145,
124,
145,
113,
145,
120,
145,
113,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1047,
225,
145,
126,
145,
113,
146,
227,
145,
118,
146,
234,
145,
121,
145,
118,
30,
145,
115,
145,
127,
146,
227,
145,
127,
145,
115,
146,
228,
145,
123,
145,
121,
95,
225,
145,
100,
145,
251,
145,
258,
67,
145,
255,
145,
257,
145,
247,
145,
251,
145,
102,
30,
145,
246,
145,
254,
145,
243,
145,
246,
289,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.