Transaction Hash:
Block:
22590978 at May-29-2025 09:07:35 PM +UTC
Transaction Fee:
0.0003962352030428 ETH
$0.99
Gas Used:
99,685 Gas / 3.97487288 Gwei
Emitted Events:
229 |
ERC20PredicateProxy.0x9b217a401a5ddf7c4d474074aff9958a18d48690d77cc2151c4706aa7348b401( 0x9b217a401a5ddf7c4d474074aff9958a18d48690d77cc2151c4706aa7348b401, 0x000000000000000000000000ca74f404e0c7bfa35b13b511097df966d5a65597, 0x000000000000000000000000ca74f404e0c7bfa35b13b511097df966d5a65597, 0x0000000000000000000000006b0b3a982b4634ac68dd83a4dbf02311ce324181, 000000000000000000000000000000000000000000000797f3c18da9d8663000 )
|
230 |
AliERC20v2.Transfer( by=ERC20PredicateProxy, from=[Sender] 0xca74f404e0c7bfa35b13b511097df966d5a65597, to=ERC20PredicateProxy, value=35859588211000000000000 )
|
231 |
AliERC20v2.Transfer( from=[Sender] 0xca74f404e0c7bfa35b13b511097df966d5a65597, to=ERC20PredicateProxy, value=35859588211000000000000 )
|
232 |
StateSender.StateSynced( id=3071425, contractAddress=0xA6FA4fB5...9C5d1C0aa, data=0x87A7811F4BFEDEA3D341AD165680AE306B01AAEACC205D227629CF157DD9F821000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000A0000000000000000000000000CA74F404E0C7BFA35B13B511097DF966D5A655970000000000000000000000006B0B3A982B4634AC68DD83A4DBF02311CE32418100000000000000000000000000000000000000000000000000000000000000600000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000797F3C18DA9D8663000 )
|
Account State Difference:
Address | Before | After | State Difference | ||
---|---|---|---|---|---|
0x28e4F3a7...189A5bFbE | (Polygon (Matic): State Syncer) | ||||
0x6B0b3a98...1cE324181 | |||||
0xcA74F404...6D5a65597 |
2.250931181052125897 Eth
Nonce: 422491
|
2.250534945849083097 Eth
Nonce: 422492
| 0.0003962352030428 | ||
0xdadB0d80...24f783711
Miner
| (BuilderNet) | 46.423683330603683106 Eth | 46.423728368286683106 Eth | 0.000045037683 |
Execution Trace
RootChainManagerProxy.e3dec8fb( )

RootChainManager.depositFor( user=0xcA74F404E0C7bfA35B13B511097df966D5a65597, rootToken=0x6B0b3a982b4634aC68dD83a4DBF02311cE324181, depositData=0x000000000000000000000000000000000000000000000797F3C18DA9D8663000 )
ERC20PredicateProxy.e375b64e( )
ERC20Predicate.lockTokens( depositor=0xcA74F404E0C7bfA35B13B511097df966D5a65597, depositReceiver=0xcA74F404E0C7bfA35B13B511097df966D5a65597, rootToken=0x6B0b3a982b4634aC68dD83a4DBF02311cE324181, depositData=0x000000000000000000000000000000000000000000000797F3C18DA9D8663000 )
-
AliERC20v2.transferFrom( _from=0xcA74F404E0C7bfA35B13B511097df966D5a65597, _to=0x40ec5B33f54e0E8A33A975908C5BA1c14e5BbbDf, _value=35859588211000000000000 ) => ( success=True )
-
-
StateSender.syncState( receiver=0xA6FA4fB5f76172d178d61B04b0ecd319C5d1C0aa, data=0x87A7811F4BFEDEA3D341AD165680AE306B01AAEACC205D227629CF157DD9F821000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000A0000000000000000000000000CA74F404E0C7BFA35B13B511097DF966D5A655970000000000000000000000006B0B3A982B4634AC68DD83A4DBF02311CE32418100000000000000000000000000000000000000000000000000000000000000600000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000797F3C18DA9D8663000 )
depositFor[RootChainManager (ln:243)]
_depositFor[RootChainManager (ln:252)]
lockTokens[RootChainManager (ln:284)]
_msgSender[RootChainManager (ln:285)]
msgSender[RootChainManager (ln:47)]
encode[RootChainManager (ln:290)]
syncState[RootChainManager (ln:291)]
encode[RootChainManager (ln:293)]
File 1 of 6: RootChainManagerProxy
File 2 of 6: ERC20PredicateProxy
File 3 of 6: AliERC20v2
File 4 of 6: StateSender
File 5 of 6: RootChainManager
File 6 of 6: ERC20Predicate
// File: contracts/common/Proxy/IERCProxy.sol pragma solidity 0.6.6; interface IERCProxy { function proxyType() external pure returns (uint256 proxyTypeId); function implementation() external view returns (address codeAddr); } // File: contracts/common/Proxy/Proxy.sol pragma solidity 0.6.6; abstract contract Proxy is IERCProxy { function delegatedFwd(address _dst, bytes memory _calldata) internal { // solium-disable-next-line security/no-inline-assembly assembly { let result := delegatecall( sub(gas(), 10000), _dst, add(_calldata, 0x20), mload(_calldata), 0, 0 ) let size := returndatasize() let ptr := mload(0x40) returndatacopy(ptr, 0, size) // revert instead of invalid() bc if the underlying call failed with invalid() it already wasted gas. // if the call returned error data, forward it switch result case 0 { revert(ptr, size) } default { return(ptr, size) } } } function proxyType() external virtual override pure returns (uint256 proxyTypeId) { // Upgradeable proxy proxyTypeId = 2; } function implementation() external virtual override view returns (address); } // File: contracts/common/Proxy/UpgradableProxy.sol pragma solidity 0.6.6; contract UpgradableProxy is Proxy { event ProxyUpdated(address indexed _new, address indexed _old); event ProxyOwnerUpdate(address _new, address _old); bytes32 constant IMPLEMENTATION_SLOT = keccak256("matic.network.proxy.implementation"); bytes32 constant OWNER_SLOT = keccak256("matic.network.proxy.owner"); constructor(address _proxyTo) public { setProxyOwner(msg.sender); setImplementation(_proxyTo); } fallback() external payable { delegatedFwd(loadImplementation(), msg.data); } receive() external payable { delegatedFwd(loadImplementation(), msg.data); } modifier onlyProxyOwner() { require(loadProxyOwner() == msg.sender, "NOT_OWNER"); _; } function proxyOwner() external view returns(address) { return loadProxyOwner(); } function loadProxyOwner() internal view returns(address) { address _owner; bytes32 position = OWNER_SLOT; assembly { _owner := sload(position) } return _owner; } function implementation() external override view returns (address) { return loadImplementation(); } function loadImplementation() internal view returns(address) { address _impl; bytes32 position = IMPLEMENTATION_SLOT; assembly { _impl := sload(position) } return _impl; } function transferProxyOwnership(address newOwner) public onlyProxyOwner { require(newOwner != address(0), "ZERO_ADDRESS"); emit ProxyOwnerUpdate(newOwner, loadProxyOwner()); setProxyOwner(newOwner); } function setProxyOwner(address newOwner) private { bytes32 position = OWNER_SLOT; assembly { sstore(position, newOwner) } } function updateImplementation(address _newProxyTo) public onlyProxyOwner { require(_newProxyTo != address(0x0), "INVALID_PROXY_ADDRESS"); require(isContract(_newProxyTo), "DESTINATION_ADDRESS_IS_NOT_A_CONTRACT"); emit ProxyUpdated(_newProxyTo, loadImplementation()); setImplementation(_newProxyTo); } function updateAndCall(address _newProxyTo, bytes memory data) payable public onlyProxyOwner { updateImplementation(_newProxyTo); (bool success, bytes memory returnData) = address(this).call{value: msg.value}(data); require(success, string(returnData)); } function setImplementation(address _newProxyTo) private { bytes32 position = IMPLEMENTATION_SLOT; assembly { sstore(position, _newProxyTo) } } function isContract(address _target) internal view returns (bool) { if (_target == address(0)) { return false; } uint256 size; assembly { size := extcodesize(_target) } return size > 0; } } // File: contracts/root/RootChainManager/RootChainManagerProxy.sol pragma solidity 0.6.6; contract RootChainManagerProxy is UpgradableProxy { constructor(address _proxyTo) public UpgradableProxy(_proxyTo) {} }
File 2 of 6: ERC20PredicateProxy
// File: contracts/common/Proxy/IERCProxy.sol pragma solidity 0.6.6; interface IERCProxy { function proxyType() external pure returns (uint256 proxyTypeId); function implementation() external view returns (address codeAddr); } // File: contracts/common/Proxy/Proxy.sol pragma solidity 0.6.6; abstract contract Proxy is IERCProxy { function delegatedFwd(address _dst, bytes memory _calldata) internal { // solium-disable-next-line security/no-inline-assembly assembly { let result := delegatecall( sub(gas(), 10000), _dst, add(_calldata, 0x20), mload(_calldata), 0, 0 ) let size := returndatasize() let ptr := mload(0x40) returndatacopy(ptr, 0, size) // revert instead of invalid() bc if the underlying call failed with invalid() it already wasted gas. // if the call returned error data, forward it switch result case 0 { revert(ptr, size) } default { return(ptr, size) } } } function proxyType() external virtual override pure returns (uint256 proxyTypeId) { // Upgradeable proxy proxyTypeId = 2; } function implementation() external virtual override view returns (address); } // File: contracts/common/Proxy/UpgradableProxy.sol pragma solidity 0.6.6; contract UpgradableProxy is Proxy { event ProxyUpdated(address indexed _new, address indexed _old); event ProxyOwnerUpdate(address _new, address _old); bytes32 constant IMPLEMENTATION_SLOT = keccak256("matic.network.proxy.implementation"); bytes32 constant OWNER_SLOT = keccak256("matic.network.proxy.owner"); constructor(address _proxyTo) public { setProxyOwner(msg.sender); setImplementation(_proxyTo); } fallback() external payable { delegatedFwd(loadImplementation(), msg.data); } receive() external payable { delegatedFwd(loadImplementation(), msg.data); } modifier onlyProxyOwner() { require(loadProxyOwner() == msg.sender, "NOT_OWNER"); _; } function proxyOwner() external view returns(address) { return loadProxyOwner(); } function loadProxyOwner() internal view returns(address) { address _owner; bytes32 position = OWNER_SLOT; assembly { _owner := sload(position) } return _owner; } function implementation() external override view returns (address) { return loadImplementation(); } function loadImplementation() internal view returns(address) { address _impl; bytes32 position = IMPLEMENTATION_SLOT; assembly { _impl := sload(position) } return _impl; } function transferProxyOwnership(address newOwner) public onlyProxyOwner { require(newOwner != address(0), "ZERO_ADDRESS"); emit ProxyOwnerUpdate(newOwner, loadProxyOwner()); setProxyOwner(newOwner); } function setProxyOwner(address newOwner) private { bytes32 position = OWNER_SLOT; assembly { sstore(position, newOwner) } } function updateImplementation(address _newProxyTo) public onlyProxyOwner { require(_newProxyTo != address(0x0), "INVALID_PROXY_ADDRESS"); require(isContract(_newProxyTo), "DESTINATION_ADDRESS_IS_NOT_A_CONTRACT"); emit ProxyUpdated(_newProxyTo, loadImplementation()); setImplementation(_newProxyTo); } function updateAndCall(address _newProxyTo, bytes memory data) payable public onlyProxyOwner { updateImplementation(_newProxyTo); (bool success, bytes memory returnData) = address(this).call{value: msg.value}(data); require(success, string(returnData)); } function setImplementation(address _newProxyTo) private { bytes32 position = IMPLEMENTATION_SLOT; assembly { sstore(position, _newProxyTo) } } function isContract(address _target) internal view returns (bool) { if (_target == address(0)) { return false; } uint256 size; assembly { size := extcodesize(_target) } return size > 0; } } // File: contracts/root/TokenPredicates/ERC20PredicateProxy.sol pragma solidity 0.6.6; contract ERC20PredicateProxy is UpgradableProxy { constructor(address _proxyTo) public UpgradableProxy(_proxyTo) {} }
File 3 of 6: AliERC20v2
// SPDX-License-Identifier: MIT pragma solidity 0.8.7; import "../interfaces/ERC1363Spec.sol"; import "../interfaces/EIP2612.sol"; import "../interfaces/EIP3009.sol"; import "../utils/AccessControl.sol"; import "../lib/AddressUtils.sol"; import "../lib/ECDSA.sol"; /** * @title Artificial Liquid Intelligence ERC20 Token (Alethea, ALI) * * @notice ALI is the native utility token of the Alethea AI Protocol. * It serves as protocol currency, participates in iNFTs lifecycle, * (locked when iNFT is created, released when iNFT is destroyed, * consumed when iNFT is upgraded). * ALI token powers up the governance protocol (Alethea DAO) * * @notice Token Summary: * - Symbol: ALI * - Name: Artificial Liquid Intelligence Token * - Decimals: 18 * - Initial/maximum total supply: 10,000,000,000 ALI * - Initial supply holder (initial holder) address: // TODO: [DEFINE] * - Not mintable: new tokens cannot be created * - Burnable: existing tokens may get destroyed, total supply may decrease * - DAO Support: supports voting delegation * * @notice Features Summary: * - Supports atomic allowance modification, resolves well-known ERC20 issue with approve (arXiv:1907.00903) * - Voting delegation and delegation on behalf via EIP-712 (like in Compound CMP token) - gives ALI token * powerful governance capabilities by allowing holders to form voting groups by electing delegates * - Unlimited approval feature (like in 0x ZRX token) - saves gas for transfers on behalf * by eliminating the need to update “unlimited” allowance value * - ERC-1363 Payable Token - ERC721-like callback execution mechanism for transfers, * transfers on behalf and approvals; allows creation of smart contracts capable of executing callbacks * in response to transfer or approval in a single transaction * - EIP-2612: permit - 712-signed approvals - improves user experience by allowing to use a token * without having an ETH to pay gas fees * - EIP-3009: Transfer With Authorization - improves user experience by allowing to use a token * without having an ETH to pay gas fees * * @dev Even though smart contract has mint() function which is used to mint initial token supply, * the function is disabled forever after smart contract deployment by revoking `TOKEN_CREATOR` * permission from the deployer account * * @dev Token balances and total supply are effectively 192 bits long, meaning that maximum * possible total supply smart contract is able to track is 2^192 (close to 10^40 tokens) * * @dev Smart contract doesn't use safe math. All arithmetic operations are overflow/underflow safe. * Additionally, Solidity 0.8.7 enforces overflow/underflow safety. * * @dev Multiple Withdrawal Attack on ERC20 Tokens (arXiv:1907.00903) - resolved * Related events and functions are marked with "arXiv:1907.00903" tag: * - event Transfer(address indexed _by, address indexed _from, address indexed _to, uint256 _value) * - event Approve(address indexed _owner, address indexed _spender, uint256 _oldValue, uint256 _value) * - function increaseAllowance(address _spender, uint256 _value) public returns (bool) * - function decreaseAllowance(address _spender, uint256 _value) public returns (bool) * See: https://arxiv.org/abs/1907.00903v1 * https://ieeexplore.ieee.org/document/8802438 * See: https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * @dev Reviewed * ERC-20 - according to https://eips.ethereum.org/EIPS/eip-20 * ERC-1363 - according to https://eips.ethereum.org/EIPS/eip-1363 * EIP-2612 - according to https://eips.ethereum.org/EIPS/eip-2612 * EIP-3009 - according to https://eips.ethereum.org/EIPS/eip-3009 * * @dev ERC20: contract has passed * - OpenZeppelin ERC20 tests * https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/test/token/ERC20/ERC20.behavior.js * https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/test/token/ERC20/ERC20.test.js * - Ref ERC1363 tests * https://github.com/vittominacori/erc1363-payable-token/blob/master/test/token/ERC1363/ERC1363.behaviour.js * - OpenZeppelin EIP2612 tests * https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/test/token/ERC20/extensions/draft-ERC20Permit.test.js * - Coinbase EIP3009 tests * https://github.com/CoinbaseStablecoin/eip-3009/blob/master/test/EIP3009.test.ts * - Compound voting delegation tests * https://github.com/compound-finance/compound-protocol/blob/master/tests/Governance/CompTest.js * https://github.com/compound-finance/compound-protocol/blob/master/tests/Utils/EIP712.js * - OpenZeppelin voting delegation tests * https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/test/token/ERC20/extensions/ERC20Votes.test.js * See adopted copies of all the tests in the project test folder * * @dev Compound-like voting delegation functions', public getters', and events' names * were changed for better code readability (Alethea Name <- Comp/Zeppelin name): * - votingDelegates <- delegates * - votingPowerHistory <- checkpoints * - votingPowerHistoryLength <- numCheckpoints * - totalSupplyHistory <- _totalSupplyCheckpoints (private) * - usedNonces <- nonces (note: nonces are random instead of sequential) * - DelegateChanged (unchanged) * - VotingPowerChanged <- DelegateVotesChanged * - votingPowerOf <- getCurrentVotes * - votingPowerAt <- getPriorVotes * - totalSupplyAt <- getPriorTotalSupply * - delegate (unchanged) * - delegateWithAuthorization <- delegateBySig * @dev Compound-like voting delegation improved to allow the use of random nonces like in EIP-3009, * instead of sequential; same `usedNonces` EIP-3009 mapping is used to track nonces * * @dev Reference implementations "used": * - Atomic allowance: https://github.com/OpenZeppelin/openzeppelin-contracts * - Unlimited allowance: https://github.com/0xProject/protocol * - Voting delegation: https://github.com/compound-finance/compound-protocol * https://github.com/OpenZeppelin/openzeppelin-contracts * - ERC-1363: https://github.com/vittominacori/erc1363-payable-token * - EIP-2612: https://github.com/Uniswap/uniswap-v2-core * - EIP-3009: https://github.com/centrehq/centre-tokens * https://github.com/CoinbaseStablecoin/eip-3009 * - Meta transactions: https://github.com/0xProject/protocol * * @dev Includes resolutions for ALI ERC20 Audit by Miguel Palhas, https://hackmd.io/@naps62/alierc20-audit */ contract AliERC20v2 is ERC1363, EIP2612, EIP3009, AccessControl { \t/** \t * @dev Smart contract unique identifier, a random number \t * \t * @dev Should be regenerated each time smart contact source code is changed \t * and changes smart contract itself is to be redeployed \t * \t * @dev Generated using https://www.random.org/bytes/ \t */ \tuint256 public constant TOKEN_UID = 0x8d4fb97da97378ef7d0ad259aec651f42bd22c200159282baa58486bb390286b; \t/** \t * @notice Name of the token: Artificial Liquid Intelligence Token \t * \t * @notice ERC20 name of the token (long name) \t * \t * @dev ERC20 `function name() public view returns (string)` \t * \t * @dev Field is declared public: getter name() is created when compiled, \t * it returns the name of the token. \t */ \tstring public constant name = "Artificial Liquid Intelligence Token"; \t/** \t * @notice Symbol of the token: ALI \t * \t * @notice ERC20 symbol of that token (short name) \t * \t * @dev ERC20 `function symbol() public view returns (string)` \t * \t * @dev Field is declared public: getter symbol() is created when compiled, \t * it returns the symbol of the token \t */ \tstring public constant symbol = "ALI"; \t/** \t * @notice Decimals of the token: 18 \t * \t * @dev ERC20 `function decimals() public view returns (uint8)` \t * \t * @dev Field is declared public: getter decimals() is created when compiled, \t * it returns the number of decimals used to get its user representation. \t * For example, if `decimals` equals `6`, a balance of `1,500,000` tokens should \t * be displayed to a user as `1,5` (`1,500,000 / 10 ** 6`). \t * \t * @dev NOTE: This information is only used for _display_ purposes: it in \t * no way affects any of the arithmetic of the contract, including balanceOf() and transfer(). \t */ \tuint8 public constant decimals = 18; \t/** \t * @notice Total supply of the token: initially 10,000,000,000, \t * with the potential to decline over time as some tokens may get burnt but not minted \t * \t * @dev ERC20 `function totalSupply() public view returns (uint256)` \t * \t * @dev Field is declared public: getter totalSupply() is created when compiled, \t * it returns the amount of tokens in existence. \t */ \tuint256 public override totalSupply; // is set to 10 billion * 10^18 in the constructor \t/** \t * @dev A record of all the token balances \t * @dev This mapping keeps record of all token owners: \t * owner => balance \t */ \tmapping(address => uint256) private tokenBalances; \t/** \t * @notice A record of each account's voting delegate \t * \t * @dev Auxiliary data structure used to sum up an account's voting power \t * \t * @dev This mapping keeps record of all voting power delegations: \t * voting delegator (token owner) => voting delegate \t */ \tmapping(address => address) public votingDelegates; \t/** \t * @notice Auxiliary structure to store key-value pair, used to store: \t * - voting power record (key: block.timestamp, value: voting power) \t * - total supply record (key: block.timestamp, value: total supply) \t * @notice A voting power record binds voting power of a delegate to a particular \t * block when the voting power delegation change happened \t * k: block.number when delegation has changed; starting from \t * that block voting power value is in effect \t * v: cumulative voting power a delegate has obtained starting \t * from the block stored in blockNumber \t * @notice Total supply record binds total token supply to a particular \t * block when total supply change happened (due to mint/burn operations) \t */ \tstruct KV { \t\t/* \t\t * @dev key, a block number \t\t */ \t\tuint64 k; \t\t/* \t\t * @dev value, token balance or voting power \t\t */ \t\tuint192 v; \t} \t/** \t * @notice A record of each account's voting power historical data \t * \t * @dev Primarily data structure to store voting power for each account. \t * Voting power sums up from the account's token balance and delegated \t * balances. \t * \t * @dev Stores current value and entire history of its changes. \t * The changes are stored as an array of checkpoints (key-value pairs). \t * Checkpoint is an auxiliary data structure containing voting \t * power (number of votes) and block number when the checkpoint is saved \t * \t * @dev Maps voting delegate => voting power record \t */ \tmapping(address => KV[]) public votingPowerHistory; \t/** \t * @notice A record of total token supply historical data \t * \t * @dev Primarily data structure to store total token supply. \t * \t * @dev Stores current value and entire history of its changes. \t * The changes are stored as an array of checkpoints (key-value pairs). \t * Checkpoint is an auxiliary data structure containing total \t * token supply and block number when the checkpoint is saved \t */ \tKV[] public totalSupplyHistory; \t/** \t * @dev A record of nonces for signing/validating signatures in EIP-2612 `permit` \t * \t * @dev Note: EIP2612 doesn't imply a possibility for nonce randomization like in EIP-3009 \t * \t * @dev Maps delegate address => delegate nonce \t */ \tmapping(address => uint256) public override nonces; \t/** \t * @dev A record of used nonces for EIP-3009 transactions \t * \t * @dev A record of used nonces for signing/validating signatures \t * in `delegateWithAuthorization` for every delegate \t * \t * @dev Maps authorizer address => nonce => true/false (used unused) \t */ \tmapping(address => mapping(bytes32 => bool)) private usedNonces; \t/** \t * @notice A record of all the allowances to spend tokens on behalf \t * @dev Maps token owner address to an address approved to spend \t * some tokens on behalf, maps approved address to that amount \t * @dev owner => spender => value \t */ \tmapping(address => mapping(address => uint256)) private transferAllowances; \t/** \t * @notice Enables ERC20 transfers of the tokens \t * (transfer by the token owner himself) \t * @dev Feature FEATURE_TRANSFERS must be enabled in order for \t * `transfer()` function to succeed \t */ \tuint32 public constant FEATURE_TRANSFERS = 0x0000_0001; \t/** \t * @notice Enables ERC20 transfers on behalf \t * (transfer by someone else on behalf of token owner) \t * @dev Feature FEATURE_TRANSFERS_ON_BEHALF must be enabled in order for \t * `transferFrom()` function to succeed \t * @dev Token owner must call `approve()` first to authorize \t * the transfer on behalf \t */ \tuint32 public constant FEATURE_TRANSFERS_ON_BEHALF = 0x0000_0002; \t/** \t * @dev Defines if the default behavior of `transfer` and `transferFrom` \t * checks if the receiver smart contract supports ERC20 tokens \t * @dev When feature FEATURE_UNSAFE_TRANSFERS is enabled the transfers do not \t * check if the receiver smart contract supports ERC20 tokens, \t * i.e. `transfer` and `transferFrom` behave like `unsafeTransferFrom` \t * @dev When feature FEATURE_UNSAFE_TRANSFERS is disabled (default) the transfers \t * check if the receiver smart contract supports ERC20 tokens, \t * i.e. `transfer` and `transferFrom` behave like `transferFromAndCall` \t */ \tuint32 public constant FEATURE_UNSAFE_TRANSFERS = 0x0000_0004; \t/** \t * @notice Enables token owners to burn their own tokens \t * \t * @dev Feature FEATURE_OWN_BURNS must be enabled in order for \t * `burn()` function to succeed when called by token owner \t */ \tuint32 public constant FEATURE_OWN_BURNS = 0x0000_0008; \t/** \t * @notice Enables approved operators to burn tokens on behalf of their owners \t * \t * @dev Feature FEATURE_BURNS_ON_BEHALF must be enabled in order for \t * `burn()` function to succeed when called by approved operator \t */ \tuint32 public constant FEATURE_BURNS_ON_BEHALF = 0x0000_0010; \t/** \t * @notice Enables delegators to elect delegates \t * @dev Feature FEATURE_DELEGATIONS must be enabled in order for \t * `delegate()` function to succeed \t */ \tuint32 public constant FEATURE_DELEGATIONS = 0x0000_0020; \t/** \t * @notice Enables delegators to elect delegates on behalf \t * (via an EIP712 signature) \t * @dev Feature FEATURE_DELEGATIONS_ON_BEHALF must be enabled in order for \t * `delegateWithAuthorization()` function to succeed \t */ \tuint32 public constant FEATURE_DELEGATIONS_ON_BEHALF = 0x0000_0040; \t/** \t * @notice Enables ERC-1363 transfers with callback \t * @dev Feature FEATURE_ERC1363_TRANSFERS must be enabled in order for \t * ERC-1363 `transferFromAndCall` functions to succeed \t */ \tuint32 public constant FEATURE_ERC1363_TRANSFERS = 0x0000_0080; \t/** \t * @notice Enables ERC-1363 approvals with callback \t * @dev Feature FEATURE_ERC1363_APPROVALS must be enabled in order for \t * ERC-1363 `approveAndCall` functions to succeed \t */ \tuint32 public constant FEATURE_ERC1363_APPROVALS = 0x0000_0100; \t/** \t * @notice Enables approvals on behalf (EIP2612 permits \t * via an EIP712 signature) \t * @dev Feature FEATURE_EIP2612_PERMITS must be enabled in order for \t * `permit()` function to succeed \t */ \tuint32 public constant FEATURE_EIP2612_PERMITS = 0x0000_0200; \t/** \t * @notice Enables meta transfers on behalf (EIP3009 transfers \t * via an EIP712 signature) \t * @dev Feature FEATURE_EIP3009_TRANSFERS must be enabled in order for \t * `transferWithAuthorization()` function to succeed \t */ \tuint32 public constant FEATURE_EIP3009_TRANSFERS = 0x0000_0400; \t/** \t * @notice Enables meta transfers on behalf (EIP3009 transfers \t * via an EIP712 signature) \t * @dev Feature FEATURE_EIP3009_RECEPTIONS must be enabled in order for \t * `receiveWithAuthorization()` function to succeed \t */ \tuint32 public constant FEATURE_EIP3009_RECEPTIONS = 0x0000_0800; \t/** \t * @notice Token creator is responsible for creating (minting) \t * tokens to an arbitrary address \t * @dev Role ROLE_TOKEN_CREATOR allows minting tokens \t * (calling `mint` function) \t */ \tuint32 public constant ROLE_TOKEN_CREATOR = 0x0001_0000; \t/** \t * @notice Token destroyer is responsible for destroying (burning) \t * tokens owned by an arbitrary address \t * @dev Role ROLE_TOKEN_DESTROYER allows burning tokens \t * (calling `burn` function) \t */ \tuint32 public constant ROLE_TOKEN_DESTROYER = 0x0002_0000; \t/** \t * @notice ERC20 receivers are allowed to receive tokens without ERC20 safety checks, \t * which may be useful to simplify tokens transfers into "legacy" smart contracts \t * @dev When `FEATURE_UNSAFE_TRANSFERS` is not enabled addresses having \t * `ROLE_ERC20_RECEIVER` permission are allowed to receive tokens \t * via `transfer` and `transferFrom` functions in the same way they \t * would via `unsafeTransferFrom` function \t * @dev When `FEATURE_UNSAFE_TRANSFERS` is enabled `ROLE_ERC20_RECEIVER` permission \t * doesn't affect the transfer behaviour since \t * `transfer` and `transferFrom` behave like `unsafeTransferFrom` for any receiver \t * @dev ROLE_ERC20_RECEIVER is a shortening for ROLE_UNSAFE_ERC20_RECEIVER \t */ \tuint32 public constant ROLE_ERC20_RECEIVER = 0x0004_0000; \t/** \t * @notice ERC20 senders are allowed to send tokens without ERC20 safety checks, \t * which may be useful to simplify tokens transfers into "legacy" smart contracts \t * @dev When `FEATURE_UNSAFE_TRANSFERS` is not enabled senders having \t * `ROLE_ERC20_SENDER` permission are allowed to send tokens \t * via `transfer` and `transferFrom` functions in the same way they \t * would via `unsafeTransferFrom` function \t * @dev When `FEATURE_UNSAFE_TRANSFERS` is enabled `ROLE_ERC20_SENDER` permission \t * doesn't affect the transfer behaviour since \t * `transfer` and `transferFrom` behave like `unsafeTransferFrom` for any receiver \t * @dev ROLE_ERC20_SENDER is a shortening for ROLE_UNSAFE_ERC20_SENDER \t */ \tuint32 public constant ROLE_ERC20_SENDER = 0x0008_0000; \t/** \t * @notice EIP-712 contract's domain typeHash, \t * see https://eips.ethereum.org/EIPS/eip-712#rationale-for-typehash \t * \t * @dev Note: we do not include version into the domain typehash/separator, \t * it is implied version is concatenated to the name field, like "AliERC20v2" \t */ \t// keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)") \tbytes32 public constant DOMAIN_TYPEHASH = 0x8cad95687ba82c2ce50e74f7b754645e5117c3a5bec8151c0726d5857980a866; \t/** \t * @notice EIP-712 contract's domain separator, \t * see https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator \t */ \tbytes32 public immutable override DOMAIN_SEPARATOR; \t/** \t * @notice EIP-712 delegation struct typeHash, \t * see https://eips.ethereum.org/EIPS/eip-712#rationale-for-typehash \t */ \t// keccak256("Delegation(address delegate,uint256 nonce,uint256 expiry)") \tbytes32 public constant DELEGATION_TYPEHASH = 0xff41620983935eb4d4a3c7384a066ca8c1d10cef9a5eca9eb97ca735cd14a755; \t/** \t * @notice EIP-712 permit (EIP-2612) struct typeHash, \t * see https://eips.ethereum.org/EIPS/eip-712#rationale-for-typehash \t */ \t// keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)") \tbytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; \t/** \t * @notice EIP-712 TransferWithAuthorization (EIP-3009) struct typeHash, \t * see https://eips.ethereum.org/EIPS/eip-712#rationale-for-typehash \t */ \t// keccak256("TransferWithAuthorization(address from,address to,uint256 value,uint256 validAfter,uint256 validBefore,bytes32 nonce)") \tbytes32 public constant TRANSFER_WITH_AUTHORIZATION_TYPEHASH = 0x7c7c6cdb67a18743f49ec6fa9b35f50d52ed05cbed4cc592e13b44501c1a2267; \t/** \t * @notice EIP-712 ReceiveWithAuthorization (EIP-3009) struct typeHash, \t * see https://eips.ethereum.org/EIPS/eip-712#rationale-for-typehash \t */ \t// keccak256("ReceiveWithAuthorization(address from,address to,uint256 value,uint256 validAfter,uint256 validBefore,bytes32 nonce)") \tbytes32 public constant RECEIVE_WITH_AUTHORIZATION_TYPEHASH = 0xd099cc98ef71107a616c4f0f941f04c322d8e254fe26b3c6668db87aae413de8; \t/** \t * @notice EIP-712 CancelAuthorization (EIP-3009) struct typeHash, \t * see https://eips.ethereum.org/EIPS/eip-712#rationale-for-typehash \t */ \t// keccak256("CancelAuthorization(address authorizer,bytes32 nonce)") \tbytes32 public constant CANCEL_AUTHORIZATION_TYPEHASH = 0x158b0a9edf7a828aad02f63cd515c68ef2f50ba807396f6d12842833a1597429; \t/** \t * @dev Fired in mint() function \t * \t * @param by an address which minted some tokens (transaction sender) \t * @param to an address the tokens were minted to \t * @param value an amount of tokens minted \t */ \tevent Minted(address indexed by, address indexed to, uint256 value); \t/** \t * @dev Fired in burn() function \t * \t * @param by an address which burned some tokens (transaction sender) \t * @param from an address the tokens were burnt from \t * @param value an amount of tokens burnt \t */ \tevent Burnt(address indexed by, address indexed from, uint256 value); \t/** \t * @dev Resolution for the Multiple Withdrawal Attack on ERC20 Tokens (arXiv:1907.00903) \t * \t * @dev Similar to ERC20 Transfer event, but also logs an address which executed transfer \t * \t * @dev Fired in transfer(), transferFrom() and some other (non-ERC20) functions \t * \t * @param by an address which performed the transfer \t * @param from an address tokens were consumed from \t * @param to an address tokens were sent to \t * @param value number of tokens transferred \t */ \tevent Transfer(address indexed by, address indexed from, address indexed to, uint256 value); \t/** \t * @dev Resolution for the Multiple Withdrawal Attack on ERC20 Tokens (arXiv:1907.00903) \t * \t * @dev Similar to ERC20 Approve event, but also logs old approval value \t * \t * @dev Fired in approve(), increaseAllowance(), decreaseAllowance() functions, \t * may get fired in transfer functions \t * \t * @param owner an address which granted a permission to transfer \t * tokens on its behalf \t * @param spender an address which received a permission to transfer \t * tokens on behalf of the owner `_owner` \t * @param oldValue previously granted amount of tokens to transfer on behalf \t * @param value new granted amount of tokens to transfer on behalf \t */ \tevent Approval(address indexed owner, address indexed spender, uint256 oldValue, uint256 value); \t/** \t * @dev Notifies that a key-value pair in `votingDelegates` mapping has changed, \t * i.e. a delegator address has changed its delegate address \t * \t * @param source delegator address, a token owner, effectively transaction sender (`by`) \t * @param from old delegate, an address which delegate right is revoked \t * @param to new delegate, an address which received the voting power \t */ \tevent DelegateChanged(address indexed source, address indexed from, address indexed to); \t/** \t * @dev Notifies that a key-value pair in `votingPowerHistory` mapping has changed, \t * i.e. a delegate's voting power has changed. \t * \t * @param by an address which executed delegate, mint, burn, or transfer operation \t * which had led to delegate voting power change \t * @param target delegate whose voting power has changed \t * @param fromVal previous number of votes delegate had \t * @param toVal new number of votes delegate has \t */ \tevent VotingPowerChanged(address indexed by, address indexed target, uint256 fromVal, uint256 toVal); \t/** \t * @dev Deploys the token smart contract, \t * assigns initial token supply to the address specified \t * \t * @param _initialHolder owner of the initial token supply \t */ \tconstructor(address _initialHolder) { \t\t// verify initial holder address non-zero (is set) \t\trequire(_initialHolder != address(0), "_initialHolder not set (zero address)"); \t\t// build the EIP-712 contract domain separator, see https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator \t\t// note: we specify contract version in its name \t\tDOMAIN_SEPARATOR = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes("AliERC20v2")), block.chainid, address(this))); \t\t// mint initial supply \t\tmint(_initialHolder, 10_000_000_000e18); \t} \t/** \t * @inheritdoc ERC165 \t */ \tfunction supportsInterface(bytes4 interfaceId) public pure override returns (bool) { \t\t// reconstruct from current interface(s) and super interface(s) (if any) \t\treturn interfaceId == type(ERC165).interfaceId \t\t || interfaceId == type(ERC20).interfaceId \t\t || interfaceId == type(ERC1363).interfaceId \t\t || interfaceId == type(EIP2612).interfaceId \t\t || interfaceId == type(EIP3009).interfaceId; \t} \t// ===== Start: ERC-1363 functions ===== \t/** \t * @notice Transfers some tokens and then executes `onTransferReceived` callback on the receiver \t * \t * @inheritdoc ERC1363 \t * \t * @dev Called by token owner (an address which has a \t * positive token balance tracked by this smart contract) \t * @dev Throws on any error like \t * * insufficient token balance or \t * * incorrect `_to` address: \t * * zero address or \t * * same as `_from` address (self transfer) \t * * EOA or smart contract which doesn't support ERC1363Receiver interface \t * @dev Returns true on success, throws otherwise \t * \t * @param _to an address to transfer tokens to, \t * must be a smart contract, implementing ERC1363Receiver \t * @param _value amount of tokens to be transferred,, zero \t * value is allowed \t * @return true unless throwing \t */ \tfunction transferAndCall(address _to, uint256 _value) public override returns (bool) { \t\t// delegate to `transferFromAndCall` passing `msg.sender` as `_from` \t\treturn transferFromAndCall(msg.sender, _to, _value); \t} \t/** \t * @notice Transfers some tokens and then executes `onTransferReceived` callback on the receiver \t * \t * @inheritdoc ERC1363 \t * \t * @dev Called by token owner (an address which has a \t * positive token balance tracked by this smart contract) \t * @dev Throws on any error like \t * * insufficient token balance or \t * * incorrect `_to` address: \t * * zero address or \t * * same as `_from` address (self transfer) \t * * EOA or smart contract which doesn't support ERC1363Receiver interface \t * @dev Returns true on success, throws otherwise \t * \t * @param _to an address to transfer tokens to, \t * must be a smart contract, implementing ERC1363Receiver \t * @param _value amount of tokens to be transferred,, zero \t * value is allowed \t * @param _data [optional] additional data with no specified format, \t * sent in onTransferReceived call to `_to` \t * @return true unless throwing \t */ \tfunction transferAndCall(address _to, uint256 _value, bytes memory _data) public override returns (bool) { \t\t// delegate to `transferFromAndCall` passing `msg.sender` as `_from` \t\treturn transferFromAndCall(msg.sender, _to, _value, _data); \t} \t/** \t * @notice Transfers some tokens on behalf of address `_from' (token owner) \t * to some other address `_to` and then executes `onTransferReceived` callback on the receiver \t * \t * @inheritdoc ERC1363 \t * \t * @dev Called by token owner on his own or approved address, \t * an address approved earlier by token owner to \t * transfer some amount of tokens on its behalf \t * @dev Throws on any error like \t * * insufficient token balance or \t * * incorrect `_to` address: \t * * zero address or \t * * same as `_from` address (self transfer) \t * * EOA or smart contract which doesn't support ERC1363Receiver interface \t * @dev Returns true on success, throws otherwise \t * \t * @param _from token owner which approved caller (transaction sender) \t * to transfer `_value` of tokens on its behalf \t * @param _to an address to transfer tokens to, \t * must be a smart contract, implementing ERC1363Receiver \t * @param _value amount of tokens to be transferred,, zero \t * value is allowed \t * @return true unless throwing \t */ \tfunction transferFromAndCall(address _from, address _to, uint256 _value) public override returns (bool) { \t\t// delegate to `transferFromAndCall` passing empty data param \t\treturn transferFromAndCall(_from, _to, _value, ""); \t} \t/** \t * @notice Transfers some tokens on behalf of address `_from' (token owner) \t * to some other address `_to` and then executes a `onTransferReceived` callback on the receiver \t * \t * @inheritdoc ERC1363 \t * \t * @dev Called by token owner on his own or approved address, \t * an address approved earlier by token owner to \t * transfer some amount of tokens on its behalf \t * @dev Throws on any error like \t * * insufficient token balance or \t * * incorrect `_to` address: \t * * zero address or \t * * same as `_from` address (self transfer) \t * * EOA or smart contract which doesn't support ERC1363Receiver interface \t * @dev Returns true on success, throws otherwise \t * \t * @param _from token owner which approved caller (transaction sender) \t * to transfer `_value` of tokens on its behalf \t * @param _to an address to transfer tokens to, \t * must be a smart contract, implementing ERC1363Receiver \t * @param _value amount of tokens to be transferred,, zero \t * value is allowed \t * @param _data [optional] additional data with no specified format, \t * sent in onTransferReceived call to `_to` \t * @return true unless throwing \t */ \tfunction transferFromAndCall(address _from, address _to, uint256 _value, bytes memory _data) public override returns (bool) { \t\t// ensure ERC-1363 transfers are enabled \t\trequire(isFeatureEnabled(FEATURE_ERC1363_TRANSFERS), "ERC1363 transfers are disabled"); \t\t// first delegate call to `unsafeTransferFrom` to perform the unsafe token(s) transfer \t\tunsafeTransferFrom(_from, _to, _value); \t\t// after the successful transfer - check if receiver supports \t\t// ERC1363Receiver and execute a callback handler `onTransferReceived`, \t\t// reverting whole transaction on any error \t\t_notifyTransferred(_from, _to, _value, _data, false); \t\t// function throws on any error, so if we're here - it means operation successful, just return true \t\treturn true; \t} \t/** \t * @notice Approves address called `_spender` to transfer some amount \t * of tokens on behalf of the owner, then executes a `onApprovalReceived` callback on `_spender` \t * \t * @inheritdoc ERC1363 \t * \t * @dev Caller must not necessarily own any tokens to grant the permission \t * \t * @dev Throws if `_spender` is an EOA or a smart contract which doesn't support ERC1363Spender interface \t * \t * @param _spender an address approved by the caller (token owner) \t * to spend some tokens on its behalf \t * @param _value an amount of tokens spender `_spender` is allowed to \t * transfer on behalf of the token owner \t * @return success true on success, throws otherwise \t */ \tfunction approveAndCall(address _spender, uint256 _value) public override returns (bool) { \t\t// delegate to `approveAndCall` passing empty data \t\treturn approveAndCall(_spender, _value, ""); \t} \t/** \t * @notice Approves address called `_spender` to transfer some amount \t * of tokens on behalf of the owner, then executes a callback on `_spender` \t * \t * @inheritdoc ERC1363 \t * \t * @dev Caller must not necessarily own any tokens to grant the permission \t * \t * @param _spender an address approved by the caller (token owner) \t * to spend some tokens on its behalf \t * @param _value an amount of tokens spender `_spender` is allowed to \t * transfer on behalf of the token owner \t * @param _data [optional] additional data with no specified format, \t * sent in onApprovalReceived call to `_spender` \t * @return success true on success, throws otherwise \t */ \tfunction approveAndCall(address _spender, uint256 _value, bytes memory _data) public override returns (bool) { \t\t// ensure ERC-1363 approvals are enabled \t\trequire(isFeatureEnabled(FEATURE_ERC1363_APPROVALS), "ERC1363 approvals are disabled"); \t\t// execute regular ERC20 approve - delegate to `approve` \t\tapprove(_spender, _value); \t\t// after the successful approve - check if receiver supports \t\t// ERC1363Spender and execute a callback handler `onApprovalReceived`, \t\t// reverting whole transaction on any error \t\t_notifyApproved(_spender, _value, _data); \t\t// function throws on any error, so if we're here - it means operation successful, just return true \t\treturn true; \t} \t/** \t * @dev Auxiliary function to invoke `onTransferReceived` on a target address \t * The call is not executed if the target address is not a contract; in such \t * a case function throws if `allowEoa` is set to false, succeeds if it's true \t * \t * @dev Throws on any error; returns silently on success \t * \t * @param _from representing the previous owner of the given token value \t * @param _to target address that will receive the tokens \t * @param _value the amount mount of tokens to be transferred \t * @param _data [optional] data to send along with the call \t * @param allowEoa indicates if function should fail if `_to` is an EOA \t */ \tfunction _notifyTransferred(address _from, address _to, uint256 _value, bytes memory _data, bool allowEoa) private { \t\t// if recipient `_to` is EOA \t\tif (!AddressUtils.isContract(_to)) { \t\t\t// ensure EOA recipient is allowed \t\t\trequire(allowEoa, "EOA recipient"); \t\t\t// exit if successful \t\t\treturn; \t\t} \t\t// otherwise - if `_to` is a contract - execute onTransferReceived \t\tbytes4 response = ERC1363Receiver(_to).onTransferReceived(msg.sender, _from, _value, _data); \t\t// expected response is ERC1363Receiver(_to).onTransferReceived.selector \t\t// bytes4(keccak256("onTransferReceived(address,address,uint256,bytes)")) \t\trequire(response == ERC1363Receiver(_to).onTransferReceived.selector, "invalid onTransferReceived response"); \t} \t/** \t * @dev Auxiliary function to invoke `onApprovalReceived` on a target address \t * The call is not executed if the target address is not a contract; in such \t * a case function throws if `allowEoa` is set to false, succeeds if it's true \t * \t * @dev Throws on any error; returns silently on success \t * \t * @param _spender the address which will spend the funds \t * @param _value the amount of tokens to be spent \t * @param _data [optional] data to send along with the call \t */ \tfunction _notifyApproved(address _spender, uint256 _value, bytes memory _data) private { \t\t// ensure recipient is not EOA \t\trequire(AddressUtils.isContract(_spender), "EOA spender"); \t\t// otherwise - if `_to` is a contract - execute onApprovalReceived \t\tbytes4 response = ERC1363Spender(_spender).onApprovalReceived(msg.sender, _value, _data); \t\t// expected response is ERC1363Spender(_to).onApprovalReceived.selector \t\t// bytes4(keccak256("onApprovalReceived(address,uint256,bytes)")) \t\trequire(response == ERC1363Spender(_spender).onApprovalReceived.selector, "invalid onApprovalReceived response"); \t} \t// ===== End: ERC-1363 functions ===== \t// ===== Start: ERC20 functions ===== \t/** \t * @notice Gets the balance of a particular address \t * \t * @inheritdoc ERC20 \t * \t * @param _owner the address to query the the balance for \t * @return balance an amount of tokens owned by the address specified \t */ \tfunction balanceOf(address _owner) public view override returns (uint256 balance) { \t\t// read the balance and return \t\treturn tokenBalances[_owner]; \t} \t/** \t * @notice Transfers some tokens to an external address or a smart contract \t * \t * @inheritdoc ERC20 \t * \t * @dev Called by token owner (an address which has a \t * positive token balance tracked by this smart contract) \t * @dev Throws on any error like \t * * insufficient token balance or \t * * incorrect `_to` address: \t * * zero address or \t * * self address or \t * * smart contract which doesn't support ERC20 \t * \t * @param _to an address to transfer tokens to, \t * must be either an external address or a smart contract, \t * compliant with the ERC20 standard \t * @param _value amount of tokens to be transferred,, zero \t * value is allowed \t * @return success true on success, throws otherwise \t */ \tfunction transfer(address _to, uint256 _value) public override returns (bool success) { \t\t// just delegate call to `transferFrom`, \t\t// `FEATURE_TRANSFERS` is verified inside it \t\treturn transferFrom(msg.sender, _to, _value); \t} \t/** \t * @notice Transfers some tokens on behalf of address `_from' (token owner) \t * to some other address `_to` \t * \t * @inheritdoc ERC20 \t * \t * @dev Called by token owner on his own or approved address, \t * an address approved earlier by token owner to \t * transfer some amount of tokens on its behalf \t * @dev Throws on any error like \t * * insufficient token balance or \t * * incorrect `_to` address: \t * * zero address or \t * * same as `_from` address (self transfer) \t * * smart contract which doesn't support ERC20 \t * \t * @param _from token owner which approved caller (transaction sender) \t * to transfer `_value` of tokens on its behalf \t * @param _to an address to transfer tokens to, \t * must be either an external address or a smart contract, \t * compliant with the ERC20 standard \t * @param _value amount of tokens to be transferred,, zero \t * value is allowed \t * @return success true on success, throws otherwise \t */ \tfunction transferFrom(address _from, address _to, uint256 _value) public override returns (bool success) { \t\t// depending on `FEATURE_UNSAFE_TRANSFERS` we execute either safe (default) \t\t// or unsafe transfer \t\t// if `FEATURE_UNSAFE_TRANSFERS` is enabled \t\t// or receiver has `ROLE_ERC20_RECEIVER` permission \t\t// or sender has `ROLE_ERC20_SENDER` permission \t\tif(isFeatureEnabled(FEATURE_UNSAFE_TRANSFERS) \t\t\t|| isOperatorInRole(_to, ROLE_ERC20_RECEIVER) \t\t\t|| isSenderInRole(ROLE_ERC20_SENDER)) { \t\t\t// we execute unsafe transfer - delegate call to `unsafeTransferFrom`, \t\t\t// `FEATURE_TRANSFERS` is verified inside it \t\t\tunsafeTransferFrom(_from, _to, _value); \t\t} \t\t// otherwise - if `FEATURE_UNSAFE_TRANSFERS` is disabled \t\t// and receiver doesn't have `ROLE_ERC20_RECEIVER` permission \t\telse { \t\t\t// we execute safe transfer - delegate call to `safeTransferFrom`, passing empty `_data`, \t\t\t// `FEATURE_TRANSFERS` is verified inside it \t\t\tsafeTransferFrom(_from, _to, _value, ""); \t\t} \t\t// both `unsafeTransferFrom` and `safeTransferFrom` throw on any error, so \t\t// if we're here - it means operation successful, \t\t// just return true \t\treturn true; \t} \t/** \t * @notice Transfers some tokens on behalf of address `_from' (token owner) \t * to some other address `_to` and then executes `onTransferReceived` callback \t * on the receiver if it is a smart contract (not an EOA) \t * \t * @dev Called by token owner on his own or approved address, \t * an address approved earlier by token owner to \t * transfer some amount of tokens on its behalf \t * @dev Throws on any error like \t * * insufficient token balance or \t * * incorrect `_to` address: \t * * zero address or \t * * same as `_from` address (self transfer) \t * * smart contract which doesn't support ERC1363Receiver interface \t * @dev Returns true on success, throws otherwise \t * \t * @param _from token owner which approved caller (transaction sender) \t * to transfer `_value` of tokens on its behalf \t * @param _to an address to transfer tokens to, \t * must be either an external address or a smart contract, \t * implementing ERC1363Receiver \t * @param _value amount of tokens to be transferred,, zero \t * value is allowed \t * @param _data [optional] additional data with no specified format, \t * sent in onTransferReceived call to `_to` in case if its a smart contract \t * @return true unless throwing \t */ \tfunction safeTransferFrom(address _from, address _to, uint256 _value, bytes memory _data) public returns (bool) { \t\t// first delegate call to `unsafeTransferFrom` to perform the unsafe token(s) transfer \t\tunsafeTransferFrom(_from, _to, _value); \t\t// after the successful transfer - check if receiver supports \t\t// ERC1363Receiver and execute a callback handler `onTransferReceived`, \t\t// reverting whole transaction on any error \t\t_notifyTransferred(_from, _to, _value, _data, true); \t\t// function throws on any error, so if we're here - it means operation successful, just return true \t\treturn true; \t} \t/** \t * @notice Transfers some tokens on behalf of address `_from' (token owner) \t * to some other address `_to` \t * \t * @dev In contrast to `transferFromAndCall` doesn't check recipient \t * smart contract to support ERC20 tokens (ERC1363Receiver) \t * @dev Designed to be used by developers when the receiver is known \t * to support ERC20 tokens but doesn't implement ERC1363Receiver interface \t * @dev Called by token owner on his own or approved address, \t * an address approved earlier by token owner to \t * transfer some amount of tokens on its behalf \t * @dev Throws on any error like \t * * insufficient token balance or \t * * incorrect `_to` address: \t * * zero address or \t * * same as `_from` address (self transfer) \t * @dev Returns silently on success, throws otherwise \t * \t * @param _from token sender, token owner which approved caller (transaction sender) \t * to transfer `_value` of tokens on its behalf \t * @param _to token receiver, an address to transfer tokens to \t * @param _value amount of tokens to be transferred,, zero \t * value is allowed \t */ \tfunction unsafeTransferFrom(address _from, address _to, uint256 _value) public { \t\t// make an internal transferFrom - delegate to `__transferFrom` \t\t__transferFrom(msg.sender, _from, _to, _value); \t} \t/** \t * @dev Powers the meta transactions for `unsafeTransferFrom` - EIP-3009 `transferWithAuthorization` \t * and `receiveWithAuthorization` \t * \t * @dev See `unsafeTransferFrom` and `transferFrom` soldoc for details \t * \t * @param _by an address executing the transfer, it can be token owner itself, \t * or an operator previously approved with `approve()` \t * @param _from token sender, token owner which approved caller (transaction sender) \t * to transfer `_value` of tokens on its behalf \t * @param _to token receiver, an address to transfer tokens to \t * @param _value amount of tokens to be transferred,, zero \t * value is allowed \t */ \tfunction __transferFrom(address _by, address _from, address _to, uint256 _value) private { \t\t// if `_from` is equal to sender, require transfers feature to be enabled \t\t// otherwise require transfers on behalf feature to be enabled \t\trequire(_from == _by && isFeatureEnabled(FEATURE_TRANSFERS) \t\t || _from != _by && isFeatureEnabled(FEATURE_TRANSFERS_ON_BEHALF), \t\t _from == _by? "transfers are disabled": "transfers on behalf are disabled"); \t\t// non-zero source address check - Zeppelin \t\t// obviously, zero source address is a client mistake \t\t// it's not part of ERC20 standard but it's reasonable to fail fast \t\t// since for zero value transfer transaction succeeds otherwise \t\trequire(_from != address(0), "transfer from the zero address"); \t\t// non-zero recipient address check \t\trequire(_to != address(0), "transfer to the zero address"); \t\t// sender and recipient cannot be the same \t\trequire(_from != _to, "sender and recipient are the same (_from = _to)"); \t\t// sending tokens to the token smart contract itself is a client mistake \t\trequire(_to != address(this), "invalid recipient (transfer to the token smart contract itself)"); \t\t// according to ERC-20 Token Standard, https://eips.ethereum.org/EIPS/eip-20 \t\t// "Transfers of 0 values MUST be treated as normal transfers and fire the Transfer event." \t\tif(_value == 0) { \t\t\t// emit an ERC20 transfer event \t\t\temit Transfer(_from, _to, _value); \t\t\t// don't forget to return - we're done \t\t\treturn; \t\t} \t\t// no need to make arithmetic overflow check on the _value - by design of mint() \t\t// in case of transfer on behalf \t\tif(_from != _by) { \t\t\t// read allowance value - the amount of tokens allowed to transfer - into the stack \t\t\tuint256 _allowance = transferAllowances[_from][_by]; \t\t\t// verify sender has an allowance to transfer amount of tokens requested \t\t\trequire(_allowance >= _value, "transfer amount exceeds allowance"); \t\t\t// we treat max uint256 allowance value as an "unlimited" and \t\t\t// do not decrease allowance when it is set to "unlimited" value \t\t\tif(_allowance < type(uint256).max) { \t\t\t\t// update allowance value on the stack \t\t\t\t_allowance -= _value; \t\t\t\t// update the allowance value in storage \t\t\t\ttransferAllowances[_from][_by] = _allowance; \t\t\t\t// emit an improved atomic approve event \t\t\t\temit Approval(_from, _by, _allowance + _value, _allowance); \t\t\t\t// emit an ERC20 approval event to reflect the decrease \t\t\t\temit Approval(_from, _by, _allowance); \t\t\t} \t\t} \t\t// verify sender has enough tokens to transfer on behalf \t\trequire(tokenBalances[_from] >= _value, "transfer amount exceeds balance"); \t\t// perform the transfer: \t\t// decrease token owner (sender) balance \t\ttokenBalances[_from] -= _value; \t\t// increase `_to` address (receiver) balance \t\ttokenBalances[_to] += _value; \t\t// move voting power associated with the tokens transferred \t\t__moveVotingPower(_by, votingDelegates[_from], votingDelegates[_to], _value); \t\t// emit an improved transfer event (arXiv:1907.00903) \t\temit Transfer(_by, _from, _to, _value); \t\t// emit an ERC20 transfer event \t\temit Transfer(_from, _to, _value); \t} \t/** \t * @notice Approves address called `_spender` to transfer some amount \t * of tokens on behalf of the owner (transaction sender) \t * \t * @inheritdoc ERC20 \t * \t * @dev Transaction sender must not necessarily own any tokens to grant the permission \t * \t * @param _spender an address approved by the caller (token owner) \t * to spend some tokens on its behalf \t * @param _value an amount of tokens spender `_spender` is allowed to \t * transfer on behalf of the token owner \t * @return success true on success, throws otherwise \t */ \tfunction approve(address _spender, uint256 _value) public override returns (bool success) { \t\t// make an internal approve - delegate to `__approve` \t\t__approve(msg.sender, _spender, _value); \t\t// operation successful, return true \t\treturn true; \t} \t/** \t * @dev Powers the meta transaction for `approve` - EIP-2612 `permit` \t * \t * @dev Approves address called `_spender` to transfer some amount \t * of tokens on behalf of the `_owner` \t * \t * @dev `_owner` must not necessarily own any tokens to grant the permission \t * @dev Throws if `_spender` is a zero address \t * \t * @param _owner owner of the tokens to set approval on behalf of \t * @param _spender an address approved by the token owner \t * to spend some tokens on its behalf \t * @param _value an amount of tokens spender `_spender` is allowed to \t * transfer on behalf of the token owner \t */ \tfunction __approve(address _owner, address _spender, uint256 _value) private { \t\t// non-zero spender address check - Zeppelin \t\t// obviously, zero spender address is a client mistake \t\t// it's not part of ERC20 standard but it's reasonable to fail fast \t\trequire(_spender != address(0), "approve to the zero address"); \t\t// read old approval value to emmit an improved event (arXiv:1907.00903) \t\tuint256 _oldValue = transferAllowances[_owner][_spender]; \t\t// perform an operation: write value requested into the storage \t\ttransferAllowances[_owner][_spender] = _value; \t\t// emit an improved atomic approve event (arXiv:1907.00903) \t\temit Approval(_owner, _spender, _oldValue, _value); \t\t// emit an ERC20 approval event \t\temit Approval(_owner, _spender, _value); \t} \t/** \t * @notice Returns the amount which _spender is still allowed to withdraw from _owner. \t * \t * @inheritdoc ERC20 \t * \t * @dev A function to check an amount of tokens owner approved \t * to transfer on its behalf by some other address called "spender" \t * \t * @param _owner an address which approves transferring some tokens on its behalf \t * @param _spender an address approved to transfer some tokens on behalf \t * @return remaining an amount of tokens approved address `_spender` can transfer on behalf \t * of token owner `_owner` \t */ \tfunction allowance(address _owner, address _spender) public view override returns (uint256 remaining) { \t\t// read the value from storage and return \t\treturn transferAllowances[_owner][_spender]; \t} \t// ===== End: ERC20 functions ===== \t// ===== Start: Resolution for the Multiple Withdrawal Attack on ERC20 Tokens (arXiv:1907.00903) ===== \t/** \t * @notice Increases the allowance granted to `spender` by the transaction sender \t * \t * @dev Resolution for the Multiple Withdrawal Attack on ERC20 Tokens (arXiv:1907.00903) \t * \t * @dev Throws if value to increase by is zero or too big and causes arithmetic overflow \t * \t * @param _spender an address approved by the caller (token owner) \t * to spend some tokens on its behalf \t * @param _value an amount of tokens to increase by \t * @return success true on success, throws otherwise \t */ \tfunction increaseAllowance(address _spender, uint256 _value) public returns (bool) { \t\t// read current allowance value \t\tuint256 currentVal = transferAllowances[msg.sender][_spender]; \t\t// non-zero _value and arithmetic overflow check on the allowance \t\tunchecked { \t\t\t// put operation into unchecked block to display user-friendly overflow error message for Solidity 0.8+ \t\t\trequire(currentVal + _value > currentVal, "zero value approval increase or arithmetic overflow"); \t\t} \t\t// delegate call to `approve` with the new value \t\treturn approve(_spender, currentVal + _value); \t} \t/** \t * @notice Decreases the allowance granted to `spender` by the caller. \t * \t * @dev Resolution for the Multiple Withdrawal Attack on ERC20 Tokens (arXiv:1907.00903) \t * \t * @dev Throws if value to decrease by is zero or is greater than currently allowed value \t * \t * @param _spender an address approved by the caller (token owner) \t * to spend some tokens on its behalf \t * @param _value an amount of tokens to decrease by \t * @return success true on success, throws otherwise \t */ \tfunction decreaseAllowance(address _spender, uint256 _value) public returns (bool) { \t\t// read current allowance value \t\tuint256 currentVal = transferAllowances[msg.sender][_spender]; \t\t// non-zero _value check on the allowance \t\trequire(_value > 0, "zero value approval decrease"); \t\t// verify allowance decrease doesn't underflow \t\trequire(currentVal >= _value, "ERC20: decreased allowance below zero"); \t\t// delegate call to `approve` with the new value \t\treturn approve(_spender, currentVal - _value); \t} \t// ===== End: Resolution for the Multiple Withdrawal Attack on ERC20 Tokens (arXiv:1907.00903) ===== \t// ===== Start: Minting/burning extension ===== \t/** \t * @dev Mints (creates) some tokens to address specified \t * @dev The value specified is treated as is without taking \t * into account what `decimals` value is \t * \t * @dev Requires executor to have `ROLE_TOKEN_CREATOR` permission \t * \t * @dev Throws on overflow, if totalSupply + _value doesn't fit into uint256 \t * \t * @param _to an address to mint tokens to \t * @param _value an amount of tokens to mint (create) \t */ \tfunction mint(address _to, uint256 _value) public { \t\t// check if caller has sufficient permissions to mint tokens \t\trequire(isSenderInRole(ROLE_TOKEN_CREATOR), "access denied"); \t\t// non-zero recipient address check \t\trequire(_to != address(0), "zero address"); \t\t// non-zero _value and arithmetic overflow check on the total supply \t\t// this check automatically secures arithmetic overflow on the individual balance \t\tunchecked { \t\t\t// put operation into unchecked block to display user-friendly overflow error message for Solidity 0.8+ \t\t\trequire(totalSupply + _value > totalSupply, "zero value or arithmetic overflow"); \t\t} \t\t// uint192 overflow check (required by voting delegation) \t\trequire(totalSupply + _value <= type(uint192).max, "total supply overflow (uint192)"); \t\t// perform mint: \t\t// increase total amount of tokens value \t\ttotalSupply += _value; \t\t// increase `_to` address balance \t\ttokenBalances[_to] += _value; \t\t// update total token supply history \t\t__updateHistory(totalSupplyHistory, add, _value); \t\t// create voting power associated with the tokens minted \t\t__moveVotingPower(msg.sender, address(0), votingDelegates[_to], _value); \t\t// fire a minted event \t\temit Minted(msg.sender, _to, _value); \t\t// emit an improved transfer event (arXiv:1907.00903) \t\temit Transfer(msg.sender, address(0), _to, _value); \t\t// fire ERC20 compliant transfer event \t\temit Transfer(address(0), _to, _value); \t} \t/** \t * @dev Burns (destroys) some tokens from the address specified \t * \t * @dev The value specified is treated as is without taking \t * into account what `decimals` value is \t * \t * @dev Requires executor to have `ROLE_TOKEN_DESTROYER` permission \t * or FEATURE_OWN_BURNS/FEATURE_BURNS_ON_BEHALF features to be enabled \t * \t * @dev Can be disabled by the contract creator forever by disabling \t * FEATURE_OWN_BURNS/FEATURE_BURNS_ON_BEHALF features and then revoking \t * its own roles to burn tokens and to enable burning features \t * \t * @param _from an address to burn some tokens from \t * @param _value an amount of tokens to burn (destroy) \t */ \tfunction burn(address _from, uint256 _value) public { \t\t// check if caller has sufficient permissions to burn tokens \t\t// and if not - check for possibility to burn own tokens or to burn on behalf \t\tif(!isSenderInRole(ROLE_TOKEN_DESTROYER)) { \t\t\t// if `_from` is equal to sender, require own burns feature to be enabled \t\t\t// otherwise require burns on behalf feature to be enabled \t\t\trequire(_from == msg.sender && isFeatureEnabled(FEATURE_OWN_BURNS) \t\t\t || _from != msg.sender && isFeatureEnabled(FEATURE_BURNS_ON_BEHALF), \t\t\t _from == msg.sender? "burns are disabled": "burns on behalf are disabled"); \t\t\t// in case of burn on behalf \t\t\tif(_from != msg.sender) { \t\t\t\t// read allowance value - the amount of tokens allowed to be burnt - into the stack \t\t\t\tuint256 _allowance = transferAllowances[_from][msg.sender]; \t\t\t\t// verify sender has an allowance to burn amount of tokens requested \t\t\t\trequire(_allowance >= _value, "burn amount exceeds allowance"); \t\t\t\t// we treat max uint256 allowance value as an "unlimited" and \t\t\t\t// do not decrease allowance when it is set to "unlimited" value \t\t\t\tif(_allowance < type(uint256).max) { \t\t\t\t\t// update allowance value on the stack \t\t\t\t\t_allowance -= _value; \t\t\t\t\t// update the allowance value in storage \t\t\t\t\ttransferAllowances[_from][msg.sender] = _allowance; \t\t\t\t\t// emit an improved atomic approve event (arXiv:1907.00903) \t\t\t\t\temit Approval(msg.sender, _from, _allowance + _value, _allowance); \t\t\t\t\t// emit an ERC20 approval event to reflect the decrease \t\t\t\t\temit Approval(_from, msg.sender, _allowance); \t\t\t\t} \t\t\t} \t\t} \t\t// at this point we know that either sender is ROLE_TOKEN_DESTROYER or \t\t// we burn own tokens or on behalf (in latest case we already checked and updated allowances) \t\t// we have left to execute balance checks and burning logic itself \t\t// non-zero burn value check \t\trequire(_value != 0, "zero value burn"); \t\t// non-zero source address check - Zeppelin \t\trequire(_from != address(0), "burn from the zero address"); \t\t// verify `_from` address has enough tokens to destroy \t\t// (basically this is a arithmetic overflow check) \t\trequire(tokenBalances[_from] >= _value, "burn amount exceeds balance"); \t\t// perform burn: \t\t// decrease `_from` address balance \t\ttokenBalances[_from] -= _value; \t\t// decrease total amount of tokens value \t\ttotalSupply -= _value; \t\t// update total token supply history \t\t__updateHistory(totalSupplyHistory, sub, _value); \t\t// destroy voting power associated with the tokens burnt \t\t__moveVotingPower(msg.sender, votingDelegates[_from], address(0), _value); \t\t// fire a burnt event \t\temit Burnt(msg.sender, _from, _value); \t\t// emit an improved transfer event (arXiv:1907.00903) \t\temit Transfer(msg.sender, _from, address(0), _value); \t\t// fire ERC20 compliant transfer event \t\temit Transfer(_from, address(0), _value); \t} \t// ===== End: Minting/burning extension ===== \t// ===== Start: EIP-2612 functions ===== \t/** \t * @inheritdoc EIP2612 \t * \t * @dev Executes approve(_spender, _value) on behalf of the owner who EIP-712 \t * signed the transaction, i.e. as if transaction sender is the EIP712 signer \t * \t * @dev Sets the `_value` as the allowance of `_spender` over `_owner` tokens, \t * given `_owner` EIP-712 signed approval \t * \t * @dev Inherits the Multiple Withdrawal Attack on ERC20 Tokens (arXiv:1907.00903) \t * vulnerability in the same way as ERC20 `approve`, use standard ERC20 workaround \t * if this might become an issue: \t * https://docs.google.com/document/d/1YLPtQxZu1UAvO9cZ1O2RPXBbT0mooh4DYKjA_jp-RLM/edit \t * \t * @dev Emits `Approval` event(s) in the same way as `approve` does \t * \t * @dev Requires: \t * - `_spender` to be non-zero address \t * - `_exp` to be a timestamp in the future \t * - `v`, `r` and `s` to be a valid `secp256k1` signature from `_owner` \t * over the EIP712-formatted function arguments. \t * - the signature to use `_owner` current nonce (see `nonces`). \t * \t * @dev For more information on the signature format, see the \t * https://eips.ethereum.org/EIPS/eip-2612#specification \t * \t * @param _owner owner of the tokens to set approval on behalf of, \t * an address which signed the EIP-712 message \t * @param _spender an address approved by the token owner \t * to spend some tokens on its behalf \t * @param _value an amount of tokens spender `_spender` is allowed to \t * transfer on behalf of the token owner \t * @param _exp signature expiration time (unix timestamp) \t * @param v the recovery byte of the signature \t * @param r half of the ECDSA signature pair \t * @param s half of the ECDSA signature pair \t */ \tfunction permit(address _owner, address _spender, uint256 _value, uint256 _exp, uint8 v, bytes32 r, bytes32 s) public override { \t\t// verify permits are enabled \t\trequire(isFeatureEnabled(FEATURE_EIP2612_PERMITS), "EIP2612 permits are disabled"); \t\t// derive signer of the EIP712 Permit message, and \t\t// update the nonce for that particular signer to avoid replay attack!!! --------->>> ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓ \t\taddress signer = __deriveSigner(abi.encode(PERMIT_TYPEHASH, _owner, _spender, _value, nonces[_owner]++, _exp), v, r, s); \t\t// perform message integrity and security validations \t\trequire(signer == _owner, "invalid signature"); \t\trequire(block.timestamp < _exp, "signature expired"); \t\t// delegate call to `__approve` - execute the logic required \t\t__approve(_owner, _spender, _value); \t} \t// ===== End: EIP-2612 functions ===== \t// ===== Start: EIP-3009 functions ===== \t/** \t * @inheritdoc EIP3009 \t * \t * @notice Checks if specified nonce was already used \t * \t * @dev Nonces are expected to be client-side randomly generated 32-byte values \t * unique to the authorizer's address \t * \t * @dev Alias for usedNonces(authorizer, nonce) \t * \t * @param _authorizer an address to check nonce for \t * @param _nonce a nonce to check \t * @return true if the nonce was used, false otherwise \t */ \tfunction authorizationState(address _authorizer, bytes32 _nonce) public override view returns (bool) { \t\t// simply return the value from the mapping \t\treturn usedNonces[_authorizer][_nonce]; \t} \t/** \t * @inheritdoc EIP3009 \t * \t * @notice Execute a transfer with a signed authorization \t * \t * @param _from token sender and transaction authorizer \t * @param _to token receiver \t * @param _value amount to be transferred \t * @param _validAfter signature valid after time (unix timestamp) \t * @param _validBefore signature valid before time (unix timestamp) \t * @param _nonce unique random nonce \t * @param v the recovery byte of the signature \t * @param r half of the ECDSA signature pair \t * @param s half of the ECDSA signature pair \t */ \tfunction transferWithAuthorization( \t\taddress _from, \t\taddress _to, \t\tuint256 _value, \t\tuint256 _validAfter, \t\tuint256 _validBefore, \t\tbytes32 _nonce, \t\tuint8 v, \t\tbytes32 r, \t\tbytes32 s \t) public override { \t\t// ensure EIP-3009 transfers are enabled \t\trequire(isFeatureEnabled(FEATURE_EIP3009_TRANSFERS), "EIP3009 transfers are disabled"); \t\t// derive signer of the EIP712 TransferWithAuthorization message \t\taddress signer = __deriveSigner(abi.encode(TRANSFER_WITH_AUTHORIZATION_TYPEHASH, _from, _to, _value, _validAfter, _validBefore, _nonce), v, r, s); \t\t// perform message integrity and security validations \t\trequire(signer == _from, "invalid signature"); \t\trequire(block.timestamp > _validAfter, "signature not yet valid"); \t\trequire(block.timestamp < _validBefore, "signature expired"); \t\t// use the nonce supplied (verify, mark as used, emit event) \t\t__useNonce(_from, _nonce, false); \t\t// delegate call to `__transferFrom` - execute the logic required \t\t__transferFrom(signer, _from, _to, _value); \t} \t/** \t * @inheritdoc EIP3009 \t * \t * @notice Receive a transfer with a signed authorization from the payer \t * \t * @dev This has an additional check to ensure that the payee's address \t * matches the caller of this function to prevent front-running attacks. \t * \t * @param _from token sender and transaction authorizer \t * @param _to token receiver \t * @param _value amount to be transferred \t * @param _validAfter signature valid after time (unix timestamp) \t * @param _validBefore signature valid before time (unix timestamp) \t * @param _nonce unique random nonce \t * @param v the recovery byte of the signature \t * @param r half of the ECDSA signature pair \t * @param s half of the ECDSA signature pair \t */ \tfunction receiveWithAuthorization( \t\taddress _from, \t\taddress _to, \t\tuint256 _value, \t\tuint256 _validAfter, \t\tuint256 _validBefore, \t\tbytes32 _nonce, \t\tuint8 v, \t\tbytes32 r, \t\tbytes32 s \t) public override { \t\t// verify EIP3009 receptions are enabled \t\trequire(isFeatureEnabled(FEATURE_EIP3009_RECEPTIONS), "EIP3009 receptions are disabled"); \t\t// derive signer of the EIP712 ReceiveWithAuthorization message \t\taddress signer = __deriveSigner(abi.encode(RECEIVE_WITH_AUTHORIZATION_TYPEHASH, _from, _to, _value, _validAfter, _validBefore, _nonce), v, r, s); \t\t// perform message integrity and security validations \t\trequire(signer == _from, "invalid signature"); \t\trequire(block.timestamp > _validAfter, "signature not yet valid"); \t\trequire(block.timestamp < _validBefore, "signature expired"); \t\trequire(_to == msg.sender, "access denied"); \t\t// use the nonce supplied (verify, mark as used, emit event) \t\t__useNonce(_from, _nonce, false); \t\t// delegate call to `__transferFrom` - execute the logic required \t\t__transferFrom(signer, _from, _to, _value); \t} \t/** \t * @inheritdoc EIP3009 \t * \t * @notice Attempt to cancel an authorization \t * \t * @param _authorizer transaction authorizer \t * @param _nonce unique random nonce to cancel (mark as used) \t * @param v the recovery byte of the signature \t * @param r half of the ECDSA signature pair \t * @param s half of the ECDSA signature pair \t */ \tfunction cancelAuthorization( \t\taddress _authorizer, \t\tbytes32 _nonce, \t\tuint8 v, \t\tbytes32 r, \t\tbytes32 s \t) public override { \t\t// derive signer of the EIP712 ReceiveWithAuthorization message \t\taddress signer = __deriveSigner(abi.encode(CANCEL_AUTHORIZATION_TYPEHASH, _authorizer, _nonce), v, r, s); \t\t// perform message integrity and security validations \t\trequire(signer == _authorizer, "invalid signature"); \t\t// cancel the nonce supplied (verify, mark as used, emit event) \t\t__useNonce(_authorizer, _nonce, true); \t} \t/** \t * @dev Auxiliary function to verify structured EIP712 message signature and derive its signer \t * \t * @param abiEncodedTypehash abi.encode of the message typehash together with all its parameters \t * @param v the recovery byte of the signature \t * @param r half of the ECDSA signature pair \t * @param s half of the ECDSA signature pair \t */ \tfunction __deriveSigner(bytes memory abiEncodedTypehash, uint8 v, bytes32 r, bytes32 s) private view returns(address) { \t\t// build the EIP-712 hashStruct of the message \t\tbytes32 hashStruct = keccak256(abiEncodedTypehash); \t\t// calculate the EIP-712 digest "\\x19\\x01" ‖ domainSeparator ‖ hashStruct(message) \t\tbytes32 digest = keccak256(abi.encodePacked("\\x19\\x01", DOMAIN_SEPARATOR, hashStruct)); \t\t// recover the address which signed the message with v, r, s \t\taddress signer = ECDSA.recover(digest, v, r, s); \t\t// return the signer address derived from the signature \t\treturn signer; \t} \t/** \t * @dev Auxiliary function to use/cancel the nonce supplied for a given authorizer: \t * 1. Verifies the nonce was not used before \t * 2. Marks the nonce as used \t * 3. Emits an event that the nonce was used/cancelled \t * \t * @dev Set `_cancellation` to false (default) to use nonce, \t * set `_cancellation` to true to cancel nonce \t * \t * @dev It is expected that the nonce supplied is a randomly \t * generated uint256 generated by the client \t * \t * @param _authorizer an address to use/cancel nonce for \t * @param _nonce random nonce to use \t * @param _cancellation true to emit `AuthorizationCancelled`, false to emit `AuthorizationUsed` event \t */ \tfunction __useNonce(address _authorizer, bytes32 _nonce, bool _cancellation) private { \t\t// verify nonce was not used before \t\trequire(!usedNonces[_authorizer][_nonce], "invalid nonce"); \t\t// update the nonce state to "used" for that particular signer to avoid replay attack \t\tusedNonces[_authorizer][_nonce] = true; \t\t// depending on the usage type (use/cancel) \t\tif(_cancellation) { \t\t\t// emit an event regarding the nonce cancelled \t\t\temit AuthorizationCanceled(_authorizer, _nonce); \t\t} \t\telse { \t\t\t// emit an event regarding the nonce used \t\t\temit AuthorizationUsed(_authorizer, _nonce); \t\t} \t} \t// ===== End: EIP-3009 functions ===== \t// ===== Start: DAO Support (Compound-like voting delegation) ===== \t/** \t * @notice Gets current voting power of the account `_of` \t * \t * @param _of the address of account to get voting power of \t * @return current cumulative voting power of the account, \t * sum of token balances of all its voting delegators \t */ \tfunction votingPowerOf(address _of) public view returns (uint256) { \t\t// get a link to an array of voting power history records for an address specified \t\tKV[] storage history = votingPowerHistory[_of]; \t\t// lookup the history and return latest element \t\treturn history.length == 0? 0: history[history.length - 1].v; \t} \t/** \t * @notice Gets past voting power of the account `_of` at some block `_blockNum` \t * \t * @dev Throws if `_blockNum` is not in the past (not the finalized block) \t * \t * @param _of the address of account to get voting power of \t * @param _blockNum block number to get the voting power at \t * @return past cumulative voting power of the account, \t * sum of token balances of all its voting delegators at block number `_blockNum` \t */ \tfunction votingPowerAt(address _of, uint256 _blockNum) public view returns (uint256) { \t\t// make sure block number is not in the past (not the finalized block) \t\trequire(_blockNum < block.number, "block not yet mined"); // Compound msg not yet determined \t\t// `votingPowerHistory[_of]` is an array ordered by `blockNumber`, ascending; \t\t// apply binary search on `votingPowerHistory[_of]` to find such an entry number `i`, that \t\t// `votingPowerHistory[_of][i].k <= _blockNum`, but in the same time \t\t// `votingPowerHistory[_of][i + 1].k > _blockNum` \t\t// return the result - voting power found at index `i` \t\treturn __binaryLookup(votingPowerHistory[_of], _blockNum); \t} \t/** \t * @dev Reads an entire voting power history array for the delegate specified \t * \t * @param _of delegate to query voting power history for \t * @return voting power history array for the delegate of interest \t */ \tfunction votingPowerHistoryOf(address _of) public view returns(KV[] memory) { \t\t// return an entire array as memory \t\treturn votingPowerHistory[_of]; \t} \t/** \t * @dev Returns length of the voting power history array for the delegate specified; \t * useful since reading an entire array just to get its length is expensive (gas cost) \t * \t * @param _of delegate to query voting power history length for \t * @return voting power history array length for the delegate of interest \t */ \tfunction votingPowerHistoryLength(address _of) public view returns(uint256) { \t\t// read array length and return \t\treturn votingPowerHistory[_of].length; \t} \t/** \t * @notice Gets past total token supply value at some block `_blockNum` \t * \t * @dev Throws if `_blockNum` is not in the past (not the finalized block) \t * \t * @param _blockNum block number to get the total token supply at \t * @return past total token supply at block number `_blockNum` \t */ \tfunction totalSupplyAt(uint256 _blockNum) public view returns(uint256) { \t\t// make sure block number is not in the past (not the finalized block) \t\trequire(_blockNum < block.number, "block not yet mined"); \t\t// `totalSupplyHistory` is an array ordered by `k`, ascending; \t\t// apply binary search on `totalSupplyHistory` to find such an entry number `i`, that \t\t// `totalSupplyHistory[i].k <= _blockNum`, but in the same time \t\t// `totalSupplyHistory[i + 1].k > _blockNum` \t\t// return the result - value `totalSupplyHistory[i].v` found at index `i` \t\treturn __binaryLookup(totalSupplyHistory, _blockNum); \t} \t/** \t * @dev Reads an entire total token supply history array \t * \t * @return total token supply history array, a key-value pair array, \t * where key is a block number and value is total token supply at that block \t */ \tfunction entireSupplyHistory() public view returns(KV[] memory) { \t\t// return an entire array as memory \t\treturn totalSupplyHistory; \t} \t/** \t * @dev Returns length of the total token supply history array; \t * useful since reading an entire array just to get its length is expensive (gas cost) \t * \t * @return total token supply history array \t */ \tfunction totalSupplyHistoryLength() public view returns(uint256) { \t\t// read array length and return \t\treturn totalSupplyHistory.length; \t} \t/** \t * @notice Delegates voting power of the delegator `msg.sender` to the delegate `_to` \t * \t * @dev Accepts zero value address to delegate voting power to, effectively \t * removing the delegate in that case \t * \t * @param _to address to delegate voting power to \t */ \tfunction delegate(address _to) public { \t\t// verify delegations are enabled \t\trequire(isFeatureEnabled(FEATURE_DELEGATIONS), "delegations are disabled"); \t\t// delegate call to `__delegate` \t\t__delegate(msg.sender, _to); \t} \t/** \t * @dev Powers the meta transaction for `delegate` - `delegateWithAuthorization` \t * \t * @dev Auxiliary function to delegate delegator's `_from` voting power to the delegate `_to` \t * @dev Writes to `votingDelegates` and `votingPowerHistory` mappings \t * \t * @param _from delegator who delegates his voting power \t * @param _to delegate who receives the voting power \t */ \tfunction __delegate(address _from, address _to) private { \t\t// read current delegate to be replaced by a new one \t\taddress _fromDelegate = votingDelegates[_from]; \t\t// read current voting power (it is equal to token balance) \t\tuint256 _value = tokenBalances[_from]; \t\t// reassign voting delegate to `_to` \t\tvotingDelegates[_from] = _to; \t\t// update voting power for `_fromDelegate` and `_to` \t\t__moveVotingPower(_from, _fromDelegate, _to, _value); \t\t// emit an event \t\temit DelegateChanged(_from, _fromDelegate, _to); \t} \t/** \t * @notice Delegates voting power of the delegator (represented by its signature) to the delegate `_to` \t * \t * @dev Accepts zero value address to delegate voting power to, effectively \t * removing the delegate in that case \t * \t * @dev Compliant with EIP-712: Ethereum typed structured data hashing and signing, \t * see https://eips.ethereum.org/EIPS/eip-712 \t * \t * @param _to address to delegate voting power to \t * @param _nonce nonce used to construct the signature, and used to validate it; \t * nonce is increased by one after successful signature validation and vote delegation \t * @param _exp signature expiration time \t * @param v the recovery byte of the signature \t * @param r half of the ECDSA signature pair \t * @param s half of the ECDSA signature pair \t */ \tfunction delegateWithAuthorization(address _to, bytes32 _nonce, uint256 _exp, uint8 v, bytes32 r, bytes32 s) public { \t\t// verify delegations on behalf are enabled \t\trequire(isFeatureEnabled(FEATURE_DELEGATIONS_ON_BEHALF), "delegations on behalf are disabled"); \t\t// derive signer of the EIP712 Delegation message \t\taddress signer = __deriveSigner(abi.encode(DELEGATION_TYPEHASH, _to, _nonce, _exp), v, r, s); \t\t// perform message integrity and security validations \t\trequire(block.timestamp < _exp, "signature expired"); // Compound msg \t\t// use the nonce supplied (verify, mark as used, emit event) \t\t__useNonce(signer, _nonce, false); \t\t// delegate call to `__delegate` - execute the logic required \t\t__delegate(signer, _to); \t} \t/** \t * @dev Auxiliary function to move voting power `_value` \t * from delegate `_from` to the delegate `_to` \t * \t * @dev Doesn't have any effect if `_from == _to`, or if `_value == 0` \t * \t * @param _by an address which executed delegate, mint, burn, or transfer operation \t * which had led to delegate voting power change \t * @param _from delegate to move voting power from \t * @param _to delegate to move voting power to \t * @param _value voting power to move from `_from` to `_to` \t */ \tfunction __moveVotingPower(address _by, address _from, address _to, uint256 _value) private { \t\t// if there is no move (`_from == _to`) or there is nothing to move (`_value == 0`) \t\tif(_from == _to || _value == 0) { \t\t\t// return silently with no action \t\t\treturn; \t\t} \t\t// if source address is not zero - decrease its voting power \t\tif(_from != address(0)) { \t\t\t// get a link to an array of voting power history records for an address specified \t\t\tKV[] storage _h = votingPowerHistory[_from]; \t\t\t// update source voting power: decrease by `_value` \t\t\t(uint256 _fromVal, uint256 _toVal) = __updateHistory(_h, sub, _value); \t\t\t// emit an event \t\t\temit VotingPowerChanged(_by, _from, _fromVal, _toVal); \t\t} \t\t// if destination address is not zero - increase its voting power \t\tif(_to != address(0)) { \t\t\t// get a link to an array of voting power history records for an address specified \t\t\tKV[] storage _h = votingPowerHistory[_to]; \t\t\t// update destination voting power: increase by `_value` \t\t\t(uint256 _fromVal, uint256 _toVal) = __updateHistory(_h, add, _value); \t\t\t// emit an event \t\t\temit VotingPowerChanged(_by, _to, _fromVal, _toVal); \t\t} \t} \t/** \t * @dev Auxiliary function to append key-value pair to an array, \t * sets the key to the current block number and \t * value as derived \t * \t * @param _h array of key-value pairs to append to \t * @param op a function (add/subtract) to apply \t * @param _delta the value for a key-value pair to add/subtract \t */ \tfunction __updateHistory( \t\tKV[] storage _h, \t\tfunction(uint256,uint256) pure returns(uint256) op, \t\tuint256 _delta \t) private returns(uint256 _fromVal, uint256 _toVal) { \t\t// init the old value - value of the last pair of the array \t\t_fromVal = _h.length == 0? 0: _h[_h.length - 1].v; \t\t// init the new value - result of the operation on the old value \t\t_toVal = op(_fromVal, _delta); \t\t// if there is an existing voting power value stored for current block \t\tif(_h.length != 0 && _h[_h.length - 1].k == block.number) { \t\t\t// update voting power which is already stored in the current block \t\t\t_h[_h.length - 1].v = uint192(_toVal); \t\t} \t\t// otherwise - if there is no value stored for current block \t\telse { \t\t\t// add new element into array representing the value for current block \t\t\t_h.push(KV(uint64(block.number), uint192(_toVal))); \t\t} \t} \t/** \t * @dev Auxiliary function to lookup for a value in a sorted by key (ascending) \t * array of key-value pairs \t * \t * @dev This function finds a key-value pair element in an array with the closest key \t * to the key of interest (not exceeding that key) and returns the value \t * of the key-value pair element found \t * \t * @dev An array to search in is a KV[] key-value pair array ordered by key `k`, \t * it is sorted in ascending order (`k` increases as array index increases) \t * \t * @dev Returns zero for an empty array input regardless of the key input \t * \t * @param _h an array of key-value pair elements to search in \t * @param _k key of interest to look the value for \t * @return the value of the key-value pair of the key-value pair element with the closest \t * key to the key of interest (not exceeding that key) \t */ \tfunction __binaryLookup(KV[] storage _h, uint256 _k) private view returns(uint256) { \t\t// if an array is empty, there is nothing to lookup in \t\tif(_h.length == 0) { \t\t\t// by documented agreement, fall back to a zero result \t\t\treturn 0; \t\t} \t\t// check last key-value pair key: \t\t// if the key is smaller than the key of interest \t\tif(_h[_h.length - 1].k <= _k) { \t\t\t// we're done - return the value from the last element \t\t\treturn _h[_h.length - 1].v; \t\t} \t\t// check first voting power history record block number: \t\t// if history was never updated before the block of interest \t\tif(_h[0].k > _k) { \t\t\t// we're done - voting power at the block num of interest was zero \t\t\treturn 0; \t\t} \t\t// left bound of the search interval, originally start of the array \t\tuint256 i = 0; \t\t// right bound of the search interval, originally end of the array \t\tuint256 j = _h.length - 1; \t\t// the iteration process narrows down the bounds by \t\t// splitting the interval in a half oce per each iteration \t\twhile(j > i) { \t\t\t// get an index in the middle of the interval [i, j] \t\t\tuint256 k = j - (j - i) / 2; \t\t\t// read an element to compare it with the value of interest \t\t\tKV memory kv = _h[k]; \t\t\t// if we've got a strict equal - we're lucky and done \t\t\tif(kv.k == _k) { \t\t\t\t// just return the result - pair value at index `k` \t\t\t\treturn kv.v; \t\t\t} \t\t\t// if the value of interest is larger - move left bound to the middle \t\t\telse if (kv.k < _k) { \t\t\t\t// move left bound `i` to the middle position `k` \t\t\t\ti = k; \t\t\t} \t\t\t// otherwise, when the value of interest is smaller - move right bound to the middle \t\t\telse { \t\t\t\t// move right bound `j` to the middle position `k - 1`: \t\t\t\t// element at position `k` is greater and cannot be the result \t\t\t\tj = k - 1; \t\t\t} \t\t} \t\t// reaching that point means no exact match found \t\t// since we're interested in the element which is not larger than the \t\t// element of interest, we return the lower bound `i` \t\treturn _h[i].v; \t} \t/** \t * @dev Adds a + b \t * Function is used as a parameter for other functions \t * \t * @param a addition term 1 \t * @param b addition term 2 \t * @return a + b \t */ \tfunction add(uint256 a, uint256 b) private pure returns(uint256) { \t\t// add `a` to `b` and return \t\treturn a + b; \t} \t/** \t * @dev Subtracts a - b \t * Function is used as a parameter for other functions \t * \t * @dev Requires a ≥ b \t * \t * @param a subtraction term 1 \t * @param b subtraction term 2, b ≤ a \t * @return a - b \t */ \tfunction sub(uint256 a, uint256 b) private pure returns(uint256) { \t\t// subtract `b` from `a` and return \t\treturn a - b; \t} \t// ===== End: DAO Support (Compound-like voting delegation) ===== } // SPDX-License-Identifier: MIT pragma solidity 0.8.7; import "./ERC20Spec.sol"; import "./ERC165Spec.sol"; /** * @title ERC1363 Interface * * @dev Interface defining a ERC1363 Payable Token contract. * Implementing contracts MUST implement the ERC1363 interface as well as the ERC20 and ERC165 interfaces. */ interface ERC1363 is ERC20, ERC165 { \t/* \t * Note: the ERC-165 identifier for this interface is 0xb0202a11. \t * 0xb0202a11 === \t * bytes4(keccak256('transferAndCall(address,uint256)')) ^ \t * bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^ \t * bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^ \t * bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^ \t * bytes4(keccak256('approveAndCall(address,uint256)')) ^ \t * bytes4(keccak256('approveAndCall(address,uint256,bytes)')) \t */ \t/** \t * @notice Transfer tokens from `msg.sender` to another address and then call `onTransferReceived` on receiver \t * @param to address The address which you want to transfer to \t * @param value uint256 The amount of tokens to be transferred \t * @return true unless throwing \t */ \tfunction transferAndCall(address to, uint256 value) external returns (bool); \t/** \t * @notice Transfer tokens from `msg.sender` to another address and then call `onTransferReceived` on receiver \t * @param to address The address which you want to transfer to \t * @param value uint256 The amount of tokens to be transferred \t * @param data bytes Additional data with no specified format, sent in call to `to` \t * @return true unless throwing \t */ \tfunction transferAndCall(address to, uint256 value, bytes memory data) external returns (bool); \t/** \t * @notice Transfer tokens from one address to another and then call `onTransferReceived` on receiver \t * @param from address The address which you want to send tokens from \t * @param to address The address which you want to transfer to \t * @param value uint256 The amount of tokens to be transferred \t * @return true unless throwing \t */ \tfunction transferFromAndCall(address from, address to, uint256 value) external returns (bool); \t/** \t * @notice Transfer tokens from one address to another and then call `onTransferReceived` on receiver \t * @param from address The address which you want to send tokens from \t * @param to address The address which you want to transfer to \t * @param value uint256 The amount of tokens to be transferred \t * @param data bytes Additional data with no specified format, sent in call to `to` \t * @return true unless throwing \t */ \tfunction transferFromAndCall(address from, address to, uint256 value, bytes memory data) external returns (bool); \t/** \t * @notice Approve the passed address to spend the specified amount of tokens on behalf of msg.sender \t * and then call `onApprovalReceived` on spender. \t * @param spender address The address which will spend the funds \t * @param value uint256 The amount of tokens to be spent \t */ \tfunction approveAndCall(address spender, uint256 value) external returns (bool); \t/** \t * @notice Approve the passed address to spend the specified amount of tokens on behalf of msg.sender \t * and then call `onApprovalReceived` on spender. \t * @param spender address The address which will spend the funds \t * @param value uint256 The amount of tokens to be spent \t * @param data bytes Additional data with no specified format, sent in call to `spender` \t */ \tfunction approveAndCall(address spender, uint256 value, bytes memory data) external returns (bool); } /** * @title ERC1363Receiver Interface * * @dev Interface for any contract that wants to support `transferAndCall` or `transferFromAndCall` * from ERC1363 token contracts. */ interface ERC1363Receiver { \t/* \t * Note: the ERC-165 identifier for this interface is 0x88a7ca5c. \t * 0x88a7ca5c === bytes4(keccak256("onTransferReceived(address,address,uint256,bytes)")) \t */ \t/** \t * @notice Handle the receipt of ERC1363 tokens \t * \t * @dev Any ERC1363 smart contract calls this function on the recipient \t * after a `transfer` or a `transferFrom`. This function MAY throw to revert and reject the \t * transfer. Return of other than the magic value MUST result in the \t * transaction being reverted. \t * Note: the token contract address is always the message sender. \t * \t * @param operator address The address which called `transferAndCall` or `transferFromAndCall` function \t * @param from address The address which are token transferred from \t * @param value uint256 The amount of tokens transferred \t * @param data bytes Additional data with no specified format \t * @return `bytes4(keccak256("onTransferReceived(address,address,uint256,bytes)"))` \t * unless throwing \t */ \tfunction onTransferReceived(address operator, address from, uint256 value, bytes memory data) external returns (bytes4); } /** * @title ERC1363Spender Interface * * @dev Interface for any contract that wants to support `approveAndCall` * from ERC1363 token contracts. */ interface ERC1363Spender { \t/* \t * Note: the ERC-165 identifier for this interface is 0x7b04a2d0. \t * 0x7b04a2d0 === bytes4(keccak256("onApprovalReceived(address,uint256,bytes)")) \t */ \t/** \t * @notice Handle the approval of ERC1363 tokens \t * \t * @dev Any ERC1363 smart contract calls this function on the recipient \t * after an `approve`. This function MAY throw to revert and reject the \t * approval. Return of other than the magic value MUST result in the \t * transaction being reverted. \t * Note: the token contract address is always the message sender. \t * \t * @param owner address The address which called `approveAndCall` function \t * @param value uint256 The amount of tokens to be spent \t * @param data bytes Additional data with no specified format \t * @return `bytes4(keccak256("onApprovalReceived(address,uint256,bytes)"))` \t * unless throwing \t */ \tfunction onApprovalReceived(address owner, uint256 value, bytes memory data) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity 0.8.7; /** * @title EIP-2612: permit - 712-signed approvals * * @notice A function permit extending ERC-20 which allows for approvals to be made via secp256k1 signatures. * This kind of “account abstraction for ERC-20” brings about two main benefits: * - transactions involving ERC-20 operations can be paid using the token itself rather than ETH, * - approve and pull operations can happen in a single transaction instead of two consecutive transactions, * - while adding as little as possible over the existing ERC-20 standard. * * @notice See https://eips.ethereum.org/EIPS/eip-2612#specification */ interface EIP2612 { \t/** \t * @notice EIP712 domain separator of the smart contract. It should be unique to the contract \t * and chain to prevent replay attacks from other domains, and satisfy the requirements of EIP-712, \t * but is otherwise unconstrained. \t */ \tfunction DOMAIN_SEPARATOR() external view returns (bytes32); \t/** \t * @notice Counter of the nonces used for the given address; nonce are used sequentially \t * \t * @dev To prevent from replay attacks nonce is incremented for each address after a successful `permit` execution \t * \t * @param owner an address to query number of used nonces for \t * @return number of used nonce, nonce number to be used next \t */ \tfunction nonces(address owner) external view returns (uint); \t/** \t * @notice For all addresses owner, spender, uint256s value, deadline and nonce, uint8 v, bytes32 r and s, \t * a call to permit(owner, spender, value, deadline, v, r, s) will set approval[owner][spender] to value, \t * increment nonces[owner] by 1, and emit a corresponding Approval event, \t * if and only if the following conditions are met: \t * - The current blocktime is less than or equal to deadline. \t * - owner is not the zero address. \t * - nonces[owner] (before the state update) is equal to nonce. \t * - r, s and v is a valid secp256k1 signature from owner of the message: \t * \t * @param owner token owner address, granting an approval to spend its tokens \t * @param spender an address approved by the owner (token owner) \t * to spend some tokens on its behalf \t * @param value an amount of tokens spender `spender` is allowed to \t * transfer on behalf of the token owner \t * @param v the recovery byte of the signature \t * @param r half of the ECDSA signature pair \t * @param s half of the ECDSA signature pair \t */ \tfunction permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.7; /** * @title EIP-3009: Transfer With Authorization * * @notice A contract interface that enables transferring of fungible assets via a signed authorization. * See https://eips.ethereum.org/EIPS/eip-3009 * See https://eips.ethereum.org/EIPS/eip-3009#specification */ interface EIP3009 { \t/** \t * @dev Fired whenever the nonce gets used (ex.: `transferWithAuthorization`, `receiveWithAuthorization`) \t * \t * @param authorizer an address which has used the nonce \t * @param nonce the nonce used \t */ \tevent AuthorizationUsed(address indexed authorizer, bytes32 indexed nonce); \t/** \t * @dev Fired whenever the nonce gets cancelled (ex.: `cancelAuthorization`) \t * \t * @dev Both `AuthorizationUsed` and `AuthorizationCanceled` imply the nonce \t * cannot be longer used, the only difference is that `AuthorizationCanceled` \t * implies no smart contract state change made (except the nonce marked as cancelled) \t * \t * @param authorizer an address which has cancelled the nonce \t * @param nonce the nonce cancelled \t */ \tevent AuthorizationCanceled(address indexed authorizer, bytes32 indexed nonce); \t/** \t * @notice Returns the state of an authorization, more specifically \t * if the specified nonce was already used by the address specified \t * \t * @dev Nonces are expected to be client-side randomly generated 32-byte data \t * unique to the authorizer's address \t * \t * @param authorizer Authorizer's address \t * @param nonce Nonce of the authorization \t * @return true if the nonce is used \t */ \tfunction authorizationState( \t\taddress authorizer, \t\tbytes32 nonce \t) external view returns (bool); \t/** \t * @notice Execute a transfer with a signed authorization \t * \t * @param from Payer's address (Authorizer) \t * @param to Payee's address \t * @param value Amount to be transferred \t * @param validAfter The time after which this is valid (unix time) \t * @param validBefore The time before which this is valid (unix time) \t * @param nonce Unique nonce \t * @param v v of the signature \t * @param r r of the signature \t * @param s s of the signature \t */ \tfunction transferWithAuthorization( \t\taddress from, \t\taddress to, \t\tuint256 value, \t\tuint256 validAfter, \t\tuint256 validBefore, \t\tbytes32 nonce, \t\tuint8 v, \t\tbytes32 r, \t\tbytes32 s \t) external; \t/** \t * @notice Receive a transfer with a signed authorization from the payer \t * \t * @dev This has an additional check to ensure that the payee's address matches \t * the caller of this function to prevent front-running attacks. \t * @dev See https://eips.ethereum.org/EIPS/eip-3009#security-considerations \t * \t * @param from Payer's address (Authorizer) \t * @param to Payee's address \t * @param value Amount to be transferred \t * @param validAfter The time after which this is valid (unix time) \t * @param validBefore The time before which this is valid (unix time) \t * @param nonce Unique nonce \t * @param v v of the signature \t * @param r r of the signature \t * @param s s of the signature \t */ \tfunction receiveWithAuthorization( \t\taddress from, \t\taddress to, \t\tuint256 value, \t\tuint256 validAfter, \t\tuint256 validBefore, \t\tbytes32 nonce, \t\tuint8 v, \t\tbytes32 r, \t\tbytes32 s \t) external; \t/** \t * @notice Attempt to cancel an authorization \t * \t * @param authorizer Authorizer's address \t * @param nonce Nonce of the authorization \t * @param v v of the signature \t * @param r r of the signature \t * @param s s of the signature \t */ \tfunction cancelAuthorization( \t\taddress authorizer, \t\tbytes32 nonce, \t\tuint8 v, \t\tbytes32 r, \t\tbytes32 s \t) external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.7; /** * @title Access Control List * * @notice Access control smart contract provides an API to check * if specific operation is permitted globally and/or * if particular user has a permission to execute it. * * @notice It deals with two main entities: features and roles. * * @notice Features are designed to be used to enable/disable specific * functions (public functions) of the smart contract for everyone. * @notice User roles are designed to restrict access to specific * functions (restricted functions) of the smart contract to some users. * * @notice Terms "role", "permissions" and "set of permissions" have equal meaning * in the documentation text and may be used interchangeably. * @notice Terms "permission", "single permission" implies only one permission bit set. * * @notice Access manager is a special role which allows to grant/revoke other roles. * Access managers can only grant/revoke permissions which they have themselves. * As an example, access manager with no other roles set can only grant/revoke its own * access manager permission and nothing else. * * @notice Access manager permission should be treated carefully, as a super admin permission: * Access manager with even no other permission can interfere with another account by * granting own access manager permission to it and effectively creating more powerful * permission set than its own. * * @dev Both current and OpenZeppelin AccessControl implementations feature a similar API * to check/know "who is allowed to do this thing". * @dev Zeppelin implementation is more flexible: * - it allows setting unlimited number of roles, while current is limited to 256 different roles * - it allows setting an admin for each role, while current allows having only one global admin * @dev Current implementation is more lightweight: * - it uses only 1 bit per role, while Zeppelin uses 256 bits * - it allows setting up to 256 roles at once, in a single transaction, while Zeppelin allows * setting only one role in a single transaction * * @dev This smart contract is designed to be inherited by other * smart contracts which require access control management capabilities. * * @dev Access manager permission has a bit 255 set. * This bit must not be used by inheriting contracts for any other permissions/features. */ contract AccessControl { \t/** \t * @notice Access manager is responsible for assigning the roles to users, \t * enabling/disabling global features of the smart contract \t * @notice Access manager can add, remove and update user roles, \t * remove and update global features \t * \t * @dev Role ROLE_ACCESS_MANAGER allows modifying user roles and global features \t * @dev Role ROLE_ACCESS_MANAGER has single bit at position 255 enabled \t */ \tuint256 public constant ROLE_ACCESS_MANAGER = 0x8000000000000000000000000000000000000000000000000000000000000000; \t/** \t * @dev Bitmask representing all the possible permissions (super admin role) \t * @dev Has all the bits are enabled (2^256 - 1 value) \t */ \tuint256 private constant FULL_PRIVILEGES_MASK = type(uint256).max; // before 0.8.0: uint256(-1) overflows to 0xFFFF... \t/** \t * @notice Privileged addresses with defined roles/permissions \t * @notice In the context of ERC20/ERC721 tokens these can be permissions to \t * allow minting or burning tokens, transferring on behalf and so on \t * \t * @dev Maps user address to the permissions bitmask (role), where each bit \t * represents a permission \t * @dev Bitmask 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF \t * represents all possible permissions \t * @dev 'This' address mapping represents global features of the smart contract \t */ \tmapping(address => uint256) public userRoles; \t/** \t * @dev Fired in updateRole() and updateFeatures() \t * \t * @param _by operator which called the function \t * @param _to address which was granted/revoked permissions \t * @param _requested permissions requested \t * @param _actual permissions effectively set \t */ \tevent RoleUpdated(address indexed _by, address indexed _to, uint256 _requested, uint256 _actual); \t/** \t * @notice Creates an access control instance, \t * setting contract creator to have full privileges \t */ \tconstructor() { \t\t// contract creator has full privileges \t\tuserRoles[msg.sender] = FULL_PRIVILEGES_MASK; \t} \t/** \t * @notice Retrieves globally set of features enabled \t * \t * @dev Effectively reads userRoles role for the contract itself \t * \t * @return 256-bit bitmask of the features enabled \t */ \tfunction features() public view returns(uint256) { \t\t// features are stored in 'this' address mapping of `userRoles` structure \t\treturn userRoles[address(this)]; \t} \t/** \t * @notice Updates set of the globally enabled features (`features`), \t * taking into account sender's permissions \t * \t * @dev Requires transaction sender to have `ROLE_ACCESS_MANAGER` permission \t * @dev Function is left for backward compatibility with older versions \t * \t * @param _mask bitmask representing a set of features to enable/disable \t */ \tfunction updateFeatures(uint256 _mask) public { \t\t// delegate call to `updateRole` \t\tupdateRole(address(this), _mask); \t} \t/** \t * @notice Updates set of permissions (role) for a given user, \t * taking into account sender's permissions. \t * \t * @dev Setting role to zero is equivalent to removing an all permissions \t * @dev Setting role to `FULL_PRIVILEGES_MASK` is equivalent to \t * copying senders' permissions (role) to the user \t * @dev Requires transaction sender to have `ROLE_ACCESS_MANAGER` permission \t * \t * @param operator address of a user to alter permissions for or zero \t * to alter global features of the smart contract \t * @param role bitmask representing a set of permissions to \t * enable/disable for a user specified \t */ \tfunction updateRole(address operator, uint256 role) public { \t\t// caller must have a permission to update user roles \t\trequire(isSenderInRole(ROLE_ACCESS_MANAGER), "access denied"); \t\t// evaluate the role and reassign it \t\tuserRoles[operator] = evaluateBy(msg.sender, userRoles[operator], role); \t\t// fire an event \t\temit RoleUpdated(msg.sender, operator, role, userRoles[operator]); \t} \t/** \t * @notice Determines the permission bitmask an operator can set on the \t * target permission set \t * @notice Used to calculate the permission bitmask to be set when requested \t * in `updateRole` and `updateFeatures` functions \t * \t * @dev Calculated based on: \t * 1) operator's own permission set read from userRoles[operator] \t * 2) target permission set - what is already set on the target \t * 3) desired permission set - what do we want set target to \t * \t * @dev Corner cases: \t * 1) Operator is super admin and its permission set is `FULL_PRIVILEGES_MASK`: \t * `desired` bitset is returned regardless of the `target` permission set value \t * (what operator sets is what they get) \t * 2) Operator with no permissions (zero bitset): \t * `target` bitset is returned regardless of the `desired` value \t * (operator has no authority and cannot modify anything) \t * \t * @dev Example: \t * Consider an operator with the permissions bitmask 00001111 \t * is about to modify the target permission set 01010101 \t * Operator wants to set that permission set to 00110011 \t * Based on their role, an operator has the permissions \t * to update only lowest 4 bits on the target, meaning that \t * high 4 bits of the target set in this example is left \t * unchanged and low 4 bits get changed as desired: 01010011 \t * \t * @param operator address of the contract operator which is about to set the permissions \t * @param target input set of permissions to operator is going to modify \t * @param desired desired set of permissions operator would like to set \t * @return resulting set of permissions given operator will set \t */ \tfunction evaluateBy(address operator, uint256 target, uint256 desired) public view returns(uint256) { \t\t// read operator's permissions \t\tuint256 p = userRoles[operator]; \t\t// taking into account operator's permissions, \t\t// 1) enable the permissions desired on the `target` \t\ttarget |= p & desired; \t\t// 2) disable the permissions desired on the `target` \t\ttarget &= FULL_PRIVILEGES_MASK ^ (p & (FULL_PRIVILEGES_MASK ^ desired)); \t\t// return calculated result \t\treturn target; \t} \t/** \t * @notice Checks if requested set of features is enabled globally on the contract \t * \t * @param required set of features to check against \t * @return true if all the features requested are enabled, false otherwise \t */ \tfunction isFeatureEnabled(uint256 required) public view returns(bool) { \t\t// delegate call to `__hasRole`, passing `features` property \t\treturn __hasRole(features(), required); \t} \t/** \t * @notice Checks if transaction sender `msg.sender` has all the permissions required \t * \t * @param required set of permissions (role) to check against \t * @return true if all the permissions requested are enabled, false otherwise \t */ \tfunction isSenderInRole(uint256 required) public view returns(bool) { \t\t// delegate call to `isOperatorInRole`, passing transaction sender \t\treturn isOperatorInRole(msg.sender, required); \t} \t/** \t * @notice Checks if operator has all the permissions (role) required \t * \t * @param operator address of the user to check role for \t * @param required set of permissions (role) to check \t * @return true if all the permissions requested are enabled, false otherwise \t */ \tfunction isOperatorInRole(address operator, uint256 required) public view returns(bool) { \t\t// delegate call to `__hasRole`, passing operator's permissions (role) \t\treturn __hasRole(userRoles[operator], required); \t} \t/** \t * @dev Checks if role `actual` contains all the permissions required `required` \t * \t * @param actual existent role \t * @param required required role \t * @return true if actual has required role (all permissions), false otherwise \t */ \tfunction __hasRole(uint256 actual, uint256 required) internal pure returns(bool) { \t\t// check the bitmask for the role required and return the result \t\treturn actual & required == required; \t} } // SPDX-License-Identifier: MIT pragma solidity 0.8.7; /** * @title Address Utils * * @dev Utility library of inline functions on addresses * * @dev Copy of the Zeppelin's library: * https://github.com/gnosis/openzeppelin-solidity/blob/master/contracts/AddressUtils.sol */ library AddressUtils { \t/** \t * @notice Checks if the target address is a contract \t * \t * @dev It is unsafe to assume that an address for which this function returns \t * false is an externally-owned account (EOA) and not a contract. \t * \t * @dev Among others, `isContract` will return false for the following \t * types of addresses: \t * - an externally-owned account \t * - a contract in construction \t * - an address where a contract will be created \t * - an address where a contract lived, but was destroyed \t * \t * @param addr address to check \t * @return whether the target address is a contract \t */ \tfunction isContract(address addr) internal view returns (bool) { \t\t// a variable to load `extcodesize` to \t\tuint256 size = 0; \t\t// XXX Currently there is no better way to check if there is a contract in an address \t\t// than to check the size of the code at that address. \t\t// See https://ethereum.stackexchange.com/a/14016/36603 for more details about how this works. \t\t// TODO: Check this again before the Serenity release, because all addresses will be contracts. \t\t// solium-disable-next-line security/no-inline-assembly \t\tassembly { \t\t\t// retrieve the size of the code at address `addr` \t\t\tsize := extcodesize(addr) \t\t} \t\t// positive size indicates a smart contract address \t\treturn size > 0; \t} } // SPDX-License-Identifier: MIT pragma solidity 0.8.7; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. * * @dev Copy of the Zeppelin's library: * https://github.com/OpenZeppelin/openzeppelin-contracts/blob/b0cf6fbb7a70f31527f36579ad644e1cf12fdf4e/contracts/utils/cryptography/ECDSA.sol */ library ECDSA { \t/** \t * @dev Returns the address that signed a hashed message (`hash`) with \t * `signature`. This address can then be used for verification purposes. \t * \t * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: \t * this function rejects them by requiring the `s` value to be in the lower \t * half order, and the `v` value to be either 27 or 28. \t * \t * IMPORTANT: `hash` _must_ be the result of a hash operation for the \t * verification to be secure: it is possible to craft signatures that \t * recover to arbitrary addresses for non-hashed data. A safe way to ensure \t * this is by receiving a hash of the original message (which may otherwise \t * be too long), and then calling {toEthSignedMessageHash} on it. \t * \t * Documentation for signature generation: \t * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] \t * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] \t */ \tfunction recover(bytes32 hash, bytes memory signature) internal pure returns (address) { \t\t// Divide the signature in r, s and v variables \t\tbytes32 r; \t\tbytes32 s; \t\tuint8 v; \t\t// Check the signature length \t\t// - case 65: r,s,v signature (standard) \t\t// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ \t\tif (signature.length == 65) { \t\t\t// ecrecover takes the signature parameters, and the only way to get them \t\t\t// currently is to use assembly. \t\t\tassembly { \t\t\t\tr := mload(add(signature, 0x20)) \t\t\t\ts := mload(add(signature, 0x40)) \t\t\t\tv := byte(0, mload(add(signature, 0x60))) \t\t\t} \t\t} \t\telse if (signature.length == 64) { \t\t\t// ecrecover takes the signature parameters, and the only way to get them \t\t\t// currently is to use assembly. \t\t\tassembly { \t\t\t\tlet vs := mload(add(signature, 0x40)) \t\t\t\tr := mload(add(signature, 0x20)) \t\t\t\ts := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) \t\t\t\tv := add(shr(255, vs), 27) \t\t\t} \t\t} \t\telse { \t\t\trevert("invalid signature length"); \t\t} \t\treturn recover(hash, v, r, s); \t} \t/** \t * @dev Overload of {ECDSA-recover} that receives the `v`, \t * `r` and `s` signature fields separately. \t */ \tfunction recover( \t\tbytes32 hash, \t\tuint8 v, \t\tbytes32 r, \t\tbytes32 s \t) internal pure returns (address) { \t\t// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature \t\t// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines \t\t// the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most \t\t// signatures from current libraries generate a unique signature with an s-value in the lower half order. \t\t// \t\t// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value \t\t// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or \t\t// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept \t\t// these malleable signatures as well. \t\trequire( \t\t\tuint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, \t\t\t"invalid signature 's' value" \t\t); \t\trequire(v == 27 || v == 28, "invalid signature 'v' value"); \t\t// If the signature is valid (and not malleable), return the signer address \t\taddress signer = ecrecover(hash, v, r, s); \t\trequire(signer != address(0), "invalid signature"); \t\treturn signer; \t} \t/** \t * @dev Returns an Ethereum Signed Message, created from a `hash`. This \t * produces hash corresponding to the one signed with the \t * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] \t * JSON-RPC method as part of EIP-191. \t * \t * See {recover}. \t */ \tfunction toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { \t\t// 32 is the length in bytes of hash, \t\t// enforced by the type signature above \t\treturn keccak256(abi.encodePacked("\\x19Ethereum Signed Message:\ 32", hash)); \t} \t/** \t * @dev Returns an Ethereum Signed Typed Data, created from a \t * `domainSeparator` and a `structHash`. This produces hash corresponding \t * to the one signed with the \t * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] \t * JSON-RPC method as part of EIP-712. \t * \t * See {recover}. \t */ \tfunction toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { \t\treturn keccak256(abi.encodePacked("\\x19\\x01", domainSeparator, structHash)); \t} } // SPDX-License-Identifier: MIT pragma solidity 0.8.7; /** * @title EIP-20: ERC-20 Token Standard * * @notice The ERC-20 (Ethereum Request for Comments 20), proposed by Fabian Vogelsteller in November 2015, * is a Token Standard that implements an API for tokens within Smart Contracts. * * @notice It provides functionalities like to transfer tokens from one account to another, * to get the current token balance of an account and also the total supply of the token available on the network. * Besides these it also has some other functionalities like to approve that an amount of * token from an account can be spent by a third party account. * * @notice If a Smart Contract implements the following methods and events it can be called an ERC-20 Token * Contract and, once deployed, it will be responsible to keep track of the created tokens on Ethereum. * * @notice See https://ethereum.org/en/developers/docs/standards/tokens/erc-20/ * @notice See https://eips.ethereum.org/EIPS/eip-20 */ interface ERC20 { \t/** \t * @dev Fired in transfer(), transferFrom() to indicate that token transfer happened \t * \t * @param from an address tokens were consumed from \t * @param to an address tokens were sent to \t * @param value number of tokens transferred \t */ \tevent Transfer(address indexed from, address indexed to, uint256 value); \t/** \t * @dev Fired in approve() to indicate an approval event happened \t * \t * @param owner an address which granted a permission to transfer \t * tokens on its behalf \t * @param spender an address which received a permission to transfer \t * tokens on behalf of the owner `_owner` \t * @param value amount of tokens granted to transfer on behalf \t */ \tevent Approval(address indexed owner, address indexed spender, uint256 value); \t/** \t * @return name of the token (ex.: USD Coin) \t */ \t// OPTIONAL - This method can be used to improve usability, \t// but interfaces and other contracts MUST NOT expect these values to be present. \t// function name() external view returns (string memory); \t/** \t * @return symbol of the token (ex.: USDC) \t */ \t// OPTIONAL - This method can be used to improve usability, \t// but interfaces and other contracts MUST NOT expect these values to be present. \t// function symbol() external view returns (string memory); \t/** \t * @dev Returns the number of decimals used to get its user representation. \t * For example, if `decimals` equals `2`, a balance of `505` tokens should \t * be displayed to a user as `5,05` (`505 / 10 ** 2`). \t * \t * @dev Tokens usually opt for a value of 18, imitating the relationship between \t * Ether and Wei. This is the value {ERC20} uses, unless this function is \t * overridden; \t * \t * @dev NOTE: This information is only used for _display_ purposes: it in \t * no way affects any of the arithmetic of the contract, including \t * {IERC20-balanceOf} and {IERC20-transfer}. \t * \t * @return token decimals \t */ \t// OPTIONAL - This method can be used to improve usability, \t// but interfaces and other contracts MUST NOT expect these values to be present. \t// function decimals() external view returns (uint8); \t/** \t * @return the amount of tokens in existence \t */ \tfunction totalSupply() external view returns (uint256); \t/** \t * @notice Gets the balance of a particular address \t * \t * @param _owner the address to query the the balance for \t * @return balance an amount of tokens owned by the address specified \t */ \tfunction balanceOf(address _owner) external view returns (uint256 balance); \t/** \t * @notice Transfers some tokens to an external address or a smart contract \t * \t * @dev Called by token owner (an address which has a \t * positive token balance tracked by this smart contract) \t * @dev Throws on any error like \t * * insufficient token balance or \t * * incorrect `_to` address: \t * * zero address or \t * * self address or \t * * smart contract which doesn't support ERC20 \t * \t * @param _to an address to transfer tokens to, \t * must be either an external address or a smart contract, \t * compliant with the ERC20 standard \t * @param _value amount of tokens to be transferred,, zero \t * value is allowed \t * @return success true on success, throws otherwise \t */ \tfunction transfer(address _to, uint256 _value) external returns (bool success); \t/** \t * @notice Transfers some tokens on behalf of address `_from' (token owner) \t * to some other address `_to` \t * \t * @dev Called by token owner on his own or approved address, \t * an address approved earlier by token owner to \t * transfer some amount of tokens on its behalf \t * @dev Throws on any error like \t * * insufficient token balance or \t * * incorrect `_to` address: \t * * zero address or \t * * same as `_from` address (self transfer) \t * * smart contract which doesn't support ERC20 \t * \t * @param _from token owner which approved caller (transaction sender) \t * to transfer `_value` of tokens on its behalf \t * @param _to an address to transfer tokens to, \t * must be either an external address or a smart contract, \t * compliant with the ERC20 standard \t * @param _value amount of tokens to be transferred,, zero \t * value is allowed \t * @return success true on success, throws otherwise \t */ \tfunction transferFrom(address _from, address _to, uint256 _value) external returns (bool success); \t/** \t * @notice Approves address called `_spender` to transfer some amount \t * of tokens on behalf of the owner (transaction sender) \t * \t * @dev Transaction sender must not necessarily own any tokens to grant the permission \t * \t * @param _spender an address approved by the caller (token owner) \t * to spend some tokens on its behalf \t * @param _value an amount of tokens spender `_spender` is allowed to \t * transfer on behalf of the token owner \t * @return success true on success, throws otherwise \t */ \tfunction approve(address _spender, uint256 _value) external returns (bool success); \t/** \t * @notice Returns the amount which _spender is still allowed to withdraw from _owner. \t * \t * @dev A function to check an amount of tokens owner approved \t * to transfer on its behalf by some other address called "spender" \t * \t * @param _owner an address which approves transferring some tokens on its behalf \t * @param _spender an address approved to transfer some tokens on behalf \t * @return remaining an amount of tokens approved address `_spender` can transfer on behalf \t * of token owner `_owner` \t */ \tfunction allowance(address _owner, address _spender) external view returns (uint256 remaining); } // SPDX-License-Identifier: MIT pragma solidity 0.8.7; /** * @title ERC-165 Standard Interface Detection * * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * @dev Implementers can declare support of contract interfaces, * which can then be queried by others. * * @author Christian Reitwießner, Nick Johnson, Fabian Vogelsteller, Jordi Baylina, Konrad Feldmeier, William Entriken */ interface ERC165 { \t/** \t * @notice Query if a contract implements an interface \t * \t * @dev Interface identification is specified in ERC-165. \t * This function uses less than 30,000 gas. \t * \t * @param interfaceID The interface identifier, as specified in ERC-165 \t * @return `true` if the contract implements `interfaceID` and \t * `interfaceID` is not 0xffffffff, `false` otherwise \t */ \tfunction supportsInterface(bytes4 interfaceID) external view returns (bool); }
File 4 of 6: StateSender
/** Matic network contracts */ pragma solidity ^0.5.2; contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @return the address of the owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner()); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Allows the current owner to relinquish control of the contract. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. * @notice Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } contract StateSender is Ownable { using SafeMath for uint256; uint256 public counter; mapping(address => address) public registrations; event NewRegistration( address indexed user, address indexed sender, address indexed receiver ); event RegistrationUpdated( address indexed user, address indexed sender, address indexed receiver ); event StateSynced( uint256 indexed id, address indexed contractAddress, bytes data ); modifier onlyRegistered(address receiver) { require(registrations[receiver] == msg.sender, "Invalid sender"); _; } function syncState(address receiver, bytes calldata data) external onlyRegistered(receiver) { counter = counter.add(1); emit StateSynced(counter, receiver, data); } // register new contract for state sync function register(address sender, address receiver) public { require( isOwner() || registrations[receiver] == msg.sender, "StateSender.register: Not authorized to register" ); registrations[receiver] = sender; if (registrations[receiver] == address(0)) { emit NewRegistration(msg.sender, sender, receiver); } else { emit RegistrationUpdated(msg.sender, sender, receiver); } } }
File 5 of 6: RootChainManager
pragma solidity 0.6.6; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {IRootChainManager} from "./IRootChainManager.sol"; import {RootChainManagerStorage} from "./RootChainManagerStorage.sol"; import {IStateSender} from "../StateSender/IStateSender.sol"; import {ICheckpointManager} from "../ICheckpointManager.sol"; import {RLPReader} from "../../lib/RLPReader.sol"; import {ExitPayloadReader} from "../../lib/ExitPayloadReader.sol"; import {MerklePatriciaProof} from "../../lib/MerklePatriciaProof.sol"; import {Merkle} from "../../lib/Merkle.sol"; import {ITokenPredicate} from "../TokenPredicates/ITokenPredicate.sol"; import {Initializable} from "../../common/Initializable.sol"; import {NativeMetaTransaction} from "../../common/NativeMetaTransaction.sol"; import {AccessControl} from "@openzeppelin/contracts/access/AccessControl.sol"; import {AccessControlMixin} from "../../common/AccessControlMixin.sol"; import {ContextMixin} from "../../common/ContextMixin.sol"; contract RootChainManager is IRootChainManager, Initializable, AccessControl, // included to match old storage layout while upgrading RootChainManagerStorage, // created to match old storage layout while upgrading AccessControlMixin, NativeMetaTransaction, ContextMixin { using ExitPayloadReader for bytes; using ExitPayloadReader for ExitPayloadReader.ExitPayload; using ExitPayloadReader for ExitPayloadReader.Log; using ExitPayloadReader for ExitPayloadReader.Receipt; using Merkle for bytes32; using SafeMath for uint256; // maybe DEPOSIT and MAP_TOKEN can be reduced to bytes4 bytes32 public constant DEPOSIT = keccak256("DEPOSIT"); bytes32 public constant MAP_TOKEN = keccak256("MAP_TOKEN"); address public constant ETHER_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; bytes32 public constant MAPPER_ROLE = keccak256("MAPPER_ROLE"); constructor() public { // Disable initializer on implementation contract _disableInitializer(); } function _msgSender() internal override view returns (address payable sender) { return ContextMixin.msgSender(); } /** * @notice Deposit ether by directly sending to the contract * The account sending ether receives WETH on child chain */ receive() external payable { _depositEtherFor(_msgSender()); } /** * @notice Initialize the contract after it has been proxified * @dev meant to be called once immediately after deployment * @param _owner the account that should be granted admin role */ function initialize( address _owner ) external initializer { _initializeEIP712("RootChainManager"); _setupContractId("RootChainManager"); _setupRole(DEFAULT_ADMIN_ROLE, _owner); _setupRole(MAPPER_ROLE, _owner); } // adding seperate function setupContractId since initialize is already called with old implementation function setupContractId() external only(DEFAULT_ADMIN_ROLE) { _setupContractId("RootChainManager"); } // adding seperate function initializeEIP712 since initialize is already called with old implementation function initializeEIP712() external only(DEFAULT_ADMIN_ROLE) { _setDomainSeperator("RootChainManager"); } /** * @notice Set the state sender, callable only by admins * @dev This should be the state sender from plasma contracts * It is used to send bytes from root to child chain * @param newStateSender address of state sender contract */ function setStateSender(address newStateSender) external only(DEFAULT_ADMIN_ROLE) { require(newStateSender != address(0), "RootChainManager: BAD_NEW_STATE_SENDER"); _stateSender = IStateSender(newStateSender); } /** * @notice Get the address of contract set as state sender * @return The address of state sender contract */ function stateSenderAddress() external view returns (address) { return address(_stateSender); } /** * @notice Set the checkpoint manager, callable only by admins * @dev This should be the plasma contract responsible for keeping track of checkpoints * @param newCheckpointManager address of checkpoint manager contract */ function setCheckpointManager(address newCheckpointManager) external only(DEFAULT_ADMIN_ROLE) { require(newCheckpointManager != address(0), "RootChainManager: BAD_NEW_CHECKPOINT_MANAGER"); _checkpointManager = ICheckpointManager(newCheckpointManager); } /** * @notice Get the address of contract set as checkpoint manager * @return The address of checkpoint manager contract */ function checkpointManagerAddress() external view returns (address) { return address(_checkpointManager); } /** * @notice Set the child chain manager, callable only by admins * @dev This should be the contract responsible to receive deposit bytes on child chain * @param newChildChainManager address of child chain manager contract */ function setChildChainManagerAddress(address newChildChainManager) external only(DEFAULT_ADMIN_ROLE) { require(newChildChainManager != address(0x0), "RootChainManager: INVALID_CHILD_CHAIN_ADDRESS"); childChainManagerAddress = newChildChainManager; } /** * @notice Register a token predicate address against its type, callable only by ADMIN * @dev A predicate is a contract responsible to process the token specific logic while locking or exiting tokens * @param tokenType bytes32 unique identifier for the token type * @param predicateAddress address of token predicate address */ function registerPredicate(bytes32 tokenType, address predicateAddress) external override only(DEFAULT_ADMIN_ROLE) { typeToPredicate[tokenType] = predicateAddress; emit PredicateRegistered(tokenType, predicateAddress); } /** * @notice Map a token to enable its movement via the PoS Portal, callable only by mappers * @param rootToken address of token on root chain * @param childToken address of token on child chain * @param tokenType bytes32 unique identifier for the token type */ function mapToken( address rootToken, address childToken, bytes32 tokenType ) external override only(MAPPER_ROLE) { // explicit check if token is already mapped to avoid accidental remaps require( rootToChildToken[rootToken] == address(0) && childToRootToken[childToken] == address(0), "RootChainManager: ALREADY_MAPPED" ); _mapToken(rootToken, childToken, tokenType); } /** * @notice Clean polluted token mapping * @param rootToken address of token on root chain. Since rename token was introduced later stage, * clean method is used to clean pollulated mapping */ function cleanMapToken( address rootToken, address childToken ) external override only(DEFAULT_ADMIN_ROLE) { rootToChildToken[rootToken] = address(0); childToRootToken[childToken] = address(0); tokenToType[rootToken] = bytes32(0); emit TokenMapped(rootToken, childToken, tokenToType[rootToken]); } /** * @notice Remap a token that has already been mapped, properly cleans up old mapping * Callable only by ADMIN * @param rootToken address of token on root chain * @param childToken address of token on child chain * @param tokenType bytes32 unique identifier for the token type */ function remapToken( address rootToken, address childToken, bytes32 tokenType ) external override only(DEFAULT_ADMIN_ROLE) { // cleanup old mapping address oldChildToken = rootToChildToken[rootToken]; address oldRootToken = childToRootToken[childToken]; if (rootToChildToken[oldRootToken] != address(0)) { rootToChildToken[oldRootToken] = address(0); tokenToType[oldRootToken] = bytes32(0); } if (childToRootToken[oldChildToken] != address(0)) { childToRootToken[oldChildToken] = address(0); } _mapToken(rootToken, childToken, tokenType); } function _mapToken( address rootToken, address childToken, bytes32 tokenType ) private { require( typeToPredicate[tokenType] != address(0x0), "RootChainManager: TOKEN_TYPE_NOT_SUPPORTED" ); rootToChildToken[rootToken] = childToken; childToRootToken[childToken] = rootToken; tokenToType[rootToken] = tokenType; emit TokenMapped(rootToken, childToken, tokenType); bytes memory syncData = abi.encode(rootToken, childToken, tokenType); _stateSender.syncState( childChainManagerAddress, abi.encode(MAP_TOKEN, syncData) ); } /** * @notice Move ether from root to child chain, accepts ether transfer * Keep in mind this ether cannot be used to pay gas on child chain * Use Matic tokens deposited using plasma mechanism for that * @param user address of account that should receive WETH on child chain */ function depositEtherFor(address user) external override payable { _depositEtherFor(user); } /** * @notice Move tokens from root to child chain * @dev This mechanism supports arbitrary tokens as long as its predicate has been registered and the token is mapped * @param user address of account that should receive this deposit on child chain * @param rootToken address of token that is being deposited * @param depositData bytes data that is sent to predicate and child token contracts to handle deposit */ function depositFor( address user, address rootToken, bytes calldata depositData ) external override { require( rootToken != ETHER_ADDRESS, "RootChainManager: INVALID_ROOT_TOKEN" ); _depositFor(user, rootToken, depositData); } function _depositEtherFor(address user) private { bytes memory depositData = abi.encode(msg.value); _depositFor(user, ETHER_ADDRESS, depositData); // payable(typeToPredicate[tokenToType[ETHER_ADDRESS]]).transfer(msg.value); // transfer doesn't work as expected when receiving contract is proxified so using call (bool success, /* bytes memory data */) = typeToPredicate[tokenToType[ETHER_ADDRESS]].call{value: msg.value}(""); if (!success) { revert("RootChainManager: ETHER_TRANSFER_FAILED"); } } function _depositFor( address user, address rootToken, bytes memory depositData ) private { bytes32 tokenType = tokenToType[rootToken]; require( rootToChildToken[rootToken] != address(0x0) && tokenType != 0, "RootChainManager: TOKEN_NOT_MAPPED" ); address predicateAddress = typeToPredicate[tokenType]; require( predicateAddress != address(0), "RootChainManager: INVALID_TOKEN_TYPE" ); require( user != address(0), "RootChainManager: INVALID_USER" ); ITokenPredicate(predicateAddress).lockTokens( _msgSender(), user, rootToken, depositData ); bytes memory syncData = abi.encode(user, rootToken, depositData); _stateSender.syncState( childChainManagerAddress, abi.encode(DEPOSIT, syncData) ); } /** * @notice exit tokens by providing proof * @dev This function verifies if the transaction actually happened on child chain * the transaction log is then sent to token predicate to handle it accordingly * * @param inputData RLP encoded data of the reference tx containing following list of fields * 0 - headerNumber - Checkpoint header block number containing the reference tx * 1 - blockProof - Proof that the block header (in the child chain) is a leaf in the submitted merkle root * 2 - blockNumber - Block number containing the reference tx on child chain * 3 - blockTime - Reference tx block time * 4 - txRoot - Transactions root of block * 5 - receiptRoot - Receipts root of block * 6 - receipt - Receipt of the reference transaction * 7 - receiptProof - Merkle proof of the reference receipt * 8 - branchMask - 32 bits denoting the path of receipt in merkle tree * 9 - receiptLogIndex - Log Index to read from the receipt */ function exit(bytes calldata inputData) external override { ExitPayloadReader.ExitPayload memory payload = inputData.toExitPayload(); bytes memory branchMaskBytes = payload.getBranchMaskAsBytes(); // checking if exit has already been processed // unique exit is identified using hash of (blockNumber, branchMask, receiptLogIndex) bytes32 exitHash = keccak256( abi.encodePacked( payload.getBlockNumber(), // first 2 nibbles are dropped while generating nibble array // this allows branch masks that are valid but bypass exitHash check (changing first 2 nibbles only) // so converting to nibble array and then hashing it MerklePatriciaProof._getNibbleArray(branchMaskBytes), payload.getReceiptLogIndex() ) ); require( processedExits[exitHash] == false, "RootChainManager: EXIT_ALREADY_PROCESSED" ); processedExits[exitHash] = true; ExitPayloadReader.Receipt memory receipt = payload.getReceipt(); ExitPayloadReader.Log memory log = receipt.getLog(); // log should be emmited only by the child token address rootToken = childToRootToken[log.getEmitter()]; require( rootToken != address(0), "RootChainManager: TOKEN_NOT_MAPPED" ); address predicateAddress = typeToPredicate[ tokenToType[rootToken] ]; // branch mask can be maximum 32 bits require( payload.getBranchMaskAsUint() & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000 == 0, "RootChainManager: INVALID_BRANCH_MASK" ); // verify receipt inclusion require( MerklePatriciaProof.verify( receipt.toBytes(), branchMaskBytes, payload.getReceiptProof(), payload.getReceiptRoot() ), "RootChainManager: INVALID_PROOF" ); // verify checkpoint inclusion _checkBlockMembershipInCheckpoint( payload.getBlockNumber(), payload.getBlockTime(), payload.getTxRoot(), payload.getReceiptRoot(), payload.getHeaderNumber(), payload.getBlockProof() ); ITokenPredicate(predicateAddress).exitTokens( _msgSender(), rootToken, log.toRlpBytes() ); } function _checkBlockMembershipInCheckpoint( uint256 blockNumber, uint256 blockTime, bytes32 txRoot, bytes32 receiptRoot, uint256 headerNumber, bytes memory blockProof ) private view { ( bytes32 headerRoot, uint256 startBlock, , , ) = _checkpointManager.headerBlocks(headerNumber); require( keccak256( abi.encodePacked(blockNumber, blockTime, txRoot, receiptRoot) ) .checkMembership( blockNumber.sub(startBlock), headerRoot, blockProof ), "RootChainManager: INVALID_HEADER" ); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } pragma solidity 0.6.6; interface IRootChainManager { event TokenMapped( address indexed rootToken, address indexed childToken, bytes32 indexed tokenType ); event PredicateRegistered( bytes32 indexed tokenType, address indexed predicateAddress ); function registerPredicate(bytes32 tokenType, address predicateAddress) external; function mapToken( address rootToken, address childToken, bytes32 tokenType ) external; function cleanMapToken( address rootToken, address childToken ) external; function remapToken( address rootToken, address childToken, bytes32 tokenType ) external; function depositEtherFor(address user) external payable; function depositFor( address user, address rootToken, bytes calldata depositData ) external; function exit(bytes calldata inputData) external; } pragma solidity 0.6.6; import {IStateSender} from "../StateSender/IStateSender.sol"; import {ICheckpointManager} from "../ICheckpointManager.sol"; abstract contract RootChainManagerStorage { mapping(bytes32 => address) public typeToPredicate; mapping(address => address) public rootToChildToken; mapping(address => address) public childToRootToken; mapping(address => bytes32) public tokenToType; mapping(bytes32 => bool) public processedExits; IStateSender internal _stateSender; ICheckpointManager internal _checkpointManager; address public childChainManagerAddress; } pragma solidity 0.6.6; interface IStateSender { function syncState(address receiver, bytes calldata data) external; } pragma solidity 0.6.6; contract ICheckpointManager { struct HeaderBlock { bytes32 root; uint256 start; uint256 end; uint256 createdAt; address proposer; } /** * @notice mapping of checkpoint header numbers to block details * @dev These checkpoints are submited by plasma contracts */ mapping(uint256 => HeaderBlock) public headerBlocks; } /* * @author Hamdi Allam [email protected] * Please reach out with any questions or concerns * https://github.com/hamdiallam/Solidity-RLP/blob/e681e25a376dbd5426b509380bc03446f05d0f97/contracts/RLPReader.sol */ pragma solidity 0.6.6; library RLPReader { uint8 constant STRING_SHORT_START = 0x80; uint8 constant STRING_LONG_START = 0xb8; uint8 constant LIST_SHORT_START = 0xc0; uint8 constant LIST_LONG_START = 0xf8; uint8 constant WORD_SIZE = 32; struct RLPItem { uint len; uint memPtr; } struct Iterator { RLPItem item; // Item that's being iterated over. uint nextPtr; // Position of the next item in the list. } /* * @dev Returns the next element in the iteration. Reverts if it has not next element. * @param self The iterator. * @return The next element in the iteration. */ function next(Iterator memory self) internal pure returns (RLPItem memory) { require(hasNext(self)); uint ptr = self.nextPtr; uint itemLength = _itemLength(ptr); self.nextPtr = ptr + itemLength; return RLPItem(itemLength, ptr); } /* * @dev Returns true if the iteration has more elements. * @param self The iterator. * @return true if the iteration has more elements. */ function hasNext(Iterator memory self) internal pure returns (bool) { RLPItem memory item = self.item; return self.nextPtr < item.memPtr + item.len; } /* * @param item RLP encoded bytes */ function toRlpItem(bytes memory item) internal pure returns (RLPItem memory) { uint memPtr; assembly { memPtr := add(item, 0x20) } return RLPItem(item.length, memPtr); } /* * @dev Create an iterator. Reverts if item is not a list. * @param self The RLP item. * @return An 'Iterator' over the item. */ function iterator(RLPItem memory self) internal pure returns (Iterator memory) { require(isList(self)); uint ptr = self.memPtr + _payloadOffset(self.memPtr); return Iterator(self, ptr); } /* * @param the RLP item. */ function rlpLen(RLPItem memory item) internal pure returns (uint) { return item.len; } /* * @param the RLP item. * @return (memPtr, len) pair: location of the item's payload in memory. */ function payloadLocation(RLPItem memory item) internal pure returns (uint, uint) { uint offset = _payloadOffset(item.memPtr); uint memPtr = item.memPtr + offset; uint len = item.len - offset; // data length return (memPtr, len); } /* * @param the RLP item. */ function payloadLen(RLPItem memory item) internal pure returns (uint) { (, uint len) = payloadLocation(item); return len; } /* * @param the RLP item containing the encoded list. */ function toList(RLPItem memory item) internal pure returns (RLPItem[] memory) { require(isList(item)); uint items = numItems(item); RLPItem[] memory result = new RLPItem[](items); uint memPtr = item.memPtr + _payloadOffset(item.memPtr); uint dataLen; for (uint i = 0; i < items; i++) { dataLen = _itemLength(memPtr); result[i] = RLPItem(dataLen, memPtr); memPtr = memPtr + dataLen; } require(memPtr - item.memPtr == item.len, "Wrong total length."); return result; } // @return indicator whether encoded payload is a list. negate this function call for isData. function isList(RLPItem memory item) internal pure returns (bool) { if (item.len == 0) return false; uint8 byte0; uint memPtr = item.memPtr; assembly { byte0 := byte(0, mload(memPtr)) } if (byte0 < LIST_SHORT_START) return false; return true; } /* * @dev A cheaper version of keccak256(toRlpBytes(item)) that avoids copying memory. * @return keccak256 hash of RLP encoded bytes. */ function rlpBytesKeccak256(RLPItem memory item) internal pure returns (bytes32) { uint256 ptr = item.memPtr; uint256 len = item.len; bytes32 result; assembly { result := keccak256(ptr, len) } return result; } /* * @dev A cheaper version of keccak256(toBytes(item)) that avoids copying memory. * @return keccak256 hash of the item payload. */ function payloadKeccak256(RLPItem memory item) internal pure returns (bytes32) { (uint memPtr, uint len) = payloadLocation(item); bytes32 result; assembly { result := keccak256(memPtr, len) } return result; } /** RLPItem conversions into data types **/ // @returns raw rlp encoding in bytes function toRlpBytes(RLPItem memory item) internal pure returns (bytes memory) { bytes memory result = new bytes(item.len); if (result.length == 0) return result; uint ptr; assembly { ptr := add(0x20, result) } copy(item.memPtr, ptr, item.len); return result; } // any non-zero byte except "0x80" is considered true function toBoolean(RLPItem memory item) internal pure returns (bool) { require(item.len == 1); uint result; uint memPtr = item.memPtr; assembly { result := byte(0, mload(memPtr)) } // SEE Github Issue #5. // Summary: Most commonly used RLP libraries (i.e Geth) will encode // "0" as "0x80" instead of as "0". We handle this edge case explicitly // here. if (result == 0 || result == STRING_SHORT_START) { return false; } else { return true; } } function toAddress(RLPItem memory item) internal pure returns (address) { // 1 byte for the length prefix require(item.len == 21); return address(toUint(item)); } function toUint(RLPItem memory item) internal pure returns (uint) { require(item.len > 0 && item.len <= 33); (uint memPtr, uint len) = payloadLocation(item); uint result; assembly { result := mload(memPtr) // shfit to the correct location if neccesary if lt(len, 32) { result := div(result, exp(256, sub(32, len))) } } return result; } // enforces 32 byte length function toUintStrict(RLPItem memory item) internal pure returns (uint) { // one byte prefix require(item.len == 33); uint result; uint memPtr = item.memPtr + 1; assembly { result := mload(memPtr) } return result; } function toBytes(RLPItem memory item) internal pure returns (bytes memory) { require(item.len > 0); (uint memPtr, uint len) = payloadLocation(item); bytes memory result = new bytes(len); uint destPtr; assembly { destPtr := add(0x20, result) } copy(memPtr, destPtr, len); return result; } /* * Private Helpers */ // @return number of payload items inside an encoded list. function numItems(RLPItem memory item) private pure returns (uint) { if (item.len == 0) return 0; uint count = 0; uint currPtr = item.memPtr + _payloadOffset(item.memPtr); uint endPtr = item.memPtr + item.len; while (currPtr < endPtr) { currPtr = currPtr + _itemLength(currPtr); // skip over an item count++; } return count; } // @return entire rlp item byte length function _itemLength(uint memPtr) private pure returns (uint) { uint itemLen; uint byte0; assembly { byte0 := byte(0, mload(memPtr)) } if (byte0 < STRING_SHORT_START) itemLen = 1; else if (byte0 < STRING_LONG_START) itemLen = byte0 - STRING_SHORT_START + 1; else if (byte0 < LIST_SHORT_START) { assembly { let byteLen := sub(byte0, 0xb7) // # of bytes the actual length is memPtr := add(memPtr, 1) // skip over the first byte /* 32 byte word size */ let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to get the len itemLen := add(dataLen, add(byteLen, 1)) } } else if (byte0 < LIST_LONG_START) { itemLen = byte0 - LIST_SHORT_START + 1; } else { assembly { let byteLen := sub(byte0, 0xf7) memPtr := add(memPtr, 1) let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to the correct length itemLen := add(dataLen, add(byteLen, 1)) } } return itemLen; } // @return number of bytes until the data function _payloadOffset(uint memPtr) private pure returns (uint) { uint byte0; assembly { byte0 := byte(0, mload(memPtr)) } if (byte0 < STRING_SHORT_START) return 0; else if (byte0 < STRING_LONG_START || (byte0 >= LIST_SHORT_START && byte0 < LIST_LONG_START)) return 1; else if (byte0 < LIST_SHORT_START) // being explicit return byte0 - (STRING_LONG_START - 1) + 1; else return byte0 - (LIST_LONG_START - 1) + 1; } /* * @param src Pointer to source * @param dest Pointer to destination * @param len Amount of memory to copy from the source */ function copy(uint src, uint dest, uint len) private pure { if (len == 0) return; // copy as many word sizes as possible for (; len >= WORD_SIZE; len -= WORD_SIZE) { assembly { mstore(dest, mload(src)) } src += WORD_SIZE; dest += WORD_SIZE; } if (len > 0) { // left over bytes. Mask is used to remove unwanted bytes from the word uint mask = 256 ** (WORD_SIZE - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) // zero out src let destpart := and(mload(dest), mask) // retrieve the bytes mstore(dest, or(destpart, srcpart)) } } } } pragma solidity 0.6.6; import { RLPReader } from "./RLPReader.sol"; library ExitPayloadReader { using RLPReader for bytes; using RLPReader for RLPReader.RLPItem; uint8 constant WORD_SIZE = 32; struct ExitPayload { RLPReader.RLPItem[] data; } struct Receipt { RLPReader.RLPItem[] data; bytes raw; uint256 logIndex; } struct Log { RLPReader.RLPItem data; RLPReader.RLPItem[] list; } struct LogTopics { RLPReader.RLPItem[] data; } // copy paste of private copy() from RLPReader to avoid changing of existing contracts function copy(uint src, uint dest, uint len) private pure { if (len == 0) return; // copy as many word sizes as possible for (; len >= WORD_SIZE; len -= WORD_SIZE) { assembly { mstore(dest, mload(src)) } src += WORD_SIZE; dest += WORD_SIZE; } // left over bytes. Mask is used to remove unwanted bytes from the word uint mask = 256 ** (WORD_SIZE - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) // zero out src let destpart := and(mload(dest), mask) // retrieve the bytes mstore(dest, or(destpart, srcpart)) } } function toExitPayload(bytes memory data) internal pure returns (ExitPayload memory) { RLPReader.RLPItem[] memory payloadData = data .toRlpItem() .toList(); return ExitPayload(payloadData); } function getHeaderNumber(ExitPayload memory payload) internal pure returns(uint256) { return payload.data[0].toUint(); } function getBlockProof(ExitPayload memory payload) internal pure returns(bytes memory) { return payload.data[1].toBytes(); } function getBlockNumber(ExitPayload memory payload) internal pure returns(uint256) { return payload.data[2].toUint(); } function getBlockTime(ExitPayload memory payload) internal pure returns(uint256) { return payload.data[3].toUint(); } function getTxRoot(ExitPayload memory payload) internal pure returns(bytes32) { return bytes32(payload.data[4].toUint()); } function getReceiptRoot(ExitPayload memory payload) internal pure returns(bytes32) { return bytes32(payload.data[5].toUint()); } function getReceipt(ExitPayload memory payload) internal pure returns(Receipt memory receipt) { receipt.raw = payload.data[6].toBytes(); RLPReader.RLPItem memory receiptItem = receipt.raw.toRlpItem(); if (receiptItem.isList()) { // legacy tx receipt.data = receiptItem.toList(); } else { // pop first byte before parsting receipt bytes memory typedBytes = receipt.raw; bytes memory result = new bytes(typedBytes.length - 1); uint256 srcPtr; uint256 destPtr; assembly { srcPtr := add(33, typedBytes) destPtr := add(0x20, result) } copy(srcPtr, destPtr, result.length); receipt.data = result.toRlpItem().toList(); } receipt.logIndex = getReceiptLogIndex(payload); return receipt; } function getReceiptProof(ExitPayload memory payload) internal pure returns(bytes memory) { return payload.data[7].toBytes(); } function getBranchMaskAsBytes(ExitPayload memory payload) internal pure returns(bytes memory) { return payload.data[8].toBytes(); } function getBranchMaskAsUint(ExitPayload memory payload) internal pure returns(uint256) { return payload.data[8].toUint(); } function getReceiptLogIndex(ExitPayload memory payload) internal pure returns(uint256) { return payload.data[9].toUint(); } // Receipt methods function toBytes(Receipt memory receipt) internal pure returns(bytes memory) { return receipt.raw; } function getLog(Receipt memory receipt) internal pure returns(Log memory) { RLPReader.RLPItem memory logData = receipt.data[3].toList()[receipt.logIndex]; return Log(logData, logData.toList()); } // Log methods function getEmitter(Log memory log) internal pure returns(address) { return RLPReader.toAddress(log.list[0]); } function getTopics(Log memory log) internal pure returns(LogTopics memory) { return LogTopics(log.list[1].toList()); } function getData(Log memory log) internal pure returns(bytes memory) { return log.list[2].toBytes(); } function toRlpBytes(Log memory log) internal pure returns(bytes memory) { return log.data.toRlpBytes(); } // LogTopics methods function getField(LogTopics memory topics, uint256 index) internal pure returns(RLPReader.RLPItem memory) { return topics.data[index]; } } /* * @title MerklePatriciaVerifier * @author Sam Mayo ([email protected]) * * @dev Library for verifing merkle patricia proofs. */ pragma solidity 0.6.6; import {RLPReader} from "./RLPReader.sol"; library MerklePatriciaProof { /* * @dev Verifies a merkle patricia proof. * @param value The terminating value in the trie. * @param encodedPath The path in the trie leading to value. * @param rlpParentNodes The rlp encoded stack of nodes. * @param root The root hash of the trie. * @return The boolean validity of the proof. */ function verify( bytes memory value, bytes memory encodedPath, bytes memory rlpParentNodes, bytes32 root ) internal pure returns (bool) { RLPReader.RLPItem memory item = RLPReader.toRlpItem(rlpParentNodes); RLPReader.RLPItem[] memory parentNodes = RLPReader.toList(item); bytes memory currentNode; RLPReader.RLPItem[] memory currentNodeList; bytes32 nodeKey = root; uint256 pathPtr = 0; bytes memory path = _getNibbleArray(encodedPath); if (path.length == 0) { return false; } for (uint256 i = 0; i < parentNodes.length; i++) { if (pathPtr > path.length) { return false; } currentNode = RLPReader.toRlpBytes(parentNodes[i]); if (nodeKey != keccak256(currentNode)) { return false; } currentNodeList = RLPReader.toList(parentNodes[i]); if (currentNodeList.length == 17) { if (pathPtr == path.length) { if ( keccak256(RLPReader.toBytes(currentNodeList[16])) == keccak256(value) ) { return true; } else { return false; } } uint8 nextPathNibble = uint8(path[pathPtr]); if (nextPathNibble > 16) { return false; } nodeKey = bytes32( RLPReader.toUintStrict(currentNodeList[nextPathNibble]) ); pathPtr += 1; } else if (currentNodeList.length == 2) { bytes memory nodeValue = RLPReader.toBytes(currentNodeList[0]); uint256 traversed = _nibblesToTraverse( nodeValue, path, pathPtr ); //enforce correct nibble bytes1 prefix = _getNthNibbleOfBytes(0, nodeValue); if (pathPtr + traversed == path.length) { //leaf node if ( keccak256(RLPReader.toBytes(currentNodeList[1])) == keccak256(value) && (prefix == bytes1(uint8(2)) || prefix == bytes1(uint8(3))) ) { return true; } else { return false; } } //extension node if (traversed == 0 || (prefix != bytes1(uint8(0)) && prefix != bytes1(uint8(1)))) { return false; } pathPtr += traversed; nodeKey = bytes32(RLPReader.toUintStrict(currentNodeList[1])); } else { return false; } } return false; // default } function _nibblesToTraverse( bytes memory encodedPartialPath, bytes memory path, uint256 pathPtr ) private pure returns (uint256) { uint256 len = 0; // encodedPartialPath has elements that are each two hex characters (1 byte), but partialPath // and slicedPath have elements that are each one hex character (1 nibble) bytes memory partialPath = _getNibbleArray(encodedPartialPath); bytes memory slicedPath = new bytes(partialPath.length); // pathPtr counts nibbles in path // partialPath.length is a number of nibbles for (uint256 i = pathPtr; i < pathPtr + partialPath.length; i++) { bytes1 pathNibble = path[i]; slicedPath[i - pathPtr] = pathNibble; } if (keccak256(partialPath) == keccak256(slicedPath)) { len = partialPath.length; } else { len = 0; } return len; } // bytes b must be hp encoded function _getNibbleArray(bytes memory b) internal pure returns (bytes memory) { bytes memory nibbles = ""; if (b.length > 0) { uint8 offset; uint8 hpNibble = uint8(_getNthNibbleOfBytes(0, b)); if (hpNibble == 1 || hpNibble == 3) { nibbles = new bytes(b.length * 2 - 1); bytes1 oddNibble = _getNthNibbleOfBytes(1, b); nibbles[0] = oddNibble; offset = 1; } else { nibbles = new bytes(b.length * 2 - 2); offset = 0; } for (uint256 i = offset; i < nibbles.length; i++) { nibbles[i] = _getNthNibbleOfBytes(i - offset + 2, b); } } return nibbles; } function _getNthNibbleOfBytes(uint256 n, bytes memory str) private pure returns (bytes1) { return bytes1( n % 2 == 0 ? uint8(str[n / 2]) / 0x10 : uint8(str[n / 2]) % 0x10 ); } } pragma solidity 0.6.6; library Merkle { function checkMembership( bytes32 leaf, uint256 index, bytes32 rootHash, bytes memory proof ) internal pure returns (bool) { require(proof.length % 32 == 0, "Invalid proof length"); uint256 proofHeight = proof.length / 32; // Proof of size n means, height of the tree is n+1. // In a tree of height n+1, max #leafs possible is 2 ^ n require(index < 2 ** proofHeight, "Leaf index is too big"); bytes32 proofElement; bytes32 computedHash = leaf; for (uint256 i = 32; i <= proof.length; i += 32) { assembly { proofElement := mload(add(proof, i)) } if (index % 2 == 0) { computedHash = keccak256( abi.encodePacked(computedHash, proofElement) ); } else { computedHash = keccak256( abi.encodePacked(proofElement, computedHash) ); } index = index / 2; } return computedHash == rootHash; } } pragma solidity 0.6.6; import {RLPReader} from "../../lib/RLPReader.sol"; /// @title Token predicate interface for all pos portal predicates /// @notice Abstract interface that defines methods for custom predicates interface ITokenPredicate { /** * @notice Deposit tokens into pos portal * @dev When `depositor` deposits tokens into pos portal, tokens get locked into predicate contract. * @param depositor Address who wants to deposit tokens * @param depositReceiver Address (address) who wants to receive tokens on side chain * @param rootToken Token which gets deposited * @param depositData Extra data for deposit (amount for ERC20, token id for ERC721 etc.) [ABI encoded] */ function lockTokens( address depositor, address depositReceiver, address rootToken, bytes calldata depositData ) external; /** * @notice Validates and processes exit while withdraw process * @dev Validates exit log emitted on sidechain. Reverts if validation fails. * @dev Processes withdraw based on custom logic. Example: transfer ERC20/ERC721, mint ERC721 if mintable withdraw * @param sender unused for polygon predicates, being kept for abi compatability * @param rootToken Token which gets withdrawn * @param logRLPList Valid sidechain log for data like amount, token id etc. */ function exitTokens( address sender, address rootToken, bytes calldata logRLPList ) external; } pragma solidity 0.6.6; contract Initializable { bool inited = false; modifier initializer() { require(!inited, "already inited"); _; inited = true; } function _disableInitializer() internal { inited = true; } } pragma solidity 0.6.6; /** * @notice DISCLAIMER: * Do not use NativeMetaTransaction and ContextMixin together with OpenZeppelin's "multicall" * nor any other form of self delegatecall! * Risk of address spoofing attacks. * Read more: https://blog.openzeppelin.com/arbitrary-address-spoofing-vulnerability-erc2771context-multicall-public-disclosure */ import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {EIP712Base} from "./EIP712Base.sol"; contract NativeMetaTransaction is EIP712Base { using SafeMath for uint256; bytes32 private constant META_TRANSACTION_TYPEHASH = keccak256( bytes( "MetaTransaction(uint256 nonce,address from,bytes functionSignature)" ) ); event MetaTransactionExecuted( address indexed userAddress, address payable indexed relayerAddress, bytes functionSignature ); mapping(address => uint256) nonces; /* * Meta transaction structure. * No point of including value field here as if user is doing value transfer then he has the funds to pay for gas * He should call the desired function directly in that case. */ struct MetaTransaction { uint256 nonce; address from; bytes functionSignature; } function executeMetaTransaction( address userAddress, bytes calldata functionSignature, bytes32 sigR, bytes32 sigS, uint8 sigV ) external payable returns (bytes memory) { MetaTransaction memory metaTx = MetaTransaction({ nonce: nonces[userAddress], from: userAddress, functionSignature: functionSignature }); require( verify(userAddress, metaTx, sigR, sigS, sigV), "Signer and signature do not match" ); // increase nonce for user (to avoid re-use) ++nonces[userAddress]; emit MetaTransactionExecuted( userAddress, msg.sender, functionSignature ); // Append userAddress and relayer address at the end to extract it from calling context (bool success, bytes memory returnData) = address(this).call( abi.encodePacked(functionSignature, userAddress) ); require(success, "Function call not successful"); return returnData; } function getNonce(address user) external view returns (uint256 nonce) { nonce = nonces[user]; } function hashMetaTransaction(MetaTransaction memory metaTx) internal pure returns (bytes32) { return keccak256( abi.encode( META_TRANSACTION_TYPEHASH, metaTx.nonce, metaTx.from, keccak256(metaTx.functionSignature) ) ); } function verify( address signer, MetaTransaction memory metaTx, bytes32 sigR, bytes32 sigS, uint8 sigV ) internal view returns (bool) { require(signer != address(0), "NativeMetaTransaction: INVALID_SIGNER"); return signer == ecrecover( toTypedMessageHash(hashMetaTransaction(metaTx)), sigV, sigR, sigS ); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "../utils/EnumerableSet.sol"; import "../utils/Address.sol"; import "../GSN/Context.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context { using EnumerableSet for EnumerableSet.AddressSet; using Address for address; struct RoleData { EnumerableSet.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, _roles[role].adminRole, adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } } pragma solidity 0.6.6; import {AccessControl} from "@openzeppelin/contracts/access/AccessControl.sol"; contract AccessControlMixin is AccessControl { string private _revertMsg; function _setupContractId(string memory contractId) internal { _revertMsg = string(abi.encodePacked(contractId, ": INSUFFICIENT_PERMISSIONS")); } modifier only(bytes32 role) { require( hasRole(role, _msgSender()), _revertMsg ); _; } } pragma solidity 0.6.6; /** * @notice DISCLAIMER: * Do not use NativeMetaTransaction and ContextMixin together with OpenZeppelin's "multicall" * nor any other form of self delegatecall! * Risk of address spoofing attacks. * Read more: https://blog.openzeppelin.com/arbitrary-address-spoofing-vulnerability-erc2771context-multicall-public-disclosure */ abstract contract ContextMixin { function msgSender() internal view returns (address payable sender) { if (msg.sender == address(this)) { bytes memory array = msg.data; uint256 index = msg.data.length; assembly { // Load the 32 bytes word from memory with the address on the lower 20 bytes, and mask those. sender := and( mload(add(array, index)), 0xffffffffffffffffffffffffffffffffffffffff ) } } else { sender = msg.sender; } return sender; } } pragma solidity 0.6.6; import {Initializable} from "./Initializable.sol"; contract EIP712Base is Initializable { struct EIP712Domain { string name; string version; address verifyingContract; bytes32 salt; } string constant public ERC712_VERSION = "1"; bytes32 internal constant EIP712_DOMAIN_TYPEHASH = keccak256( bytes( "EIP712Domain(string name,string version,address verifyingContract,bytes32 salt)" ) ); bytes32 internal domainSeperator; // supposed to be called once while initializing. // one of the contractsa that inherits this contract follows proxy pattern // so it is not possible to do this in a constructor function _initializeEIP712( string memory name ) internal initializer { _setDomainSeperator(name); } function _setDomainSeperator(string memory name) internal { domainSeperator = keccak256( abi.encode( EIP712_DOMAIN_TYPEHASH, keccak256(bytes(name)), keccak256(bytes(ERC712_VERSION)), address(this), bytes32(getChainId()) ) ); } function getDomainSeperator() public view returns (bytes32) { return domainSeperator; } function getChainId() public pure returns (uint256) { uint256 id; assembly { id := chainid() } return id; } /** * Accept message hash and returns hash message in EIP712 compatible form * So that it can be used to recover signer from signature signed using EIP712 formatted data * https://eips.ethereum.org/EIPS/eip-712 * "\\\\x19" makes the encoding deterministic * "\\\\x01" is the version byte to make it compatible to EIP-191 */ function toTypedMessageHash(bytes32 messageHash) internal view returns (bytes32) { return keccak256( abi.encodePacked("\\x19\\x01", getDomainSeperator(), messageHash) ); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256` * (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } }
File 6 of 6: ERC20Predicate
pragma solidity 0.6.6; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import {AccessControlMixin} from "../../common/AccessControlMixin.sol"; import {RLPReader} from "../../lib/RLPReader.sol"; import {ITokenPredicate} from "./ITokenPredicate.sol"; import {Initializable} from "../../common/Initializable.sol"; contract ERC20Predicate is ITokenPredicate, AccessControlMixin, Initializable { using RLPReader for bytes; using RLPReader for RLPReader.RLPItem; using SafeERC20 for IERC20; bytes32 public constant MANAGER_ROLE = keccak256("MANAGER_ROLE"); bytes32 public constant TOKEN_TYPE = keccak256("ERC20"); bytes32 public constant TRANSFER_EVENT_SIG = 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef; event LockedERC20( address indexed depositor, address indexed depositReceiver, address indexed rootToken, uint256 amount ); event ExitedERC20( address indexed exitor, address indexed rootToken, uint256 amount ); constructor() public { // Disable initializer on implementation contract _disableInitializer(); } function initialize(address _owner) external initializer { _setupContractId("ERC20Predicate"); _setupRole(DEFAULT_ADMIN_ROLE, _owner); _setupRole(MANAGER_ROLE, _owner); } /** * @notice Lock ERC20 tokens for deposit, callable only by manager * @param depositor Address who wants to deposit tokens * @param depositReceiver Address (address) who wants to receive tokens on child chain * @param rootToken Token which gets deposited * @param depositData ABI encoded amount */ function lockTokens( address depositor, address depositReceiver, address rootToken, bytes calldata depositData ) external override only(MANAGER_ROLE) { uint256 amount = abi.decode(depositData, (uint256)); emit LockedERC20(depositor, depositReceiver, rootToken, amount); IERC20(rootToken).safeTransferFrom(depositor, address(this), amount); } /** * @notice Validates log signature, from and to address * then sends the correct amount to withdrawer * callable only by manager * @notice address unused, being kept for abi compatability * @param rootToken Token which gets withdrawn * @param log Valid ERC20 burn log from child chain */ function exitTokens( address, address rootToken, bytes calldata log ) external override only(MANAGER_ROLE) { RLPReader.RLPItem[] memory logRLPList = log.toRlpItem().toList(); RLPReader.RLPItem[] memory logTopicRLPList = logRLPList[1].toList(); // topics require( bytes32(logTopicRLPList[0].toUint()) == TRANSFER_EVENT_SIG, // topic0 is event sig "ERC20Predicate: INVALID_SIGNATURE" ); address withdrawer = address(logTopicRLPList[1].toUint()); // topic1 is from address require( address(logTopicRLPList[2].toUint()) == address(0), // topic2 is to address "ERC20Predicate: INVALID_RECEIVER" ); uint256 amount = logRLPList[2].toUint(); // log data field is the amount IERC20(rootToken).safeTransfer( withdrawer, amount ); emit ExitedERC20(withdrawer, rootToken, amount); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } pragma solidity 0.6.6; import {AccessControl} from "@openzeppelin/contracts/access/AccessControl.sol"; contract AccessControlMixin is AccessControl { string private _revertMsg; function _setupContractId(string memory contractId) internal { _revertMsg = string(abi.encodePacked(contractId, ": INSUFFICIENT_PERMISSIONS")); } modifier only(bytes32 role) { require( hasRole(role, _msgSender()), _revertMsg ); _; } } /* * @author Hamdi Allam [email protected] * Please reach out with any questions or concerns * https://github.com/hamdiallam/Solidity-RLP/blob/e681e25a376dbd5426b509380bc03446f05d0f97/contracts/RLPReader.sol */ pragma solidity 0.6.6; library RLPReader { uint8 constant STRING_SHORT_START = 0x80; uint8 constant STRING_LONG_START = 0xb8; uint8 constant LIST_SHORT_START = 0xc0; uint8 constant LIST_LONG_START = 0xf8; uint8 constant WORD_SIZE = 32; struct RLPItem { uint len; uint memPtr; } struct Iterator { RLPItem item; // Item that's being iterated over. uint nextPtr; // Position of the next item in the list. } /* * @dev Returns the next element in the iteration. Reverts if it has not next element. * @param self The iterator. * @return The next element in the iteration. */ function next(Iterator memory self) internal pure returns (RLPItem memory) { require(hasNext(self)); uint ptr = self.nextPtr; uint itemLength = _itemLength(ptr); self.nextPtr = ptr + itemLength; return RLPItem(itemLength, ptr); } /* * @dev Returns true if the iteration has more elements. * @param self The iterator. * @return true if the iteration has more elements. */ function hasNext(Iterator memory self) internal pure returns (bool) { RLPItem memory item = self.item; return self.nextPtr < item.memPtr + item.len; } /* * @param item RLP encoded bytes */ function toRlpItem(bytes memory item) internal pure returns (RLPItem memory) { uint memPtr; assembly { memPtr := add(item, 0x20) } return RLPItem(item.length, memPtr); } /* * @dev Create an iterator. Reverts if item is not a list. * @param self The RLP item. * @return An 'Iterator' over the item. */ function iterator(RLPItem memory self) internal pure returns (Iterator memory) { require(isList(self)); uint ptr = self.memPtr + _payloadOffset(self.memPtr); return Iterator(self, ptr); } /* * @param the RLP item. */ function rlpLen(RLPItem memory item) internal pure returns (uint) { return item.len; } /* * @param the RLP item. * @return (memPtr, len) pair: location of the item's payload in memory. */ function payloadLocation(RLPItem memory item) internal pure returns (uint, uint) { uint offset = _payloadOffset(item.memPtr); uint memPtr = item.memPtr + offset; uint len = item.len - offset; // data length return (memPtr, len); } /* * @param the RLP item. */ function payloadLen(RLPItem memory item) internal pure returns (uint) { (, uint len) = payloadLocation(item); return len; } /* * @param the RLP item containing the encoded list. */ function toList(RLPItem memory item) internal pure returns (RLPItem[] memory) { require(isList(item)); uint items = numItems(item); RLPItem[] memory result = new RLPItem[](items); uint memPtr = item.memPtr + _payloadOffset(item.memPtr); uint dataLen; for (uint i = 0; i < items; i++) { dataLen = _itemLength(memPtr); result[i] = RLPItem(dataLen, memPtr); memPtr = memPtr + dataLen; } require(memPtr - item.memPtr == item.len, "Wrong total length."); return result; } // @return indicator whether encoded payload is a list. negate this function call for isData. function isList(RLPItem memory item) internal pure returns (bool) { if (item.len == 0) return false; uint8 byte0; uint memPtr = item.memPtr; assembly { byte0 := byte(0, mload(memPtr)) } if (byte0 < LIST_SHORT_START) return false; return true; } /* * @dev A cheaper version of keccak256(toRlpBytes(item)) that avoids copying memory. * @return keccak256 hash of RLP encoded bytes. */ function rlpBytesKeccak256(RLPItem memory item) internal pure returns (bytes32) { uint256 ptr = item.memPtr; uint256 len = item.len; bytes32 result; assembly { result := keccak256(ptr, len) } return result; } /* * @dev A cheaper version of keccak256(toBytes(item)) that avoids copying memory. * @return keccak256 hash of the item payload. */ function payloadKeccak256(RLPItem memory item) internal pure returns (bytes32) { (uint memPtr, uint len) = payloadLocation(item); bytes32 result; assembly { result := keccak256(memPtr, len) } return result; } /** RLPItem conversions into data types **/ // @returns raw rlp encoding in bytes function toRlpBytes(RLPItem memory item) internal pure returns (bytes memory) { bytes memory result = new bytes(item.len); if (result.length == 0) return result; uint ptr; assembly { ptr := add(0x20, result) } copy(item.memPtr, ptr, item.len); return result; } // any non-zero byte except "0x80" is considered true function toBoolean(RLPItem memory item) internal pure returns (bool) { require(item.len == 1); uint result; uint memPtr = item.memPtr; assembly { result := byte(0, mload(memPtr)) } // SEE Github Issue #5. // Summary: Most commonly used RLP libraries (i.e Geth) will encode // "0" as "0x80" instead of as "0". We handle this edge case explicitly // here. if (result == 0 || result == STRING_SHORT_START) { return false; } else { return true; } } function toAddress(RLPItem memory item) internal pure returns (address) { // 1 byte for the length prefix require(item.len == 21); return address(toUint(item)); } function toUint(RLPItem memory item) internal pure returns (uint) { require(item.len > 0 && item.len <= 33); (uint memPtr, uint len) = payloadLocation(item); uint result; assembly { result := mload(memPtr) // shfit to the correct location if neccesary if lt(len, 32) { result := div(result, exp(256, sub(32, len))) } } return result; } // enforces 32 byte length function toUintStrict(RLPItem memory item) internal pure returns (uint) { // one byte prefix require(item.len == 33); uint result; uint memPtr = item.memPtr + 1; assembly { result := mload(memPtr) } return result; } function toBytes(RLPItem memory item) internal pure returns (bytes memory) { require(item.len > 0); (uint memPtr, uint len) = payloadLocation(item); bytes memory result = new bytes(len); uint destPtr; assembly { destPtr := add(0x20, result) } copy(memPtr, destPtr, len); return result; } /* * Private Helpers */ // @return number of payload items inside an encoded list. function numItems(RLPItem memory item) private pure returns (uint) { if (item.len == 0) return 0; uint count = 0; uint currPtr = item.memPtr + _payloadOffset(item.memPtr); uint endPtr = item.memPtr + item.len; while (currPtr < endPtr) { currPtr = currPtr + _itemLength(currPtr); // skip over an item count++; } return count; } // @return entire rlp item byte length function _itemLength(uint memPtr) private pure returns (uint) { uint itemLen; uint byte0; assembly { byte0 := byte(0, mload(memPtr)) } if (byte0 < STRING_SHORT_START) itemLen = 1; else if (byte0 < STRING_LONG_START) itemLen = byte0 - STRING_SHORT_START + 1; else if (byte0 < LIST_SHORT_START) { assembly { let byteLen := sub(byte0, 0xb7) // # of bytes the actual length is memPtr := add(memPtr, 1) // skip over the first byte /* 32 byte word size */ let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to get the len itemLen := add(dataLen, add(byteLen, 1)) } } else if (byte0 < LIST_LONG_START) { itemLen = byte0 - LIST_SHORT_START + 1; } else { assembly { let byteLen := sub(byte0, 0xf7) memPtr := add(memPtr, 1) let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to the correct length itemLen := add(dataLen, add(byteLen, 1)) } } return itemLen; } // @return number of bytes until the data function _payloadOffset(uint memPtr) private pure returns (uint) { uint byte0; assembly { byte0 := byte(0, mload(memPtr)) } if (byte0 < STRING_SHORT_START) return 0; else if (byte0 < STRING_LONG_START || (byte0 >= LIST_SHORT_START && byte0 < LIST_LONG_START)) return 1; else if (byte0 < LIST_SHORT_START) // being explicit return byte0 - (STRING_LONG_START - 1) + 1; else return byte0 - (LIST_LONG_START - 1) + 1; } /* * @param src Pointer to source * @param dest Pointer to destination * @param len Amount of memory to copy from the source */ function copy(uint src, uint dest, uint len) private pure { if (len == 0) return; // copy as many word sizes as possible for (; len >= WORD_SIZE; len -= WORD_SIZE) { assembly { mstore(dest, mload(src)) } src += WORD_SIZE; dest += WORD_SIZE; } if (len > 0) { // left over bytes. Mask is used to remove unwanted bytes from the word uint mask = 256 ** (WORD_SIZE - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) // zero out src let destpart := and(mload(dest), mask) // retrieve the bytes mstore(dest, or(destpart, srcpart)) } } } } pragma solidity 0.6.6; import {RLPReader} from "../../lib/RLPReader.sol"; /// @title Token predicate interface for all pos portal predicates /// @notice Abstract interface that defines methods for custom predicates interface ITokenPredicate { /** * @notice Deposit tokens into pos portal * @dev When `depositor` deposits tokens into pos portal, tokens get locked into predicate contract. * @param depositor Address who wants to deposit tokens * @param depositReceiver Address (address) who wants to receive tokens on side chain * @param rootToken Token which gets deposited * @param depositData Extra data for deposit (amount for ERC20, token id for ERC721 etc.) [ABI encoded] */ function lockTokens( address depositor, address depositReceiver, address rootToken, bytes calldata depositData ) external; /** * @notice Validates and processes exit while withdraw process * @dev Validates exit log emitted on sidechain. Reverts if validation fails. * @dev Processes withdraw based on custom logic. Example: transfer ERC20/ERC721, mint ERC721 if mintable withdraw * @param sender unused for polygon predicates, being kept for abi compatability * @param rootToken Token which gets withdrawn * @param logRLPList Valid sidechain log for data like amount, token id etc. */ function exitTokens( address sender, address rootToken, bytes calldata logRLPList ) external; } pragma solidity 0.6.6; contract Initializable { bool inited = false; modifier initializer() { require(!inited, "already inited"); _; inited = true; } function _disableInitializer() internal { inited = true; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "../utils/EnumerableSet.sol"; import "../utils/Address.sol"; import "../GSN/Context.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context { using EnumerableSet for EnumerableSet.AddressSet; using Address for address; struct RoleData { EnumerableSet.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, _roles[role].adminRole, adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256` * (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } }