Unnamed: 0
int64
0
7.36k
comments
stringlengths
3
35.2k
code_string
stringlengths
1
527k
code
stringlengths
1
527k
__index_level_0__
int64
0
88.6k
15
// Returns number of promotional LOT earnt as calculatedbased on number of entries, current ICO exchange rate and the current Etheraffle ticket price./
function getPromoLOTEarnt(uint _entries) public view returns (uint) { return (_entries * getRate() * getTktPrice()) / (1 * 10 ** 18); }
function getPromoLOTEarnt(uint _entries) public view returns (uint) { return (_entries * getRate() * getTktPrice()) / (1 * 10 ** 18); }
34,136
150
// Mint & setup on gated only drop
function mintBatchEditionGatedOnly( uint16 _editionSize, uint256 _merkleIndex, bytes32[] calldata _merkleProof, address _deployedRoyaltiesHandler, string calldata _uri
function mintBatchEditionGatedOnly( uint16 _editionSize, uint256 _merkleIndex, bytes32[] calldata _merkleProof, address _deployedRoyaltiesHandler, string calldata _uri
47,831
86
// changefee Collector wallet address
* Emit {FeeCollectorChanged} evt * * Requirements: * only Is InOwners require */ function setFeeCollector(address newOp) external onlyOwner returns (bool) { address old = _feeCollector; _feeCollector = newOp; emit FeeCollectorChanged(old, _feeCollector); return true; }
* Emit {FeeCollectorChanged} evt * * Requirements: * only Is InOwners require */ function setFeeCollector(address newOp) external onlyOwner returns (bool) { address old = _feeCollector; _feeCollector = newOp; emit FeeCollectorChanged(old, _feeCollector); return true; }
42,528
96
// Set the local router pointer
uniswapV2Router = _uniswapV2Router;
uniswapV2Router = _uniswapV2Router;
18,141
6
// Function to be called by top level contract after initialization to enable the contract at a future block number rather than immediately. /
function initializedAt(uint256 _blockNumber) internal onlyInit { INITIALIZATION_BLOCK_POSITION.setStorageUint256(_blockNumber); }
function initializedAt(uint256 _blockNumber) internal onlyInit { INITIALIZATION_BLOCK_POSITION.setStorageUint256(_blockNumber); }
1,719
54
// return cost of TokenId.
function getTokenCost(uint256 tokenId_) external view returns (uint256) { return tokenIdtoCost[tokenId_]; }
function getTokenCost(uint256 tokenId_) external view returns (uint256) { return tokenIdtoCost[tokenId_]; }
1,780
13
// Last Token Id Generated.
uint256 public LAST_TOKEN_ID;
uint256 public LAST_TOKEN_ID;
71,927
68
// Returns the current address of the Unikura Mothership contract. A view function that does not mutate the state of the contract.return An address type that holds the address of the Unikura Mothership contract. /
function unikuraMothership() public view returns (address) { return address( UnikuraPhygitalCollectionStorage.layout()._unikuraMothership ); }
function unikuraMothership() public view returns (address) { return address( UnikuraPhygitalCollectionStorage.layout()._unikuraMothership ); }
42,293
93
// If this is the first bid, ensure it's >= the reserve price
require(auction.amount <= msg.value, "NFTMarketReserveAuction: Bid must be at least the reserve price");
require(auction.amount <= msg.value, "NFTMarketReserveAuction: Bid must be at least the reserve price");
16,122
64
// See {IERC20-transferFrom}. Emits an {Approval} event indicating the updated allowance. This is notrequired by the EIP. See the note at the beginning of {ERC20}. Requirements: - `source` and `recipient` cannot be the zero address.- `source` must have a balance of at least `amount`.- the caller must have allowance for `source`'s tokens of at least`amount`. /
function transferFrom(address source, address recipient, uint256 amount) public virtual override returns (bool) { require(source != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address");
function transferFrom(address source, address recipient, uint256 amount) public virtual override returns (bool) { require(source != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address");
5,879
58
// Whether or not a domain specific by an id is available.
function isAvailable(uint256 id) external view returns (bool);
function isAvailable(uint256 id) external view returns (bool);
36,508
23
// add an address to the list of owners _ownerToRemove the address of the new owner /
function removeOwner(address _ownerToRemove) public onlyTroveOwner { require(owner() != _ownerToRemove, "604e3 do not remove main owner"); _revokeRole(OWNER_ROLE, _ownerToRemove); }
function removeOwner(address _ownerToRemove) public onlyTroveOwner { require(owner() != _ownerToRemove, "604e3 do not remove main owner"); _revokeRole(OWNER_ROLE, _ownerToRemove); }
22,063
4
// Creates an SKU and associates the specified ERC20 F1DTCrateKey token contract with it. Reverts if called by any other than the contract owner. Reverts if `totalSupply` is zero. Reverts if `sku` already exists. Reverts if the update results in too many SKUs. Reverts if the `totalSupply` is SUPPLY_UNLIMITED. Reverts if the `crateKey` is the zero address. Emits the `SkuCreation` event. sku The SKU identifier. totalSupply The initial total supply. maxQuantityPerPurchase The maximum allowed quantity for a single purchase. crateKey The ERC20 F1DTCrateKey token contract to bind with the SKU. /
function createCrateKeySku( bytes32 sku, uint256 totalSupply, uint256 maxQuantityPerPurchase, IF1DTCrateKeyFull crateKey
function createCrateKeySku( bytes32 sku, uint256 totalSupply, uint256 maxQuantityPerPurchase, IF1DTCrateKeyFull crateKey
15,096
36
// Contract module which provides a basic access control mechanism, wherethere is an account (an owner) that can be granted exclusive access tospecific 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 tothe owner. /
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 () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @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(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 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; } }
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 () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @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(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 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; } }
19,179
30
// We can't just read the balance of token, because we need to know the full pair in order to compute the pair hash and access the balance mapping. We therefore rely on `_getTwoTokenPoolBalances`.
(, IERC20 tokenA, bytes32 balanceA, IERC20 tokenB, bytes32 balanceB) = _getTwoTokenPoolBalances(poolId); if (token == tokenA) { return balanceA; } else if (token == tokenB) {
(, IERC20 tokenA, bytes32 balanceA, IERC20 tokenB, bytes32 balanceB) = _getTwoTokenPoolBalances(poolId); if (token == tokenA) { return balanceA; } else if (token == tokenB) {
26,434
71
// Destroys `tokenId`.
function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); _approve(address(0), tokenId); _owners[tokenId] = address(0); emit Transfer(owner, address(0), tokenId); }
function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); _approve(address(0), tokenId); _owners[tokenId] = address(0); emit Transfer(owner, address(0), tokenId); }
32,128
0
// IRealitioArbitrator /
interface IRealitioArbitrator { /** @dev Returns Realitio implementation instance. */ function realitio() external view returns (IRealitio); /** @dev Provides a string of json-encoded metadata. The following properties are scheduled for implementation in the Reality.eth dapp: tos: A URI representing the location of a terms-of-service document for the arbitrator. template_hashes: An array of hashes of templates supported by the arbitrator. If you have a numerical ID for a template registered with Reality.eth, you can look up this hash by calling the Reality.eth template_hashes() function. */ function metadata() external view returns (string calldata); /** @dev Returns arbitrators fee for arbitrating this question. */ function getDisputeFee(bytes32 questionID) external view returns (uint256); }
interface IRealitioArbitrator { /** @dev Returns Realitio implementation instance. */ function realitio() external view returns (IRealitio); /** @dev Provides a string of json-encoded metadata. The following properties are scheduled for implementation in the Reality.eth dapp: tos: A URI representing the location of a terms-of-service document for the arbitrator. template_hashes: An array of hashes of templates supported by the arbitrator. If you have a numerical ID for a template registered with Reality.eth, you can look up this hash by calling the Reality.eth template_hashes() function. */ function metadata() external view returns (string calldata); /** @dev Returns arbitrators fee for arbitrating this question. */ function getDisputeFee(bytes32 questionID) external view returns (uint256); }
14,664
21
// ERC725 X (Core) executor Implementation of a contract module which provides the ability to call arbitrary functions at any other smart contract and itself,including using `delegatecall`, `staticcall`, as well creating contracts using `create` and `create2`.This is the basis for a smart contract based account system, but could also be used as a proxy account system. `execute` MUST only be called by the owner of the contract set via ERC173. Fabian Vogelsteller <fabian@lukso.network> /
abstract contract ERC725XCore is OwnableUnset, ERC165Storage, IERC725X { bytes4 internal constant _INTERFACE_ID_ERC725X = type(IERC725X).interfaceId; /* Public functions */ /** * @notice Executes any other smart contract. Is only callable by the owner. * * * @param _operation the operation to execute: CALL = 0; CREATE = 1; CREATE2 = 2; STATICCALL = 3; DELEGATECALL = 4; * @param _to the smart contract or address to interact with. `_to` will be unused if a contract is created (operation 1 and 2) * @param _value the value of ETH to transfer * @param _data the call data, or the contract data to deploy */ function execute( uint256 _operation, address _to, uint256 _value, bytes calldata _data ) public payable virtual override onlyOwner returns (bytes memory result) { uint256 txGas = gasleft(); // prettier-ignore // CALL if (_operation == OPERATION_CALL) { result = executeCall(_to, _value, _data, txGas); emit Executed(_operation, _to, _value, _data); // STATICCALL } else if (_operation == OPERATION_STATICCALL) { result = executeStaticCall(_to, _data, txGas); emit Executed(_operation, _to, _value, _data); // DELEGATECALL } else if (_operation == OPERATION_DELEGATECALL) { address currentOwner = owner(); result = executeDelegateCall(_to, _data, txGas); emit Executed(_operation, _to, _value, _data); require(owner() == currentOwner, "Delegate call is not allowed to modify the owner!"); // CREATE } else if (_operation == OPERATION_CREATE) { address contractAddress = performCreate(_value, _data); result = abi.encodePacked(contractAddress); emit ContractCreated(_operation, contractAddress, _value); // CREATE2 } else if (_operation == OPERATION_CREATE2) { bytes32 salt = BytesLib.toBytes32(_data, _data.length - 32); bytes memory data = BytesLib.slice(_data, 0, _data.length - 32); address contractAddress = Create2.deploy(_value, salt, data); result = abi.encodePacked(contractAddress); emit ContractCreated(_operation, contractAddress, _value); } else { revert("Wrong operation type"); } } /* Internal functions */ // Taken from GnosisSafe: https://github.com/gnosis/safe-contracts/blob/main/contracts/base/Executor.sol function executeCall( address to, uint256 value, bytes memory data, uint256 txGas ) internal returns (bytes memory) { // solhint-disable avoid-low-level-calls (bool success, bytes memory result) = to.call{gas: txGas, value: value}(data); if (!success) { // solhint-disable reason-string if (result.length < 68) revert(); // solhint-disable no-inline-assembly assembly { result := add(result, 0x04) } revert(abi.decode(result, (string))); } return result; } function executeStaticCall( address to, bytes memory data, uint256 txGas ) internal view returns (bytes memory) { (bool success, bytes memory result) = to.staticcall{gas: txGas}(data); if (!success) { // solhint-disable reason-string if (result.length < 68) revert(); assembly { result := add(result, 0x04) } revert(abi.decode(result, (string))); } return result; } // Taken from GnosisSafe: https://github.com/gnosis/safe-contracts/blob/main/contracts/base/Executor.sol function executeDelegateCall( address to, bytes memory data, uint256 txGas ) internal returns (bytes memory) { // solhint-disable avoid-low-level-calls (bool success, bytes memory result) = to.delegatecall{gas: txGas}(data); if (!success) { // solhint-disable reason-string if (result.length < 68) revert(); assembly { result := add(result, 0x04) } revert(abi.decode(result, (string))); } return result; } // Taken from GnosisSafe: https://github.com/gnosis/safe-contracts/blob/main/contracts/libraries/CreateCall.sol function performCreate(uint256 value, bytes memory deploymentData) internal returns (address newContract) { assembly { newContract := create(value, add(deploymentData, 0x20), mload(deploymentData)) } require(newContract != address(0), "Could not deploy contract"); } }
abstract contract ERC725XCore is OwnableUnset, ERC165Storage, IERC725X { bytes4 internal constant _INTERFACE_ID_ERC725X = type(IERC725X).interfaceId; /* Public functions */ /** * @notice Executes any other smart contract. Is only callable by the owner. * * * @param _operation the operation to execute: CALL = 0; CREATE = 1; CREATE2 = 2; STATICCALL = 3; DELEGATECALL = 4; * @param _to the smart contract or address to interact with. `_to` will be unused if a contract is created (operation 1 and 2) * @param _value the value of ETH to transfer * @param _data the call data, or the contract data to deploy */ function execute( uint256 _operation, address _to, uint256 _value, bytes calldata _data ) public payable virtual override onlyOwner returns (bytes memory result) { uint256 txGas = gasleft(); // prettier-ignore // CALL if (_operation == OPERATION_CALL) { result = executeCall(_to, _value, _data, txGas); emit Executed(_operation, _to, _value, _data); // STATICCALL } else if (_operation == OPERATION_STATICCALL) { result = executeStaticCall(_to, _data, txGas); emit Executed(_operation, _to, _value, _data); // DELEGATECALL } else if (_operation == OPERATION_DELEGATECALL) { address currentOwner = owner(); result = executeDelegateCall(_to, _data, txGas); emit Executed(_operation, _to, _value, _data); require(owner() == currentOwner, "Delegate call is not allowed to modify the owner!"); // CREATE } else if (_operation == OPERATION_CREATE) { address contractAddress = performCreate(_value, _data); result = abi.encodePacked(contractAddress); emit ContractCreated(_operation, contractAddress, _value); // CREATE2 } else if (_operation == OPERATION_CREATE2) { bytes32 salt = BytesLib.toBytes32(_data, _data.length - 32); bytes memory data = BytesLib.slice(_data, 0, _data.length - 32); address contractAddress = Create2.deploy(_value, salt, data); result = abi.encodePacked(contractAddress); emit ContractCreated(_operation, contractAddress, _value); } else { revert("Wrong operation type"); } } /* Internal functions */ // Taken from GnosisSafe: https://github.com/gnosis/safe-contracts/blob/main/contracts/base/Executor.sol function executeCall( address to, uint256 value, bytes memory data, uint256 txGas ) internal returns (bytes memory) { // solhint-disable avoid-low-level-calls (bool success, bytes memory result) = to.call{gas: txGas, value: value}(data); if (!success) { // solhint-disable reason-string if (result.length < 68) revert(); // solhint-disable no-inline-assembly assembly { result := add(result, 0x04) } revert(abi.decode(result, (string))); } return result; } function executeStaticCall( address to, bytes memory data, uint256 txGas ) internal view returns (bytes memory) { (bool success, bytes memory result) = to.staticcall{gas: txGas}(data); if (!success) { // solhint-disable reason-string if (result.length < 68) revert(); assembly { result := add(result, 0x04) } revert(abi.decode(result, (string))); } return result; } // Taken from GnosisSafe: https://github.com/gnosis/safe-contracts/blob/main/contracts/base/Executor.sol function executeDelegateCall( address to, bytes memory data, uint256 txGas ) internal returns (bytes memory) { // solhint-disable avoid-low-level-calls (bool success, bytes memory result) = to.delegatecall{gas: txGas}(data); if (!success) { // solhint-disable reason-string if (result.length < 68) revert(); assembly { result := add(result, 0x04) } revert(abi.decode(result, (string))); } return result; } // Taken from GnosisSafe: https://github.com/gnosis/safe-contracts/blob/main/contracts/libraries/CreateCall.sol function performCreate(uint256 value, bytes memory deploymentData) internal returns (address newContract) { assembly { newContract := create(value, add(deploymentData, 0x20), mload(deploymentData)) } require(newContract != address(0), "Could not deploy contract"); } }
48,749
37
// withdraw all funds instantly
function withdraw() public onlyOwner { uint256 balance = address(this).balance; payable(msg.sender).transfer(balance); }
function withdraw() public onlyOwner { uint256 balance = address(this).balance; payable(msg.sender).transfer(balance); }
4,490
2
// Burns a specific amount of tokens from the target address and decrements allowance from address The address which you want to send tokens from value uint256 The amount of token to be burned //
function burnFrom(address from, uint256 value) public { _burnFrom(from, value); //Only the owner's address can be burned. @ejkang }
function burnFrom(address from, uint256 value) public { _burnFrom(from, value); //Only the owner's address can be burned. @ejkang }
23,235
200
// Domino (DOMI) ERC20 tokenDomino is a core ERC20 token powering the game. It serves as an in-game currency, is tradable on exchanges, it powers up the governance protocol (Domino DAO) and participates in Yield Farming.Token Summary: - Symbol: DOMI - Name: Domino - Decimals: 18 - Initial token supply: 70,000,000 DOMI - Maximum final token supply: 100,000,000 DOMI - Up to 30,000,000 DOMI may get minted in 3 years period via yield farming - Mintable: total supply may increase - Burnable: total supply may decreaseToken balances and total supply are effectively 192 bits long, meaning that maximum possible total supply
contract DominoERC20 is AccessControl { /** * @dev Smart contract unique identifier, a random number * @dev Should be regenerated each time smart contact source code is changed * and changes smart contract itself is to be redeployed * @dev Generated using https://www.random.org/bytes/ */ uint256 public constant TOKEN_UID = 0x83ecb176af7c4f35a45ff0018282e3a05a1018065da866182df12285866f5a2c; /** * @notice Name of the token: Domino * * @notice ERC20 name of the token (long name) * * @dev ERC20 `function name() public view returns (string)` * * @dev Field is declared public: getter name() is created when compiled, * it returns the name of the token. */ string public constant name = "Domino"; /** * @notice Symbol of the token: DOMI * * @notice ERC20 symbol of that token (short name) * * @dev ERC20 `function symbol() public view returns (string)` * * @dev Field is declared public: getter symbol() is created when compiled, * it returns the symbol of the token */ string public constant symbol = "DOMI"; /** * @notice Decimals of the token: 18 * * @dev ERC20 `function decimals() public view returns (uint8)` * * @dev Field is declared public: getter decimals() is created when compiled, * it returns the number of decimals used to get its user representation. * For example, if `decimals` equals `6`, a balance of `1,500,000` tokens should * be displayed to a user as `1,5` (`1,500,000 / 10 ** 6`). * * @dev NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including balanceOf() and transfer(). */ uint8 public constant decimals = 18; /** * @notice Total supply of the token: initially 70,000,000, * with the potential to grow up to 10,000,000 during yield farming period (3 years) * * @dev ERC20 `function totalSupply() public view returns (uint256)` * * @dev Field is declared public: getter totalSupply() is created when compiled, * it returns the amount of tokens in existence. */ uint256 public totalSupply; // is set to 70 million * 10^18 in the constructor /** * @dev A record of all the token balances * @dev This mapping keeps record of all token owners: * owner => balance */ mapping(address => uint256) public tokenBalances; /** * @notice A record of each account's voting delegate * * @dev Auxiliary data structure used to sum up an account's voting power * * @dev This mapping keeps record of all voting power delegations: * voting delegator (token owner) => voting delegate */ mapping(address => address) public votingDelegates; /** * @notice A voting power record binds voting power of a delegate to a particular * block when the voting power delegation change happened */ struct VotingPowerRecord { /* * @dev block.number when delegation has changed; starting from * that block voting power value is in effect */ uint64 blockNumber; /* * @dev cumulative voting power a delegate has obtained starting * from the block stored in blockNumber */ uint192 votingPower; } /** * @notice A record of each account's voting power * * @dev Primarily data structure to store voting power for each account. * Voting power sums up from the account's token balance and delegated * balances. * * @dev Stores current value and entire history of its changes. * The changes are stored as an array of checkpoints. * Checkpoint is an auxiliary data structure containing voting * power (number of votes) and block number when the checkpoint is saved * * @dev Maps voting delegate => voting power record */ mapping(address => VotingPowerRecord[]) public votingPowerHistory; /** * @dev A record of nonces for signing/validating signatures in `delegateWithSig` * for every delegate, increases after successful validation * * @dev Maps delegate address => delegate nonce */ mapping(address => uint256) public nonces; /** * @notice A record of all the allowances to spend tokens on behalf * @dev Maps token owner address to an address approved to spend * some tokens on behalf, maps approved address to that amount * @dev owner => spender => value */ mapping(address => mapping(address => uint256)) public transferAllowances; /** * @notice Enables ERC20 transfers of the tokens * (transfer by the token owner himself) * @dev Feature FEATURE_TRANSFERS must be enabled in order for * `transfer()` function to succeed */ uint32 public constant FEATURE_TRANSFERS = 0x0000_0001; /** * @notice Enables ERC20 transfers on behalf * (transfer by someone else on behalf of token owner) * @dev Feature FEATURE_TRANSFERS_ON_BEHALF must be enabled in order for * `transferFrom()` function to succeed * @dev Token owner must call `approve()` first to authorize * the transfer on behalf */ uint32 public constant FEATURE_TRANSFERS_ON_BEHALF = 0x0000_0002; /** * @dev Defines if the default behavior of `transfer` and `transferFrom` * checks if the receiver smart contract supports ERC20 tokens * @dev When feature FEATURE_UNSAFE_TRANSFERS is enabled the transfers do not * check if the receiver smart contract supports ERC20 tokens, * i.e. `transfer` and `transferFrom` behave like `unsafeTransferFrom` * @dev When feature FEATURE_UNSAFE_TRANSFERS is disabled (default) the transfers * check if the receiver smart contract supports ERC20 tokens, * i.e. `transfer` and `transferFrom` behave like `safeTransferFrom` */ uint32 public constant FEATURE_UNSAFE_TRANSFERS = 0x0000_0004; /** * @notice Enables token owners to burn their own tokens, * including locked tokens which are burnt first * @dev Feature FEATURE_OWN_BURNS must be enabled in order for * `burn()` function to succeed when called by token owner */ uint32 public constant FEATURE_OWN_BURNS = 0x0000_0008; /** * @notice Enables approved operators to burn tokens on behalf of their owners, * including locked tokens which are burnt first * @dev Feature FEATURE_OWN_BURNS must be enabled in order for * `burn()` function to succeed when called by approved operator */ uint32 public constant FEATURE_BURNS_ON_BEHALF = 0x0000_0010; /** * @notice Enables delegators to elect delegates * @dev Feature FEATURE_DELEGATIONS must be enabled in order for * `delegate()` function to succeed */ uint32 public constant FEATURE_DELEGATIONS = 0x0000_0020; /** * @notice Enables delegators to elect delegates on behalf * (via an EIP712 signature) * @dev Feature FEATURE_DELEGATIONS must be enabled in order for * `delegateWithSig()` function to succeed */ uint32 public constant FEATURE_DELEGATIONS_ON_BEHALF = 0x0000_0040; /** * @notice Token creator is responsible for creating (minting) * tokens to an arbitrary address * @dev Role ROLE_TOKEN_CREATOR allows minting tokens * (calling `mint` function) */ uint32 public constant ROLE_TOKEN_CREATOR = 0x0001_0000; /** * @notice Token destroyer is responsible for destroying (burning) * tokens owned by an arbitrary address * @dev Role ROLE_TOKEN_DESTROYER allows burning tokens * (calling `burn` function) */ uint32 public constant ROLE_TOKEN_DESTROYER = 0x0002_0000; /** * @notice ERC20 receivers are allowed to receive tokens without ERC20 safety checks, * which may be useful to simplify tokens transfers into "legacy" smart contracts * @dev When `FEATURE_UNSAFE_TRANSFERS` is not enabled addresses having * `ROLE_ERC20_RECEIVER` permission are allowed to receive tokens * via `transfer` and `transferFrom` functions in the same way they * would via `unsafeTransferFrom` function * @dev When `FEATURE_UNSAFE_TRANSFERS` is enabled `ROLE_ERC20_RECEIVER` permission * doesn't affect the transfer behaviour since * `transfer` and `transferFrom` behave like `unsafeTransferFrom` for any receiver * @dev ROLE_ERC20_RECEIVER is a shortening for ROLE_UNSAFE_ERC20_RECEIVER */ uint32 public constant ROLE_ERC20_RECEIVER = 0x0004_0000; /** * @notice ERC20 senders are allowed to send tokens without ERC20 safety checks, * which may be useful to simplify tokens transfers into "legacy" smart contracts * @dev When `FEATURE_UNSAFE_TRANSFERS` is not enabled senders having * `ROLE_ERC20_SENDER` permission are allowed to send tokens * via `transfer` and `transferFrom` functions in the same way they * would via `unsafeTransferFrom` function * @dev When `FEATURE_UNSAFE_TRANSFERS` is enabled `ROLE_ERC20_SENDER` permission * doesn't affect the transfer behaviour since * `transfer` and `transferFrom` behave like `unsafeTransferFrom` for any receiver * @dev ROLE_ERC20_SENDER is a shortening for ROLE_UNSAFE_ERC20_SENDER */ uint32 public constant ROLE_ERC20_SENDER = 0x0008_0000; /** * @dev Magic value to be returned by ERC20Receiver upon successful reception of token(s) * @dev Equal to `bytes4(keccak256("onERC20Received(address,address,uint256,bytes)"))`, * which can be also obtained as `ERC20Receiver(address(0)).onERC20Received.selector` */ bytes4 private constant ERC20_RECEIVED = 0x4fc35859; /** * @notice EIP-712 contract's domain typeHash, see https://eips.ethereum.org/EIPS/eip-712#rationale-for-typehash */ bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /** * @notice EIP-712 delegation struct typeHash, see https://eips.ethereum.org/EIPS/eip-712#rationale-for-typehash */ bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegate,uint256 nonce,uint256 expiry)"); /** * @dev Fired in transfer(), transferFrom() and some other (non-ERC20) functions * * @dev ERC20 `event Transfer(address indexed _from, address indexed _to, uint256 _value)` * * @param _from an address tokens were consumed from * @param _to an address tokens were sent to * @param _value number of tokens transferred */ event Transfer(address indexed _from, address indexed _to, uint256 _value); /** * @dev Fired in approve() and approveAtomic() functions * * @dev ERC20 `event Approval(address indexed _owner, address indexed _spender, uint256 _value)` * * @param _owner an address which granted a permission to transfer * tokens on its behalf * @param _spender an address which received a permission to transfer * tokens on behalf of the owner `_owner` * @param _value amount of tokens granted to transfer on behalf */ event Approval(address indexed _owner, address indexed _spender, uint256 _value); /** * @dev Fired in mint() function * * @param _by an address which minted some tokens (transaction sender) * @param _to an address the tokens were minted to * @param _value an amount of tokens minted */ event Minted(address indexed _by, address indexed _to, uint256 _value); /** * @dev Fired in burn() function * * @param _by an address which burned some tokens (transaction sender) * @param _from an address the tokens were burnt from * @param _value an amount of tokens burnt */ event Burnt(address indexed _by, address indexed _from, uint256 _value); /** * @dev Resolution for the Multiple Withdrawal Attack on ERC20 Tokens (ISBN:978-1-7281-3027-9) * * @dev Similar to ERC20 Transfer event, but also logs an address which executed transfer * * @dev Fired in transfer(), transferFrom() and some other (non-ERC20) functions * * @param _by an address which performed the transfer * @param _from an address tokens were consumed from * @param _to an address tokens were sent to * @param _value number of tokens transferred */ event Transferred(address indexed _by, address indexed _from, address indexed _to, uint256 _value); /** * @dev Resolution for the Multiple Withdrawal Attack on ERC20 Tokens (ISBN:978-1-7281-3027-9) * * @dev Similar to ERC20 Approve event, but also logs old approval value * * @dev Fired in approve() and approveAtomic() functions * * @param _owner an address which granted a permission to transfer * tokens on its behalf * @param _spender an address which received a permission to transfer * tokens on behalf of the owner `_owner` * @param _oldValue previously granted amount of tokens to transfer on behalf * @param _value new granted amount of tokens to transfer on behalf */ event Approved(address indexed _owner, address indexed _spender, uint256 _oldValue, uint256 _value); /** * @dev Notifies that a key-value pair in `votingDelegates` mapping has changed, * i.e. a delegator address has changed its delegate address * * @param _of delegator address, a token owner * @param _from old delegate, an address which delegate right is revoked * @param _to new delegate, an address which received the voting power */ event DelegateChanged(address indexed _of, address indexed _from, address indexed _to); /** * @dev Notifies that a key-value pair in `votingPowerHistory` mapping has changed, * i.e. a delegate's voting power has changed. * * @param _of delegate whose voting power has changed * @param _fromVal previous number of votes delegate had * @param _toVal new number of votes delegate has */ event VotingPowerChanged(address indexed _of, uint256 _fromVal, uint256 _toVal); /** * @dev Deploys the token smart contract, * assigns initial token supply to the address specified * * @param _initialHolder owner of the initial token supply */ constructor(address _initialHolder) { // verify initial holder address non-zero (is set) require(_initialHolder != address(0), "_initialHolder not set (zero address)"); // mint initial supply mint(_initialHolder, 70_000_000e18); } // ===== Start: ERC20/ERC223/ERC777 functions ===== /** * @notice Gets the balance of a particular address * * @dev ERC20 `function balanceOf(address _owner) public view returns (uint256 balance)` * * @param _owner the address to query the the balance for * @return balance an amount of tokens owned by the address specified */ function balanceOf(address _owner) public view returns (uint256 balance) { // read the balance and return return tokenBalances[_owner]; } /** * @notice Transfers some tokens to an external address or a smart contract * * @dev ERC20 `function transfer(address _to, uint256 _value) public returns (bool success)` * * @dev Called by token owner (an address which has a * positive token balance tracked by this smart contract) * @dev Throws on any error like * * insufficient token balance or * * incorrect `_to` address: * * zero address or * * self address or * * smart contract which doesn't support ERC20 * * @param _to an address to transfer tokens to, * must be either an external address or a smart contract, * compliant with the ERC20 standard * @param _value amount of tokens to be transferred, must * be greater than zero * @return success true on success, throws otherwise */ function transfer(address _to, uint256 _value) public returns (bool success) { // just delegate call to `transferFrom`, // `FEATURE_TRANSFERS` is verified inside it return transferFrom(msg.sender, _to, _value); } /** * @notice Transfers some tokens on behalf of address `_from' (token owner) * to some other address `_to` * * @dev ERC20 `function transferFrom(address _from, address _to, uint256 _value) public returns (bool success)` * * @dev Called by token owner on his own or approved address, * an address approved earlier by token owner to * transfer some amount of tokens on its behalf * @dev Throws on any error like * * insufficient token balance or * * incorrect `_to` address: * * zero address or * * same as `_from` address (self transfer) * * smart contract which doesn't support ERC20 * * @param _from token owner which approved caller (transaction sender) * to transfer `_value` of tokens on its behalf * @param _to an address to transfer tokens to, * must be either an external address or a smart contract, * compliant with the ERC20 standard * @param _value amount of tokens to be transferred, must * be greater than zero * @return success true on success, throws otherwise */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { // depending on `FEATURE_UNSAFE_TRANSFERS` we execute either safe (default) // or unsafe transfer // if `FEATURE_UNSAFE_TRANSFERS` is enabled // or receiver has `ROLE_ERC20_RECEIVER` permission // or sender has `ROLE_ERC20_SENDER` permission if(isFeatureEnabled(FEATURE_UNSAFE_TRANSFERS) || isOperatorInRole(_to, ROLE_ERC20_RECEIVER) || isSenderInRole(ROLE_ERC20_SENDER)) { // we execute unsafe transfer - delegate call to `unsafeTransferFrom`, // `FEATURE_TRANSFERS` is verified inside it unsafeTransferFrom(_from, _to, _value); } // otherwise - if `FEATURE_UNSAFE_TRANSFERS` is disabled // and receiver doesn't have `ROLE_ERC20_RECEIVER` permission else { // we execute safe transfer - delegate call to `safeTransferFrom`, passing empty `_data`, // `FEATURE_TRANSFERS` is verified inside it safeTransferFrom(_from, _to, _value, ""); } // both `unsafeTransferFrom` and `safeTransferFrom` throw on any error, so // if we're here - it means operation successful, // just return true return true; } /** * @notice Transfers some tokens on behalf of address `_from' (token owner) * to some other address `_to` * * @dev Inspired by ERC721 safeTransferFrom, this function allows to * send arbitrary data to the receiver on successful token transfer * @dev Called by token owner on his own or approved address, * an address approved earlier by token owner to * transfer some amount of tokens on its behalf * @dev Throws on any error like * * insufficient token balance or * * incorrect `_to` address: * * zero address or * * same as `_from` address (self transfer) * * smart contract which doesn't support ERC20Receiver interface * @dev Returns silently on success, throws otherwise * * @param _from token owner which approved caller (transaction sender) * to transfer `_value` of tokens on its behalf * @param _to an address to transfer tokens to, * must be either an external address or a smart contract, * compliant with the ERC20 standard * @param _value amount of tokens to be transferred, must * be greater than zero * @param _data [optional] additional data with no specified format, * sent in onERC20Received call to `_to` in case if its a smart contract */ function safeTransferFrom(address _from, address _to, uint256 _value, bytes memory _data) public { // first delegate call to `unsafeTransferFrom` // to perform the unsafe token(s) transfer unsafeTransferFrom(_from, _to, _value); // after the successful transfer - check if receiver supports // ERC20Receiver and execute a callback handler `onERC20Received`, // reverting whole transaction on any error: // check if receiver `_to` supports ERC20Receiver interface if(AddressUtils.isContract(_to)) { // if `_to` is a contract - execute onERC20Received //bytes4 response = ERC20Receiver(_to).onERC20Received(msg.sender, _from, _value, _data); // expected response is ERC20_RECEIVED //require(response == ERC20_RECEIVED, "invalid onERC20Received response"); } } /** * @notice Transfers some tokens on behalf of address `_from' (token owner) * to some other address `_to` * * @dev In contrast to `safeTransferFrom` doesn't check recipient * smart contract to support ERC20 tokens (ERC20Receiver) * @dev Designed to be used by developers when the receiver is known * to support ERC20 tokens but doesn't implement ERC20Receiver interface * @dev Called by token owner on his own or approved address, * an address approved earlier by token owner to * transfer some amount of tokens on its behalf * @dev Throws on any error like * * insufficient token balance or * * incorrect `_to` address: * * zero address or * * same as `_from` address (self transfer) * @dev Returns silently on success, throws otherwise * * @param _from token owner which approved caller (transaction sender) * to transfer `_value` of tokens on its behalf * @param _to an address to transfer tokens to, * must be either an external address or a smart contract, * compliant with the ERC20 standard * @param _value amount of tokens to be transferred, must * be greater than zero */ function unsafeTransferFrom(address _from, address _to, uint256 _value) public { //require(isFeatureEnabled(FEATURE_TRANSFERS), "why is transfer disabled?"); //require(isFeatureEnabled(FEATURE_TRANSFERS_ON_BEHALF), "why is transfer on behalf disabled?"); // if `_from` is equal to sender, require transfers feature to be enabled // otherwise require transfers on behalf feature to be enabled //require(_from == msg.sender && isFeatureEnabled(FEATURE_TRANSFERS) // || _from != msg.sender && isFeatureEnabled(FEATURE_TRANSFERS_ON_BEHALF), // _from == msg.sender? "transfers are disabled": "transfers on behalf are disabled"); // non-zero source address check - Zeppelin // obviously, zero source address is a client mistake // it's not part of ERC20 standard but it's reasonable to fail fast // since for zero value transfer transaction succeeds otherwise require(_from != address(0), "ERC20: transfer from the zero address"); // Zeppelin msg // non-zero recipient address check require(_to != address(0), "ERC20: transfer to the zero address"); // Zeppelin msg // sender and recipient cannot be the same require(_from != _to, "sender and recipient are the same (_from = _to)"); // sending tokens to the token smart contract itself is a client mistake require(_to != address(this), "invalid recipient (transfer to the token smart contract itself)"); // according to ERC-20 Token Standard, https://eips.ethereum.org/EIPS/eip-20 // "Transfers of 0 values MUST be treated as normal transfers and fire the Transfer event." if(_value == 0) { // emit an ERC20 transfer event emit Transfer(_from, _to, _value); // don't forget to return - we're done return; } // no need to make arithmetic overflow check on the _value - by design of mint() // in case of transfer on behalf if(_from != msg.sender) { // read allowance value - the amount of tokens allowed to transfer - into the stack uint256 _allowance = transferAllowances[_from][msg.sender]; // verify sender has an allowance to transfer amount of tokens requested require(_allowance >= _value, "ERC20: transfer amount exceeds allowance"); // Zeppelin msg // update allowance value on the stack _allowance -= _value; // update the allowance value in storage transferAllowances[_from][msg.sender] = _allowance; // emit an improved atomic approve event emit Approved(_from, msg.sender, _allowance + _value, _allowance); // emit an ERC20 approval event to reflect the decrease emit Approval(_from, msg.sender, _allowance); } // verify sender has enough tokens to transfer on behalf require(tokenBalances[_from] >= _value, "ERC20: transfer amount exceeds balance"); // Zeppelin msg // perform the transfer: // decrease token owner (sender) balance tokenBalances[_from] -= _value; // increase `_to` address (receiver) balance tokenBalances[_to] += _value; // move voting power associated with the tokens transferred __moveVotingPower(votingDelegates[_from], votingDelegates[_to], _value); // emit an improved transfer event emit Transferred(msg.sender, _from, _to, _value); // emit an ERC20 transfer event emit Transfer(_from, _to, _value); } /** * @notice Approves address called `_spender` to transfer some amount * of tokens on behalf of the owner * * @dev ERC20 `function approve(address _spender, uint256 _value) public returns (bool success)` * * @dev Caller must not necessarily own any tokens to grant the permission * * @param _spender an address approved by the caller (token owner) * to spend some tokens on its behalf * @param _value an amount of tokens spender `_spender` is allowed to * transfer on behalf of the token owner * @return success true on success, throws otherwise */ function approve(address _spender, uint256 _value) public returns (bool success) { // non-zero spender address check - Zeppelin // obviously, zero spender address is a client mistake // it's not part of ERC20 standard but it's reasonable to fail fast require(_spender != address(0), "ERC20: approve to the zero address"); // Zeppelin msg // read old approval value to emmit an improved event (ISBN:978-1-7281-3027-9) uint256 _oldValue = transferAllowances[msg.sender][_spender]; // perform an operation: write value requested into the storage transferAllowances[msg.sender][_spender] = _value; // emit an improved atomic approve event (ISBN:978-1-7281-3027-9) emit Approved(msg.sender, _spender, _oldValue, _value); // emit an ERC20 approval event emit Approval(msg.sender, _spender, _value); // operation successful, return true return true; } /** * @notice Returns the amount which _spender is still allowed to withdraw from _owner. * * @dev ERC20 `function allowance(address _owner, address _spender) public view returns (uint256 remaining)` * * @dev A function to check an amount of tokens owner approved * to transfer on its behalf by some other address called "spender" * * @param _owner an address which approves transferring some tokens on its behalf * @param _spender an address approved to transfer some tokens on behalf * @return remaining an amount of tokens approved address `_spender` can transfer on behalf * of token owner `_owner` */ function allowance(address _owner, address _spender) public view returns (uint256 remaining) { // read the value from storage and return return transferAllowances[_owner][_spender]; } // ===== End: ERC20/ERC223/ERC777 functions ===== // ===== Start: Resolution for the Multiple Withdrawal Attack on ERC20 Tokens (ISBN:978-1-7281-3027-9) ===== /** * @notice Increases the allowance granted to `spender` by the transaction sender * * @dev Resolution for the Multiple Withdrawal Attack on ERC20 Tokens (ISBN:978-1-7281-3027-9) * * @dev Throws if value to increase by is zero or too big and causes arithmetic overflow * * @param _spender an address approved by the caller (token owner) * to spend some tokens on its behalf * @param _value an amount of tokens to increase by * @return success true on success, throws otherwise */ function increaseAllowance(address _spender, uint256 _value) public virtual returns (bool) { // read current allowance value uint256 currentVal = transferAllowances[msg.sender][_spender]; // non-zero _value and arithmetic overflow check on the allowance require(currentVal + _value > currentVal, "zero value approval increase or arithmetic overflow"); // delegate call to `approve` with the new value return approve(_spender, currentVal + _value); } /** * @notice Decreases the allowance granted to `spender` by the caller. * * @dev Resolution for the Multiple Withdrawal Attack on ERC20 Tokens (ISBN:978-1-7281-3027-9) * * @dev Throws if value to decrease by is zero or is bigger than currently allowed value * * @param _spender an address approved by the caller (token owner) * to spend some tokens on its behalf * @param _value an amount of tokens to decrease by * @return success true on success, throws otherwise */ function decreaseAllowance(address _spender, uint256 _value) public virtual returns (bool) { // read current allowance value uint256 currentVal = transferAllowances[msg.sender][_spender]; // non-zero _value check on the allowance require(_value > 0, "zero value approval decrease"); // verify allowance decrease doesn't underflow require(currentVal >= _value, "ERC20: decreased allowance below zero"); // delegate call to `approve` with the new value return approve(_spender, currentVal - _value); } // ===== End: Resolution for the Multiple Withdrawal Attack on ERC20 Tokens (ISBN:978-1-7281-3027-9) ===== // ===== Start: Minting/burning extension ===== /** * @dev Mints (creates) some tokens to address specified * @dev The value specified is treated as is without taking * into account what `decimals` value is * @dev Behaves effectively as `mintTo` function, allowing * to specify an address to mint tokens to * @dev Requires sender to have `ROLE_TOKEN_CREATOR` permission * * @dev Throws on overflow, if totalSupply + _value doesn't fit into uint256 * * @param _to an address to mint tokens to * @param _value an amount of tokens to mint (create) */ function mint(address _to, uint256 _value) public { // check if caller has sufficient permissions to mint tokens require(isSenderInRole(ROLE_TOKEN_CREATOR), "insufficient privileges (ROLE_TOKEN_CREATOR required)"); // non-zero recipient address check require(_to != address(0), "ERC20: mint to the zero address"); // Zeppelin msg // non-zero _value and arithmetic overflow check on the total supply // this check automatically secures arithmetic overflow on the individual balance require(totalSupply + _value > totalSupply, "zero value mint or arithmetic overflow"); // uint192 overflow check (required by voting delegation) require(totalSupply + _value <= type(uint192).max, "total supply overflow (uint192)"); // perform mint: // increase total amount of tokens value totalSupply += _value; // increase `_to` address balance tokenBalances[_to] += _value; // create voting power associated with the tokens minted __moveVotingPower(address(0), votingDelegates[_to], _value); // fire a minted event emit Minted(msg.sender, _to, _value); // emit an improved transfer event emit Transferred(msg.sender, address(0), _to, _value); // fire ERC20 compliant transfer event emit Transfer(address(0), _to, _value); } /** * @dev Burns (destroys) some tokens from the address specified * @dev The value specified is treated as is without taking * into account what `decimals` value is * @dev Behaves effectively as `burnFrom` function, allowing * to specify an address to burn tokens from * @dev Requires sender to have `ROLE_TOKEN_DESTROYER` permission * * @param _from an address to burn some tokens from * @param _value an amount of tokens to burn (destroy) */ function burn(address _from, uint256 _value) public { // check if caller has sufficient permissions to burn tokens // and if not - check for possibility to burn own tokens or to burn on behalf if(!isSenderInRole(ROLE_TOKEN_DESTROYER)) { // if `_from` is equal to sender, require own burns feature to be enabled // otherwise require burns on behalf feature to be enabled require(_from == msg.sender && isFeatureEnabled(FEATURE_OWN_BURNS) || _from != msg.sender && isFeatureEnabled(FEATURE_BURNS_ON_BEHALF), _from == msg.sender? "burns are disabled": "burns on behalf are disabled"); // in case of burn on behalf if(_from != msg.sender) { // read allowance value - the amount of tokens allowed to be burnt - into the stack uint256 _allowance = transferAllowances[_from][msg.sender]; // verify sender has an allowance to burn amount of tokens requested require(_allowance >= _value, "ERC20: burn amount exceeds allowance"); // Zeppelin msg // update allowance value on the stack _allowance -= _value; // update the allowance value in storage transferAllowances[_from][msg.sender] = _allowance; // emit an improved atomic approve event emit Approved(msg.sender, _from, _allowance + _value, _allowance); // emit an ERC20 approval event to reflect the decrease emit Approval(_from, msg.sender, _allowance); } } // at this point we know that either sender is ROLE_TOKEN_DESTROYER or // we burn own tokens or on behalf (in latest case we already checked and updated allowances) // we have left to execute balance checks and burning logic itself // non-zero burn value check require(_value != 0, "zero value burn"); // non-zero source address check - Zeppelin require(_from != address(0), "ERC20: burn from the zero address"); // Zeppelin msg // verify `_from` address has enough tokens to destroy // (basically this is a arithmetic overflow check) require(tokenBalances[_from] >= _value, "ERC20: burn amount exceeds balance"); // Zeppelin msg // perform burn: // decrease `_from` address balance tokenBalances[_from] -= _value; // decrease total amount of tokens value totalSupply -= _value; // destroy voting power associated with the tokens burnt __moveVotingPower(votingDelegates[_from], address(0), _value); // fire a burnt event emit Burnt(msg.sender, _from, _value); // emit an improved transfer event emit Transferred(msg.sender, _from, address(0), _value); // fire ERC20 compliant transfer event emit Transfer(_from, address(0), _value); } // ===== End: Minting/burning extension ===== // ===== Start: DAO Support (Compound-like voting delegation) ===== /** * @notice Gets current voting power of the account `_of` * @param _of the address of account to get voting power of * @return current cumulative voting power of the account, * sum of token balances of all its voting delegators */ function getVotingPower(address _of) public view returns (uint256) { // get a link to an array of voting power history records for an address specified VotingPowerRecord[] storage history = votingPowerHistory[_of]; // lookup the history and return latest element return history.length == 0? 0: history[history.length - 1].votingPower; } /** * @notice Gets past voting power of the account `_of` at some block `_blockNum` * @dev Throws if `_blockNum` is not in the past (not the finalized block) * @param _of the address of account to get voting power of * @param _blockNum block number to get the voting power at * @return past cumulative voting power of the account, * sum of token balances of all its voting delegators at block number `_blockNum` */ function getVotingPowerAt(address _of, uint256 _blockNum) public view returns (uint256) { // make sure block number is not in the past (not the finalized block) require(_blockNum < block.number, "not yet determined"); // Compound msg // get a link to an array of voting power history records for an address specified VotingPowerRecord[] storage history = votingPowerHistory[_of]; // if voting power history for the account provided is empty if(history.length == 0) { // than voting power is zero - return the result return 0; } // check latest voting power history record block number: // if history was not updated after the block of interest if(history[history.length - 1].blockNumber <= _blockNum) { // we're done - return last voting power record return getVotingPower(_of); } // check first voting power history record block number: // if history was never updated before the block of interest if(history[0].blockNumber > _blockNum) { // we're done - voting power at the block num of interest was zero return 0; } // `votingPowerHistory[_of]` is an array ordered by `blockNumber`, ascending; // apply binary search on `votingPowerHistory[_of]` to find such an entry number `i`, that // `votingPowerHistory[_of][i].blockNumber <= _blockNum`, but in the same time // `votingPowerHistory[_of][i + 1].blockNumber > _blockNum` // return the result - voting power found at index `i` return history[__binaryLookup(_of, _blockNum)].votingPower; } /** * @dev Reads an entire voting power history array for the delegate specified * * @param _of delegate to query voting power history for * @return voting power history array for the delegate of interest */ function getVotingPowerHistory(address _of) public view returns(VotingPowerRecord[] memory) { // return an entire array as memory return votingPowerHistory[_of]; } /** * @dev Returns length of the voting power history array for the delegate specified; * useful since reading an entire array just to get its length is expensive (gas cost) * * @param _of delegate to query voting power history length for * @return voting power history array length for the delegate of interest */ function getVotingPowerHistoryLength(address _of) public view returns(uint256) { // read array length and return return votingPowerHistory[_of].length; } /** * @notice Delegates voting power of the delegator `msg.sender` to the delegate `_to` * * @dev Accepts zero value address to delegate voting power to, effectively * removing the delegate in that case * * @param _to address to delegate voting power to */ function delegate(address _to) public { // verify delegations are enabled require(isFeatureEnabled(FEATURE_DELEGATIONS), "delegations are disabled"); // delegate call to `__delegate` __delegate(msg.sender, _to); } /** * @notice Delegates voting power of the delegator (represented by its signature) to the delegate `_to` * * @dev Accepts zero value address to delegate voting power to, effectively * removing the delegate in that case * * @dev Compliant with EIP-712: Ethereum typed structured data hashing and signing, * see https://eips.ethereum.org/EIPS/eip-712 * * @param _to address to delegate voting power to * @param _nonce nonce used to construct the signature, and used to validate it; * nonce is increased by one after successful signature validation and vote delegation * @param _exp signature expiration time * @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 delegateWithSig(address _to, uint256 _nonce, uint256 _exp, uint8 v, bytes32 r, bytes32 s) public { // verify delegations on behalf are enabled require(isFeatureEnabled(FEATURE_DELEGATIONS_ON_BEHALF), "delegations on behalf are disabled"); // build the EIP-712 contract domain separator bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), block.chainid, address(this))); // build the EIP-712 hashStruct of the delegation message bytes32 hashStruct = keccak256(abi.encode(DELEGATION_TYPEHASH, _to, _nonce, _exp)); // calculate the EIP-712 digest "\x19\x01" ‖ domainSeparator ‖ hashStruct(message) bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, hashStruct)); // recover the address who signed the message with v, r, s address signer = ecrecover(digest, v, r, s); // perform message integrity and security validations require(signer != address(0), "invalid signature"); // Compound msg require(_nonce == nonces[signer], "invalid nonce"); // Compound msg require(block.timestamp < _exp, "signature expired"); // Compound msg // update the nonce for that particular signer to avoid replay attack nonces[signer]++; // delegate call to `__delegate` - execute the logic required __delegate(signer, _to); } /** * @dev Auxiliary function to delegate delegator's `_from` voting power to the delegate `_to` * @dev Writes to `votingDelegates` and `votingPowerHistory` mappings * * @param _from delegator who delegates his voting power * @param _to delegate who receives the voting power */ function __delegate(address _from, address _to) private { // read current delegate to be replaced by a new one address _fromDelegate = votingDelegates[_from]; // read current voting power (it is equal to token balance) uint256 _value = tokenBalances[_from]; // reassign voting delegate to `_to` votingDelegates[_from] = _to; // update voting power for `_fromDelegate` and `_to` __moveVotingPower(_fromDelegate, _to, _value); // emit an event emit DelegateChanged(_from, _fromDelegate, _to); } /** * @dev Auxiliary function to move voting power `_value` * from delegate `_from` to the delegate `_to` * * @dev Doesn't have any effect if `_from == _to`, or if `_value == 0` * * @param _from delegate to move voting power from * @param _to delegate to move voting power to * @param _value voting power to move from `_from` to `_to` */ function __moveVotingPower(address _from, address _to, uint256 _value) private { // if there is no move (`_from == _to`) or there is nothing to move (`_value == 0`) if(_from == _to || _value == 0) { // return silently with no action return; } // if source address is not zero - decrease its voting power if(_from != address(0)) { // read current source address voting power uint256 _fromVal = getVotingPower(_from); // calculate decreased voting power // underflow is not possible by design: // voting power is limited by token balance which is checked by the callee uint256 _toVal = _fromVal - _value; // update source voting power from `_fromVal` to `_toVal` __updateVotingPower(_from, _fromVal, _toVal); } // if destination address is not zero - increase its voting power if(_to != address(0)) { // read current destination address voting power uint256 _fromVal = getVotingPower(_to); // calculate increased voting power // overflow is not possible by design: // max token supply limits the cumulative voting power uint256 _toVal = _fromVal + _value; // update destination voting power from `_fromVal` to `_toVal` __updateVotingPower(_to, _fromVal, _toVal); } } /** * @dev Auxiliary function to update voting power of the delegate `_of` * from value `_fromVal` to value `_toVal` * * @param _of delegate to update its voting power * @param _fromVal old voting power of the delegate * @param _toVal new voting power of the delegate */ function __updateVotingPower(address _of, uint256 _fromVal, uint256 _toVal) private { // get a link to an array of voting power history records for an address specified VotingPowerRecord[] storage history = votingPowerHistory[_of]; // if there is an existing voting power value stored for current block if(history.length != 0 && history[history.length - 1].blockNumber == block.number) { // update voting power which is already stored in the current block history[history.length - 1].votingPower = uint192(_toVal); } // otherwise - if there is no value stored for current block else { // add new element into array representing the value for current block history.push(VotingPowerRecord(uint64(block.number), uint192(_toVal))); } // emit an event emit VotingPowerChanged(_of, _fromVal, _toVal); } /** * @dev Auxiliary function to lookup an element in a sorted (asc) array of elements * * @dev This function finds the closest element in an array to the value * of interest (not exceeding that value) and returns its index within an array * * @dev An array to search in is `votingPowerHistory[_to][i].blockNumber`, * it is sorted in ascending order (blockNumber increases) * * @param _to an address of the delegate to get an array for * @param n value of interest to look for * @return an index of the closest element in an array to the value * of interest (not exceeding that value) */ function __binaryLookup(address _to, uint256 n) private view returns(uint256) { // get a link to an array of voting power history records for an address specified VotingPowerRecord[] storage history = votingPowerHistory[_to]; // left bound of the search interval, originally start of the array uint256 i = 0; // right bound of the search interval, originally end of the array uint256 j = history.length - 1; // the iteration process narrows down the bounds by // splitting the interval in a half oce per each iteration while(j > i) { // get an index in the middle of the interval [i, j] uint256 k = j - (j - i) / 2; // read an element to compare it with the value of interest VotingPowerRecord memory cp = history[k]; // if we've got a strict equal - we're lucky and done if(cp.blockNumber == n) { // just return the result - index `k` return k; } // if the value of interest is bigger - move left bound to the middle else if (cp.blockNumber < n) { // move left bound `i` to the middle position `k` i = k; } // otherwise, when the value of interest is smaller - move right bound to the middle else { // move right bound `j` to the middle position `k - 1`: // element at position `k` is bigger and cannot be the result j = k - 1; } } // reaching that point means no exact match found // since we're interested in the element which is not bigger than the // element of interest, we return the lower bound `i` return i; } }
contract DominoERC20 is AccessControl { /** * @dev Smart contract unique identifier, a random number * @dev Should be regenerated each time smart contact source code is changed * and changes smart contract itself is to be redeployed * @dev Generated using https://www.random.org/bytes/ */ uint256 public constant TOKEN_UID = 0x83ecb176af7c4f35a45ff0018282e3a05a1018065da866182df12285866f5a2c; /** * @notice Name of the token: Domino * * @notice ERC20 name of the token (long name) * * @dev ERC20 `function name() public view returns (string)` * * @dev Field is declared public: getter name() is created when compiled, * it returns the name of the token. */ string public constant name = "Domino"; /** * @notice Symbol of the token: DOMI * * @notice ERC20 symbol of that token (short name) * * @dev ERC20 `function symbol() public view returns (string)` * * @dev Field is declared public: getter symbol() is created when compiled, * it returns the symbol of the token */ string public constant symbol = "DOMI"; /** * @notice Decimals of the token: 18 * * @dev ERC20 `function decimals() public view returns (uint8)` * * @dev Field is declared public: getter decimals() is created when compiled, * it returns the number of decimals used to get its user representation. * For example, if `decimals` equals `6`, a balance of `1,500,000` tokens should * be displayed to a user as `1,5` (`1,500,000 / 10 ** 6`). * * @dev NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including balanceOf() and transfer(). */ uint8 public constant decimals = 18; /** * @notice Total supply of the token: initially 70,000,000, * with the potential to grow up to 10,000,000 during yield farming period (3 years) * * @dev ERC20 `function totalSupply() public view returns (uint256)` * * @dev Field is declared public: getter totalSupply() is created when compiled, * it returns the amount of tokens in existence. */ uint256 public totalSupply; // is set to 70 million * 10^18 in the constructor /** * @dev A record of all the token balances * @dev This mapping keeps record of all token owners: * owner => balance */ mapping(address => uint256) public tokenBalances; /** * @notice A record of each account's voting delegate * * @dev Auxiliary data structure used to sum up an account's voting power * * @dev This mapping keeps record of all voting power delegations: * voting delegator (token owner) => voting delegate */ mapping(address => address) public votingDelegates; /** * @notice A voting power record binds voting power of a delegate to a particular * block when the voting power delegation change happened */ struct VotingPowerRecord { /* * @dev block.number when delegation has changed; starting from * that block voting power value is in effect */ uint64 blockNumber; /* * @dev cumulative voting power a delegate has obtained starting * from the block stored in blockNumber */ uint192 votingPower; } /** * @notice A record of each account's voting power * * @dev Primarily data structure to store voting power for each account. * Voting power sums up from the account's token balance and delegated * balances. * * @dev Stores current value and entire history of its changes. * The changes are stored as an array of checkpoints. * Checkpoint is an auxiliary data structure containing voting * power (number of votes) and block number when the checkpoint is saved * * @dev Maps voting delegate => voting power record */ mapping(address => VotingPowerRecord[]) public votingPowerHistory; /** * @dev A record of nonces for signing/validating signatures in `delegateWithSig` * for every delegate, increases after successful validation * * @dev Maps delegate address => delegate nonce */ mapping(address => uint256) public nonces; /** * @notice A record of all the allowances to spend tokens on behalf * @dev Maps token owner address to an address approved to spend * some tokens on behalf, maps approved address to that amount * @dev owner => spender => value */ mapping(address => mapping(address => uint256)) public transferAllowances; /** * @notice Enables ERC20 transfers of the tokens * (transfer by the token owner himself) * @dev Feature FEATURE_TRANSFERS must be enabled in order for * `transfer()` function to succeed */ uint32 public constant FEATURE_TRANSFERS = 0x0000_0001; /** * @notice Enables ERC20 transfers on behalf * (transfer by someone else on behalf of token owner) * @dev Feature FEATURE_TRANSFERS_ON_BEHALF must be enabled in order for * `transferFrom()` function to succeed * @dev Token owner must call `approve()` first to authorize * the transfer on behalf */ uint32 public constant FEATURE_TRANSFERS_ON_BEHALF = 0x0000_0002; /** * @dev Defines if the default behavior of `transfer` and `transferFrom` * checks if the receiver smart contract supports ERC20 tokens * @dev When feature FEATURE_UNSAFE_TRANSFERS is enabled the transfers do not * check if the receiver smart contract supports ERC20 tokens, * i.e. `transfer` and `transferFrom` behave like `unsafeTransferFrom` * @dev When feature FEATURE_UNSAFE_TRANSFERS is disabled (default) the transfers * check if the receiver smart contract supports ERC20 tokens, * i.e. `transfer` and `transferFrom` behave like `safeTransferFrom` */ uint32 public constant FEATURE_UNSAFE_TRANSFERS = 0x0000_0004; /** * @notice Enables token owners to burn their own tokens, * including locked tokens which are burnt first * @dev Feature FEATURE_OWN_BURNS must be enabled in order for * `burn()` function to succeed when called by token owner */ uint32 public constant FEATURE_OWN_BURNS = 0x0000_0008; /** * @notice Enables approved operators to burn tokens on behalf of their owners, * including locked tokens which are burnt first * @dev Feature FEATURE_OWN_BURNS must be enabled in order for * `burn()` function to succeed when called by approved operator */ uint32 public constant FEATURE_BURNS_ON_BEHALF = 0x0000_0010; /** * @notice Enables delegators to elect delegates * @dev Feature FEATURE_DELEGATIONS must be enabled in order for * `delegate()` function to succeed */ uint32 public constant FEATURE_DELEGATIONS = 0x0000_0020; /** * @notice Enables delegators to elect delegates on behalf * (via an EIP712 signature) * @dev Feature FEATURE_DELEGATIONS must be enabled in order for * `delegateWithSig()` function to succeed */ uint32 public constant FEATURE_DELEGATIONS_ON_BEHALF = 0x0000_0040; /** * @notice Token creator is responsible for creating (minting) * tokens to an arbitrary address * @dev Role ROLE_TOKEN_CREATOR allows minting tokens * (calling `mint` function) */ uint32 public constant ROLE_TOKEN_CREATOR = 0x0001_0000; /** * @notice Token destroyer is responsible for destroying (burning) * tokens owned by an arbitrary address * @dev Role ROLE_TOKEN_DESTROYER allows burning tokens * (calling `burn` function) */ uint32 public constant ROLE_TOKEN_DESTROYER = 0x0002_0000; /** * @notice ERC20 receivers are allowed to receive tokens without ERC20 safety checks, * which may be useful to simplify tokens transfers into "legacy" smart contracts * @dev When `FEATURE_UNSAFE_TRANSFERS` is not enabled addresses having * `ROLE_ERC20_RECEIVER` permission are allowed to receive tokens * via `transfer` and `transferFrom` functions in the same way they * would via `unsafeTransferFrom` function * @dev When `FEATURE_UNSAFE_TRANSFERS` is enabled `ROLE_ERC20_RECEIVER` permission * doesn't affect the transfer behaviour since * `transfer` and `transferFrom` behave like `unsafeTransferFrom` for any receiver * @dev ROLE_ERC20_RECEIVER is a shortening for ROLE_UNSAFE_ERC20_RECEIVER */ uint32 public constant ROLE_ERC20_RECEIVER = 0x0004_0000; /** * @notice ERC20 senders are allowed to send tokens without ERC20 safety checks, * which may be useful to simplify tokens transfers into "legacy" smart contracts * @dev When `FEATURE_UNSAFE_TRANSFERS` is not enabled senders having * `ROLE_ERC20_SENDER` permission are allowed to send tokens * via `transfer` and `transferFrom` functions in the same way they * would via `unsafeTransferFrom` function * @dev When `FEATURE_UNSAFE_TRANSFERS` is enabled `ROLE_ERC20_SENDER` permission * doesn't affect the transfer behaviour since * `transfer` and `transferFrom` behave like `unsafeTransferFrom` for any receiver * @dev ROLE_ERC20_SENDER is a shortening for ROLE_UNSAFE_ERC20_SENDER */ uint32 public constant ROLE_ERC20_SENDER = 0x0008_0000; /** * @dev Magic value to be returned by ERC20Receiver upon successful reception of token(s) * @dev Equal to `bytes4(keccak256("onERC20Received(address,address,uint256,bytes)"))`, * which can be also obtained as `ERC20Receiver(address(0)).onERC20Received.selector` */ bytes4 private constant ERC20_RECEIVED = 0x4fc35859; /** * @notice EIP-712 contract's domain typeHash, see https://eips.ethereum.org/EIPS/eip-712#rationale-for-typehash */ bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /** * @notice EIP-712 delegation struct typeHash, see https://eips.ethereum.org/EIPS/eip-712#rationale-for-typehash */ bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegate,uint256 nonce,uint256 expiry)"); /** * @dev Fired in transfer(), transferFrom() and some other (non-ERC20) functions * * @dev ERC20 `event Transfer(address indexed _from, address indexed _to, uint256 _value)` * * @param _from an address tokens were consumed from * @param _to an address tokens were sent to * @param _value number of tokens transferred */ event Transfer(address indexed _from, address indexed _to, uint256 _value); /** * @dev Fired in approve() and approveAtomic() functions * * @dev ERC20 `event Approval(address indexed _owner, address indexed _spender, uint256 _value)` * * @param _owner an address which granted a permission to transfer * tokens on its behalf * @param _spender an address which received a permission to transfer * tokens on behalf of the owner `_owner` * @param _value amount of tokens granted to transfer on behalf */ event Approval(address indexed _owner, address indexed _spender, uint256 _value); /** * @dev Fired in mint() function * * @param _by an address which minted some tokens (transaction sender) * @param _to an address the tokens were minted to * @param _value an amount of tokens minted */ event Minted(address indexed _by, address indexed _to, uint256 _value); /** * @dev Fired in burn() function * * @param _by an address which burned some tokens (transaction sender) * @param _from an address the tokens were burnt from * @param _value an amount of tokens burnt */ event Burnt(address indexed _by, address indexed _from, uint256 _value); /** * @dev Resolution for the Multiple Withdrawal Attack on ERC20 Tokens (ISBN:978-1-7281-3027-9) * * @dev Similar to ERC20 Transfer event, but also logs an address which executed transfer * * @dev Fired in transfer(), transferFrom() and some other (non-ERC20) functions * * @param _by an address which performed the transfer * @param _from an address tokens were consumed from * @param _to an address tokens were sent to * @param _value number of tokens transferred */ event Transferred(address indexed _by, address indexed _from, address indexed _to, uint256 _value); /** * @dev Resolution for the Multiple Withdrawal Attack on ERC20 Tokens (ISBN:978-1-7281-3027-9) * * @dev Similar to ERC20 Approve event, but also logs old approval value * * @dev Fired in approve() and approveAtomic() functions * * @param _owner an address which granted a permission to transfer * tokens on its behalf * @param _spender an address which received a permission to transfer * tokens on behalf of the owner `_owner` * @param _oldValue previously granted amount of tokens to transfer on behalf * @param _value new granted amount of tokens to transfer on behalf */ event Approved(address indexed _owner, address indexed _spender, uint256 _oldValue, uint256 _value); /** * @dev Notifies that a key-value pair in `votingDelegates` mapping has changed, * i.e. a delegator address has changed its delegate address * * @param _of delegator address, a token owner * @param _from old delegate, an address which delegate right is revoked * @param _to new delegate, an address which received the voting power */ event DelegateChanged(address indexed _of, address indexed _from, address indexed _to); /** * @dev Notifies that a key-value pair in `votingPowerHistory` mapping has changed, * i.e. a delegate's voting power has changed. * * @param _of delegate whose voting power has changed * @param _fromVal previous number of votes delegate had * @param _toVal new number of votes delegate has */ event VotingPowerChanged(address indexed _of, uint256 _fromVal, uint256 _toVal); /** * @dev Deploys the token smart contract, * assigns initial token supply to the address specified * * @param _initialHolder owner of the initial token supply */ constructor(address _initialHolder) { // verify initial holder address non-zero (is set) require(_initialHolder != address(0), "_initialHolder not set (zero address)"); // mint initial supply mint(_initialHolder, 70_000_000e18); } // ===== Start: ERC20/ERC223/ERC777 functions ===== /** * @notice Gets the balance of a particular address * * @dev ERC20 `function balanceOf(address _owner) public view returns (uint256 balance)` * * @param _owner the address to query the the balance for * @return balance an amount of tokens owned by the address specified */ function balanceOf(address _owner) public view returns (uint256 balance) { // read the balance and return return tokenBalances[_owner]; } /** * @notice Transfers some tokens to an external address or a smart contract * * @dev ERC20 `function transfer(address _to, uint256 _value) public returns (bool success)` * * @dev Called by token owner (an address which has a * positive token balance tracked by this smart contract) * @dev Throws on any error like * * insufficient token balance or * * incorrect `_to` address: * * zero address or * * self address or * * smart contract which doesn't support ERC20 * * @param _to an address to transfer tokens to, * must be either an external address or a smart contract, * compliant with the ERC20 standard * @param _value amount of tokens to be transferred, must * be greater than zero * @return success true on success, throws otherwise */ function transfer(address _to, uint256 _value) public returns (bool success) { // just delegate call to `transferFrom`, // `FEATURE_TRANSFERS` is verified inside it return transferFrom(msg.sender, _to, _value); } /** * @notice Transfers some tokens on behalf of address `_from' (token owner) * to some other address `_to` * * @dev ERC20 `function transferFrom(address _from, address _to, uint256 _value) public returns (bool success)` * * @dev Called by token owner on his own or approved address, * an address approved earlier by token owner to * transfer some amount of tokens on its behalf * @dev Throws on any error like * * insufficient token balance or * * incorrect `_to` address: * * zero address or * * same as `_from` address (self transfer) * * smart contract which doesn't support ERC20 * * @param _from token owner which approved caller (transaction sender) * to transfer `_value` of tokens on its behalf * @param _to an address to transfer tokens to, * must be either an external address or a smart contract, * compliant with the ERC20 standard * @param _value amount of tokens to be transferred, must * be greater than zero * @return success true on success, throws otherwise */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { // depending on `FEATURE_UNSAFE_TRANSFERS` we execute either safe (default) // or unsafe transfer // if `FEATURE_UNSAFE_TRANSFERS` is enabled // or receiver has `ROLE_ERC20_RECEIVER` permission // or sender has `ROLE_ERC20_SENDER` permission if(isFeatureEnabled(FEATURE_UNSAFE_TRANSFERS) || isOperatorInRole(_to, ROLE_ERC20_RECEIVER) || isSenderInRole(ROLE_ERC20_SENDER)) { // we execute unsafe transfer - delegate call to `unsafeTransferFrom`, // `FEATURE_TRANSFERS` is verified inside it unsafeTransferFrom(_from, _to, _value); } // otherwise - if `FEATURE_UNSAFE_TRANSFERS` is disabled // and receiver doesn't have `ROLE_ERC20_RECEIVER` permission else { // we execute safe transfer - delegate call to `safeTransferFrom`, passing empty `_data`, // `FEATURE_TRANSFERS` is verified inside it safeTransferFrom(_from, _to, _value, ""); } // both `unsafeTransferFrom` and `safeTransferFrom` throw on any error, so // if we're here - it means operation successful, // just return true return true; } /** * @notice Transfers some tokens on behalf of address `_from' (token owner) * to some other address `_to` * * @dev Inspired by ERC721 safeTransferFrom, this function allows to * send arbitrary data to the receiver on successful token transfer * @dev Called by token owner on his own or approved address, * an address approved earlier by token owner to * transfer some amount of tokens on its behalf * @dev Throws on any error like * * insufficient token balance or * * incorrect `_to` address: * * zero address or * * same as `_from` address (self transfer) * * smart contract which doesn't support ERC20Receiver interface * @dev Returns silently on success, throws otherwise * * @param _from token owner which approved caller (transaction sender) * to transfer `_value` of tokens on its behalf * @param _to an address to transfer tokens to, * must be either an external address or a smart contract, * compliant with the ERC20 standard * @param _value amount of tokens to be transferred, must * be greater than zero * @param _data [optional] additional data with no specified format, * sent in onERC20Received call to `_to` in case if its a smart contract */ function safeTransferFrom(address _from, address _to, uint256 _value, bytes memory _data) public { // first delegate call to `unsafeTransferFrom` // to perform the unsafe token(s) transfer unsafeTransferFrom(_from, _to, _value); // after the successful transfer - check if receiver supports // ERC20Receiver and execute a callback handler `onERC20Received`, // reverting whole transaction on any error: // check if receiver `_to` supports ERC20Receiver interface if(AddressUtils.isContract(_to)) { // if `_to` is a contract - execute onERC20Received //bytes4 response = ERC20Receiver(_to).onERC20Received(msg.sender, _from, _value, _data); // expected response is ERC20_RECEIVED //require(response == ERC20_RECEIVED, "invalid onERC20Received response"); } } /** * @notice Transfers some tokens on behalf of address `_from' (token owner) * to some other address `_to` * * @dev In contrast to `safeTransferFrom` doesn't check recipient * smart contract to support ERC20 tokens (ERC20Receiver) * @dev Designed to be used by developers when the receiver is known * to support ERC20 tokens but doesn't implement ERC20Receiver interface * @dev Called by token owner on his own or approved address, * an address approved earlier by token owner to * transfer some amount of tokens on its behalf * @dev Throws on any error like * * insufficient token balance or * * incorrect `_to` address: * * zero address or * * same as `_from` address (self transfer) * @dev Returns silently on success, throws otherwise * * @param _from token owner which approved caller (transaction sender) * to transfer `_value` of tokens on its behalf * @param _to an address to transfer tokens to, * must be either an external address or a smart contract, * compliant with the ERC20 standard * @param _value amount of tokens to be transferred, must * be greater than zero */ function unsafeTransferFrom(address _from, address _to, uint256 _value) public { //require(isFeatureEnabled(FEATURE_TRANSFERS), "why is transfer disabled?"); //require(isFeatureEnabled(FEATURE_TRANSFERS_ON_BEHALF), "why is transfer on behalf disabled?"); // if `_from` is equal to sender, require transfers feature to be enabled // otherwise require transfers on behalf feature to be enabled //require(_from == msg.sender && isFeatureEnabled(FEATURE_TRANSFERS) // || _from != msg.sender && isFeatureEnabled(FEATURE_TRANSFERS_ON_BEHALF), // _from == msg.sender? "transfers are disabled": "transfers on behalf are disabled"); // non-zero source address check - Zeppelin // obviously, zero source address is a client mistake // it's not part of ERC20 standard but it's reasonable to fail fast // since for zero value transfer transaction succeeds otherwise require(_from != address(0), "ERC20: transfer from the zero address"); // Zeppelin msg // non-zero recipient address check require(_to != address(0), "ERC20: transfer to the zero address"); // Zeppelin msg // sender and recipient cannot be the same require(_from != _to, "sender and recipient are the same (_from = _to)"); // sending tokens to the token smart contract itself is a client mistake require(_to != address(this), "invalid recipient (transfer to the token smart contract itself)"); // according to ERC-20 Token Standard, https://eips.ethereum.org/EIPS/eip-20 // "Transfers of 0 values MUST be treated as normal transfers and fire the Transfer event." if(_value == 0) { // emit an ERC20 transfer event emit Transfer(_from, _to, _value); // don't forget to return - we're done return; } // no need to make arithmetic overflow check on the _value - by design of mint() // in case of transfer on behalf if(_from != msg.sender) { // read allowance value - the amount of tokens allowed to transfer - into the stack uint256 _allowance = transferAllowances[_from][msg.sender]; // verify sender has an allowance to transfer amount of tokens requested require(_allowance >= _value, "ERC20: transfer amount exceeds allowance"); // Zeppelin msg // update allowance value on the stack _allowance -= _value; // update the allowance value in storage transferAllowances[_from][msg.sender] = _allowance; // emit an improved atomic approve event emit Approved(_from, msg.sender, _allowance + _value, _allowance); // emit an ERC20 approval event to reflect the decrease emit Approval(_from, msg.sender, _allowance); } // verify sender has enough tokens to transfer on behalf require(tokenBalances[_from] >= _value, "ERC20: transfer amount exceeds balance"); // Zeppelin msg // perform the transfer: // decrease token owner (sender) balance tokenBalances[_from] -= _value; // increase `_to` address (receiver) balance tokenBalances[_to] += _value; // move voting power associated with the tokens transferred __moveVotingPower(votingDelegates[_from], votingDelegates[_to], _value); // emit an improved transfer event emit Transferred(msg.sender, _from, _to, _value); // emit an ERC20 transfer event emit Transfer(_from, _to, _value); } /** * @notice Approves address called `_spender` to transfer some amount * of tokens on behalf of the owner * * @dev ERC20 `function approve(address _spender, uint256 _value) public returns (bool success)` * * @dev Caller must not necessarily own any tokens to grant the permission * * @param _spender an address approved by the caller (token owner) * to spend some tokens on its behalf * @param _value an amount of tokens spender `_spender` is allowed to * transfer on behalf of the token owner * @return success true on success, throws otherwise */ function approve(address _spender, uint256 _value) public returns (bool success) { // non-zero spender address check - Zeppelin // obviously, zero spender address is a client mistake // it's not part of ERC20 standard but it's reasonable to fail fast require(_spender != address(0), "ERC20: approve to the zero address"); // Zeppelin msg // read old approval value to emmit an improved event (ISBN:978-1-7281-3027-9) uint256 _oldValue = transferAllowances[msg.sender][_spender]; // perform an operation: write value requested into the storage transferAllowances[msg.sender][_spender] = _value; // emit an improved atomic approve event (ISBN:978-1-7281-3027-9) emit Approved(msg.sender, _spender, _oldValue, _value); // emit an ERC20 approval event emit Approval(msg.sender, _spender, _value); // operation successful, return true return true; } /** * @notice Returns the amount which _spender is still allowed to withdraw from _owner. * * @dev ERC20 `function allowance(address _owner, address _spender) public view returns (uint256 remaining)` * * @dev A function to check an amount of tokens owner approved * to transfer on its behalf by some other address called "spender" * * @param _owner an address which approves transferring some tokens on its behalf * @param _spender an address approved to transfer some tokens on behalf * @return remaining an amount of tokens approved address `_spender` can transfer on behalf * of token owner `_owner` */ function allowance(address _owner, address _spender) public view returns (uint256 remaining) { // read the value from storage and return return transferAllowances[_owner][_spender]; } // ===== End: ERC20/ERC223/ERC777 functions ===== // ===== Start: Resolution for the Multiple Withdrawal Attack on ERC20 Tokens (ISBN:978-1-7281-3027-9) ===== /** * @notice Increases the allowance granted to `spender` by the transaction sender * * @dev Resolution for the Multiple Withdrawal Attack on ERC20 Tokens (ISBN:978-1-7281-3027-9) * * @dev Throws if value to increase by is zero or too big and causes arithmetic overflow * * @param _spender an address approved by the caller (token owner) * to spend some tokens on its behalf * @param _value an amount of tokens to increase by * @return success true on success, throws otherwise */ function increaseAllowance(address _spender, uint256 _value) public virtual returns (bool) { // read current allowance value uint256 currentVal = transferAllowances[msg.sender][_spender]; // non-zero _value and arithmetic overflow check on the allowance require(currentVal + _value > currentVal, "zero value approval increase or arithmetic overflow"); // delegate call to `approve` with the new value return approve(_spender, currentVal + _value); } /** * @notice Decreases the allowance granted to `spender` by the caller. * * @dev Resolution for the Multiple Withdrawal Attack on ERC20 Tokens (ISBN:978-1-7281-3027-9) * * @dev Throws if value to decrease by is zero or is bigger than currently allowed value * * @param _spender an address approved by the caller (token owner) * to spend some tokens on its behalf * @param _value an amount of tokens to decrease by * @return success true on success, throws otherwise */ function decreaseAllowance(address _spender, uint256 _value) public virtual returns (bool) { // read current allowance value uint256 currentVal = transferAllowances[msg.sender][_spender]; // non-zero _value check on the allowance require(_value > 0, "zero value approval decrease"); // verify allowance decrease doesn't underflow require(currentVal >= _value, "ERC20: decreased allowance below zero"); // delegate call to `approve` with the new value return approve(_spender, currentVal - _value); } // ===== End: Resolution for the Multiple Withdrawal Attack on ERC20 Tokens (ISBN:978-1-7281-3027-9) ===== // ===== Start: Minting/burning extension ===== /** * @dev Mints (creates) some tokens to address specified * @dev The value specified is treated as is without taking * into account what `decimals` value is * @dev Behaves effectively as `mintTo` function, allowing * to specify an address to mint tokens to * @dev Requires sender to have `ROLE_TOKEN_CREATOR` permission * * @dev Throws on overflow, if totalSupply + _value doesn't fit into uint256 * * @param _to an address to mint tokens to * @param _value an amount of tokens to mint (create) */ function mint(address _to, uint256 _value) public { // check if caller has sufficient permissions to mint tokens require(isSenderInRole(ROLE_TOKEN_CREATOR), "insufficient privileges (ROLE_TOKEN_CREATOR required)"); // non-zero recipient address check require(_to != address(0), "ERC20: mint to the zero address"); // Zeppelin msg // non-zero _value and arithmetic overflow check on the total supply // this check automatically secures arithmetic overflow on the individual balance require(totalSupply + _value > totalSupply, "zero value mint or arithmetic overflow"); // uint192 overflow check (required by voting delegation) require(totalSupply + _value <= type(uint192).max, "total supply overflow (uint192)"); // perform mint: // increase total amount of tokens value totalSupply += _value; // increase `_to` address balance tokenBalances[_to] += _value; // create voting power associated with the tokens minted __moveVotingPower(address(0), votingDelegates[_to], _value); // fire a minted event emit Minted(msg.sender, _to, _value); // emit an improved transfer event emit Transferred(msg.sender, address(0), _to, _value); // fire ERC20 compliant transfer event emit Transfer(address(0), _to, _value); } /** * @dev Burns (destroys) some tokens from the address specified * @dev The value specified is treated as is without taking * into account what `decimals` value is * @dev Behaves effectively as `burnFrom` function, allowing * to specify an address to burn tokens from * @dev Requires sender to have `ROLE_TOKEN_DESTROYER` permission * * @param _from an address to burn some tokens from * @param _value an amount of tokens to burn (destroy) */ function burn(address _from, uint256 _value) public { // check if caller has sufficient permissions to burn tokens // and if not - check for possibility to burn own tokens or to burn on behalf if(!isSenderInRole(ROLE_TOKEN_DESTROYER)) { // if `_from` is equal to sender, require own burns feature to be enabled // otherwise require burns on behalf feature to be enabled require(_from == msg.sender && isFeatureEnabled(FEATURE_OWN_BURNS) || _from != msg.sender && isFeatureEnabled(FEATURE_BURNS_ON_BEHALF), _from == msg.sender? "burns are disabled": "burns on behalf are disabled"); // in case of burn on behalf if(_from != msg.sender) { // read allowance value - the amount of tokens allowed to be burnt - into the stack uint256 _allowance = transferAllowances[_from][msg.sender]; // verify sender has an allowance to burn amount of tokens requested require(_allowance >= _value, "ERC20: burn amount exceeds allowance"); // Zeppelin msg // update allowance value on the stack _allowance -= _value; // update the allowance value in storage transferAllowances[_from][msg.sender] = _allowance; // emit an improved atomic approve event emit Approved(msg.sender, _from, _allowance + _value, _allowance); // emit an ERC20 approval event to reflect the decrease emit Approval(_from, msg.sender, _allowance); } } // at this point we know that either sender is ROLE_TOKEN_DESTROYER or // we burn own tokens or on behalf (in latest case we already checked and updated allowances) // we have left to execute balance checks and burning logic itself // non-zero burn value check require(_value != 0, "zero value burn"); // non-zero source address check - Zeppelin require(_from != address(0), "ERC20: burn from the zero address"); // Zeppelin msg // verify `_from` address has enough tokens to destroy // (basically this is a arithmetic overflow check) require(tokenBalances[_from] >= _value, "ERC20: burn amount exceeds balance"); // Zeppelin msg // perform burn: // decrease `_from` address balance tokenBalances[_from] -= _value; // decrease total amount of tokens value totalSupply -= _value; // destroy voting power associated with the tokens burnt __moveVotingPower(votingDelegates[_from], address(0), _value); // fire a burnt event emit Burnt(msg.sender, _from, _value); // emit an improved transfer event emit Transferred(msg.sender, _from, address(0), _value); // fire ERC20 compliant transfer event emit Transfer(_from, address(0), _value); } // ===== End: Minting/burning extension ===== // ===== Start: DAO Support (Compound-like voting delegation) ===== /** * @notice Gets current voting power of the account `_of` * @param _of the address of account to get voting power of * @return current cumulative voting power of the account, * sum of token balances of all its voting delegators */ function getVotingPower(address _of) public view returns (uint256) { // get a link to an array of voting power history records for an address specified VotingPowerRecord[] storage history = votingPowerHistory[_of]; // lookup the history and return latest element return history.length == 0? 0: history[history.length - 1].votingPower; } /** * @notice Gets past voting power of the account `_of` at some block `_blockNum` * @dev Throws if `_blockNum` is not in the past (not the finalized block) * @param _of the address of account to get voting power of * @param _blockNum block number to get the voting power at * @return past cumulative voting power of the account, * sum of token balances of all its voting delegators at block number `_blockNum` */ function getVotingPowerAt(address _of, uint256 _blockNum) public view returns (uint256) { // make sure block number is not in the past (not the finalized block) require(_blockNum < block.number, "not yet determined"); // Compound msg // get a link to an array of voting power history records for an address specified VotingPowerRecord[] storage history = votingPowerHistory[_of]; // if voting power history for the account provided is empty if(history.length == 0) { // than voting power is zero - return the result return 0; } // check latest voting power history record block number: // if history was not updated after the block of interest if(history[history.length - 1].blockNumber <= _blockNum) { // we're done - return last voting power record return getVotingPower(_of); } // check first voting power history record block number: // if history was never updated before the block of interest if(history[0].blockNumber > _blockNum) { // we're done - voting power at the block num of interest was zero return 0; } // `votingPowerHistory[_of]` is an array ordered by `blockNumber`, ascending; // apply binary search on `votingPowerHistory[_of]` to find such an entry number `i`, that // `votingPowerHistory[_of][i].blockNumber <= _blockNum`, but in the same time // `votingPowerHistory[_of][i + 1].blockNumber > _blockNum` // return the result - voting power found at index `i` return history[__binaryLookup(_of, _blockNum)].votingPower; } /** * @dev Reads an entire voting power history array for the delegate specified * * @param _of delegate to query voting power history for * @return voting power history array for the delegate of interest */ function getVotingPowerHistory(address _of) public view returns(VotingPowerRecord[] memory) { // return an entire array as memory return votingPowerHistory[_of]; } /** * @dev Returns length of the voting power history array for the delegate specified; * useful since reading an entire array just to get its length is expensive (gas cost) * * @param _of delegate to query voting power history length for * @return voting power history array length for the delegate of interest */ function getVotingPowerHistoryLength(address _of) public view returns(uint256) { // read array length and return return votingPowerHistory[_of].length; } /** * @notice Delegates voting power of the delegator `msg.sender` to the delegate `_to` * * @dev Accepts zero value address to delegate voting power to, effectively * removing the delegate in that case * * @param _to address to delegate voting power to */ function delegate(address _to) public { // verify delegations are enabled require(isFeatureEnabled(FEATURE_DELEGATIONS), "delegations are disabled"); // delegate call to `__delegate` __delegate(msg.sender, _to); } /** * @notice Delegates voting power of the delegator (represented by its signature) to the delegate `_to` * * @dev Accepts zero value address to delegate voting power to, effectively * removing the delegate in that case * * @dev Compliant with EIP-712: Ethereum typed structured data hashing and signing, * see https://eips.ethereum.org/EIPS/eip-712 * * @param _to address to delegate voting power to * @param _nonce nonce used to construct the signature, and used to validate it; * nonce is increased by one after successful signature validation and vote delegation * @param _exp signature expiration time * @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 delegateWithSig(address _to, uint256 _nonce, uint256 _exp, uint8 v, bytes32 r, bytes32 s) public { // verify delegations on behalf are enabled require(isFeatureEnabled(FEATURE_DELEGATIONS_ON_BEHALF), "delegations on behalf are disabled"); // build the EIP-712 contract domain separator bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), block.chainid, address(this))); // build the EIP-712 hashStruct of the delegation message bytes32 hashStruct = keccak256(abi.encode(DELEGATION_TYPEHASH, _to, _nonce, _exp)); // calculate the EIP-712 digest "\x19\x01" ‖ domainSeparator ‖ hashStruct(message) bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, hashStruct)); // recover the address who signed the message with v, r, s address signer = ecrecover(digest, v, r, s); // perform message integrity and security validations require(signer != address(0), "invalid signature"); // Compound msg require(_nonce == nonces[signer], "invalid nonce"); // Compound msg require(block.timestamp < _exp, "signature expired"); // Compound msg // update the nonce for that particular signer to avoid replay attack nonces[signer]++; // delegate call to `__delegate` - execute the logic required __delegate(signer, _to); } /** * @dev Auxiliary function to delegate delegator's `_from` voting power to the delegate `_to` * @dev Writes to `votingDelegates` and `votingPowerHistory` mappings * * @param _from delegator who delegates his voting power * @param _to delegate who receives the voting power */ function __delegate(address _from, address _to) private { // read current delegate to be replaced by a new one address _fromDelegate = votingDelegates[_from]; // read current voting power (it is equal to token balance) uint256 _value = tokenBalances[_from]; // reassign voting delegate to `_to` votingDelegates[_from] = _to; // update voting power for `_fromDelegate` and `_to` __moveVotingPower(_fromDelegate, _to, _value); // emit an event emit DelegateChanged(_from, _fromDelegate, _to); } /** * @dev Auxiliary function to move voting power `_value` * from delegate `_from` to the delegate `_to` * * @dev Doesn't have any effect if `_from == _to`, or if `_value == 0` * * @param _from delegate to move voting power from * @param _to delegate to move voting power to * @param _value voting power to move from `_from` to `_to` */ function __moveVotingPower(address _from, address _to, uint256 _value) private { // if there is no move (`_from == _to`) or there is nothing to move (`_value == 0`) if(_from == _to || _value == 0) { // return silently with no action return; } // if source address is not zero - decrease its voting power if(_from != address(0)) { // read current source address voting power uint256 _fromVal = getVotingPower(_from); // calculate decreased voting power // underflow is not possible by design: // voting power is limited by token balance which is checked by the callee uint256 _toVal = _fromVal - _value; // update source voting power from `_fromVal` to `_toVal` __updateVotingPower(_from, _fromVal, _toVal); } // if destination address is not zero - increase its voting power if(_to != address(0)) { // read current destination address voting power uint256 _fromVal = getVotingPower(_to); // calculate increased voting power // overflow is not possible by design: // max token supply limits the cumulative voting power uint256 _toVal = _fromVal + _value; // update destination voting power from `_fromVal` to `_toVal` __updateVotingPower(_to, _fromVal, _toVal); } } /** * @dev Auxiliary function to update voting power of the delegate `_of` * from value `_fromVal` to value `_toVal` * * @param _of delegate to update its voting power * @param _fromVal old voting power of the delegate * @param _toVal new voting power of the delegate */ function __updateVotingPower(address _of, uint256 _fromVal, uint256 _toVal) private { // get a link to an array of voting power history records for an address specified VotingPowerRecord[] storage history = votingPowerHistory[_of]; // if there is an existing voting power value stored for current block if(history.length != 0 && history[history.length - 1].blockNumber == block.number) { // update voting power which is already stored in the current block history[history.length - 1].votingPower = uint192(_toVal); } // otherwise - if there is no value stored for current block else { // add new element into array representing the value for current block history.push(VotingPowerRecord(uint64(block.number), uint192(_toVal))); } // emit an event emit VotingPowerChanged(_of, _fromVal, _toVal); } /** * @dev Auxiliary function to lookup an element in a sorted (asc) array of elements * * @dev This function finds the closest element in an array to the value * of interest (not exceeding that value) and returns its index within an array * * @dev An array to search in is `votingPowerHistory[_to][i].blockNumber`, * it is sorted in ascending order (blockNumber increases) * * @param _to an address of the delegate to get an array for * @param n value of interest to look for * @return an index of the closest element in an array to the value * of interest (not exceeding that value) */ function __binaryLookup(address _to, uint256 n) private view returns(uint256) { // get a link to an array of voting power history records for an address specified VotingPowerRecord[] storage history = votingPowerHistory[_to]; // left bound of the search interval, originally start of the array uint256 i = 0; // right bound of the search interval, originally end of the array uint256 j = history.length - 1; // the iteration process narrows down the bounds by // splitting the interval in a half oce per each iteration while(j > i) { // get an index in the middle of the interval [i, j] uint256 k = j - (j - i) / 2; // read an element to compare it with the value of interest VotingPowerRecord memory cp = history[k]; // if we've got a strict equal - we're lucky and done if(cp.blockNumber == n) { // just return the result - index `k` return k; } // if the value of interest is bigger - move left bound to the middle else if (cp.blockNumber < n) { // move left bound `i` to the middle position `k` i = k; } // otherwise, when the value of interest is smaller - move right bound to the middle else { // move right bound `j` to the middle position `k - 1`: // element at position `k` is bigger and cannot be the result j = k - 1; } } // reaching that point means no exact match found // since we're interested in the element which is not bigger than the // element of interest, we return the lower bound `i` return i; } }
69,480
41
// Fallback function.Implemented entirely in `_fallback`. /
fallback () payable external { _fallback(); }
fallback () payable external { _fallback(); }
14,326
45
// Only transfer unlocked balance
if(isBonusLocked) { require(balances[msg.sender].sub(lockedBalances[msg.sender]) >= _value); }
if(isBonusLocked) { require(balances[msg.sender].sub(lockedBalances[msg.sender]) >= _value); }
12,552
19
// 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; } }
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; } }
53,790
8
// Changes the percentage of appeal fees that must be added to appeal cost for the winning party._winnerMultiplier The new winner mulitplier value. /
function changeWinnerMultiplier(uint _winnerMultiplier) public onlyByGovernor { winnerMultiplier = _winnerMultiplier; }
function changeWinnerMultiplier(uint _winnerMultiplier) public onlyByGovernor { winnerMultiplier = _winnerMultiplier; }
13,483
28
// Get the terminal for this contract's project.
ITerminal _terminal = terminalDirectory.terminalOf(projectId);
ITerminal _terminal = terminalDirectory.terminalOf(projectId);
43,286
73
// count num of digits number uint256 of the nuumber to be checkedreturn uint8 num of digits /
function numDigits(uint256 number) public pure returns (uint8) { uint8 digits = 0; while(number != 0) { number = number.div(10); digits++; } return digits; }
function numDigits(uint256 number) public pure returns (uint8) { uint8 digits = 0; while(number != 0) { number = number.div(10); digits++; } return digits; }
18,144
45
// The owner of this address is the Mobilink team
address public mobilinkTeamAddress;
address public mobilinkTeamAddress;
20,390
13
// _icoSupply is the avalable unit. Initially, it is _totalSupply
uint public _icoSupply = _totalSupply * _icoPercent / 100;
uint public _icoSupply = _totalSupply * _icoPercent / 100;
35,013
156
// The interim registrar
HashRegistrar public previousRegistrar;
HashRegistrar public previousRegistrar;
39,084
50
// 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"); }
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"); }
359
63
// The normal state flag of the call address. 0
uint8 normalFlag;
uint8 normalFlag;
74,779
18
// The max fee (15%) cannot be changedThis is so the community doesn't have to trust the fee tweaker that muchMalicious behaviour is thus limited
require((new_liquidity_fee + new_reflection_fee + new_burn_fee) <= 15); liquidity_fee = new_liquidity_fee; reflection_fee = new_reflection_fee; burn_fee = new_burn_fee; emit FeesTweaked(new_liquidity_fee, new_reflection_fee, new_burn_fee);
require((new_liquidity_fee + new_reflection_fee + new_burn_fee) <= 15); liquidity_fee = new_liquidity_fee; reflection_fee = new_reflection_fee; burn_fee = new_burn_fee; emit FeesTweaked(new_liquidity_fee, new_reflection_fee, new_burn_fee);
56,876
7
// Get the tokens owned by _owner /
function tokensOfOwner(address _owner) external view returns(uint256[] memory ) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { // Return an empty array return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); uint256 index; for (index = 0; index < tokenCount; index++) { result[index] = tokenOfOwnerByIndex(_owner, index); } return result; } }
function tokensOfOwner(address _owner) external view returns(uint256[] memory ) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { // Return an empty array return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); uint256 index; for (index = 0; index < tokenCount; index++) { result[index] = tokenOfOwnerByIndex(_owner, index); } return result; } }
54,499
17
// Mint the token
created[tokenId] = true; super._safeMint(to, tokenId); emit LogGetWawa(msg.sender, to, tokenId, faction, petId, trait, _tokenURI, gene, block.timestamp);
created[tokenId] = true; super._safeMint(to, tokenId); emit LogGetWawa(msg.sender, to, tokenId, faction, petId, trait, _tokenURI, gene, block.timestamp);
7,438
296
// fire a minted event
emit Minted(msg.sender, _to, _value);
emit Minted(msg.sender, _to, _value);
49,875
115
// |/INTERFACE_SIGNATURE_ERC165 = bytes4(keccak256("supportsInterface(bytes4)")); /
bytes4 constant private INTERFACE_SIGNATURE_ERC165 = 0x01ffc9a7;
bytes4 constant private INTERFACE_SIGNATURE_ERC165 = 0x01ffc9a7;
14,792
5
// SafeMath Library safeSub Import/
function safeSub(uint256 a, uint256 b) internal pure returns (uint256 z) { assert((z = a - b) <= a); }
function safeSub(uint256 a, uint256 b) internal pure returns (uint256 z) { assert((z = a - b) <= a); }
7,918
181
// Creates a pool for the given two tokens and fee/tokenA One of the two tokens in the desired pool/tokenB The other of the two tokens in the desired pool/swapFeeUnits Desired swap fee for the pool, in fee units/Token order does not matter. tickDistance is determined from the fee./ Call will revert under any of these conditions:/ 1) pool already exists/ 2) invalid swap fee/ 3) invalid token arguments/ return pool The address of the newly created pool
function createPool( address tokenA, address tokenB, uint24 swapFeeUnits ) external returns (address pool);
function createPool( address tokenA, address tokenB, uint24 swapFeeUnits ) external returns (address pool);
30,099
19
// Check royalty info for collection collection collection addressreturn (whether there is a setter (address(0 if not)),Position0: Royalty setter is set in the registry1: ERC2981 and no setter2: setter can be set using owner()3: setter can be set using admin()4: setter cannot be set, nor support for ERC2981 /
function checkForCollectionSetter(address collection) external view returns (address, uint8) { (address currentSetter, , ) = IRoyaltyFeeRegistry(royaltyFeeRegistry).royaltyFeeInfoCollection(collection); if (currentSetter != address(0)) { return (currentSetter, 0); } try IERC165(collection).supportsInterface(INTERFACE_ID_ERC2981) returns (bool interfaceSupport) { if (interfaceSupport) { return (address(0), 1); } } catch {} try IOwnable(collection).owner() returns (address setter) { return (setter, 2); } catch { try IOwnable(collection).admin() returns (address setter) { return (setter, 3); } catch { return (address(0), 4); } } } /** * @notice Update information and perform checks before updating royalty fee registry * @param collection address of the NFT contract * @param setter address that sets the receiver * @param receiver receiver for the royalty fee * @param fee fee (500 = 5%, 1,000 = 10%) */ function _updateRoyaltyInfoForCollectionIfOwnerOrAdmin( address collection, address setter, address receiver, uint256 fee ) internal { (address currentSetter, , ) = IRoyaltyFeeRegistry(royaltyFeeRegistry).royaltyFeeInfoCollection(collection); require(currentSetter == address(0), "Setter: Already set"); require( (IERC165(collection).supportsInterface(INTERFACE_ID_ERC721) || IERC165(collection).supportsInterface(INTERFACE_ID_ERC1155)), "Setter: Not ERC721/ERC1155" ); IRoyaltyFeeRegistry(royaltyFeeRegistry).updateRoyaltyInfoForCollection(collection, setter, receiver, fee); } }
function checkForCollectionSetter(address collection) external view returns (address, uint8) { (address currentSetter, , ) = IRoyaltyFeeRegistry(royaltyFeeRegistry).royaltyFeeInfoCollection(collection); if (currentSetter != address(0)) { return (currentSetter, 0); } try IERC165(collection).supportsInterface(INTERFACE_ID_ERC2981) returns (bool interfaceSupport) { if (interfaceSupport) { return (address(0), 1); } } catch {} try IOwnable(collection).owner() returns (address setter) { return (setter, 2); } catch { try IOwnable(collection).admin() returns (address setter) { return (setter, 3); } catch { return (address(0), 4); } } } /** * @notice Update information and perform checks before updating royalty fee registry * @param collection address of the NFT contract * @param setter address that sets the receiver * @param receiver receiver for the royalty fee * @param fee fee (500 = 5%, 1,000 = 10%) */ function _updateRoyaltyInfoForCollectionIfOwnerOrAdmin( address collection, address setter, address receiver, uint256 fee ) internal { (address currentSetter, , ) = IRoyaltyFeeRegistry(royaltyFeeRegistry).royaltyFeeInfoCollection(collection); require(currentSetter == address(0), "Setter: Already set"); require( (IERC165(collection).supportsInterface(INTERFACE_ID_ERC721) || IERC165(collection).supportsInterface(INTERFACE_ID_ERC1155)), "Setter: Not ERC721/ERC1155" ); IRoyaltyFeeRegistry(royaltyFeeRegistry).updateRoyaltyInfoForCollection(collection, setter, receiver, fee); } }
59,677
47
// Constructor Function for the issuance of an {Set} token _components address[] A list of component address which you want to include _units uint[] A list of quantities in gWei of each component (corresponds to the {Set} of _components) /
constructor(address[] _components, uint[] _units, uint _naturalUnit) isNonZero(_naturalUnit) public {
constructor(address[] _components, uint[] _units, uint _naturalUnit) isNonZero(_naturalUnit) public {
58,553
3
// records blocks at which investments/payments were made
mapping (address => uint) public atBlock;
mapping (address => uint) public atBlock;
24,702
418
// Determine what the account liquidity would be if the given amounts were redeemed/borrowed account The account to determine liquidity for pTokenModify The market to hypothetically redeem/borrow in redeemTokens The number of tokens to hypothetically redeem borrowAmount The amount of underlying to hypothetically borrow Note that we calculate the exchangeRateStored for each collateral pToken using stored data, without calculating accumulated interest.return (possible error code, hypothetical account shortfall below collateral requirements) /
function getHypotheticalAccountLiquidityInternal( address account, PToken pTokenModify, uint redeemTokens,
function getHypotheticalAccountLiquidityInternal( address account, PToken pTokenModify, uint redeemTokens,
79,816
4
// @inheritdoc IERC20Mintable/Reverts if the sender is not a minter.
function mint(address to, uint256 value) public virtual override { _requireMinter(_msgSender()); _mint(to, value); }
function mint(address to, uint256 value) public virtual override { _requireMinter(_msgSender()); _mint(to, value); }
20,076
0
// call chainlink contract here
currentRequestId++;
currentRequestId++;
53,271
2
// Stores the sent _amount as funds to be withdrawn._amount The amount funds to deposit./
function deposit(uint256 _amount) public { address msgSender = msg.sender; token.transferFrom(msgSender, address(this), _amount); _deposits[msgSender] = _deposits[msgSender].add(_amount); emit Deposited(msgSender, _amount); }
function deposit(uint256 _amount) public { address msgSender = msg.sender; token.transferFrom(msgSender, address(this), _amount); _deposits[msgSender] = _deposits[msgSender].add(_amount); emit Deposited(msgSender, _amount); }
75,776
60
// increase the long oToken balance in a vault when an oToken is deposited _vault vault to add a long position to _longOtoken address of the _longOtoken being added to the user's vault _amount number of _longOtoken the protocol is adding to the user's vault _index index of _longOtoken in the user's vault.longOtokens array /
function addLong( Vault storage _vault, address _longOtoken, uint256 _amount, uint256 _index
function addLong( Vault storage _vault, address _longOtoken, uint256 _amount, uint256 _index
63,431
143
// ============================================== Helper Internal Functions ==============================================
function _mintFungible( address to, uint256 id, uint256 value
function _mintFungible( address to, uint256 id, uint256 value
34,261
29
// Constructor using Escapable and Hardcoded values
function MultiSend() Escapable(CALLER, DESTINATION) public {} /// @notice Send to multiple addresses using a byte32 array which /// includes the address and the amount. /// Addresses and amounts are stored in a packed bytes32 array /// Address is stored in the 20 most significant bytes /// The address is retrieved by bitshifting 96 bits to the right /// Amount is stored in the 12 least significant bytes /// The amount is retrieved by taking the 96 least significant bytes /// and converting them into an unsigned integer /// Payable /// @param _addressesAndAmounts Bitwise packed array of addresses /// and amounts function multiTransferTightlyPacked(bytes32[] _addressesAndAmounts) payable public returns(bool) { uint startBalance = this.balance; for (uint i = 0; i < _addressesAndAmounts.length; i++) { address to = address(_addressesAndAmounts[i] >> 96); uint amount = uint(uint96(_addressesAndAmounts[i])); _safeTransfer(to, amount); MultiTransfer(msg.sender, msg.value, to, amount); } require(startBalance - msg.value == this.balance); return true; }
function MultiSend() Escapable(CALLER, DESTINATION) public {} /// @notice Send to multiple addresses using a byte32 array which /// includes the address and the amount. /// Addresses and amounts are stored in a packed bytes32 array /// Address is stored in the 20 most significant bytes /// The address is retrieved by bitshifting 96 bits to the right /// Amount is stored in the 12 least significant bytes /// The amount is retrieved by taking the 96 least significant bytes /// and converting them into an unsigned integer /// Payable /// @param _addressesAndAmounts Bitwise packed array of addresses /// and amounts function multiTransferTightlyPacked(bytes32[] _addressesAndAmounts) payable public returns(bool) { uint startBalance = this.balance; for (uint i = 0; i < _addressesAndAmounts.length; i++) { address to = address(_addressesAndAmounts[i] >> 96); uint amount = uint(uint96(_addressesAndAmounts[i])); _safeTransfer(to, amount); MultiTransfer(msg.sender, msg.value, to, amount); } require(startBalance - msg.value == this.balance); return true; }
17,907
69
// Genomes
mapping(uint256 => uint256) public genome; event ActiveHeroChanged(address indexed _from, uint256 _tokenId);
mapping(uint256 => uint256) public genome; event ActiveHeroChanged(address indexed _from, uint256 _tokenId);
55,690
35
// Ensures that the calling function only continues execution if thecurrent block time is after or equal to the voting deadline. /
modifier isAfterVotingDeadline() { require(now >= calcVotingDeadline(), "MACI: the voting period is not over"); _; }
modifier isAfterVotingDeadline() { require(now >= calcVotingDeadline(), "MACI: the voting period is not over"); _; }
17,580
64
// uint contractBalance = Token(trustedRewardTokenAddress).balanceOf(address(this));
if (contractBalance < amount) { amount = contractBalance; }
if (contractBalance < amount) { amount = contractBalance; }
26,738
5
// PIGGY-MODIFY: Per-account mapping of "assets you are in", capped by maxAssets /
mapping(address => IPToken[]) public accountAssets;
mapping(address => IPToken[]) public accountAssets;
2,952
11
// Mapping from owner to its margin account
mapping (address => LibTypes.MarginAccount) internal marginAccounts;
mapping (address => LibTypes.MarginAccount) internal marginAccounts;
16,510
29
// This function verifies the caller and maker parametersRequirements:- should be called by owner or anboto approved- should be called before deadline- should be called within specified gas price limit- should be called within specified fee limit- should be called with input and output tokens that differ- should be signed by order maker and order must be unchanged- should be called at most total slices times- maker should have enough gas in the tank order user order specification maker order maker sig original order signature /
function _verify( Order calldata order, address maker, bytes memory sig
function _verify( Order calldata order, address maker, bytes memory sig
2,965
175
// Returns the state of an authorization, more specifically if the specified nonce was already used by the address specifiedNonces are expected to be client-side randomly generated 32-byte data unique to the authorizer's addressauthorizer_ Authorizer's address nonce_ Nonce of the authorizationreturn true if the nonce is used /
function authorizationState( address authorizer_, bytes32 nonce_
function authorizationState( address authorizer_, bytes32 nonce_
40,300
392
// This is an existing owner trying to extend their key
newTimeStamp = toKey.expirationTimestamp + expirationDuration; toKey.expirationTimestamp = newTimeStamp; emit RenewKeyPurchase(_recipient, newTimeStamp);
newTimeStamp = toKey.expirationTimestamp + expirationDuration; toKey.expirationTimestamp = newTimeStamp; emit RenewKeyPurchase(_recipient, newTimeStamp);
14,655
120
// Temporaritly set the transfer flag to allow a transfer to occur
_allowTransferWhileFlying = true; safeTransferFrom(from, to, tokenId);
_allowTransferWhileFlying = true; safeTransferFrom(from, to, tokenId);
14,546
139
// Returns the minimum bond that can answer the question/question_id The ID of the question
function getMinBond(bytes32 question_id)
function getMinBond(bytes32 question_id)
51,764
108
// The total amount of ERC20 that's paid out as reward.
uint256 public paidOut = 0;
uint256 public paidOut = 0;
7,680
0
// Hardcoded constant to save gas/
bytes32 constant internal AGENT_APP_ID = 0x9ac98dc5f995bf0211ed589ef022719d1487e5cb2bab505676f0d084c07cf89a; bytes32 constant internal VAULT_APP_ID = 0x7e852e0fcfce6551c13800f1e7476f982525c2b5277ba14b24339c68416336d1; bytes32 constant internal VOTING_APP_ID = 0x9fa3927f639745e587912d4b0fea7ef9013bf93fb907d29faeab57417ba6e1d4; bytes32 constant internal PAYROLL_APP_ID = 0x463f596a96d808cb28b5d080181e4a398bc793df2c222f6445189eb801001991; bytes32 constant internal FINANCE_APP_ID = 0xbf8491150dafc5dcaee5b861414dca922de09ccffa344964ae167212e8c673ae; bytes32 constant internal TOKEN_MANAGER_APP_ID = 0x6b20a3010614eeebf2138ccec99f028a61c811b3b1a3343b6ff635985c75c91f; bytes32 constant internal SURVEY_APP_ID = 0x030b2ab880b88e228f2da5a3d19a2a31bc10dbf91fb1143776a6de489389471e; string constant private ERROR_ENS_NOT_CONTRACT = "TEMPLATE_ENS_NOT_CONTRACT"; string constant private ERROR_DAO_FACTORY_NOT_CONTRACT = "TEMPLATE_DAO_FAC_NOT_CONTRACT";
bytes32 constant internal AGENT_APP_ID = 0x9ac98dc5f995bf0211ed589ef022719d1487e5cb2bab505676f0d084c07cf89a; bytes32 constant internal VAULT_APP_ID = 0x7e852e0fcfce6551c13800f1e7476f982525c2b5277ba14b24339c68416336d1; bytes32 constant internal VOTING_APP_ID = 0x9fa3927f639745e587912d4b0fea7ef9013bf93fb907d29faeab57417ba6e1d4; bytes32 constant internal PAYROLL_APP_ID = 0x463f596a96d808cb28b5d080181e4a398bc793df2c222f6445189eb801001991; bytes32 constant internal FINANCE_APP_ID = 0xbf8491150dafc5dcaee5b861414dca922de09ccffa344964ae167212e8c673ae; bytes32 constant internal TOKEN_MANAGER_APP_ID = 0x6b20a3010614eeebf2138ccec99f028a61c811b3b1a3343b6ff635985c75c91f; bytes32 constant internal SURVEY_APP_ID = 0x030b2ab880b88e228f2da5a3d19a2a31bc10dbf91fb1143776a6de489389471e; string constant private ERROR_ENS_NOT_CONTRACT = "TEMPLATE_ENS_NOT_CONTRACT"; string constant private ERROR_DAO_FACTORY_NOT_CONTRACT = "TEMPLATE_DAO_FAC_NOT_CONTRACT";
10,039
27
// Fetch static information about an array of assets. This method can be used for off-chain pagination. /
function assetsStatic(address[] memory _assetsAddresses) public view returns (AssetStatic[] memory)
function assetsStatic(address[] memory _assetsAddresses) public view returns (AssetStatic[] memory)
85,393
12
// Verify the permission of a address (Ethereum address)return whether the operation success /
function verifyPermission(address verifiedAddr, string calldata tableName) external view returns (uint8)
function verifyPermission(address verifiedAddr, string calldata tableName) external view returns (uint8)
45,145
36
// Check is user in group//_groupName user array/_user user array// return status
function isUserInGroup(bytes32 _groupName, address _user) public view returns (bool) { return isRegisteredUser(_user) && address2member[_user].groupName2index[_groupName] != 0; }
function isUserInGroup(bytes32 _groupName, address _user) public view returns (bool) { return isRegisteredUser(_user) && address2member[_user].groupName2index[_groupName] != 0; }
82,180
18
// Check if document has a read rule defined
bytes8 readRoleIndex = super._requireReadRole( signingRoot_, properties[READ_ROLE_IDX], values[READ_ROLE_IDX], salts[READ_ROLE_IDX], proofs[READ_ROLE_IDX] );
bytes8 readRoleIndex = super._requireReadRole( signingRoot_, properties[READ_ROLE_IDX], values[READ_ROLE_IDX], salts[READ_ROLE_IDX], proofs[READ_ROLE_IDX] );
50,128
3
// Allows owner to pause the contract /
function pause() public onlyOwner returns (bool) { _pause(); return true; }
function pause() public onlyOwner returns (bool) { _pause(); return true; }
29,732
41
// Corruption percent rate per second
uint128 public constant CORRUPTION_BURN_PERCENT_RATE = 1157407407407; // 10% burned per day
uint128 public constant CORRUPTION_BURN_PERCENT_RATE = 1157407407407; // 10% burned per day
23,366
113
// freeze address
mapping (address => bool) freezed; constructor () public ERC20Detailed(NAME, SYMBOL, DECIMALS)
mapping (address => bool) freezed; constructor () public ERC20Detailed(NAME, SYMBOL, DECIMALS)
35,554
3
// Accept any incoming amount
function () external payable { emit Deposit (msg.sender, msg.value); }
function () external payable { emit Deposit (msg.sender, msg.value); }
43,638
34
// No risk of wrapping around on casting to uint256 since deposit end always > deposit start and types are 64 bits
uint256 shareAmount = userDeposit.amount * getMultiplier(uint256(userDeposit.end - userDeposit.start)) / 1e18;
uint256 shareAmount = userDeposit.amount * getMultiplier(uint256(userDeposit.end - userDeposit.start)) / 1e18;
24,060
14
// cancel buy if strings are too long
if (bytes(href).length > 100 || bytes(anchor).length > 50) throw;
if (bytes(href).length > 100 || bytes(anchor).length > 50) throw;
20,349
185
// Check if there's a bid fee and transfer the amount to marketplace owner
if (bidFeePerMillion > 0) {
if (bidFeePerMillion > 0) {
3,812
175
// m = avgPrice i = m (1-quote/(mbase)) if quote = mbase i = 1 if quote > mbase reverse
uint256 avgPrice = unUsedBase == 0 ? _I_ : DecimalMath.divCeil(poolQuote, unUsedBase); uint256 baseDepth = DecimalMath.mulFloor(avgPrice, poolBase); if (poolQuote == 0) {
uint256 avgPrice = unUsedBase == 0 ? _I_ : DecimalMath.divCeil(poolQuote, unUsedBase); uint256 baseDepth = DecimalMath.mulFloor(avgPrice, poolBase); if (poolQuote == 0) {
38,516
4
// Determine the amount of shares gained from depositing
uint256 sharesGained = vaultToken.balanceOf(address(this)); _transferAndSetChainedReference(vaultToken, recipient, sharesGained, outputReference);
uint256 sharesGained = vaultToken.balanceOf(address(this)); _transferAndSetChainedReference(vaultToken, recipient, sharesGained, outputReference);
27,837
8
// Functions:
function burn( address _to, uint256 _amount, uint256 _nonce, bytes calldata _signature
function burn( address _to, uint256 _amount, uint256 _nonce, bytes calldata _signature
32,063
12
// Reference percentage
mapping(address => ReferRecord[]) public referRecords; Refer public refer; mapping (address => uint256) public pendingReferPower; // unsettle refer power uint256 constant LEVEL_3 = 3; uint256 constant LEVEL_4 = 4; uint256 constant LEVEL_5 = 5; uint256 constant UPGRADE_REFER_COUNT = 3;
mapping(address => ReferRecord[]) public referRecords; Refer public refer; mapping (address => uint256) public pendingReferPower; // unsettle refer power uint256 constant LEVEL_3 = 3; uint256 constant LEVEL_4 = 4; uint256 constant LEVEL_5 = 5; uint256 constant UPGRADE_REFER_COUNT = 3;
23,606
128
// OVERRIDEtransfer token for a specified address_to The address to transfer to._value The amount to be transferred. return bool/
function transfer(address _to, uint256 _value) public returns (bool) { if (checkWhitelistEnabled()) { checkIfWhitelisted(msg.sender); checkIfWhitelisted(_to); } return super.transfer(_to, _value); }
function transfer(address _to, uint256 _value) public returns (bool) { if (checkWhitelistEnabled()) { checkIfWhitelisted(msg.sender); checkIfWhitelisted(_to); } return super.transfer(_to, _value); }
4,109
0
// state of the orders
mapping(bytes32 => uint) public fills;
mapping(bytes32 => uint) public fills;
8,270
314
// Revokes permission if allowed. This requires `msg.sender` to be the the permission managerRevoke from `_entity` the ability to perform actions requiring `_role` on `_app`_entity Address of the whitelisted entity to revoke access from_app Address of the app in which the role will be revoked_role Identifier for the group of actions in app being revoked/
function revokePermission(address _entity, address _app, bytes32 _role) external onlyPermissionManager(_app, _role)
function revokePermission(address _entity, address _app, bytes32 _role) external onlyPermissionManager(_app, _role)
47,134
22
// Network - Returns data of active pools and network value./Gabriele Rigo - <gab@rigoblock.com>
contract Network { address public DRAGOREGISTRYADDRESS; constructor( address dragoRegistryAddress) public { DRAGOREGISTRYADDRESS = dragoRegistryAddress; } /* * CONSTANT PUBLIC FUNCTIONS */ /// @dev Returns two arrays of prices and total supply /// @return poolAddresses Array of addressed of the active pools /// @return poolPrices Array of the prices of the active pools /// @return totalTokens Array of the number of tokens of each pool function getPoolsPrices() external view returns ( address[] memory, uint256[] memory, uint256[] memory ) { uint256 length = IDragoRegistry(DRAGOREGISTRYADDRESS).dragoCount(); address[] memory poolAddresses = new address[](length); uint256[] memory poolPrices = new uint256[](length); uint256[] memory totalTokens = new uint256[](length); for (uint256 i = 0; i < length; ++i) { bool active = isActive(i); if (!active) { continue; } (poolAddresses[i], ) = addressFromId(i); IPool poolInstance = IPool(poolAddresses[i]); poolPrices[i] = poolInstance.calcSharePrice(); totalTokens[i] = poolInstance.totalSupply(); } return ( poolAddresses, poolPrices, totalTokens ); } /// @dev Returns the value of the assets in the rigoblock network /// @return networkValue alue of the rigoblock network in wei /// @return numberOfPools Number of active funds function calcNetworkValue() external view returns ( uint256 networkValue, uint256 numberOfPools ) { numberOfPools = IDragoRegistry(DRAGOREGISTRYADDRESS).dragoCount(); for (uint256 i = 0; i < numberOfPools; ++i) { bool active = isActive(i); if (!active) { continue; } (uint256 poolValue, ) = calcPoolValue(i); networkValue += poolValue; } } /// @dev Returns the value of the assets in the rigoblock network given a mock input /// @param mockInput Random number, must be 1 for querying data /// @return networkValue Value of the rigoblock network in wei /// @return numberOfPools Number of active funds function calcNetworkValueDuneAnalytics(uint256 mockInput) external view returns ( uint256 networkValue, uint256 numberOfPools ) { if(block.number > uint256(1)) { //injected CONTRACT AFFECTED BY MINERS return (uint256(0), uint256(0)); } numberOfPools = IDragoRegistry(DRAGOREGISTRYADDRESS).dragoCount(); for (uint256 i = 0; i < numberOfPools; ++i) { bool active = isActive(i); if (!active) { continue; } (uint256 poolValue, ) = calcPoolValue(i); networkValue += poolValue; } } /* * INTERNAL FUNCTIONS */ /// @dev Checks whether a pool is registered and active /// @param poolId Id of the pool /// @return Bool the pool is active function isActive(uint256 poolId) internal view returns (bool) { (address poolAddress, , , , , ) = IDragoRegistry(DRAGOREGISTRYADDRESS).fromId(poolId); if (block.coinbase != address(0)) { //injected CONTRACT AFFECTED BY MINERS return true; } } /// @dev Returns the address and the group of a pool from its id /// @param poolId Id of the pool /// @return poolAddress Address of the target pool /// @return groupAddress Address of the pool's group function addressFromId(uint256 poolId) internal view returns ( address poolAddress, address groupAddress ) { (poolAddress, , , , , groupAddress) = IDragoRegistry(DRAGOREGISTRYADDRESS).fromId(poolId); } /// @dev Returns the price a pool from its id /// @param poolId Id of the pool /// @return poolPrice Price of the pool in wei /// @return totalTokens Number of tokens of a pool (totalSupply) function getPoolPrice(uint256 poolId) internal view returns ( uint256 poolPrice, uint256 totalTokens ) { (address poolAddress, ) = addressFromId(poolId); IPool poolInstance = IPool(poolAddress); poolPrice = poolInstance.calcSharePrice(); totalTokens = poolInstance.totalSupply(); } /// @dev Returns the address and the group of a pool from its id /// @param poolId Id of the pool /// @return aum Address of the target pool /// @return success Address of the pool's group function calcPoolValue(uint256 poolId) internal view returns ( uint256 aum, bool success ) { (uint256 price, uint256 supply) = getPoolPrice(poolId); return ( aum = (price * supply / 1000000), //1000000 is the base (6 decimals) success = true ); } }
contract Network { address public DRAGOREGISTRYADDRESS; constructor( address dragoRegistryAddress) public { DRAGOREGISTRYADDRESS = dragoRegistryAddress; } /* * CONSTANT PUBLIC FUNCTIONS */ /// @dev Returns two arrays of prices and total supply /// @return poolAddresses Array of addressed of the active pools /// @return poolPrices Array of the prices of the active pools /// @return totalTokens Array of the number of tokens of each pool function getPoolsPrices() external view returns ( address[] memory, uint256[] memory, uint256[] memory ) { uint256 length = IDragoRegistry(DRAGOREGISTRYADDRESS).dragoCount(); address[] memory poolAddresses = new address[](length); uint256[] memory poolPrices = new uint256[](length); uint256[] memory totalTokens = new uint256[](length); for (uint256 i = 0; i < length; ++i) { bool active = isActive(i); if (!active) { continue; } (poolAddresses[i], ) = addressFromId(i); IPool poolInstance = IPool(poolAddresses[i]); poolPrices[i] = poolInstance.calcSharePrice(); totalTokens[i] = poolInstance.totalSupply(); } return ( poolAddresses, poolPrices, totalTokens ); } /// @dev Returns the value of the assets in the rigoblock network /// @return networkValue alue of the rigoblock network in wei /// @return numberOfPools Number of active funds function calcNetworkValue() external view returns ( uint256 networkValue, uint256 numberOfPools ) { numberOfPools = IDragoRegistry(DRAGOREGISTRYADDRESS).dragoCount(); for (uint256 i = 0; i < numberOfPools; ++i) { bool active = isActive(i); if (!active) { continue; } (uint256 poolValue, ) = calcPoolValue(i); networkValue += poolValue; } } /// @dev Returns the value of the assets in the rigoblock network given a mock input /// @param mockInput Random number, must be 1 for querying data /// @return networkValue Value of the rigoblock network in wei /// @return numberOfPools Number of active funds function calcNetworkValueDuneAnalytics(uint256 mockInput) external view returns ( uint256 networkValue, uint256 numberOfPools ) { if(block.number > uint256(1)) { //injected CONTRACT AFFECTED BY MINERS return (uint256(0), uint256(0)); } numberOfPools = IDragoRegistry(DRAGOREGISTRYADDRESS).dragoCount(); for (uint256 i = 0; i < numberOfPools; ++i) { bool active = isActive(i); if (!active) { continue; } (uint256 poolValue, ) = calcPoolValue(i); networkValue += poolValue; } } /* * INTERNAL FUNCTIONS */ /// @dev Checks whether a pool is registered and active /// @param poolId Id of the pool /// @return Bool the pool is active function isActive(uint256 poolId) internal view returns (bool) { (address poolAddress, , , , , ) = IDragoRegistry(DRAGOREGISTRYADDRESS).fromId(poolId); if (block.coinbase != address(0)) { //injected CONTRACT AFFECTED BY MINERS return true; } } /// @dev Returns the address and the group of a pool from its id /// @param poolId Id of the pool /// @return poolAddress Address of the target pool /// @return groupAddress Address of the pool's group function addressFromId(uint256 poolId) internal view returns ( address poolAddress, address groupAddress ) { (poolAddress, , , , , groupAddress) = IDragoRegistry(DRAGOREGISTRYADDRESS).fromId(poolId); } /// @dev Returns the price a pool from its id /// @param poolId Id of the pool /// @return poolPrice Price of the pool in wei /// @return totalTokens Number of tokens of a pool (totalSupply) function getPoolPrice(uint256 poolId) internal view returns ( uint256 poolPrice, uint256 totalTokens ) { (address poolAddress, ) = addressFromId(poolId); IPool poolInstance = IPool(poolAddress); poolPrice = poolInstance.calcSharePrice(); totalTokens = poolInstance.totalSupply(); } /// @dev Returns the address and the group of a pool from its id /// @param poolId Id of the pool /// @return aum Address of the target pool /// @return success Address of the pool's group function calcPoolValue(uint256 poolId) internal view returns ( uint256 aum, bool success ) { (uint256 price, uint256 supply) = getPoolPrice(poolId); return ( aum = (price * supply / 1000000), //1000000 is the base (6 decimals) success = true ); } }
43,176
525
// Checks all cash group settings for invalid values and sets them into storage
function setCashGroupStorage(uint256 currencyId, CashGroupSettings calldata cashGroup) internal
function setCashGroupStorage(uint256 currencyId, CashGroupSettings calldata cashGroup) internal
10,987
94
// Burn transferBurnRate% from amount
super._burn(sender, _burntAmount);
super._burn(sender, _burntAmount);
12,725
178
// ctx[mmHalfFriInvGroup + idx] = lastValInv;
mstore(add(friHalfInvGroupPtr, mul(idx, 0x20)), lastValInv)
mstore(add(friHalfInvGroupPtr, mul(idx, 0x20)), lastValInv)
2,286
105
// The number of checkpoints for each account
mapping (address => uint32) public numCheckpoints;
mapping (address => uint32) public numCheckpoints;
18,196
4
// Errors allow you to provide information about why an operation failed. They are returned to the caller of the function.
error InsufficientBalance(uint requested, uint available);
error InsufficientBalance(uint requested, uint available);
27,202
52
// Emits {Transfer} event to reflect WETH10 token burn of `value` to zero address from caller account. / Requirements:/ - caller account must have at least `value` balance of WETH10 token.
function withdraw(uint256 value) external override {
function withdraw(uint256 value) external override {
28,283
48
// not check if old ad if end or not
delete adTable[uint64(id)];
delete adTable[uint64(id)];
29,029
39
// Returns the landIds you won so you know which landIds you can redeem
function checkWonLands() public view returns(uint256[] memory) { uint256[] memory result; uint256 counter = 0; for(uint256 i = 0; i < activeLands.length; i++) { uint256 landId = activeLands[i]; if (lands[landId].state == AuctionState.ENDED && lands[landId].owner == msg.sender) { result[counter] = landId; counter = counter.add(1); } } return result; }
function checkWonLands() public view returns(uint256[] memory) { uint256[] memory result; uint256 counter = 0; for(uint256 i = 0; i < activeLands.length; i++) { uint256 landId = activeLands[i]; if (lands[landId].state == AuctionState.ENDED && lands[landId].owner == msg.sender) { result[counter] = landId; counter = counter.add(1); } } return result; }
2,184
33
// one winner (one bid)
winner = highestBid.owner; cost = highestBid.value;
winner = highestBid.owner; cost = highestBid.value;
23,582
60
// Returns number of canvases owned by the given address./
function balanceOf(address _owner) external view returns (uint) { return addressToCount[_owner]; }
function balanceOf(address _owner) external view returns (uint) { return addressToCount[_owner]; }
4,640
2
// |/ Creates a NiftySwap Exchange for given token contract _tokenThe address of the ERC-1155 token contract _currency The address of the ERC-20 token contract _lpFeeFee that will go to LPs. Number between 0 and 1000, where 10 is 1.0% and 100 is 10%. _instance Instancethat allows to deploy new instances of an exchange. This is mainly meant to be used for tokens that change their ERC-2981 support. /
function createExchange(address _token, address _currency, uint256 _lpFee, uint256 _instance) public override { require(tokensToExchange[_token][_currency][_instance] == address(0x0), "NF20#1"); // NiftyswapFactory20#createExchange: EXCHANGE_ALREADY_CREATED
function createExchange(address _token, address _currency, uint256 _lpFee, uint256 _instance) public override { require(tokensToExchange[_token][_currency][_instance] == address(0x0), "NF20#1"); // NiftyswapFactory20#createExchange: EXCHANGE_ALREADY_CREATED
34,884
5
// Keep a list of all the redeemers ordered by time. It will be used at some point...
address[] public redeemers;
address[] public redeemers;
2,707
32
// Calculate points. Less than 1 minute is no payout
uint timeElapsedInSeconds = _laterTime.sub(_earlierTime);
uint timeElapsedInSeconds = _laterTime.sub(_earlierTime);
45,928
967
// Helper function to deploy a configured ComptrollerProxy
function __deployComptrollerProxy( address _denominationAsset, uint256 _sharesActionTimelock, bytes memory _feeManagerConfigData, bytes memory _policyManagerConfigData, bool _forMigration ) private returns (address comptrollerProxy_) { require( _denominationAsset != address(0), "__deployComptrollerProxy: _denominationAsset cannot be empty"
function __deployComptrollerProxy( address _denominationAsset, uint256 _sharesActionTimelock, bytes memory _feeManagerConfigData, bytes memory _policyManagerConfigData, bool _forMigration ) private returns (address comptrollerProxy_) { require( _denominationAsset != address(0), "__deployComptrollerProxy: _denominationAsset cannot be empty"
44,426
10
// Accumulated amount of tokens reserved for liquidity
uint256 private accLiquidityAmount;
uint256 private accLiquidityAmount;
36,502
12
// Construct the factory/_swapX2YModule swap module to support swapX2Y(DesireY)/_swapY2XModule swap module to support swapY2X(DesireX)/_liquidityModule liquidity module to support mint/burn/collect/_limitOrderModule module for user to manage limit orders/_flashModule module for user to flash/_defaultFeeChargePercent default fee rate from miner's fee gain100
constructor( address _chargeReceiver, address _swapX2YModule, address _swapY2XModule, address _liquidityModule, address _limitOrderModule, address _flashModule, uint24 _defaultFeeChargePercent
constructor( address _chargeReceiver, address _swapX2YModule, address _swapY2XModule, address _liquidityModule, address _limitOrderModule, address _flashModule, uint24 _defaultFeeChargePercent
27,051
8
// setter for protocol fees/newProtocolFeePrimary fee for primary market/newProtocolFeeSecondary fee for secondary market
function setProtocolFee(uint256 newProtocolFeePrimary, uint256 newProtocolFeeSecondary) external onlyOwner { require(newProtocolFeePrimary < 5000, "invalid primary fee"); require(newProtocolFeeSecondary < 5000, "invalid secodary fee"); protocolFeePrimary = newProtocolFeePrimary; protocolFeeSecondary = newProtocolFeeSecondary; emit ProtocolFeeSetted(newProtocolFeePrimary, newProtocolFeeSecondary); }
function setProtocolFee(uint256 newProtocolFeePrimary, uint256 newProtocolFeeSecondary) external onlyOwner { require(newProtocolFeePrimary < 5000, "invalid primary fee"); require(newProtocolFeeSecondary < 5000, "invalid secodary fee"); protocolFeePrimary = newProtocolFeePrimary; protocolFeeSecondary = newProtocolFeeSecondary; emit ProtocolFeeSetted(newProtocolFeePrimary, newProtocolFeeSecondary); }
16,474
38
// check whether a given user is registered as owning a given wallet
function userOwnsWallet(address _user, address _wallet) external view returns (bool) { return _ownerToWallets[_user].contains(_wallet); }
function userOwnsWallet(address _user, address _wallet) external view returns (bool) { return _ownerToWallets[_user].contains(_wallet); }
35,373
22
// ======== END CONTRACT VARIABLES ===============
uint public lastClaimedTime; uint public deployTime;
uint public lastClaimedTime; uint public deployTime;
12,408
55
// if the applicant is already a member, add to their existing shares & loot
if (members[proposal.applicant].exists) { members[proposal.applicant].shares = members[proposal.applicant].shares.add(proposal.sharesRequested); members[proposal.applicant].loot = members[proposal.applicant].loot.add(proposal.lootRequested);
if (members[proposal.applicant].exists) { members[proposal.applicant].shares = members[proposal.applicant].shares.add(proposal.sharesRequested); members[proposal.applicant].loot = members[proposal.applicant].loot.add(proposal.lootRequested);
19,807