file_name
stringlengths
71
779k
comments
stringlengths
0
29.4k
code_string
stringlengths
20
7.69M
__index_level_0__
int64
2
17.2M
./full_match/100/0x4f18F577073879aD47743aCC2d222035883Cd2aA/sources/contracts/official/CFC0/CFC0Token.sol
Based on how many tokens the user had at the snapshot, pay dividends of the ERC20 token Be aware that this function will pay dividends even if the tokens are currently in possession of the offer/ cache the sender read the last payment make sure we have a next payment get the total supply at this snapshot get the total token amount for this payment calculate how much he'll receive from this lot, based on the amount of tokens he was holding send the ERC20 value to the user
function _withdrawDividends() private returns (bool) { address aSender = _msgSender(); uint256 nLastPayment = mapLastPaymentSnapshot[aSender]; if (nLastPayment >= nCurrentSnapshotId) { return false; } if (nTokenBalance != 0) { uint256 nTokenSupply = totalSupplyAt(nNextUserPayment); uint256 nTotalTokens = mapERCPayment[nNextUserPayment]; uint256 nToReceive = mulDiv( nTokenBalance, nTotalTokens, nTokenSupply ); dividendsToken.transfer(aSender, nToReceive); } return true; }
14,271,047
// SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import { CrossDomainEnabled } from "@eth-optimism/contracts/contracts/libraries/bridge/CrossDomainEnabled.sol"; import { OwnableUpgradeable } from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import { IERC721 } from "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import { Address } from "@openzeppelin/contracts/utils/Address.sol"; import { L2ERC721Bridge } from "../../L2/messaging/L2ERC721Bridge.sol"; /** * @title L1ERC721Bridge * @notice The L1 ERC721 bridge is a contract which works together with the L2 ERC721 bridge to * make it possible to transfer ERC721 tokens between Optimism and Ethereum. This contract * acts as an escrow for ERC721 tokens deposted into L2. */ contract L1ERC721Bridge is CrossDomainEnabled, OwnableUpgradeable { /** * @notice Contract version number. */ uint8 public constant VERSION = 1; /** * @notice Emitted when an ERC721 bridge to the other network is initiated. * * @param localToken Address of the token on this domain. * @param remoteToken Address of the token on the remote domain. * @param from Address that initiated bridging action. * @param to Address to receive the token. * @param tokenId ID of the specific token deposited. * @param extraData Extra data for use on the client-side. */ event ERC721BridgeInitiated( address indexed localToken, address indexed remoteToken, address indexed from, address to, uint256 tokenId, bytes extraData ); /** * @notice Emitted when an ERC721 bridge from the other network is finalized. * * @param localToken Address of the token on this domain. * @param remoteToken Address of the token on the remote domain. * @param from Address that initiated bridging action. * @param to Address to receive the token. * @param tokenId ID of the specific token deposited. * @param extraData Extra data for use on the client-side. */ event ERC721BridgeFinalized( address indexed localToken, address indexed remoteToken, address indexed from, address to, uint256 tokenId, bytes extraData ); /** * @notice Address of the bridge on the other network. */ address public otherBridge; // Maps L1 token to L2 token to token ID to a boolean indicating if the token is deposited /** * @notice Mapping of L1 token to L2 token to ID to boolean, indicating if the given L1 token * by ID was deposited for a given L2 token. */ mapping(address => mapping(address => mapping(uint256 => bool))) public deposits; /** * @param _messenger Address of the CrossDomainMessenger on this network. * @param _otherBridge Address of the ERC721 bridge on the other network. */ constructor(address _messenger, address _otherBridge) CrossDomainEnabled(address(0)) { initialize(_messenger, _otherBridge); } /** * @param _messenger Address of the CrossDomainMessenger on this network. * @param _otherBridge Address of the ERC721 bridge on the other network. */ function initialize(address _messenger, address _otherBridge) public reinitializer(VERSION) { messenger = _messenger; otherBridge = _otherBridge; // Initialize upgradable OZ contracts __Ownable_init(); } /** * @notice Initiates a bridge of an NFT to the caller's account on L2. * * @param _localToken Address of the ERC721 on this domain. * @param _remoteToken Address of the ERC721 on the remote domain. * @param _tokenId Token ID to bridge. * @param _minGasLimit Minimum gas limit for the bridge message on the other domain. * @param _extraData Optional data to forward to L2. Data supplied here will not be used to * execute any code on L2 and is only emitted as extra data for the * convenience of off-chain tooling. */ function bridgeERC721( address _localToken, address _remoteToken, uint256 _tokenId, uint32 _minGasLimit, bytes calldata _extraData ) external { // Modifier requiring sender to be EOA. This check could be bypassed by a malicious // contract via initcode, but it takes care of the user error we want to avoid. require(!Address.isContract(msg.sender), "L1ERC721Bridge: account is not externally owned"); _initiateBridgeERC721( _localToken, _remoteToken, msg.sender, msg.sender, _tokenId, _minGasLimit, _extraData ); } /** * @notice Initiates a bridge of an NFT to some recipient's account on L2. * * @param _localToken Address of the ERC721 on this domain. * @param _remoteToken Address of the ERC721 on the remote domain. * @param _to Address to receive the token on the other domain. * @param _tokenId Token ID to bridge. * @param _minGasLimit Minimum gas limit for the bridge message on the other domain. * @param _extraData Optional data to forward to L2. Data supplied here will not be used to * execute any code on L2 and is only emitted as extra data for the * convenience of off-chain tooling. */ function bridgeERC721To( address _localToken, address _remoteToken, address _to, uint256 _tokenId, uint32 _minGasLimit, bytes calldata _extraData ) external { _initiateBridgeERC721( _localToken, _remoteToken, msg.sender, _to, _tokenId, _minGasLimit, _extraData ); } /************************* * Cross-chain Functions * *************************/ /** * @notice Completes an ERC721 bridge from the other domain and sends the ERC721 token to the * recipient on this domain. * * @param _localToken Address of the ERC721 token on this domain. * @param _remoteToken Address of the ERC721 token on the other domain. * @param _from Address that triggered the bridge on the other domain. * @param _to Address to receive the token on this domain. * @param _tokenId ID of the token being deposited. * @param _extraData Optional data to forward to L2. Data supplied here will not be used to * execute any code on L2 and is only emitted as extra data for the * convenience of off-chain tooling. */ function finalizeBridgeERC721( address _localToken, address _remoteToken, address _from, address _to, uint256 _tokenId, bytes calldata _extraData ) external onlyFromCrossDomainAccount(otherBridge) { // Checks that the L1/L2 token pair has a token ID that is escrowed in the L1 Bridge require( deposits[_localToken][_remoteToken][_tokenId] == true, "Token ID is not escrowed in the L1 Bridge" ); deposits[_localToken][_remoteToken][_tokenId] = false; // When a withdrawal is finalized on L1, the L1 Bridge transfers the NFT to the withdrawer // slither-disable-next-line reentrancy-events IERC721(_localToken).transferFrom(address(this), _to, _tokenId); // slither-disable-next-line reentrancy-events emit ERC721BridgeFinalized(_localToken, _remoteToken, _from, _to, _tokenId, _extraData); } /** * @notice Internal function for initiating a token bridge to the other domain. * * @param _localToken Address of the ERC721 on this domain. * @param _remoteToken Address of the ERC721 on the remote domain. * @param _from Address of the sender on this domain. * @param _to Address to receive the token on the other domain. * @param _tokenId Token ID to bridge. * @param _minGasLimit Minimum gas limit for the bridge message on the other domain. * @param _extraData Optional data to forward to L2. Data supplied here will not be used to * execute any code on L2 and is only emitted as extra data for the * convenience of off-chain tooling. */ function _initiateBridgeERC721( address _localToken, address _remoteToken, address _from, address _to, uint256 _tokenId, uint32 _minGasLimit, bytes calldata _extraData ) internal { // Construct calldata for _l2Token.finalizeBridgeERC721(_to, _tokenId) bytes memory message = abi.encodeWithSelector( L2ERC721Bridge.finalizeBridgeERC721.selector, _remoteToken, _localToken, _from, _to, _tokenId, _extraData ); // Lock token into bridge deposits[_localToken][_remoteToken][_tokenId] = true; IERC721(_localToken).transferFrom(_from, address(this), _tokenId); // Send calldata into L2 sendCrossDomainMessage(otherBridge, _minGasLimit, message); emit ERC721BridgeInitiated(_localToken, _remoteToken, _from, _to, _tokenId, _extraData); } }
Initiates a bridge of an NFT to the caller's account on L2. _localToken Address of the ERC721 on this domain. _remoteToken Address of the ERC721 on the remote domain. _tokenId Token ID to bridge. _minGasLimit Minimum gas limit for the bridge message on the other domain. _extraData Optional data to forward to L2. Data supplied here will not be used to execute any code on L2 and is only emitted as extra data for the convenience of off-chain tooling./ Modifier requiring sender to be EOA. This check could be bypassed by a malicious contract via initcode, but it takes care of the user error we want to avoid.
function bridgeERC721( address _localToken, address _remoteToken, uint256 _tokenId, uint32 _minGasLimit, bytes calldata _extraData ) external { require(!Address.isContract(msg.sender), "L1ERC721Bridge: account is not externally owned"); _initiateBridgeERC721( _localToken, _remoteToken, msg.sender, msg.sender, _tokenId, _minGasLimit, _extraData ); }
12,545,679
./full_match/1/0xA0d89D6848878463eeAbBa91C262DCbC2D06B314/sources/EthSwap.sol
Calculate the number of tokens to buy Require that EthSwap has enough tokens Transfer tokens to the user Emit on event
function buyTokens() public payable { uint tokenAmount = msg.value * rate; require(token.balanceOf(address(this)) >= tokenAmount); token.transfer(msg.sender, tokenAmount); emit TokenPurchased(msg.sender, address(token), tokenAmount, rate); }
4,953,500
pragma solidity >=0.4.22 <0.6.0; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "./Utils.sol"; /// @title Broken BTC Relay contract. FIX ME!!! /// @notice For simplicity, this example assumes: /// (i) constant difficulty /// (ii) no forks occur contract BrokenRelay { using SafeMath for uint256; using Utils for bytes; using Utils for bytes32; struct Header { uint256 blockHeight; // height of this block header bytes32 merkleRoot; // transaction Merkle tree root } // mapping of block hashes to block headers (ALL ever submitted, i.e., incl. forks) mapping(bytes32 => Header) public _headers; // mapping of block heights to block hashes of the MAIN CHAIN mapping(uint256 => bytes32) public _mainChain; // block with the most accumulated work, i.e., blockchain tip bytes32 public _heaviestBlock; uint256 public _heaviestHeight; // CONSTANTS /* * Bitcoin difficulty constants */ uint256 public constant DIFFICULTY_ADJUSTMENT_INVETVAL = 2016; uint256 public constant DIFF_TARGET = 0xffff0000000000000000000000000000000000000000000000000000; uint256 public constant TARGET_TIMESPAN = 14 * 24 * 60 * 60; // 2 weeks uint256 public constant UNROUNDED_MAX_TARGET = 2**224 - 1; uint256 public constant TARGET_TIMESPAN_DIV_4 = TARGET_TIMESPAN / 4; // store division as constant to save costs uint256 public constant TARGET_TIMESPAN_MUL_4 = TARGET_TIMESPAN * 4; // store multiplucation as constant to save costs // EVENTS /* * @param blockHash block header hash of block header submitted for storage * @param blockHeight blockHeight */ event StoreHeader(bytes32 indexed blockHash, uint256 indexed blockHeight); /* * @param txid block header hash of block header submitted for storage */ event VerityTransaction(bytes32 indexed txid, uint256 indexed blockHeight); // EXCEPTION MESSAGES // TODO: Use these error messages for the testcases! string ERR_GENESIS_ALREADY_SET = "Initial parent has already been set"; string ERR_INVALID_HEADER_FORMAT = "Invalid block header"; string ERR_DUPLICATE_BLOCK_SUBMISSION = "Block already stored"; string ERR_PREV_BLOCK_NOT_FOUND = "Previous block hash not found"; string ERR_DIFF_TARGET_HEADER = "PoW hash does not meet difficulty target of header"; string ERR_INVALID_TXID = "Invalid transaction identifier"; string ERR_CONFIRMS = "Transaction has less confirmations than requested"; string ERR_MERKLE_PROOF = "Invalid Merkle Proof structure"; string ERR_VERIFY_TX = "Incorrect Merkle Proof!"; string ERR_NOT_MAIN_CHAIN = "Main chain submission indicated, but submitted block is on a fork"; string ERR_BLOCK_NOT_FOUND = "Requested block not found in storage"; /** * @notice Initializes the relay with the provided block, i.e., defines the first block of the stored chain * @param blockHeaderBytes - 80 bytes raw Bitcoin block headers * @param blockHeight - blockHeight of genesis block */ function setInitialParent( bytes memory blockHeaderBytes, uint32 blockHeight ) public { // TESTCASE 1: Do we allow users to reset the relay with a new genesis block at will?? // TODO: add check! bytes32 blockHeaderHash = blockHashFromHeader(blockHeaderBytes); _heaviestBlock = blockHeaderHash; _heaviestHeight = blockHeight; _headers[blockHeaderHash].merkleRoot = getMerkleRootFromHeader(blockHeaderBytes); _headers[blockHeaderHash].blockHeight = blockHeight; emit StoreHeader(blockHeaderHash, blockHeight); } /** * @notice Parses, validates and stores Bitcoin block header1 to mapping * @param blockHeaderBytes Raw Bitcoin block header bytes (80 bytes) * @return bytes32 Bitcoin-like double sha256 hash of submitted block */ function submitBlockHeader(bytes memory blockHeaderBytes) public returns (bytes32) { // TESTCASE 3a, 3b: block header is provided by the user. What could go wrong??? // TODO: add check! // Extract prev and cacl. current block header hashes bytes32 hashPrevBlock = getPrevBlockHashFromHeader(blockHeaderBytes); bytes32 hashCurrentBlock = blockHashFromHeader(blockHeaderBytes); // TESTCASE 2: Maybe we should not allow duplicate submissions? // TODO: add check! // Note: merkleRoot field is always set if a block is stored // TESTCASE 4: Shall we make sure we are building a chain and not storing random blocks? // TODO: add check! // Note: merkleRoot field is always set if a block is stored uint256 target = getTargetFromHeader(blockHeaderBytes); // TESTCASE 5: Did the miner do the work? // TODO: check! // NOTE: for simplicity, we do not check retargetting here. // That is, we assume constant difficulty in this example! // A fully functional relay must check retarget! // Calc. blockheight uint256 blockHeight = 1 + _headers[hashPrevBlock].blockHeight; // Check that the submitted block is extending the main chain require(blockHeight > _heaviestHeight, ERR_NOT_MAIN_CHAIN); // Update stored heaviest block and height _heaviestBlock = hashCurrentBlock; _heaviestHeight = blockHeight; // Write block header to storage bytes32 merkleRoot = getMerkleRootFromHeader(blockHeaderBytes); _headers[hashCurrentBlock].merkleRoot = merkleRoot; _headers[hashCurrentBlock].blockHeight = blockHeight; // Update main chain reference _mainChain[blockHeight] = hashCurrentBlock; emit StoreHeader(hashCurrentBlock, blockHeight); } /** * @notice Verifies that a transaction is included in a block at a given blockheight * @param txid transaction identifier * @param txBlockHeight block height at which transacton is supposedly included * @param txIndex index of transaction in the block's tx merkle tree * @param merkleProof merkle tree path (concatenated LE sha256 hashes) * @return True if txid is at the claimed position in the block at the given blockheight, False otherwise */ function verifyTx( bytes32 txid, uint256 txBlockHeight, uint256 txIndex, bytes32[] memory merkleProof, uint256 confirmations) public returns(bool) { // TESTCASE 6: txid is provided by the user. What could go wrong? // TODO: add check! // TESTCASE 7: What must the first hash of the Merkle path be? // How can we be sure we are verifying the proof for the correct transaction? // TODO: add check! // Note: use XXX.flip32Bytes() to convert between BRE and LE! // TESTCASE 8: Are we sure this transaction is "securely" included? // TODO: add check! bytes32 blockHeaderHash = _mainChain[txBlockHeight]; bytes32 merkleRoot = _headers[blockHeaderHash].merkleRoot; // Compute merkle tree root and check if it matches the specified block's merkle tree root bytes32 calcRoot = computeMerkle(txIndex, merkleProof); require(calcRoot == merkleRoot, ERR_VERIFY_TX); emit VerityTransaction(txid, txBlockHeight); return true; } // HELPER FUNCTIONS /** * @notice Reconstructs merkle tree root given a transaction hash, index in block and merkle tree path * @param txIndex index of transaction given by hash in the corresponding block's merkle tree * @param merkleProof merkle tree path to transaction hash from block's merkle tree root * @return merkle tree root of the block containing the transaction, meaningless hash otherwise */ function computeMerkle( uint256 txIndex, bytes32[] memory merkleProof) public pure returns(bytes32) { bytes32 resultHash = merkleProof[0]; uint256 txIndexTemp = txIndex; for(uint i = 1; i < merkleProof.length; i++) { if(txIndexTemp % 2 == 1){ resultHash = concatSHA256Hash(merkleProof[i], resultHash); } else { resultHash = concatSHA256Hash(resultHash, merkleProof[i]); } txIndexTemp.div(2); } return resultHash; } /** * @notice Computes the Bitcoin double sha256 block hash for a given block header */ function blockHashFromHeader(bytes memory blockHeaderBytes) public pure returns (bytes32){ return dblSha(blockHeaderBytes).flipBytes().toBytes32(); } /** * @notice Concatenates and re-hashes two SHA256 hashes * @param left left side of the concatenation * @param right right side of the concatenation * @return sha256 hash of the concatenation of left and right */ function concatSHA256Hash(bytes32 left, bytes32 right) public pure returns (bytes32) { return dblSha(abi.encodePacked(left).concat(abi.encodePacked(right))).toBytes32(); } /** * @notice Performs Bitcoin-like double sha256 hash calculation * @param data Bytes to be flipped and double hashed s * @return Bitcoin-like double sha256 hash of parsed data */ function dblSha(bytes memory data) public pure returns (bytes memory){ return abi.encodePacked(sha256(abi.encodePacked(sha256(data)))); } /** * @notice Calculates the PoW difficulty target from compressed nBits representation, * according to https://bitcoin.org/en/developer-reference#target-nbits * @param nBits Compressed PoW target representation * @return PoW difficulty target computed from nBits */ function nBitsToTarget(uint256 nBits) private pure returns (uint256){ uint256 exp = uint256(nBits) >> 24; uint256 c = uint256(nBits) & 0xffffff; uint256 target = uint256((c * 2**(8*(exp - 3)))); return target; } // GETTERS function getMerkleRootFromHeader(bytes memory blockHeaderBytes) public pure returns(bytes32){ return blockHeaderBytes.slice(36,32).toBytes32(); } function getTargetFromHeader(bytes memory blockHeaderBytes) public pure returns(uint256){ return nBitsToTarget(getNBitsFromHeader(blockHeaderBytes)); } function getNBitsFromHeader(bytes memory blockHeaderBytes) public pure returns(uint256){ return blockHeaderBytes.slice(72, 4).flipBytes().bytesToUint(); } function getPrevBlockHashFromHeader(bytes memory blockHeaderBytes) public pure returns(bytes32){ return blockHeaderBytes.slice(4, 32).flipBytes().toBytes32(); } // https://en.bitcoin.it/wiki/Difficulty function getDifficulty(uint256 target) public pure returns(uint256){ return DIFF_TARGET.div(target); } function getBlockHeader(bytes32 blockHeaderHash) public view returns( uint256 blockHeight, bytes32 merkleRoot ){ require(_headers[blockHeaderHash].merkleRoot != bytes32(0x0), ERR_BLOCK_NOT_FOUND); blockHeight = _headers[blockHeaderHash].blockHeight; merkleRoot = _headers[blockHeaderHash].merkleRoot; return(blockHeight, merkleRoot); } }
Performs Bitcoin-like double sha256 hash calculation data Bytes to be flipped and double hashed s return Bitcoin-like double sha256 hash of parsed data/
function dblSha(bytes memory data) public pure returns (bytes memory){ return abi.encodePacked(sha256(abi.encodePacked(sha256(data)))); }
7,224,699
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/utils/Context.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/utils/introspection/ERC165.sol"; import "./IERC721LibBeforeTokenTransferHook.sol"; /* Functionality used to whitelist OpenSea trading address, if desired */ contract OwnableDelegateProxy {} contract ProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; } /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, the Enumerable extension, and Pausable. * * Closely based on and mirrors the excellent https://openzeppelin.com/contracts/. */ library ERC721Lib { using Address for address; using Strings for uint256; /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); struct ERC721Storage { // Token name string _name; // Token symbol string _symbol; // Mapping from token ID to owner address mapping (uint256 => address) _owners; // Mapping owner address to token count mapping (address => uint256) _balances; // Mapping from token ID to approved address mapping (uint256 => address) _tokenApprovals; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) _operatorApprovals; // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) _allTokensIndex; // Base URI string _baseURI; // True if token transfers are paused bool _paused; // Hook function that can be called before token is transferred, along with a pointer to its storage struct IERC721LibBeforeTokenTransferHook _beforeTokenTransferHookInterface; bytes32 _beforeTokenTransferHookStorageSlot; address proxyRegistryAddress; } function init(ERC721Storage storage s, string memory _name, string memory _symbol) external { s._name = _name; s._symbol = _symbol; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) external pure returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || interfaceId == type(IERC721Enumerable).interfaceId; } // // Start of ERC721 functions // /** * @dev See {IERC721-balanceOf}. */ function _balanceOf(ERC721Storage storage s, address owner) internal view returns (uint256) { require(owner != address(0), "Balance query for address zero"); return s._balances[owner]; } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(ERC721Storage storage s, address owner) external view returns (uint256) { return _balanceOf(s, owner); } /** * @dev See {IERC721-ownerOf}. */ function _ownerOf(ERC721Storage storage s, uint256 tokenId) internal view returns (address) { address owner = s._owners[tokenId]; require(owner != address(0), "Owner query for nonexist. token"); return owner; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(ERC721Storage storage s, uint256 tokenId) external view returns (address) { return _ownerOf(s, tokenId); } /** * @dev See {IERC721Metadata-name}. */ function name(ERC721Storage storage s) external view returns (string memory) { return s._name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol(ERC721Storage storage s) external view returns (string memory) { return s._symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(ERC721Storage storage s, uint256 tokenId) external view returns (string memory) { require(_exists(s, tokenId), "URI query for nonexistent token"); return bytes(s._baseURI).length > 0 ? string(abi.encodePacked(s._baseURI, tokenId.toString())) : ""; } /** * @dev Set base URI */ function setBaseURI(ERC721Storage storage s, string memory baseTokenURI) external { s._baseURI = baseTokenURI; } /** * @dev See {IERC721-approve}. */ function approve(ERC721Storage storage s, address to, uint256 tokenId) external { address owner = _ownerOf(s, tokenId); require(to != owner, "Approval to current owner"); require(msg.sender == owner || _isApprovedForAll(s, owner, msg.sender), "Not owner nor approved for all" ); _approve(s, to, tokenId); } /** * @dev Approve independently of who's the owner * * Obviously expose with care... */ function overrideApprove(ERC721Storage storage s, address to, uint256 tokenId) external { _approve(s, to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function _getApproved(ERC721Storage storage s, uint256 tokenId) internal view returns (address) { require(_exists(s, tokenId), "Approved query nonexist. token"); return s._tokenApprovals[tokenId]; } /** * @dev See {IERC721-getApproved}. */ function getApproved(ERC721Storage storage s, uint256 tokenId) external view returns (address) { return _getApproved(s, tokenId); } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(ERC721Storage storage s, address operator, bool approved) external { require(operator != msg.sender, "Attempted approve to caller"); s._operatorApprovals[msg.sender][operator] = approved; emit ApprovalForAll(msg.sender, operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function _isApprovedForAll(ERC721Storage storage s, address owner, address operator) internal view returns (bool) { // Whitelist OpenSea proxy contract for easy trading - if we have a valid proxy registry address on file if (s.proxyRegistryAddress != address(0)) { ProxyRegistry proxyRegistry = ProxyRegistry(s.proxyRegistryAddress); if (address(proxyRegistry.proxies(owner)) == operator) { return true; } } return s._operatorApprovals[owner][operator]; } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(ERC721Storage storage s, address owner, address operator) external view returns (bool) { return _isApprovedForAll(s, owner, operator); } /** * @dev See {IERC721-transferFrom}. */ function transferFrom(ERC721Storage storage s, address from, address to, uint256 tokenId) external { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(s, msg.sender, tokenId), "TransferFrom not owner/approved"); _transfer(s, from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(ERC721Storage storage s, address from, address to, uint256 tokenId) external { _safeTransferFrom(s, from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function _safeTransferFrom(ERC721Storage storage s, address from, address to, uint256 tokenId, bytes memory _data) internal { require(_isApprovedOrOwner(s, msg.sender, tokenId), "TransferFrom not owner/approved"); _safeTransfer(s, from, to, tokenId, _data); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(ERC721Storage storage s, address from, address to, uint256 tokenId, bytes memory _data) external { _safeTransferFrom(s, from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer(ERC721Storage storage s, address from, address to, uint256 tokenId, bytes memory _data) internal { _transfer(s, from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "Transfer to non ERC721Receiver"); } /** * @dev directSafeTransfer * * CAREFUL, this does not verify the previous ownership - only use if ownership/eligibility has been asserted by other means */ function directSafeTransfer(ERC721Storage storage s, address from, address to, uint256 tokenId, bytes memory _data) external { _safeTransfer(s, from, to, tokenId, _data); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(ERC721Storage storage s, uint256 tokenId) internal view returns (bool) { return s._owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(ERC721Storage storage s, address spender, uint256 tokenId) internal view returns (bool) { require(_exists(s, tokenId), "Operator query nonexist. token"); address owner = _ownerOf(s, tokenId); return (spender == owner || _getApproved(s, tokenId) == spender || _isApprovedForAll(s, owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(ERC721Storage storage s, address to, uint256 tokenId) internal { _safeMint(s, to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint(ERC721Storage storage s, address to, uint256 tokenId, bytes memory _data) internal { _unsafeMint(s, to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "Transfer to non ERC721Receiver"); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _unsafeMint(ERC721Storage storage s, address to, uint256 tokenId) internal { require(to != address(0), "Mint to the zero address"); require(!_exists(s, tokenId), "Token already minted"); _beforeTokenTransfer(s, address(0), to, tokenId); s._balances[to] += 1; s._owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(ERC721Storage storage s, uint256 tokenId) internal { address owner = _ownerOf(s, tokenId); _beforeTokenTransfer(s, owner, address(0), tokenId); // Clear approvals _approve(s, address(0), tokenId); s._balances[owner] -= 1; delete s._owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer(ERC721Storage storage s, address from, address to, uint256 tokenId) internal { require(_ownerOf(s, tokenId) == from, "TransferFrom not owner/approved"); require(to != address(0), "Transfer to the zero address"); _beforeTokenTransfer(s, from, to, tokenId); // Clear approvals from the previous owner _approve(s, address(0), tokenId); s._balances[from] -= 1; s._balances[to] += 1; s._owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(ERC721Storage storage s, address to, uint256 tokenId) internal { s._tokenApprovals[tokenId] = to; emit Approval(_ownerOf(s, tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(msg.sender, from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("Transfer to non ERC721Receiver"); } else { // solhint-disable-next-line no-inline-assembly assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } // // Start of functions from ERC721Enumerable // /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(ERC721Storage storage s, address owner, uint256 index) external view returns (uint256) { require(index < _balanceOf(s, owner), "Owner index out of bounds"); return s._ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function _totalSupply(ERC721Storage storage s) internal view returns (uint256) { return s._allTokens.length; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply(ERC721Storage storage s) external view returns (uint256) { return s._allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(ERC721Storage storage s, uint256 index) external view returns (uint256) { require(index < _totalSupply(s), "Global index out of bounds"); return s._allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(ERC721Storage storage s, address from, address to, uint256 tokenId) internal { if(address(s._beforeTokenTransferHookInterface) != address(0)) { // We have a hook that we need to delegate call (bool success, ) = address(s._beforeTokenTransferHookInterface).delegatecall( abi.encodeWithSelector(s._beforeTokenTransferHookInterface._beforeTokenTransferHook.selector, s._beforeTokenTransferHookStorageSlot, from, to, tokenId) ); if(!success) { // Bubble up the revert message assembly { let ptr := mload(0x40) let size := returndatasize() returndatacopy(ptr, 0, size) revert(ptr, size) } } } require(!_paused(s), "No token transfer while paused"); if (from == address(0)) { _addTokenToAllTokensEnumeration(s, tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(s, from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(s, tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(s, to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(ERC721Storage storage s, address to, uint256 tokenId) private { uint256 length = _balanceOf(s, to); s._ownedTokens[to][length] = tokenId; s._ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(ERC721Storage storage s, uint256 tokenId) private { s._allTokensIndex[tokenId] = s._allTokens.length; s._allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(ERC721Storage storage s, address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _balanceOf(s, from) - 1; uint256 tokenIndex = s._ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = s._ownedTokens[from][lastTokenIndex]; s._ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token s._ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete s._ownedTokensIndex[tokenId]; delete s._ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(ERC721Storage storage s, uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = s._allTokens.length - 1; uint256 tokenIndex = s._allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = s._allTokens[lastTokenIndex]; s._allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token s._allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete s._allTokensIndex[tokenId]; s._allTokens.pop(); } // // Start of functions from Pausable // /** * @dev Returns true if the contract is paused, and false otherwise. */ function _paused(ERC721Storage storage s) internal view returns (bool) { return s._paused; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused(ERC721Storage storage s) external view returns (bool) { return s._paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused(ERC721Storage storage s) { require(!_paused(s), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused(ERC721Storage storage s) { require(_paused(s), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause(ERC721Storage storage s) external whenNotPaused(s) { s._paused = true; emit Paused(msg.sender); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause(ERC721Storage storage s) external whenPaused(s) { s._paused = false; emit Unpaused(msg.sender); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant alphabet = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = alphabet[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./ERC721Lib.sol"; /** * @dev Interface that can be used to hook additional beforeTokenTransfer functions into ERC721Lib */ interface IERC721LibBeforeTokenTransferHook { /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransferHook(bytes32 storagePosition, address from, address to, uint256 tokenId) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); }
See {IERC721-safeTransferFrom}./
function safeTransferFrom(ERC721Storage storage s, address from, address to, uint256 tokenId, bytes memory _data) external { _safeTransferFrom(s, from, to, tokenId, _data); }
6,935,783
./partial_match/4/0x4B65B6EDBaCDCDCF5785813a42fA8F4062a9AaF1/sources/CandyMasterFarmer.sol
Update Liquidityaddr
function lpUpdate(address _newLP) public onlyAuthorized { liquidityaddr = _newLP; }
8,508,618
// SPDX-License-Identifier: MIT pragma solidity =0.7.6; pragma abicoder v2; import "./interfaces.sol"; import "./helpers.sol"; contract Resolver is Helpers { /** * @dev Sort token address * @param _token0: token0 Address * @param _token1: token1 Address */ function sort(address _token0, address _token1) external view returns (address token0, address token1) { if (_token0 < _token1) { token0 = _token1; token1 = _token0; } else { token0 = _token0; token1 = _token1; } } function getPositionInfoByTokenId(uint256 tokenId) public view returns (PositionInfo memory pInfo) { (pInfo) = positions(tokenId); } function getPositionsInfo(address user) public view returns (uint256[] memory tokenIds, PositionInfo[] memory positionsInfo) { tokenIds = userNfts(user); for (uint256 i = 0; i < tokenIds.length; i++) { uint256 tokenId = tokenIds[i]; (positionsInfo[i]) = positions(tokenId); } } function getDepositAmount( uint256 tokenId, uint256 amountA, uint256 amountB ) public view returns ( uint256 liquidity, uint256 amount0, uint256 amount1 ) { (liquidity, amount0, amount1) = depositAmount(tokenId, amountA, amountB); } function getSigleDepositAmount( uint256 tokenId, address tokenA, uint256 amountA ) public view returns ( address, uint256, address, uint256 ) { (address tokenB, uint256 amountB) = singleDepositAmount(tokenId, tokenA, amountA); return (tokenA, amountA, tokenB, amountB); } function getWithdrawAmount(uint256 tokenId, uint128 liquidity) public view returns (uint256 amountA, uint256 amountB) { (amountA, amountB) = withdrawAmount(tokenId, liquidity); } function getCollectAmount(uint256 tokenId) public view returns (uint256 amountA, uint256 amountB) { (amountA, amountB) = collectInfo(tokenId); } function getUserNFTs(address user) public view returns (uint256[] memory tokenIds) { tokenIds = userNfts(user); } } contract InstaUniswapV3Resolver is Resolver { string public constant name = "UniswapV3-Resolver-v1"; } pragma solidity =0.7.6; pragma abicoder v2; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721Metadata.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721Enumerable.sol"; interface TokenInterface { function approve(address, uint256) external; function transfer(address, uint256) external; function transferFrom( address, address, uint256 ) external; function deposit() external payable; function withdraw(uint256) external; function balanceOf(address) external view returns (uint256); function decimals() external view returns (uint256); function totalSupply() external view returns (uint256); } /// @title Callback for IUniswapV3PoolActions#swap /// @notice Any contract that calls IUniswapV3PoolActions#swap must implement this interface interface IUniswapV3SwapCallback { /// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap. /// @dev In the implementation you must pay the pool tokens owed for the swap. /// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory. /// amount0Delta and amount1Delta can both be 0 if no tokens were swapped. /// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by /// the end of the swap. If positive, the callback must send that amount of token0 to the pool. /// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by /// the end of the swap. If positive, the callback must send that amount of token1 to the pool. /// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call function uniswapV3SwapCallback( int256 amount0Delta, int256 amount1Delta, bytes calldata data ) external; } interface ISwapRouter is IUniswapV3SwapCallback { struct ExactInputSingleParams { address tokenIn; address tokenOut; uint24 fee; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; uint160 sqrtPriceLimitX96; } /// @notice Swaps `amountIn` of one token for as much as possible of another token /// @param params The parameters necessary for the swap, encoded as `ExactInputSingleParams` in calldata /// @return amountOut The amount of the received token function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut); struct ExactInputParams { bytes path; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; } /// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata /// @return amountOut The amount of the received token function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut); struct ExactOutputSingleParams { address tokenIn; address tokenOut; uint24 fee; address recipient; uint256 deadline; uint256 amountOut; uint256 amountInMaximum; uint160 sqrtPriceLimitX96; } /// @notice Swaps as little as possible of one token for `amountOut` of another token /// @param params The parameters necessary for the swap, encoded as `ExactOutputSingleParams` in calldata /// @return amountIn The amount of the input token function exactOutputSingle(ExactOutputSingleParams calldata params) external payable returns (uint256 amountIn); struct ExactOutputParams { bytes path; address recipient; uint256 deadline; uint256 amountOut; uint256 amountInMaximum; } /// @notice Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed) /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata /// @return amountIn The amount of the input token function exactOutput(ExactOutputParams calldata params) external payable returns (uint256 amountIn); } /// @title Creates and initializes V3 Pools /// @notice Provides a method for creating and initializing a pool, if necessary, for bundling with other methods that /// require the pool to exist. interface IPoolInitializer { /// @notice Creates a new pool if it does not exist, then initializes if not initialized /// @dev This method can be bundled with others via IMulticall for the first action (e.g. mint) performed against a pool /// @param token0 The contract address of token0 of the pool /// @param token1 The contract address of token1 of the pool /// @param fee The fee amount of the v3 pool for the specified token pair /// @param sqrtPriceX96 The initial square root price of the pool as a Q64.96 value /// @return pool Returns the pool address based on the pair of tokens and fee, will return the newly created pool address if necessary function createAndInitializePoolIfNecessary( address token0, address token1, uint24 fee, uint160 sqrtPriceX96 ) external payable returns (address pool); } /// @title Immutable state /// @notice Functions that return immutable state of the router interface IPeripheryImmutableState { /// @return Returns the address of the Uniswap V3 factory function factory() external view returns (address); /// @return Returns the address of WETH9 function WETH9() external view returns (address); } /// @title Periphery Payments /// @notice Functions to ease deposits and withdrawals of ETH interface IPeripheryPayments { /// @notice Unwraps the contract's WETH9 balance and sends it to recipient as ETH. /// @dev The amountMinimum parameter prevents malicious contracts from stealing WETH9 from users. /// @param amountMinimum The minimum amount of WETH9 to unwrap /// @param recipient The address receiving ETH function unwrapWETH9(uint256 amountMinimum, address recipient) external payable; /// @notice Refunds any ETH balance held by this contract to the `msg.sender` /// @dev Useful for bundling with mint or increase liquidity that uses ether, or exact output swaps /// that use ether for the input amount function refundETH() external payable; /// @notice Transfers the full amount of a token held by this contract to recipient /// @dev The amountMinimum parameter prevents malicious contracts from stealing the token from users /// @param token The contract address of the token which will be transferred to `recipient` /// @param amountMinimum The minimum amount of token required for a transfer /// @param recipient The destination address of the token function sweepToken( address token, uint256 amountMinimum, address recipient ) external payable; } /// @title ERC721 with permit /// @notice Extension to ERC721 that includes a permit function for signature based approvals interface IERC721Permit is IERC721 { /// @notice The permit typehash used in the permit signature /// @return The typehash for the permit function PERMIT_TYPEHASH() external pure returns (bytes32); /// @notice The domain separator used in the permit signature /// @return The domain seperator used in encoding of permit signature function DOMAIN_SEPARATOR() external view returns (bytes32); /// @notice Approve of a specific token ID for spending by spender via signature /// @param spender The account that is being approved /// @param tokenId The ID of the token that is being approved for spending /// @param deadline The deadline timestamp by which the call must be mined for the approve to work /// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s` /// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s` /// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v` function permit( address spender, uint256 tokenId, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external payable; } /// @title Non-fungible token for positions /// @notice Wraps Uniswap V3 positions in a non-fungible token interface which allows for them to be transferred /// and authorized. interface INonfungiblePositionManager is IPoolInitializer, IPeripheryPayments, IPeripheryImmutableState, IERC721Metadata, IERC721Enumerable, IERC721Permit { /// @notice Emitted when liquidity is increased for a position NFT /// @dev Also emitted when a token is minted /// @param tokenId The ID of the token for which liquidity was increased /// @param liquidity The amount by which liquidity for the NFT position was increased /// @param amount0 The amount of token0 that was paid for the increase in liquidity /// @param amount1 The amount of token1 that was paid for the increase in liquidity event IncreaseLiquidity(uint256 indexed tokenId, uint128 liquidity, uint256 amount0, uint256 amount1); /// @notice Emitted when liquidity is decreased for a position NFT /// @param tokenId The ID of the token for which liquidity was decreased /// @param liquidity The amount by which liquidity for the NFT position was decreased /// @param amount0 The amount of token0 that was accounted for the decrease in liquidity /// @param amount1 The amount of token1 that was accounted for the decrease in liquidity event DecreaseLiquidity(uint256 indexed tokenId, uint128 liquidity, uint256 amount0, uint256 amount1); /// @notice Emitted when tokens are collected for a position NFT /// @dev The amounts reported may not be exactly equivalent to the amounts transferred, due to rounding behavior /// @param tokenId The ID of the token for which underlying tokens were collected /// @param recipient The address of the account that received the collected tokens /// @param amount0 The amount of token0 owed to the position that was collected /// @param amount1 The amount of token1 owed to the position that was collected event Collect(uint256 indexed tokenId, address recipient, uint256 amount0, uint256 amount1); /// @notice Returns the position information associated with a given token ID. /// @dev Throws if the token ID is not valid. /// @param tokenId The ID of the token that represents the position /// @return nonce The nonce for permits /// @return operator The address that is approved for spending /// @return token0 The address of the token0 for a specific pool /// @return token1 The address of the token1 for a specific pool /// @return fee The fee associated with the pool /// @return tickLower The lower end of the tick range for the position /// @return tickUpper The higher end of the tick range for the position /// @return liquidity The liquidity of the position /// @return feeGrowthInside0LastX128 The fee growth of token0 as of the last action on the individual position /// @return feeGrowthInside1LastX128 The fee growth of token1 as of the last action on the individual position /// @return tokensOwed0 The uncollected amount of token0 owed to the position as of the last computation /// @return tokensOwed1 The uncollected amount of token1 owed to the position as of the last computation function positions(uint256 tokenId) external view returns ( uint96 nonce, address operator, address token0, address token1, uint24 fee, int24 tickLower, int24 tickUpper, uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1 ); struct MintParams { address token0; address token1; uint24 fee; int24 tickLower; int24 tickUpper; uint256 amount0Desired; uint256 amount1Desired; uint256 amount0Min; uint256 amount1Min; address recipient; uint256 deadline; } /// @notice Creates a new position wrapped in a NFT /// @dev Call this when the pool does exist and is initialized. Note that if the pool is created but not initialized /// a method does not exist, i.e. the pool is assumed to be initialized. /// @param params The params necessary to mint a position, encoded as `MintParams` in calldata /// @return tokenId The ID of the token that represents the minted position /// @return liquidity The amount of liquidity for this position /// @return amount0 The amount of token0 /// @return amount1 The amount of token1 function mint(MintParams calldata params) external payable returns ( uint256 tokenId, uint128 liquidity, uint256 amount0, uint256 amount1 ); struct IncreaseLiquidityParams { uint256 tokenId; uint256 amount0Desired; uint256 amount1Desired; uint256 amount0Min; uint256 amount1Min; uint256 deadline; } /// @notice Increases the amount of liquidity in a position, with tokens paid by the `msg.sender` /// @param params tokenId The ID of the token for which liquidity is being increased, /// amount0Desired The desired amount of token0 to be spent, /// amount1Desired The desired amount of token1 to be spent, /// amount0Min The minimum amount of token0 to spend, which serves as a slippage check, /// amount1Min The minimum amount of token1 to spend, which serves as a slippage check, /// deadline The time by which the transaction must be included to effect the change /// @return liquidity The new liquidity amount as a result of the increase /// @return amount0 The amount of token0 to acheive resulting liquidity /// @return amount1 The amount of token1 to acheive resulting liquidity function increaseLiquidity(IncreaseLiquidityParams calldata params) external payable returns ( uint128 liquidity, uint256 amount0, uint256 amount1 ); struct DecreaseLiquidityParams { uint256 tokenId; uint128 liquidity; uint256 amount0Min; uint256 amount1Min; uint256 deadline; } /// @notice Decreases the amount of liquidity in a position and accounts it to the position /// @param params tokenId The ID of the token for which liquidity is being decreased, /// amount The amount by which liquidity will be decreased, /// amount0Min The minimum amount of token0 that should be accounted for the burned liquidity, /// amount1Min The minimum amount of token1 that should be accounted for the burned liquidity, /// deadline The time by which the transaction must be included to effect the change /// @return amount0 The amount of token0 accounted to the position's tokens owed /// @return amount1 The amount of token1 accounted to the position's tokens owed function decreaseLiquidity(DecreaseLiquidityParams calldata params) external payable returns (uint256 amount0, uint256 amount1); struct CollectParams { uint256 tokenId; address recipient; uint128 amount0Max; uint128 amount1Max; } /// @notice Collects up to a maximum amount of fees owed to a specific position to the recipient /// @param params tokenId The ID of the NFT for which tokens are being collected, /// recipient The account that should receive the tokens, /// amount0Max The maximum amount of token0 to collect, /// amount1Max The maximum amount of token1 to collect /// @return amount0 The amount of fees collected in token0 /// @return amount1 The amount of fees collected in token1 function collect(CollectParams calldata params) external payable returns (uint256 amount0, uint256 amount1); /// @notice Burns a token ID, which deletes it from the NFT contract. The token must have 0 liquidity and all tokens /// must be collected first. /// @param tokenId The ID of the token that is being burned function burn(uint256 tokenId) external payable; } pragma solidity 0.7.6; pragma abicoder v2; import { DSMath } from "../../utils/dsmath.sol"; import "./contracts/interfaces/IUniswapV3Pool.sol"; import "./contracts/libraries/TickMath.sol"; import "./contracts/libraries/FullMath.sol"; import "./contracts/libraries/FixedPoint128.sol"; import "./contracts/libraries/LiquidityAmounts.sol"; import "./contracts/libraries/PositionKey.sol"; import "./contracts/libraries/PoolAddress.sol"; import "./interfaces.sol"; abstract contract Helpers is DSMath { /** * @dev Return ethereum address */ address internal constant ethAddr = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; /** * @dev Return Wrapped ETH address */ address internal constant wethAddr = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; INonfungiblePositionManager private nftManager = INonfungiblePositionManager(getUniswapNftManagerAddr()); /** * @dev Return uniswap v3 NFT Manager Address */ function getUniswapNftManagerAddr() internal pure returns (address) { return 0xC36442b4a4522E871399CD717aBDD847Ab11FE88; } function convert18ToDec(uint256 _dec, uint256 _amt) internal pure returns (uint256 amt) { amt = (_amt / 10**(18 - _dec)); } function convertTo18(uint256 _dec, uint256 _amt) internal pure returns (uint256 amt) { amt = mul(_amt, 10**(18 - _dec)); } function changeEthAddress(address buy, address sell) internal pure returns (TokenInterface _buy, TokenInterface _sell) { _buy = buy == ethAddr ? TokenInterface(wethAddr) : TokenInterface(buy); _sell = sell == ethAddr ? TokenInterface(wethAddr) : TokenInterface(sell); } /** * @dev Return uniswap v3 Swap Router Address */ function getUniswapRouterAddr() internal pure returns (address) { return 0xE592427A0AEce92De3Edee1F18E0157C05861564; } /** * @dev Get Last NFT Index * @param user: User address */ function getLastNftId(address user) internal view returns (uint256 tokenId) { uint256 len = nftManager.balanceOf(user); tokenId = nftManager.tokenOfOwnerByIndex(user, len - 1); } function userNfts(address user) internal view returns (uint256[] memory tokenIds) { uint256 len = nftManager.balanceOf(user); tokenIds = new uint256[](len); for (uint256 i = 0; i < len; i++) { uint256 tokenId = nftManager.tokenOfOwnerByIndex(user, i); tokenIds[i] = tokenId; } } function getMinAmount( TokenInterface token, uint256 amt, uint256 slippage ) internal view returns (uint256 minAmt) { uint256 _amt18 = convertTo18(token.decimals(), amt); minAmt = wmul(_amt18, sub(WAD, slippage)); minAmt = convert18ToDec(token.decimals(), minAmt); } struct PositionInfo { address token0; address token1; address pool; uint24 fee; int24 tickLower; int24 tickUpper; int24 currentTick; uint128 liquidity; uint128 tokenOwed0; uint128 tokenOwed1; uint256 amount0; uint256 amount1; uint256 collectAmount0; uint256 collectAmount1; } function positions(uint256 tokenId) internal view returns (PositionInfo memory pInfo) { ( , , pInfo.token0, pInfo.token1, pInfo.fee, pInfo.tickLower, pInfo.tickUpper, pInfo.liquidity, , , , ) = nftManager.positions(tokenId); (, , , , , , , , , , pInfo.tokenOwed0, pInfo.tokenOwed1) = nftManager.positions(tokenId); pInfo.pool = getPoolAddress(pInfo.token0, pInfo.token1, pInfo.fee); IUniswapV3Pool pool = IUniswapV3Pool(pInfo.pool); (, pInfo.currentTick, , , , , ) = pool.slot0(); (pInfo.amount0, pInfo.amount1) = withdrawAmount(tokenId, pInfo.liquidity); (pInfo.collectAmount0, pInfo.collectAmount1) = collectInfo(tokenId); } function getPoolAddress( address token0, address token1, uint24 fee ) internal view returns (address poolAddr) { poolAddr = PoolAddress.computeAddress( nftManager.factory(), PoolAddress.PoolKey({ token0: token0, token1: token1, fee: fee }) ); } function depositAmount( uint256 tokenId, uint256 amountA, uint256 amountB ) internal view returns ( uint128 liquidity, uint256 amount0, uint256 amount1 ) { (, , address _token0, address _token1, uint24 _fee, int24 tickLower, int24 tickUpper, , , , , ) = nftManager .positions(tokenId); IUniswapV3Pool pool = IUniswapV3Pool(getPoolAddress(_token0, _token1, _fee)); // compute the liquidity amount { (uint160 sqrtPriceX96, , , , , , ) = pool.slot0(); liquidity = LiquidityAmounts.getLiquidityForAmounts( sqrtPriceX96, TickMath.getSqrtRatioAtTick(tickLower), TickMath.getSqrtRatioAtTick(tickUpper), amountA, amountB ); (amount0, amount1) = LiquidityAmounts.getAmountsForLiquidity( sqrtPriceX96, TickMath.getSqrtRatioAtTick(tickLower), TickMath.getSqrtRatioAtTick(tickUpper), liquidity ); // amount0 = sub(amountA, amount0); // amount1 = sub(amountB, amount1); } } function singleDepositAmount( uint256 tokenId, address tokenA, uint256 amountA ) internal view returns (address tokenB, uint256 amountB) { (, , address _token0, address _token1, uint24 _fee, int24 tickLower, int24 tickUpper, , , , , ) = nftManager .positions(tokenId); bool reverseFlag = false; if (tokenA != _token0) { (tokenA, tokenB) = (_token0, _token1); reverseFlag = true; } else { tokenB = _token1; } if (!reverseFlag) { uint128 liquidity = LiquidityAmounts.getLiquidityForAmount0( TickMath.getSqrtRatioAtTick(tickLower), TickMath.getSqrtRatioAtTick(tickUpper), amountA ); amountB = LiquidityAmounts.getAmount1ForLiquidity( TickMath.getSqrtRatioAtTick(tickLower), TickMath.getSqrtRatioAtTick(tickUpper), liquidity ); } else { uint128 liquidity = LiquidityAmounts.getLiquidityForAmount1( TickMath.getSqrtRatioAtTick(tickLower), TickMath.getSqrtRatioAtTick(tickUpper), amountA ); amountB = LiquidityAmounts.getAmount0ForLiquidity( TickMath.getSqrtRatioAtTick(tickLower), TickMath.getSqrtRatioAtTick(tickUpper), liquidity ); } } function withdrawAmount(uint256 tokenId, uint128 liquidity) internal view returns (uint256 amount0, uint256 amount1) { require(liquidity > 0, "liquidity should greater than 0"); ( , , address _token0, address _token1, uint24 _fee, int24 tickLower, int24 tickUpper, uint128 positionLiquidity, , , , ) = nftManager.positions(tokenId); require(positionLiquidity >= liquidity, "Liquidity amount is over than position liquidity amount"); IUniswapV3Pool pool = IUniswapV3Pool(getPoolAddress(_token0, _token1, _fee)); (uint160 sqrtPriceX96, , , , , , ) = pool.slot0(); (amount0, amount1) = LiquidityAmounts.getAmountsForLiquidity( sqrtPriceX96, TickMath.getSqrtRatioAtTick(tickLower), TickMath.getSqrtRatioAtTick(tickUpper), liquidity ); } function collectInfo(uint256 tokenId) internal view returns (uint256 amount0, uint256 amount1) { ( , , address _token0, address _token1, uint24 _fee, int24 tickLower, int24 tickUpper, uint128 liquidity, uint256 _feeGrowthInside0LastX128, uint256 _feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1 ) = nftManager.positions(tokenId); IUniswapV3Pool pool = IUniswapV3Pool(getPoolAddress(_token0, _token1, _fee)); (, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, , ) = pool.positions( PositionKey.compute(getUniswapNftManagerAddr(), tickLower, tickUpper) ); tokensOwed0 += uint128( FullMath.mulDiv(feeGrowthInside0LastX128 - _feeGrowthInside0LastX128, liquidity, FixedPoint128.Q128) ); tokensOwed1 += uint128( FullMath.mulDiv(feeGrowthInside1LastX128 - _feeGrowthInside1LastX128, liquidity, FixedPoint128.Q128) ); amount0 = tokensOwed0; amount1 = tokensOwed1; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../../introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "./IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "./IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0; contract DSMath { function add(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x + y) >= x, "math-not-safe"); } function sub(uint256 x, uint256 y) internal pure returns (uint256 z) { z = x - y <= x ? x - y : 0; } function mul(uint256 x, uint256 y) internal pure returns (uint256 z) { require(y == 0 || (z = x * y) / y == x, "math-not-safe"); } function sqrt(uint256 y) internal pure returns (uint256 z) { if (y > 3) { z = y; uint256 x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 1; } } uint256 internal constant WAD = 10**18; uint256 internal constant RAY = 10**27; function rmul(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, y), RAY / 2) / RAY; } function wmul(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, y), WAD / 2) / WAD; } function rdiv(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, RAY), y / 2) / y; } function wdiv(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, WAD), y / 2) / y; } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; import "./pool/IUniswapV3PoolImmutables.sol"; import "./pool/IUniswapV3PoolState.sol"; import "./pool/IUniswapV3PoolDerivedState.sol"; import "./pool/IUniswapV3PoolActions.sol"; import "./pool/IUniswapV3PoolOwnerActions.sol"; import "./pool/IUniswapV3PoolEvents.sol"; /// @title The interface for a Uniswap V3 Pool /// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform /// to the ERC20 specification /// @dev The pool interface is broken up into many smaller pieces interface IUniswapV3Pool is IUniswapV3PoolImmutables, IUniswapV3PoolState, IUniswapV3PoolDerivedState, IUniswapV3PoolActions, IUniswapV3PoolOwnerActions, IUniswapV3PoolEvents { } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.7.0; /// @title Math library for computing sqrt prices from ticks and vice versa /// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports /// prices between 2**-128 and 2**128 library TickMath { /// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128 int24 internal constant MIN_TICK = -887272; /// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128 int24 internal constant MAX_TICK = -MIN_TICK; /// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK) uint160 internal constant MIN_SQRT_RATIO = 4295128739; /// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK) uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342; /// @notice Calculates sqrt(1.0001^tick) * 2^96 /// @dev Throws if |tick| > max tick /// @param tick The input tick for the above formula /// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0) /// at the given tick function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) { uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick)); require(absTick <= uint256(MAX_TICK), "T"); uint256 ratio = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000; if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128; if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128; if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128; if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128; if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128; if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128; if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128; if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128; if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128; if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128; if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128; if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128; if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128; if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128; if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128; if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128; if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128; if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128; if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128; if (tick > 0) ratio = type(uint256).max / ratio; // this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96. // we then downcast because we know the result always fits within 160 bits due to our tick input constraint // we round up in the division so getTickAtSqrtRatio of the output price is always consistent sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1)); } /// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio /// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may /// ever return. /// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96 /// @return tick The greatest tick for which the ratio is less than or equal to the input ratio function getTickAtSqrtRatio(uint160 sqrtPriceX96) internal pure returns (int24 tick) { // second inequality must be < because the price can never reach the price at the max tick require(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO, "R"); uint256 ratio = uint256(sqrtPriceX96) << 32; uint256 r = ratio; uint256 msb = 0; assembly { let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(5, gt(r, 0xFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(4, gt(r, 0xFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(3, gt(r, 0xFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(2, gt(r, 0xF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(1, gt(r, 0x3)) msb := or(msb, f) r := shr(f, r) } assembly { let f := gt(r, 0x1) msb := or(msb, f) } if (msb >= 128) r = ratio >> (msb - 127); else r = ratio << (127 - msb); int256 log_2 = (int256(msb) - 128) << 64; assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(63, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(62, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(61, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(60, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(59, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(58, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(57, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(56, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(55, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(54, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(53, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(52, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(51, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(50, f)) } int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128); int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128); tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow; } } // SPDX-License-Identifier: MIT pragma solidity >=0.4.0; /// @title Contains 512-bit math functions /// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision /// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits library FullMath { /// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 /// @param a The multiplicand /// @param b The multiplier /// @param denominator The divisor /// @return result The 256-bit result /// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv function mulDiv( uint256 a, uint256 b, uint256 denominator ) internal pure returns (uint256 result) { // 512-bit multiply [prod1 prod0] = a * b // Compute the product mod 2**256 and mod 2**256 - 1 // then use the Chinese Remainder Theorem to reconstruct // the 512 bit result. The result is stored in two 256 // variables such that product = prod1 * 2**256 + prod0 uint256 prod0; // Least significant 256 bits of the product uint256 prod1; // Most significant 256 bits of the product assembly { let mm := mulmod(a, b, not(0)) prod0 := mul(a, b) prod1 := sub(sub(mm, prod0), lt(mm, prod0)) } // Handle non-overflow cases, 256 by 256 division if (prod1 == 0) { require(denominator > 0); assembly { result := div(prod0, denominator) } return result; } // Make sure the result is less than 2**256. // Also prevents denominator == 0 require(denominator > prod1); /////////////////////////////////////////////// // 512 by 256 division. /////////////////////////////////////////////// // Make division exact by subtracting the remainder from [prod1 prod0] // Compute remainder using mulmod uint256 remainder; assembly { remainder := mulmod(a, b, denominator) } // Subtract 256 bit number from 512 bit number assembly { prod1 := sub(prod1, gt(remainder, prod0)) prod0 := sub(prod0, remainder) } // Factor powers of two out of denominator // Compute largest power of two divisor of denominator. // Always >= 1. uint256 twos = (type(uint256).max - denominator + 1) & denominator; // Divide denominator by power of two assembly { denominator := div(denominator, twos) } // Divide [prod1 prod0] by the factors of two assembly { prod0 := div(prod0, twos) } // Shift in bits from prod1 into prod0. For this we need // to flip `twos` such that it is 2**256 / twos. // If twos is zero, then it becomes one assembly { twos := add(div(sub(0, twos), twos), 1) } prod0 |= prod1 * twos; // Invert denominator mod 2**256 // Now that denominator is an odd number, it has an inverse // modulo 2**256 such that denominator * inv = 1 mod 2**256. // Compute the inverse by starting with a seed that is correct // correct for four bits. That is, denominator * inv = 1 mod 2**4 uint256 inv = (3 * denominator) ^ 2; // Now use Newton-Raphson iteration to improve the precision. // Thanks to Hensel's lifting lemma, this also works in modular // arithmetic, doubling the correct bits in each step. inv *= 2 - denominator * inv; // inverse mod 2**8 inv *= 2 - denominator * inv; // inverse mod 2**16 inv *= 2 - denominator * inv; // inverse mod 2**32 inv *= 2 - denominator * inv; // inverse mod 2**64 inv *= 2 - denominator * inv; // inverse mod 2**128 inv *= 2 - denominator * inv; // inverse mod 2**256 // Because the division is now exact we can divide by multiplying // with the modular inverse of denominator. This will give us the // correct result modulo 2**256. Since the precoditions guarantee // that the outcome is less than 2**256, this is the final result. // We don't need to compute the high bits of the result and prod1 // is no longer required. result = prod0 * inv; return result; } /// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 /// @param a The multiplicand /// @param b The multiplier /// @param denominator The divisor /// @return result The 256-bit result function mulDivRoundingUp( uint256 a, uint256 b, uint256 denominator ) internal pure returns (uint256 result) { result = mulDiv(a, b, denominator); if (mulmod(a, b, denominator) > 0) { require(result < type(uint256).max); result++; } } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.4.0; /// @title FixedPoint128 /// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format) library FixedPoint128 { uint256 internal constant Q128 = 0x100000000000000000000000000000000; } pragma solidity >=0.5.0; import "./FullMath.sol"; import "./FixedPoint96.sol"; library LiquidityAmounts { function toUint128(uint256 x) private pure returns (uint128 y) { require((y = uint128(x)) == x); } function getLiquidityForAmount0( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint256 amount0 ) internal pure returns (uint128 liquidity) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); uint256 intermediate = FullMath.mulDiv(sqrtRatioAX96, sqrtRatioBX96, FixedPoint96.Q96); return toUint128(FullMath.mulDiv(amount0, intermediate, sqrtRatioBX96 - sqrtRatioAX96)); } function getLiquidityForAmount1( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint256 amount1 ) internal pure returns (uint128 liquidity) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); return toUint128(FullMath.mulDiv(amount1, FixedPoint96.Q96, sqrtRatioBX96 - sqrtRatioAX96)); } function getLiquidityForAmounts( uint160 sqrtRatioX96, uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint256 amount0, uint256 amount1 ) internal pure returns (uint128 liquidity) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); if (sqrtRatioX96 <= sqrtRatioAX96) { liquidity = getLiquidityForAmount0(sqrtRatioAX96, sqrtRatioBX96, amount0); } else if (sqrtRatioX96 < sqrtRatioBX96) { uint128 liquidity0 = getLiquidityForAmount0(sqrtRatioX96, sqrtRatioBX96, amount0); uint128 liquidity1 = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioX96, amount1); liquidity = liquidity0 < liquidity1 ? liquidity0 : liquidity1; } else { liquidity = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioBX96, amount1); } } function getAmount0ForLiquidity( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity ) internal pure returns (uint256 amount0) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); return FullMath.mulDiv( uint256(liquidity) << FixedPoint96.RESOLUTION, sqrtRatioBX96 - sqrtRatioAX96, sqrtRatioBX96 ) / sqrtRatioAX96; } function getAmount1ForLiquidity( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity ) internal pure returns (uint256 amount1) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); return FullMath.mulDiv(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96); } function getAmountsForLiquidity( uint160 sqrtRatioX96, uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity ) internal pure returns (uint256 amount0, uint256 amount1) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); if (sqrtRatioX96 <= sqrtRatioAX96) { amount0 = getAmount0ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity); } else if (sqrtRatioX96 < sqrtRatioBX96) { amount0 = getAmount0ForLiquidity(sqrtRatioX96, sqrtRatioBX96, liquidity); amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioX96, liquidity); } else { amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity); } } } pragma solidity >=0.5.0; library PositionKey { function compute( address owner, int24 tickLower, int24 tickUpper ) internal pure returns (bytes32) { return keccak256(abi.encodePacked(owner, tickLower, tickUpper)); } } pragma solidity >=0.5.0; library PoolAddress { bytes32 internal constant POOL_INIT_CODE_HASH = 0xe34f199b19b2b4f47f68442619d555527d244f78a3297ea89325f843f87b8b54; struct PoolKey { address token0; address token1; uint24 fee; } function getPoolKey( address tokenA, address tokenB, uint24 fee ) internal pure returns (PoolKey memory) { if (tokenA > tokenB) (tokenA, tokenB) = (tokenB, tokenA); return PoolKey({ token0: tokenA, token1: tokenB, fee: fee }); } function computeAddress(address factory, PoolKey memory key) internal pure returns (address pool) { require(key.token0 < key.token1); pool = address( uint160( uint256( keccak256( abi.encodePacked( hex"ff", factory, keccak256(abi.encode(key.token0, key.token1, key.fee)), POOL_INIT_CODE_HASH ) ) ) ) ); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Pool state that never changes /// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values interface IUniswapV3PoolImmutables { /// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface /// @return The contract address function factory() external view returns (address); /// @notice The first of the two tokens of the pool, sorted by address /// @return The token contract address function token0() external view returns (address); /// @notice The second of the two tokens of the pool, sorted by address /// @return The token contract address function token1() external view returns (address); /// @notice The pool's fee in hundredths of a bip, i.e. 1e-6 /// @return The fee function fee() external view returns (uint24); /// @notice The pool tick spacing /// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive /// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ... /// This value is an int24 to avoid casting even though it is always positive. /// @return The tick spacing function tickSpacing() external view returns (int24); /// @notice The maximum amount of position liquidity that can use any tick in the range /// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and /// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool /// @return The max amount of liquidity per tick function maxLiquidityPerTick() external view returns (uint128); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Pool state that can change /// @notice These methods compose the pool's state, and can change with any frequency including multiple times /// per transaction interface IUniswapV3PoolState { /// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas /// when accessed externally. /// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value /// tick The current tick of the pool, i.e. according to the last tick transition that was run. /// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick /// boundary. /// observationIndex The index of the last oracle observation that was written, /// observationCardinality The current maximum number of observations stored in the pool, /// observationCardinalityNext The next maximum number of observations, to be updated when the observation. /// feeProtocol The protocol fee for both tokens of the pool. /// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0 /// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee. /// unlocked Whether the pool is currently locked to reentrancy function slot0() external view returns ( uint160 sqrtPriceX96, int24 tick, uint16 observationIndex, uint16 observationCardinality, uint16 observationCardinalityNext, uint8 feeProtocol, bool unlocked ); /// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool /// @dev This value can overflow the uint256 function feeGrowthGlobal0X128() external view returns (uint256); /// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool /// @dev This value can overflow the uint256 function feeGrowthGlobal1X128() external view returns (uint256); /// @notice The amounts of token0 and token1 that are owed to the protocol /// @dev Protocol fees will never exceed uint128 max in either token function protocolFees() external view returns (uint128 token0, uint128 token1); /// @notice The currently in range liquidity available to the pool /// @dev This value has no relationship to the total liquidity across all ticks function liquidity() external view returns (uint128); /// @notice Look up information about a specific tick in the pool /// @param tick The tick to look up /// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or /// tick upper, /// liquidityNet how much liquidity changes when the pool price crosses the tick, /// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0, /// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1, /// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick /// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick, /// secondsOutside the seconds spent on the other side of the tick from the current tick, /// initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false. /// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0. /// In addition, these values are only relative and must be used only in comparison to previous snapshots for /// a specific position. function ticks(int24 tick) external view returns ( uint128 liquidityGross, int128 liquidityNet, uint256 feeGrowthOutside0X128, uint256 feeGrowthOutside1X128, int56 tickCumulativeOutside, uint160 secondsPerLiquidityOutsideX128, uint32 secondsOutside, bool initialized ); /// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information function tickBitmap(int16 wordPosition) external view returns (uint256); /// @notice Returns the information about a position by the position's key /// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper /// @return _liquidity The amount of liquidity in the position, /// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke, /// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke, /// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke, /// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke function positions(bytes32 key) external view returns ( uint128 _liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1 ); /// @notice Returns data about a specific observation index /// @param index The element of the observations array to fetch /// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time /// ago, rather than at a specific index in the array. /// @return blockTimestamp The timestamp of the observation, /// Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp, /// Returns secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp, /// Returns initialized whether the observation has been initialized and the values are safe to use function observations(uint256 index) external view returns ( uint32 blockTimestamp, int56 tickCumulative, uint160 secondsPerLiquidityCumulativeX128, bool initialized ); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Pool state that is not stored /// @notice Contains view functions to provide information about the pool that is computed rather than stored on the /// blockchain. The functions here may have variable gas costs. interface IUniswapV3PoolDerivedState { /// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp /// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing /// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick, /// you must call it with secondsAgos = [3600, 0]. /// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in /// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio. /// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned /// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp /// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block /// timestamp function observe(uint32[] calldata secondsAgos) external view returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s); /// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range /// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed. /// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first /// snapshot is taken and the second snapshot is taken. /// @param tickLower The lower tick of the range /// @param tickUpper The upper tick of the range /// @return tickCumulativeInside The snapshot of the tick accumulator for the range /// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range /// @return secondsInside The snapshot of seconds per liquidity for the range function snapshotCumulativesInside(int24 tickLower, int24 tickUpper) external view returns ( int56 tickCumulativeInside, uint160 secondsPerLiquidityInsideX128, uint32 secondsInside ); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Permissionless pool actions /// @notice Contains pool methods that can be called by anyone interface IUniswapV3PoolActions { /// @notice Sets the initial price for the pool /// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value /// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96 function initialize(uint160 sqrtPriceX96) external; /// @notice Adds liquidity for the given recipient/tickLower/tickUpper position /// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback /// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends /// on tickLower, tickUpper, the amount of liquidity, and the current price. /// @param recipient The address for which the liquidity will be created /// @param tickLower The lower tick of the position in which to add liquidity /// @param tickUpper The upper tick of the position in which to add liquidity /// @param amount The amount of liquidity to mint /// @param data Any data that should be passed through to the callback /// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback /// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback function mint( address recipient, int24 tickLower, int24 tickUpper, uint128 amount, bytes calldata data ) external returns (uint256 amount0, uint256 amount1); /// @notice Collects tokens owed to a position /// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity. /// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or /// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the /// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity. /// @param recipient The address which should receive the fees collected /// @param tickLower The lower tick of the position for which to collect fees /// @param tickUpper The upper tick of the position for which to collect fees /// @param amount0Requested How much token0 should be withdrawn from the fees owed /// @param amount1Requested How much token1 should be withdrawn from the fees owed /// @return amount0 The amount of fees collected in token0 /// @return amount1 The amount of fees collected in token1 function collect( address recipient, int24 tickLower, int24 tickUpper, uint128 amount0Requested, uint128 amount1Requested ) external returns (uint128 amount0, uint128 amount1); /// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position /// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0 /// @dev Fees must be collected separately via a call to #collect /// @param tickLower The lower tick of the position for which to burn liquidity /// @param tickUpper The upper tick of the position for which to burn liquidity /// @param amount How much liquidity to burn /// @return amount0 The amount of token0 sent to the recipient /// @return amount1 The amount of token1 sent to the recipient function burn( int24 tickLower, int24 tickUpper, uint128 amount ) external returns (uint256 amount0, uint256 amount1); /// @notice Swap token0 for token1, or token1 for token0 /// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback /// @param recipient The address to receive the output of the swap /// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0 /// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative) /// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this /// value after the swap. If one for zero, the price cannot be greater than this value after the swap /// @param data Any data to be passed through to the callback /// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive /// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive function swap( address recipient, bool zeroForOne, int256 amountSpecified, uint160 sqrtPriceLimitX96, bytes calldata data ) external returns (int256 amount0, int256 amount1); /// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback /// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback /// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling /// with 0 amount{0,1} and sending the donation amount(s) from the callback /// @param recipient The address which will receive the token0 and token1 amounts /// @param amount0 The amount of token0 to send /// @param amount1 The amount of token1 to send /// @param data Any data to be passed through to the callback function flash( address recipient, uint256 amount0, uint256 amount1, bytes calldata data ) external; /// @notice Increase the maximum number of price and liquidity observations that this pool will store /// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to /// the input observationCardinalityNext. /// @param observationCardinalityNext The desired minimum number of observations for the pool to store function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Permissioned pool actions /// @notice Contains pool methods that may only be called by the factory owner interface IUniswapV3PoolOwnerActions { /// @notice Set the denominator of the protocol's % share of the fees /// @param feeProtocol0 new protocol fee for token0 of the pool /// @param feeProtocol1 new protocol fee for token1 of the pool function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external; /// @notice Collect the protocol fee accrued to the pool /// @param recipient The address to which collected protocol fees should be sent /// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1 /// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0 /// @return amount0 The protocol fee collected in token0 /// @return amount1 The protocol fee collected in token1 function collectProtocol( address recipient, uint128 amount0Requested, uint128 amount1Requested ) external returns (uint128 amount0, uint128 amount1); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Events emitted by a pool /// @notice Contains all events emitted by the pool interface IUniswapV3PoolEvents { /// @notice Emitted exactly once by a pool when #initialize is first called on the pool /// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize /// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96 /// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool event Initialize(uint160 sqrtPriceX96, int24 tick); /// @notice Emitted when liquidity is minted for a given position /// @param sender The address that minted the liquidity /// @param owner The owner of the position and recipient of any minted liquidity /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount The amount of liquidity minted to the position range /// @param amount0 How much token0 was required for the minted liquidity /// @param amount1 How much token1 was required for the minted liquidity event Mint( address sender, address indexed owner, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount, uint256 amount0, uint256 amount1 ); /// @notice Emitted when fees are collected by the owner of a position /// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees /// @param owner The owner of the position for which fees are collected /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount0 The amount of token0 fees collected /// @param amount1 The amount of token1 fees collected event Collect( address indexed owner, address recipient, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount0, uint128 amount1 ); /// @notice Emitted when a position's liquidity is removed /// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect /// @param owner The owner of the position for which liquidity is removed /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount The amount of liquidity to remove /// @param amount0 The amount of token0 withdrawn /// @param amount1 The amount of token1 withdrawn event Burn( address indexed owner, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount, uint256 amount0, uint256 amount1 ); /// @notice Emitted by the pool for any swaps between token0 and token1 /// @param sender The address that initiated the swap call, and that received the callback /// @param recipient The address that received the output of the swap /// @param amount0 The delta of the token0 balance of the pool /// @param amount1 The delta of the token1 balance of the pool /// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96 /// @param liquidity The liquidity of the pool after the swap /// @param tick The log base 1.0001 of price of the pool after the swap event Swap( address indexed sender, address indexed recipient, int256 amount0, int256 amount1, uint160 sqrtPriceX96, uint128 liquidity, int24 tick ); /// @notice Emitted by the pool for any flashes of token0/token1 /// @param sender The address that initiated the swap call, and that received the callback /// @param recipient The address that received the tokens from flash /// @param amount0 The amount of token0 that was flashed /// @param amount1 The amount of token1 that was flashed /// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee /// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee event Flash( address indexed sender, address indexed recipient, uint256 amount0, uint256 amount1, uint256 paid0, uint256 paid1 ); /// @notice Emitted by the pool for increases to the number of observations that can be stored /// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index /// just before a mint/swap/burn. /// @param observationCardinalityNextOld The previous value of the next observation cardinality /// @param observationCardinalityNextNew The updated value of the next observation cardinality event IncreaseObservationCardinalityNext( uint16 observationCardinalityNextOld, uint16 observationCardinalityNextNew ); /// @notice Emitted when the protocol fee is changed by the pool /// @param feeProtocol0Old The previous value of the token0 protocol fee /// @param feeProtocol1Old The previous value of the token1 protocol fee /// @param feeProtocol0New The updated value of the token0 protocol fee /// @param feeProtocol1New The updated value of the token1 protocol fee event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New); /// @notice Emitted when the collected protocol fees are withdrawn by the factory owner /// @param sender The address that collects the protocol fees /// @param recipient The address that receives the collected protocol fees /// @param amount0 The amount of token0 protocol fees that is withdrawn /// @param amount0 The amount of token1 protocol fees that is withdrawn event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.4.0; /// @title FixedPoint96 /// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format) /// @dev Used in SqrtPriceMath.sol library FixedPoint96 { uint8 internal constant RESOLUTION = 96; uint256 internal constant Q96 = 0x1000000000000000000000000; }
Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may ever return. sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96 return tick The greatest tick for which the ratio is less than or equal to the input ratio second inequality must be < because the price can never reach the price at the max tick
function getTickAtSqrtRatio(uint160 sqrtPriceX96) internal pure returns (int24 tick) { require(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO, "R"); uint256 ratio = uint256(sqrtPriceX96) << 32; uint256 r = ratio; uint256 msb = 0; assembly { let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(5, gt(r, 0xFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(4, gt(r, 0xFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(3, gt(r, 0xFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(2, gt(r, 0xF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(1, gt(r, 0x3)) msb := or(msb, f) r := shr(f, r) } assembly { let f := gt(r, 0x1) msb := or(msb, f) } if (msb >= 128) r = ratio >> (msb - 127); else r = ratio << (127 - msb); int256 log_2 = (int256(msb) - 128) << 64; assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(63, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(62, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(61, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(60, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(59, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(58, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(57, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(56, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(55, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(54, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(53, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(52, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(51, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(50, f)) } int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128); int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128); tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow; }
480,275
pragma solidity ^0.5.0; /** * @title Spawn * @author 0age * @notice This contract provides creation code that is used by Spawner in order * to initialize and deploy eip-1167 minimal proxies for a given logic contract. */ contract Spawn { constructor( address logicContract, bytes memory initializationCalldata ) public payable { // delegatecall into the logic contract to perform initialization. (bool ok, ) = logicContract.delegatecall(initializationCalldata); if (!ok) { // pass along failure message from delegatecall and revert. assembly { returndatacopy(0, 0, returndatasize) revert(0, returndatasize) } } // place eip-1167 runtime code in memory. bytes memory runtimeCode = abi.encodePacked( bytes10(0x363d3d373d3d3d363d73), logicContract, bytes15(0x5af43d82803e903d91602b57fd5bf3) ); // return eip-1167 code to write it to spawned contract runtime. assembly { return(add(0x20, runtimeCode), 45) // eip-1167 runtime code, length } } } /** * @title Spawner * @author 0age * @notice This contract spawns and initializes eip-1167 minimal proxies that * point to existing logic contracts. The logic contracts need to have an * intitializer function that should only callable when no contract exists at * their current address (i.e. it is being `DELEGATECALL`ed from a constructor). */ contract Spawner { /** * @notice Internal function for spawning an eip-1167 minimal proxy using * `CREATE2`. * @param logicContract address The address of the logic contract. * @param initializationCalldata bytes The calldata that will be supplied to * the `DELEGATECALL` from the spawned contract to the logic contract during * contract creation. * @return The address of the newly-spawned contract. */ function _spawn( address logicContract, bytes memory initializationCalldata ) internal returns (address spawnedContract) { // place creation code and constructor args of contract to spawn in memory. bytes memory initCode = abi.encodePacked( type(Spawn).creationCode, abi.encode(logicContract, initializationCalldata) ); // get salt to use during deployment using the supplied initialization code. (bytes32 salt, address target) = _getSaltAndTarget(initCode); // spawn the contract using `CREATE2`. spawnedContract = _spawnCreate2(initCode, salt, target); } /** * @notice Internal function for spawning an eip-1167 minimal proxy using * `CREATE2`. * @param logicContract address The address of the logic contract. * @param initializationCalldata bytes The calldata that will be supplied to * the `DELEGATECALL` from the spawned contract to the logic contract during * contract creation. * @param salt bytes32 A random salt * @return The address of the newly-spawned contract. */ function _spawnSalty( address logicContract, bytes memory initializationCalldata, bytes32 salt ) internal returns (address spawnedContract) { // place creation code and constructor args of contract to spawn in memory. bytes memory initCode = abi.encodePacked( type(Spawn).creationCode, abi.encode(logicContract, initializationCalldata) ); address target = _computeTargetAddress(logicContract, initializationCalldata, salt); uint256 codeSize; assembly { codeSize := extcodesize(target) } require(codeSize == 0, "contract already deployed with supplied salt"); // spawn the contract using `CREATE2`. spawnedContract = _spawnCreate2(initCode, salt, target); } /** * @notice Internal view function for finding the address of the next standard * eip-1167 minimal proxy created using `CREATE2` with a given logic contract * and initialization calldata payload. * @param logicContract address The address of the logic contract. * @param initializationCalldata bytes The calldata that will be supplied to * the `DELEGATECALL` from the spawned contract to the logic contract during * contract creation. * @return The address of the next spawned minimal proxy contract with the * given parameters. */ function _getNextAddress( address logicContract, bytes memory initializationCalldata ) internal view returns (address target) { // place creation code and constructor args of contract to spawn in memory. bytes memory initCode = abi.encodePacked( type(Spawn).creationCode, abi.encode(logicContract, initializationCalldata) ); // get target address using the constructed initialization code. (, target) = _getSaltAndTarget(initCode); } /** * @notice Internal view function for finding the address of the next standard * eip-1167 minimal proxy created using `CREATE2` with a given logic contract, * salt, and initialization calldata payload. * @param initCodeHash bytes32 The encoded hash of initCode * @param salt bytes32 A random salt * @return The address of the next spawned minimal proxy contract with the * given parameters. */ function _computeTargetAddress( bytes32 initCodeHash, bytes32 salt ) internal view returns (address target) { target = address( // derive the target deployment address. uint160( // downcast to match the address type. uint256( // cast to uint to truncate upper digits. keccak256( // compute CREATE2 hash using 4 inputs. abi.encodePacked( // pack all inputs to the hash together. bytes1(0xff), // pass in the control character. address(this), // pass in the address of this contract. salt, // pass in the salt from above. initCodeHash // pass in hash of contract creation code. ) ) ) ) ); } /** * @notice Internal view function for finding the address of the next standard * eip-1167 minimal proxy created using `CREATE2` with a given logic contract * and initialization calldata payload. * @param logicContract address The address of the logic contract. * @param initializationCalldata bytes The calldata that will be supplied to * the `DELEGATECALL` from the spawned contract to the logic contract during * contract creation. * @param salt bytes32 A random salt * @return The address of the next spawned minimal proxy contract with the * given parameters. */ function _computeTargetAddress( address logicContract, bytes memory initializationCalldata, bytes32 salt ) internal view returns (address target) { // place creation code and constructor args of contract to spawn in memory. bytes memory initCode = abi.encodePacked( type(Spawn).creationCode, abi.encode(logicContract, initializationCalldata) ); // get the keccak256 hash of the init code for address derivation. bytes32 initCodeHash = keccak256(initCode); target = _computeTargetAddress(initCodeHash, salt); } /** * @notice Private function for spawning a compact eip-1167 minimal proxy * using `CREATE2`. Provides logic that is reused by internal functions. A * salt will also be chosen based on the calling address and a computed nonce * that prevents deployments to existing addresses. * @param initCode bytes The contract creation code. * @param salt bytes32 A random salt * @param target address The expected address of the new contract * @return The address of the newly-spawned contract. */ function _spawnCreate2( bytes memory initCode, bytes32 salt, address target ) private returns (address spawnedContract) { assembly { let encoded_data := add(0x20, initCode) // load initialization code. let encoded_size := mload(initCode) // load the init code's length. spawnedContract := create2( // call `CREATE2` w/ 4 arguments. callvalue, // forward any supplied endowment. encoded_data, // pass in initialization code. encoded_size, // pass in init code's length. salt // pass in the salt value. ) // pass along failure message from failed contract deployment and revert. if iszero(spawnedContract) { returndatacopy(0, 0, returndatasize) revert(0, returndatasize) } } require(spawnedContract == target, "attempted deployment to unexpected address"); } /** * @notice Private function for determining the salt and the target deployment * address for the next spawned contract (using create2) based on the contract * creation code. */ function _getSaltAndTarget( bytes memory initCode ) private view returns (bytes32 salt, address target) { // get the keccak256 hash of the init code for address derivation. bytes32 initCodeHash = keccak256(initCode); // set the initial nonce to be provided when constructing the salt. uint256 nonce = 0; // declare variable for code size of derived address. uint256 codeSize; while (true) { // derive `CREATE2` salt using `msg.sender` and nonce. salt = keccak256(abi.encodePacked(msg.sender, nonce)); target = _computeTargetAddress(initCodeHash, salt); // determine if a contract is already deployed to the target address. assembly { codeSize := extcodesize(target) } // exit the loop if no contract is deployed to the target address. if (codeSize == 0) { break; } // otherwise, increment the nonce and derive a new salt. nonce++; } } }
Private function for determining the salt and the target deployment address for the next spawned contract (using create2) based on the contract creation code./ get the keccak256 hash of the init code for address derivation. set the initial nonce to be provided when constructing the salt. declare variable for code size of derived address. derive `CREATE2` salt using `msg.sender` and nonce. determine if a contract is already deployed to the target address. exit the loop if no contract is deployed to the target address.
function _getSaltAndTarget( bytes memory initCode ) private view returns (bytes32 salt, address target) { bytes32 initCodeHash = keccak256(initCode); uint256 nonce = 0; uint256 codeSize; while (true) { salt = keccak256(abi.encodePacked(msg.sender, nonce)); target = _computeTargetAddress(initCodeHash, salt); if (codeSize == 0) { break; } } }
12,619,490
// SPDX-License-Identifier: GPL-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; // Global Enums and Structs struct StrategyParams { uint256 performanceFee; uint256 activation; uint256 debtRatio; uint256 rateLimit; uint256 lastReport; uint256 totalDebt; uint256 totalGain; uint256 totalLoss; } // Part: Account library Account { enum Status {Normal, Liquid, Vapor} struct Info { address owner; // The address that owns the account uint256 number; // A nonce that allows a single address to control many accounts } struct Storage { mapping(uint256 => Types.Par) balances; // Mapping from marketId to principal Status status; } } // Part: Actions library Actions { enum ActionType { Deposit, // supply tokens Withdraw, // borrow tokens Transfer, // transfer balance between accounts Buy, // buy an amount of some token (publicly) Sell, // sell an amount of some token (publicly) Trade, // trade tokens against another account Liquidate, // liquidate an undercollateralized or expiring account Vaporize, // use excess tokens to zero-out a completely negative account Call // send arbitrary data to an address } enum AccountLayout {OnePrimary, TwoPrimary, PrimaryAndSecondary} enum MarketLayout {ZeroMarkets, OneMarket, TwoMarkets} struct ActionArgs { ActionType actionType; uint256 accountId; Types.AssetAmount amount; uint256 primaryMarketId; uint256 secondaryMarketId; address otherAddress; uint256 otherAccountId; bytes data; } struct DepositArgs { Types.AssetAmount amount; Account.Info account; uint256 market; address from; } struct WithdrawArgs { Types.AssetAmount amount; Account.Info account; uint256 market; address to; } struct TransferArgs { Types.AssetAmount amount; Account.Info accountOne; Account.Info accountTwo; uint256 market; } struct BuyArgs { Types.AssetAmount amount; Account.Info account; uint256 makerMarket; uint256 takerMarket; address exchangeWrapper; bytes orderData; } struct SellArgs { Types.AssetAmount amount; Account.Info account; uint256 takerMarket; uint256 makerMarket; address exchangeWrapper; bytes orderData; } struct TradeArgs { Types.AssetAmount amount; Account.Info takerAccount; Account.Info makerAccount; uint256 inputMarket; uint256 outputMarket; address autoTrader; bytes tradeData; } struct LiquidateArgs { Types.AssetAmount amount; Account.Info solidAccount; Account.Info liquidAccount; uint256 owedMarket; uint256 heldMarket; } struct VaporizeArgs { Types.AssetAmount amount; Account.Info solidAccount; Account.Info vaporAccount; uint256 owedMarket; uint256 heldMarket; } struct CallArgs { Account.Info account; address callee; bytes data; } } library Decimal { struct D256 { uint256 value; } } library Interest { struct Rate { uint256 value; } struct Index { uint96 borrow; uint96 supply; uint32 lastUpdate; } } library Monetary { struct Price { uint256 value; } struct Value { uint256 value; } } library Storage { // All information necessary for tracking a market struct Market { // Contract address of the associated ERC20 token address token; // Total aggregated supply and borrow amount of the entire market Types.TotalPar totalPar; // Interest index of the market Interest.Index index; // Contract address of the price oracle for this market address priceOracle; // Contract address of the interest setter for this market address interestSetter; // Multiplier on the marginRatio for this market Decimal.D256 marginPremium; // Multiplier on the liquidationSpread for this market Decimal.D256 spreadPremium; // Whether additional borrows are allowed for this market bool isClosing; } // The global risk parameters that govern the health and security of the system struct RiskParams { // Required ratio of over-collateralization Decimal.D256 marginRatio; // Percentage penalty incurred by liquidated accounts Decimal.D256 liquidationSpread; // Percentage of the borrower's interest fee that gets passed to the suppliers Decimal.D256 earningsRate; // The minimum absolute borrow value of an account // There must be sufficient incentivize to liquidate undercollateralized accounts Monetary.Value minBorrowedValue; } // The maximum RiskParam values that can be set struct RiskLimits { uint64 marginRatioMax; uint64 liquidationSpreadMax; uint64 earningsRateMax; uint64 marginPremiumMax; uint64 spreadPremiumMax; uint128 minBorrowedValueMax; } // The entire storage state of Solo struct State { // number of markets uint256 numMarkets; // marketId => Market mapping(uint256 => Market) markets; // owner => account number => Account mapping(address => mapping(uint256 => Account.Storage)) accounts; // Addresses that can control other users accounts mapping(address => mapping(address => bool)) operators; // Addresses that can control all users accounts mapping(address => bool) globalOperators; // mutable risk parameters of the system RiskParams riskParams; // immutable risk limits of the system RiskLimits riskLimits; } } // Part: ICallee /** * @title ICallee * @author dYdX * * Interface that Callees for Solo must implement in order to ingest data. */ interface ICallee { // ============ Public Functions ============ /** * Allows users to send this contract arbitrary data. * * @param sender The msg.sender to Solo * @param accountInfo The account from which the data is being sent * @param data Arbitrary data given by the sender */ function callFunction( address sender, Account.Info memory accountInfo, bytes memory data ) external; } // Part: ISoloMargin interface ISoloMargin { struct OperatorArg { address operator1; bool trusted; } function ownerSetSpreadPremium(uint256 marketId, Decimal.D256 memory spreadPremium) external; function getIsGlobalOperator(address operator1) external view returns (bool); function getMarketTokenAddress(uint256 marketId) external view returns (address); function ownerSetInterestSetter(uint256 marketId, address interestSetter) external; function getAccountValues(Account.Info memory account) external view returns (Monetary.Value memory, Monetary.Value memory); function getMarketPriceOracle(uint256 marketId) external view returns (address); function getMarketInterestSetter(uint256 marketId) external view returns (address); function getMarketSpreadPremium(uint256 marketId) external view returns (Decimal.D256 memory); function getNumMarkets() external view returns (uint256); function ownerWithdrawUnsupportedTokens(address token, address recipient) external returns (uint256); function ownerSetMinBorrowedValue(Monetary.Value memory minBorrowedValue) external; function ownerSetLiquidationSpread(Decimal.D256 memory spread) external; function ownerSetEarningsRate(Decimal.D256 memory earningsRate) external; function getIsLocalOperator(address owner, address operator1) external view returns (bool); function getAccountPar(Account.Info memory account, uint256 marketId) external view returns (Types.Par memory); function ownerSetMarginPremium(uint256 marketId, Decimal.D256 memory marginPremium) external; function getMarginRatio() external view returns (Decimal.D256 memory); function getMarketCurrentIndex(uint256 marketId) external view returns (Interest.Index memory); function getMarketIsClosing(uint256 marketId) external view returns (bool); function getRiskParams() external view returns (Storage.RiskParams memory); function getAccountBalances(Account.Info memory account) external view returns ( address[] memory, Types.Par[] memory, Types.Wei[] memory ); function renounceOwnership() external; function getMinBorrowedValue() external view returns (Monetary.Value memory); function setOperators(OperatorArg[] memory args) external; function getMarketPrice(uint256 marketId) external view returns (address); function owner() external view returns (address); function isOwner() external view returns (bool); function ownerWithdrawExcessTokens(uint256 marketId, address recipient) external returns (uint256); function ownerAddMarket( address token, address priceOracle, address interestSetter, Decimal.D256 memory marginPremium, Decimal.D256 memory spreadPremium ) external; function operate(Account.Info[] memory accounts, Actions.ActionArgs[] memory actions) external; function getMarketWithInfo(uint256 marketId) external view returns ( Storage.Market memory, Interest.Index memory, Monetary.Price memory, Interest.Rate memory ); function ownerSetMarginRatio(Decimal.D256 memory ratio) external; function getLiquidationSpread() external view returns (Decimal.D256 memory); function getAccountWei(Account.Info memory account, uint256 marketId) external view returns (Types.Wei memory); function getMarketTotalPar(uint256 marketId) external view returns (Types.TotalPar memory); function getLiquidationSpreadForPair(uint256 heldMarketId, uint256 owedMarketId) external view returns (Decimal.D256 memory); function getNumExcessTokens(uint256 marketId) external view returns (Types.Wei memory); function getMarketCachedIndex(uint256 marketId) external view returns (Interest.Index memory); function getAccountStatus(Account.Info memory account) external view returns (uint8); function getEarningsRate() external view returns (Decimal.D256 memory); function ownerSetPriceOracle(uint256 marketId, address priceOracle) external; function getRiskLimits() external view returns (Storage.RiskLimits memory); function getMarket(uint256 marketId) external view returns (Storage.Market memory); function ownerSetIsClosing(uint256 marketId, bool isClosing) external; function ownerSetGlobalOperator(address operator1, bool approved) external; function transferOwnership(address newOwner) external; function getAdjustedAccountValues(Account.Info memory account) external view returns (Monetary.Value memory, Monetary.Value memory); function getMarketMarginPremium(uint256 marketId) external view returns (Decimal.D256 memory); function getMarketInterestRate(uint256 marketId) external view returns (Interest.Rate memory); } // Part: IUniswapAnchoredView interface IUniswapAnchoredView { function price(string memory) external returns (uint); } // Part: IUniswapV2Router01 interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns ( uint256 amountA, uint256 amountB, uint256 liquidity ); function addLiquidityETH( address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external payable returns ( uint256 amountToken, uint256 amountETH, uint256 liquidity ); function removeLiquidity( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns (uint256 amountA, uint256 amountB); function removeLiquidityETH( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external returns (uint256 amountToken, uint256 amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountA, uint256 amountB); function removeLiquidityETHWithPermit( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountToken, uint256 amountETH); function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapTokensForExactTokens( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactETHForTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function swapTokensForExactETH( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactTokensForETH( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapETHForExactTokens( uint256 amountOut, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function quote( uint256 amountA, uint256 reserveA, uint256 reserveB ) external pure returns (uint256 amountB); function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) external pure returns (uint256 amountOut); function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) external pure returns (uint256 amountIn); function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts); function getAmountsIn(uint256 amountOut, address[] calldata path) external view returns (uint256[] memory amounts); } // Part: IUniswapV3SwapCallback /// @title Callback for IUniswapV3PoolActions#swap /// @notice Any contract that calls IUniswapV3PoolActions#swap must implement this interface interface IUniswapV3SwapCallback { /// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap. /// @dev In the implementation you must pay the pool tokens owed for the swap. /// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory. /// amount0Delta and amount1Delta can both be 0 if no tokens were swapped. /// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by /// the end of the swap. If positive, the callback must send that amount of token0 to the pool. /// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by /// the end of the swap. If positive, the callback must send that amount of token1 to the pool. /// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call function uniswapV3SwapCallback( int256 amount0Delta, int256 amount1Delta, bytes calldata data ) external; } // Part: InterestRateModel interface InterestRateModel { /** * @notice Calculates the current borrow interest rate per block * @param cash The total amount of cash the market has * @param borrows The total amount of borrows the market has outstanding * @param reserves The total amount of reserves the market has * @return The borrow rate per block (as a percentage, and scaled by 1e18) */ function getBorrowRate( uint256 cash, uint256 borrows, uint256 reserves ) external view returns (uint256, uint256); /** * @notice Calculates the current supply interest rate per block * @param cash The total amount of cash the market has * @param borrows The total amount of borrows the market has outstanding * @param reserves The total amount of reserves the market has * @param reserveFactorMantissa The current reserve factor the market has * @return The supply rate per block (as a percentage, and scaled by 1e18) */ function getSupplyRate( uint256 cash, uint256 borrows, uint256 reserves, uint256 reserveFactorMantissa ) external view returns (uint256); } // Part: OpenZeppelin/openzeppelin-contracts@3.1.0/Address /** * @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); } } } } // Part: OpenZeppelin/openzeppelin-contracts@3.1.0/IERC20 /** * @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); } // Part: OpenZeppelin/openzeppelin-contracts@3.1.0/Math /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // Part: OpenZeppelin/openzeppelin-contracts@3.1.0/SafeMath /** * @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; } } // Part: Types library Types { enum AssetDenomination { Wei, // the amount is denominated in wei Par // the amount is denominated in par } enum AssetReference { Delta, // the amount is given as a delta from the current value Target // the amount is given as an exact number to end up at } struct AssetAmount { bool sign; // true if positive AssetDenomination denomination; AssetReference ref; uint256 value; } struct TotalPar { uint128 borrow; uint128 supply; } struct Par { bool sign; // true if positive uint128 value; } struct Wei { bool sign; // true if positive uint256 value; } } // Part: iearn-finance/yearn-vaults@0.3.0-2/HealthCheck interface HealthCheck { function check( uint256 profit, uint256 loss, uint256 debtPayment, uint256 debtOutstanding, uint256 totalDebt ) external view returns (bool); } // Part: CTokenI interface CTokenI { /*** Market Events ***/ /** * @notice Event emitted when interest is accrued */ event AccrueInterest(uint256 cashPrior, uint256 interestAccumulated, uint256 borrowIndex, uint256 totalBorrows); /** * @notice Event emitted when tokens are minted */ event Mint(address minter, uint256 mintAmount, uint256 mintTokens); /** * @notice Event emitted when tokens are redeemed */ event Redeem(address redeemer, uint256 redeemAmount, uint256 redeemTokens); /** * @notice Event emitted when underlying is borrowed */ event Borrow(address borrower, uint256 borrowAmount, uint256 accountBorrows, uint256 totalBorrows); /** * @notice Event emitted when a borrow is repaid */ event RepayBorrow(address payer, address borrower, uint256 repayAmount, uint256 accountBorrows, uint256 totalBorrows); /** * @notice Event emitted when a borrow is liquidated */ event LiquidateBorrow(address liquidator, address borrower, uint256 repayAmount, address cTokenCollateral, uint256 seizeTokens); /*** Admin Events ***/ /** * @notice Event emitted when pendingAdmin is changed */ event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin); /** * @notice Event emitted when pendingAdmin is accepted, which means admin is updated */ event NewAdmin(address oldAdmin, address newAdmin); /** * @notice Event emitted when the reserve factor is changed */ event NewReserveFactor(uint256 oldReserveFactorMantissa, uint256 newReserveFactorMantissa); /** * @notice Event emitted when the reserves are added */ event ReservesAdded(address benefactor, uint256 addAmount, uint256 newTotalReserves); /** * @notice Event emitted when the reserves are reduced */ event ReservesReduced(address admin, uint256 reduceAmount, uint256 newTotalReserves); /** * @notice EIP20 Transfer event */ event Transfer(address indexed from, address indexed to, uint256 amount); /** * @notice EIP20 Approval event */ event Approval(address indexed owner, address indexed spender, uint256 amount); /** * @notice Failure event */ event Failure(uint256 error, uint256 info, uint256 detail); function transfer(address dst, uint256 amount) external returns (bool); function transferFrom( address src, address dst, uint256 amount ) external returns (bool); function approve(address spender, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function balanceOf(address owner) external view returns (uint256); function balanceOfUnderlying(address owner) external returns (uint256); function getAccountSnapshot(address account) external view returns ( uint256, uint256, uint256, uint256 ); function borrowRatePerBlock() external view returns (uint256); function supplyRatePerBlock() external view returns (uint256); function totalBorrowsCurrent() external returns (uint256); function borrowBalanceCurrent(address account) external returns (uint256); function borrowBalanceStored(address account) external view returns (uint256); function exchangeRateCurrent() external returns (uint256); function accrualBlockNumber() external view returns (uint256); function exchangeRateStored() external view returns (uint256); function getCash() external view returns (uint256); function accrueInterest() external returns (uint256); function interestRateModel() external view returns (InterestRateModel); function totalReserves() external view returns (uint256); function reserveFactorMantissa() external view returns (uint256); function seize( address liquidator, address borrower, uint256 seizeTokens ) external returns (uint256); function totalBorrows() external view returns (uint256); function totalSupply() external view returns (uint256); } // Part: IERC20Extended interface IERC20Extended is IERC20 { function decimals() external view returns (uint8); function name() external view returns (string memory); function symbol() external view returns (string memory); } // Part: IUniswapV2Router02 interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external returns (uint256 amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; } // Part: IUniswapV3Router /// @title Router token swapping functionality /// @notice Functions for swapping tokens via Uniswap V3 interface IUniswapV3Router is IUniswapV3SwapCallback { struct ExactInputSingleParams { address tokenIn; address tokenOut; uint24 fee; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; uint160 sqrtPriceLimitX96; } /// @notice Swaps `amountIn` of one token for as much as possible of another token /// @param params The parameters necessary for the swap, encoded as `ExactInputSingleParams` in calldata /// @return amountOut The amount of the received token function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut); struct ExactInputParams { bytes path; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; } /// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata /// @return amountOut The amount of the received token function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut); struct ExactOutputSingleParams { address tokenIn; address tokenOut; uint24 fee; address recipient; uint256 deadline; uint256 amountOut; uint256 amountInMaximum; uint160 sqrtPriceLimitX96; } /// @notice Swaps as little as possible of one token for `amountOut` of another token /// @param params The parameters necessary for the swap, encoded as `ExactOutputSingleParams` in calldata /// @return amountIn The amount of the input token function exactOutputSingle(ExactOutputSingleParams calldata params) external payable returns (uint256 amountIn); struct ExactOutputParams { bytes path; address recipient; uint256 deadline; uint256 amountOut; uint256 amountInMaximum; } /// @notice Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed) /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata /// @return amountIn The amount of the input token function exactOutput(ExactOutputParams calldata params) external payable returns (uint256 amountIn); } // Part: IWETH interface IWETH is IERC20 { function deposit() payable external; function withdraw(uint256) external; } // Part: OpenZeppelin/openzeppelin-contracts@3.1.0/SafeERC20 /** * @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"); } } } // Part: iearn-finance/yearn-vaults@0.3.0-2/VaultAPI interface VaultAPI is IERC20 { function apiVersion() external view returns (string memory); function withdraw(uint256 shares, address recipient) external; function token() external view returns (address); function strategies(address _strategy) external view returns (StrategyParams memory); /** * View how much the Vault would increase this Strategy's borrow limit, * based on its present performance (since its last report). Can be used to * determine expectedReturn in your Strategy. */ function creditAvailable() external view returns (uint256); /** * View how much the Vault would like to pull back from the Strategy, * based on its present performance (since its last report). Can be used to * determine expectedReturn in your Strategy. */ function debtOutstanding() external view returns (uint256); /** * View how much the Vault expect this Strategy to return at the current * block, based on its present performance (since its last report). Can be * used to determine expectedReturn in your Strategy. */ function expectedReturn() external view returns (uint256); /** * This is the main contact point where the Strategy interacts with the * Vault. It is critical that this call is handled as intended by the * Strategy. Therefore, this function will be called by BaseStrategy to * make sure the integration is correct. */ function report( uint256 _gain, uint256 _loss, uint256 _debtPayment ) external returns (uint256); /** * This function should only be used in the scenario where the Strategy is * being retired but no migration of the positions are possible, or in the * extreme scenario that the Strategy needs to be put into "Emergency Exit" * mode in order for it to exit as quickly as possible. The latter scenario * could be for any reason that is considered "critical" that the Strategy * exits its position as fast as possible, such as a sudden change in * market conditions leading to losses, or an imminent failure in an * external dependency. */ function revokeStrategy() external; /** * View the governance address of the Vault to assert privileged functions * can only be called by governance. The Strategy serves the Vault, so it * is subject to governance defined by the Vault. */ function governance() external view returns (address); } // Part: CErc20I interface CErc20I is CTokenI { function mint(uint256 mintAmount) external returns (uint256); function redeem(uint256 redeemTokens) external returns (uint256); function redeemUnderlying(uint256 redeemAmount) external returns (uint256); function borrow(uint256 borrowAmount) external returns (uint256); function repayBorrow(uint256 repayAmount) external returns (uint256); function repayBorrowBehalf(address borrower, uint256 repayAmount) external returns (uint256); function liquidateBorrow( address borrower, uint256 repayAmount, CTokenI cTokenCollateral ) external returns (uint256); function underlying() external view returns (address); } // Part: CEtherI interface CEtherI is CTokenI { function redeemUnderlying(uint256 redeemAmount) external returns (uint256); function redeem(uint256 redeemTokens) external returns (uint256); function liquidateBorrow(address borrower, CTokenI cTokenCollateral) external payable; function borrow(uint256 borrowAmount) external returns (uint); function mint() external payable; function repayBorrow() external payable; } // Part: ComptrollerI interface ComptrollerI { function enterMarkets(address[] calldata cTokens) external returns (uint256[] memory); function exitMarket(address cToken) external returns (uint256); /*** Policy Hooks ***/ function mintAllowed( address cToken, address minter, uint256 mintAmount ) external returns (uint256); function mintVerify( address cToken, address minter, uint256 mintAmount, uint256 mintTokens ) external; function redeemAllowed( address cToken, address redeemer, uint256 redeemTokens ) external returns (uint256); function redeemVerify( address cToken, address redeemer, uint256 redeemAmount, uint256 redeemTokens ) external; function borrowAllowed( address cToken, address borrower, uint256 borrowAmount ) external returns (uint256); function borrowVerify( address cToken, address borrower, uint256 borrowAmount ) external; function repayBorrowAllowed( address cToken, address payer, address borrower, uint256 repayAmount ) external returns (uint256); function repayBorrowVerify( address cToken, address payer, address borrower, uint256 repayAmount, uint256 borrowerIndex ) external; function liquidateBorrowAllowed( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint256 repayAmount ) external returns (uint256); function liquidateBorrowVerify( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint256 repayAmount, uint256 seizeTokens ) external; function seizeAllowed( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint256 seizeTokens ) external returns (uint256); function seizeVerify( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint256 seizeTokens ) external; function transferAllowed( address cToken, address src, address dst, uint256 transferTokens ) external returns (uint256); function transferVerify( address cToken, address src, address dst, uint256 transferTokens ) external; /*** Liquidity/Liquidation Calculations ***/ function liquidateCalculateSeizeTokens( address cTokenBorrowed, address cTokenCollateral, uint256 repayAmount ) external view returns (uint256, uint256); function getAccountLiquidity(address account) external view returns ( uint256, uint256, uint256 ); /*** Comp claims ****/ function claimComp(address holder) external; function claimComp(address holder, CTokenI[] memory cTokens) external; function markets(address ctoken) external view returns ( bool, uint256, bool ); function compSpeeds(address ctoken) external view returns (uint256); // will be deprecated function compSupplySpeeds(address ctoken) external view returns (uint256); function compBorrowSpeeds(address ctoken) external view returns (uint256); function oracle() external view returns (address); } // Part: iearn-finance/yearn-vaults@0.3.0-2/BaseStrategy /** * @title Yearn Base Strategy * @author yearn.finance * @notice * BaseStrategy implements all of the required functionality to interoperate * closely with the Vault contract. This contract should be inherited and the * abstract methods implemented to adapt the Strategy to the particular needs * it has to create a return. * * Of special interest is the relationship between `harvest()` and * `vault.report()'. `harvest()` may be called simply because enough time has * elapsed since the last report, and not because any funds need to be moved * or positions adjusted. This is critical so that the Vault may maintain an * accurate picture of the Strategy's performance. See `vault.report()`, * `harvest()`, and `harvestTrigger()` for further details. */ abstract contract BaseStrategy { using SafeMath for uint256; // health checks bool public doHealthCheck; address public healthCheck; /** * @notice * Used to track which version of `StrategyAPI` this Strategy * implements. * @dev The Strategy's version must match the Vault's `API_VERSION`. * @return A string which holds the current API version of this contract. */ function apiVersion() public pure returns (string memory) { return "0.3.0"; } /** * @notice This Strategy's name. * @dev * You can use this field to manage the "version" of this Strategy, e.g. * `StrategySomethingOrOtherV1`. However, "API Version" is managed by * `apiVersion()` function above. * @return This Strategy's name. */ function name() external virtual view returns (string memory); /** * @notice * The amount (priced in want) of the total assets managed by this strategy should not count * towards Yearn's TVL calculations. * @dev * You can override this field to set it to a non-zero value if some of the assets of this * Strategy is somehow delegated inside another part of of Yearn's ecosystem e.g. another Vault. * Note that this value must be strictly less than or equal to the amount provided by * `estimatedTotalAssets()` below, as the TVL calc will be total assets minus delegated assets. * @return * The amount of assets this strategy manages that should not be included in Yearn's Total Value * Locked (TVL) calculation across it's ecosystem. */ function delegatedAssets() external virtual view returns (uint256) { return 0; } VaultAPI public vault; address public strategist; address public rewards; address public keeper; IERC20 public want; // So indexers can keep track of this event Harvested(uint256 profit, uint256 loss, uint256 debtPayment, uint256 debtOutstanding); event UpdatedStrategist(address newStrategist); event UpdatedKeeper(address newKeeper); event UpdatedRewards(address rewards); event UpdatedReportDelay(uint256 delay); event UpdatedProfitFactor(uint256 profitFactor); event UpdatedDebtThreshold(uint256 debtThreshold); event EmergencyExitEnabled(); // The maximum number of seconds between harvest calls. See // `setMaxReportDelay()` for more details. uint256 public maxReportDelay = 86400; // ~ once a day // The minimum multiple that `callCost` must be above the credit/profit to // be "justifiable". See `setProfitFactor()` for more details. uint256 public profitFactor = 100; // Use this to adjust the threshold at which running a debt causes a // harvest trigger. See `setDebtThreshold()` for more details. uint256 public debtThreshold = 0; // See note on `setEmergencyExit()`. bool public emergencyExit; // modifiers modifier onlyAuthorized() { require(msg.sender == strategist || msg.sender == governance(), "!authorized"); _; } modifier onlyStrategist() { require(msg.sender == strategist, "!strategist"); _; } modifier onlyGovernance() { require(msg.sender == governance(), "!authorized"); _; } modifier onlyKeepers() { require(msg.sender == keeper || msg.sender == strategist || msg.sender == governance(), "!authorized"); _; } constructor(address _vault) public { _initialize(_vault, msg.sender, msg.sender, msg.sender); } /** * @notice * Initializes the Strategy, this is called only once, when the * contract is deployed. * @dev `_vault` should implement `VaultAPI`. * @param _vault The address of the Vault responsible for this Strategy. */ function _initialize( address _vault, address _strategist, address _rewards, address _keeper ) internal { require(address(want) == address(0), "Strategy already initialized"); vault = VaultAPI(_vault); want = IERC20(vault.token()); want.approve(_vault, uint256(-1)); // Give Vault unlimited access (might save gas) strategist = _strategist; rewards = _rewards; keeper = _keeper; vault.approve(rewards, uint256(-1)); // Allow rewards to be pulled } function setHealthCheck(address _healthCheck) external onlyGovernance { healthCheck = _healthCheck; } function setDoHealthCheck(bool _doHealthCheck) external onlyGovernance { doHealthCheck = _doHealthCheck; } /** * @notice * Used to change `strategist`. * * This may only be called by governance or the existing strategist. * @param _strategist The new address to assign as `strategist`. */ function setStrategist(address _strategist) external onlyAuthorized { require(_strategist != address(0)); strategist = _strategist; emit UpdatedStrategist(_strategist); } /** * @notice * Used to change `keeper`. * * `keeper` is the only address that may call `tend()` or `harvest()`, * other than `governance()` or `strategist`. However, unlike * `governance()` or `strategist`, `keeper` may *only* call `tend()` * and `harvest()`, and no other authorized functions, following the * principle of least privilege. * * This may only be called by governance or the strategist. * @param _keeper The new address to assign as `keeper`. */ function setKeeper(address _keeper) external onlyAuthorized { require(_keeper != address(0)); keeper = _keeper; emit UpdatedKeeper(_keeper); } /** * @notice * Used to change `rewards`. Any distributed rewards will cease flowing * to the old address and begin flowing to this address once the change * is in effect. * * This may only be called by the strategist. * @param _rewards The address to use for collecting rewards. */ function setRewards(address _rewards) external onlyStrategist { require(_rewards != address(0)); rewards = _rewards; emit UpdatedRewards(_rewards); } /** * @notice * Used to change `maxReportDelay`. `maxReportDelay` is the maximum number * of blocks that should pass for `harvest()` to be called. * * For external keepers (such as the Keep3r network), this is the maximum * time between jobs to wait. (see `harvestTrigger()` * for more details.) * * This may only be called by governance or the strategist. * @param _delay The maximum number of seconds to wait between harvests. */ function setMaxReportDelay(uint256 _delay) external onlyAuthorized { maxReportDelay = _delay; emit UpdatedReportDelay(_delay); } /** * @notice * Used to change `profitFactor`. `profitFactor` is used to determine * if it's worthwhile to harvest, given gas costs. (See `harvestTrigger()` * for more details.) * * This may only be called by governance or the strategist. * @param _profitFactor A ratio to multiply anticipated * `harvest()` gas cost against. */ function setProfitFactor(uint256 _profitFactor) external onlyAuthorized { profitFactor = _profitFactor; emit UpdatedProfitFactor(_profitFactor); } /** * @notice * Sets how far the Strategy can go into loss without a harvest and report * being required. * * By default this is 0, meaning any losses would cause a harvest which * will subsequently report the loss to the Vault for tracking. (See * `harvestTrigger()` for more details.) * * This may only be called by governance or the strategist. * @param _debtThreshold How big of a loss this Strategy may carry without * being required to report to the Vault. */ function setDebtThreshold(uint256 _debtThreshold) external onlyAuthorized { debtThreshold = _debtThreshold; emit UpdatedDebtThreshold(_debtThreshold); } /** * Resolve governance address from Vault contract, used to make assertions * on protected functions in the Strategy. */ function governance() internal view returns (address) { return vault.governance(); } /** * @notice * Provide an accurate estimate for the total amount of assets * (principle + return) that this Strategy is currently managing, * denominated in terms of `want` tokens. * * This total should be "realizable" e.g. the total value that could * *actually* be obtained from this Strategy if it were to divest its * entire position based on current on-chain conditions. * @dev * Care must be taken in using this function, since it relies on external * systems, which could be manipulated by the attacker to give an inflated * (or reduced) value produced by this function, based on current on-chain * conditions (e.g. this function is possible to influence through * flashloan attacks, oracle manipulations, or other DeFi attack * mechanisms). * * It is up to governance to use this function to correctly order this * Strategy relative to its peers in the withdrawal queue to minimize * losses for the Vault based on sudden withdrawals. This value should be * higher than the total debt of the Strategy and higher than its expected * value to be "safe". * @return The estimated total assets in this Strategy. */ function estimatedTotalAssets() public virtual view returns (uint256); /* * @notice * Provide an indication of whether this strategy is currently "active" * in that it is managing an active position, or will manage a position in * the future. This should correlate to `harvest()` activity, so that Harvest * events can be tracked externally by indexing agents. * @return True if the strategy is actively managing a position. */ function isActive() public view returns (bool) { return vault.strategies(address(this)).debtRatio > 0 || estimatedTotalAssets() > 0; } /** * Perform any Strategy unwinding or other calls necessary to capture the * "free return" this Strategy has generated since the last time its core * position(s) were adjusted. Examples include unwrapping extra rewards. * This call is only used during "normal operation" of a Strategy, and * should be optimized to minimize losses as much as possible. * * This method returns any realized profits and/or realized losses * incurred, and should return the total amounts of profits/losses/debt * payments (in `want` tokens) for the Vault's accounting (e.g. * `want.balanceOf(this) >= _debtPayment + _profit - _loss`). * * `_debtOutstanding` will be 0 if the Strategy is not past the configured * debt limit, otherwise its value will be how far past the debt limit * the Strategy is. The Strategy's debt limit is configured in the Vault. * * NOTE: `_debtPayment` should be less than or equal to `_debtOutstanding`. * It is okay for it to be less than `_debtOutstanding`, as that * should only used as a guide for how much is left to pay back. * Payments should be made to minimize loss from slippage, debt, * withdrawal fees, etc. * * See `vault.debtOutstanding()`. */ function prepareReturn(uint256 _debtOutstanding) internal virtual returns ( uint256 _profit, uint256 _loss, uint256 _debtPayment ); /** * Perform any adjustments to the core position(s) of this Strategy given * what change the Vault made in the "investable capital" available to the * Strategy. Note that all "free capital" in the Strategy after the report * was made is available for reinvestment. Also note that this number * could be 0, and you should handle that scenario accordingly. * * See comments regarding `_debtOutstanding` on `prepareReturn()`. */ function adjustPosition(uint256 _debtOutstanding) internal virtual; /** * Liquidate up to `_amountNeeded` of `want` of this strategy's positions, * irregardless of slippage. Any excess will be re-invested with `adjustPosition()`. * This function should return the amount of `want` tokens made available by the * liquidation. If there is a difference between them, `_loss` indicates whether the * difference is due to a realized loss, or if there is some other sitution at play * (e.g. locked funds). This function is used during emergency exit instead of * `prepareReturn()` to liquidate all of the Strategy's positions back to the Vault. * * NOTE: The invariant `_amountFreed + _loss <= _amountNeeded` should always be maintained */ function liquidatePosition(uint256 _amountNeeded) internal virtual returns (uint256 _liquidatedAmount, uint256 _loss); /** * `Harvest()` calls this function after shares are created during * `vault.report()`. You can customize this function to any share * distribution mechanism you want. * * See `vault.report()` for further details. */ function distributeRewards() internal virtual { // Transfer 100% of newly-minted shares awarded to this contract to the rewards address. uint256 balance = vault.balanceOf(address(this)); if (balance > 0) { vault.transfer(rewards, balance); } } /** * @notice * Provide a signal to the keeper that `tend()` should be called. The * keeper will provide the estimated gas cost that they would pay to call * `tend()`, and this function should use that estimate to make a * determination if calling it is "worth it" for the keeper. This is not * the only consideration into issuing this trigger, for example if the * position would be negatively affected if `tend()` is not called * shortly, then this can return `true` even if the keeper might be * "at a loss" (keepers are always reimbursed by Yearn). * @dev * `callCost` must be priced in terms of `want`. * * This call and `harvestTrigger()` should never return `true` at the same * time. * @param callCost The keeper's estimated cast cost to call `tend()`. * @return `true` if `tend()` should be called, `false` otherwise. */ function tendTrigger(uint256 callCost) public virtual view returns (bool) { // We usually don't need tend, but if there are positions that need // active maintainence, overriding this function is how you would // signal for that. return false; } /** * @notice * Adjust the Strategy's position. The purpose of tending isn't to * realize gains, but to maximize yield by reinvesting any returns. * * See comments on `adjustPosition()`. * * This may only be called by governance, the strategist, or the keeper. */ function tend() external onlyKeepers { // Don't take profits with this call, but adjust for better gains adjustPosition(vault.debtOutstanding()); } /** * @notice * Provide a signal to the keeper that `harvest()` should be called. The * keeper will provide the estimated gas cost that they would pay to call * `harvest()`, and this function should use that estimate to make a * determination if calling it is "worth it" for the keeper. This is not * the only consideration into issuing this trigger, for example if the * position would be negatively affected if `harvest()` is not called * shortly, then this can return `true` even if the keeper might be "at a * loss" (keepers are always reimbursed by Yearn). * @dev * `callCost` must be priced in terms of `want`. * * This call and `tendTrigger` should never return `true` at the * same time. * * See `maxReportDelay`, `profitFactor`, `debtThreshold` to adjust the * strategist-controlled parameters that will influence whether this call * returns `true` or not. These parameters will be used in conjunction * with the parameters reported to the Vault (see `params`) to determine * if calling `harvest()` is merited. * * It is expected that an external system will check `harvestTrigger()`. * This could be a script run off a desktop or cloud bot (e.g. * https://github.com/iearn-finance/yearn-vaults/blob/master/scripts/keep.py), * or via an integration with the Keep3r network (e.g. * https://github.com/Macarse/GenericKeep3rV2/blob/master/contracts/keep3r/GenericKeep3rV2.sol). * @param callCost The keeper's estimated cast cost to call `harvest()`. * @return `true` if `harvest()` should be called, `false` otherwise. */ function harvestTrigger(uint256 callCost) public virtual view returns (bool) { StrategyParams memory params = vault.strategies(address(this)); // Should not trigger if Strategy is not activated if (params.activation == 0) return false; // Should trigger if hasn't been called in a while if (block.timestamp.sub(params.lastReport) >= maxReportDelay) return true; // If some amount is owed, pay it back // NOTE: Since debt is based on deposits, it makes sense to guard against large // changes to the value from triggering a harvest directly through user // behavior. This should ensure reasonable resistance to manipulation // from user-initiated withdrawals as the outstanding debt fluctuates. uint256 outstanding = vault.debtOutstanding(); if (outstanding > debtThreshold) return true; // Check for profits and losses uint256 total = estimatedTotalAssets(); // Trigger if we have a loss to report if (total.add(debtThreshold) < params.totalDebt) return true; uint256 profit = 0; if (total > params.totalDebt) profit = total.sub(params.totalDebt); // We've earned a profit! // Otherwise, only trigger if it "makes sense" economically (gas cost // is <N% of value moved) uint256 credit = vault.creditAvailable(); return (profitFactor.mul(callCost) < credit.add(profit)); } /** * @notice * Harvests the Strategy, recognizing any profits or losses and adjusting * the Strategy's position. * * In the rare case the Strategy is in emergency shutdown, this will exit * the Strategy's position. * * This may only be called by governance, the strategist, or the keeper. * @dev * When `harvest()` is called, the Strategy reports to the Vault (via * `vault.report()`), so in some cases `harvest()` must be called in order * to take in profits, to borrow newly available funds from the Vault, or * otherwise adjust its position. In other cases `harvest()` must be * called to report to the Vault on the Strategy's position, especially if * any losses have occurred. */ function harvest() external onlyKeepers { uint256 profit = 0; uint256 loss = 0; uint256 debtOutstanding = vault.debtOutstanding(); uint256 debtPayment = 0; if (emergencyExit) { // Free up as much capital as possible uint256 totalAssets = estimatedTotalAssets(); // NOTE: use the larger of total assets or debt outstanding to book losses properly (debtPayment, loss) = liquidatePosition(totalAssets > debtOutstanding ? totalAssets : debtOutstanding); // NOTE: take up any remainder here as profit if (debtPayment > debtOutstanding) { profit = debtPayment.sub(debtOutstanding); debtPayment = debtOutstanding; } } else { // Free up returns for Vault to pull (profit, loss, debtPayment) = prepareReturn(debtOutstanding); } // Allow Vault to take up to the "harvested" balance of this contract, // which is the amount it has earned since the last time it reported to // the Vault. uint256 totalDebt = vault.strategies(address(this)).totalDebt; debtOutstanding = vault.report(profit, loss, debtPayment); // Distribute any reward shares earned by the strategy on this report distributeRewards(); // Check if free returns are left, and re-invest them adjustPosition(debtOutstanding); // call healthCheck contract if (doHealthCheck && healthCheck != address(0)) { require( HealthCheck(healthCheck).check( profit, loss, debtPayment, debtOutstanding, totalDebt ), "!healthcheck" ); } else { doHealthCheck = true; } emit Harvested(profit, loss, debtPayment, debtOutstanding); } /** * @notice * Withdraws `_amountNeeded` to `vault`. * * This may only be called by the Vault. * @param _amountNeeded How much `want` to withdraw. * @return _loss Any realized losses */ function withdraw(uint256 _amountNeeded) external returns (uint256 _loss) { require(msg.sender == address(vault), "!vault"); // Liquidate as much as possible to `want`, up to `_amount` uint256 amountFreed; (amountFreed, _loss) = liquidatePosition(_amountNeeded); // sanity check require(_amountNeeded == amountFreed.add(_loss), "!withdraw"); // Send it directly back (NOTE: Using `msg.sender` saves some gas here) want.transfer(msg.sender, amountFreed); // NOTE: Reinvest anything leftover on next `tend`/`harvest` } /** * Do anything necessary to prepare this Strategy for migration, such as * transferring any reserve or LP tokens, CDPs, or other tokens or stores of * value. */ function prepareMigration(address _newStrategy) internal virtual; /** * @notice * Transfers all `want` from this Strategy to `_newStrategy`. * * This may only be called by governance or the Vault. * @dev * The new Strategy's Vault must be the same as this Strategy's Vault. * @param _newStrategy The Strategy to migrate to. */ function migrate(address _newStrategy) external { require(msg.sender == address(vault) || msg.sender == governance()); require(BaseStrategy(_newStrategy).vault() == vault); prepareMigration(_newStrategy); want.transfer(_newStrategy, want.balanceOf(address(this))); } /** * @notice * Activates emergency exit. Once activated, the Strategy will exit its * position upon the next harvest, depositing all funds into the Vault as * quickly as is reasonable given on-chain conditions. * * This may only be called by governance or the strategist. * @dev * See `vault.setEmergencyShutdown()` and `harvest()` for further details. */ function setEmergencyExit() external onlyAuthorized { emergencyExit = true; vault.revokeStrategy(); emit EmergencyExitEnabled(); } /** * Override this to add all tokens/tokenized positions this contract * manages on a *persistent* basis (e.g. not just for swapping back to * want ephemerally). * * NOTE: Do *not* include `want`, already included in `sweep` below. * * Example: * * function protectedTokens() internal override view returns (address[] memory) { * address[] memory protected = new address[](3); * protected[0] = tokenA; * protected[1] = tokenB; * protected[2] = tokenC; * return protected; * } */ function protectedTokens() internal virtual view returns (address[] memory); /** * @notice * Removes tokens from this Strategy that are not the type of tokens * managed by this Strategy. This may be used in case of accidentally * sending the wrong kind of token to this Strategy. * * Tokens will be sent to `governance()`. * * This will fail if an attempt is made to sweep `want`, or any tokens * that are protected by this Strategy. * * This may only be called by governance. * @dev * Implement `protectedTokens()` to specify any additional tokens that * should be protected from sweeping in addition to `want`. * @param _token The token to transfer out of this vault. */ function sweep(address _token) external onlyGovernance { require(_token != address(want), "!want"); require(_token != address(vault), "!shares"); address[] memory _protectedTokens = protectedTokens(); for (uint256 i; i < _protectedTokens.length; i++) require(_token != _protectedTokens[i], "!protected"); IERC20(_token).transfer(governance(), IERC20(_token).balanceOf(address(this))); } } // Part: FlashLoanLib library FlashLoanLib { using SafeMath for uint256; event Leverage(uint256 amountRequested, uint256 amountGiven, bool deficit, address flashLoan); uint256 constant private PRICE_DECIMALS = 1e6; uint256 constant private WETH_DECIMALS = 1e18; uint256 constant private COLLAT_RATIO_ETH = 0.74 ether; address private constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address private constant WBTC = 0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599; ComptrollerI private constant COMP = ComptrollerI(0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B); ISoloMargin public constant SOLO = ISoloMargin(0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e); CEtherI public constant CETH = CEtherI(0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5); function doDyDxFlashLoan(bool deficit, uint256 amountDesired, address want) public returns (uint256) { if(amountDesired == 0){ return 0; } // calculate amount of ETH we need (uint256 requiredETH, uint256 amountWant)= getFlashLoanParams(want, amountDesired); // Array of actions to be done during FlashLoan Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3); // 1. Take FlashLoan operations[0] = _getWithdrawAction(0, requiredETH); // hardcoded market ID to 0 (ETH) // 2. Encode arguments of functions and create action for calling it bytes memory data = abi.encode(deficit, amountWant); operations[1] = _getCallAction( data ); // 3. Repay FlashLoan operations[2] = _getDepositAction(0, requiredETH.add(2)); // Create Account Info Account.Info[] memory accountInfos = new Account.Info[](1); accountInfos[0] = _getAccountInfo(); SOLO.operate(accountInfos, operations); emit Leverage(amountDesired, requiredETH, deficit, address(SOLO)); return amountWant; // we need to return the amount of Want we have changed our position in } function getFlashLoanParams(address want, uint256 amountDesired) internal returns (uint256 requiredETH, uint256 amountWant) { (uint256 priceETHWant, uint256 decimalsDifference, uint256 _requiredETH) = getPriceETHWant(want, amountDesired); // to avoid stack too deep requiredETH = _requiredETH; amountWant = amountDesired; // Not enough want in DyDx. So we take all we can uint256 dxdyLiquidity = IERC20(WETH).balanceOf(address(SOLO)); if(requiredETH > dxdyLiquidity) { requiredETH = dxdyLiquidity; // NOTE: if we cap amountETH, we reduce amountWant we are taking too amountWant = requiredETH.mul(COLLAT_RATIO_ETH).div(priceETHWant).div(1e18).div(decimalsDifference); } } function getPriceETHWant(address want, uint256 amountDesired) internal returns (uint256 priceETHWant, uint256 decimalsDifference, uint256 requiredETH) { uint256 wantDecimals = 10 ** uint256(IERC20Extended(want).decimals()); decimalsDifference = WETH_DECIMALS > wantDecimals ? WETH_DECIMALS.div(wantDecimals) : wantDecimals.div(WETH_DECIMALS); if(want == WETH) { requiredETH = amountDesired.mul(1e18).div(COLLAT_RATIO_ETH); priceETHWant = 1e6; // 1:1 } else { priceETHWant = getOraclePrice(WETH).mul(PRICE_DECIMALS).div(getOraclePrice(want)); // requiredETH = desiredWantInETH / COLLAT_RATIO_ETH // desiredWBTCInETH = (desiredWant / priceETHWant) // NOTE: decimals need adjustment (e.g. BTC: 8 / ETH: 18) requiredETH = amountDesired.mul(PRICE_DECIMALS).mul(1e18).mul(decimalsDifference).div(priceETHWant).div(COLLAT_RATIO_ETH); } } function getOraclePrice(address token) internal returns (uint256) { string memory symbol = IERC20Extended(token).symbol(); // Symbol for WBTC is BTC in oracle if(token == WBTC) { symbol = "BTC"; } else if (token == WETH) { symbol = "ETH"; } IUniswapAnchoredView oracle = IUniswapAnchoredView(COMP.oracle()); return oracle.price(symbol); } function loanLogic( bool deficit, uint256 amount, CErc20I cToken ) public { uint256 wethBal = IERC20(WETH).balanceOf(address(this)); // NOTE: weth balance should always be > amount/0.75 require(wethBal >= amount, "!bal"); // to stop malicious calls uint256 wethBalance = IERC20(WETH).balanceOf(address(this)); // 0. Unwrap WETH IWETH(WETH).withdraw(wethBalance); // 1. Deposit ETH in Compound as collateral // will revert if it fails CETH.mint{value: wethBalance}(); //if in deficit we repay amount and then withdraw if (deficit) { // 2a. if in deficit withdraw amount and repay it require(cToken.redeemUnderlying(amount) == 0, "!redeem_down"); require(cToken.repayBorrow(IERC20(cToken.underlying()).balanceOf(address(this))) == 0, "!repay_down"); } else { // 2b. if levering up borrow and deposit require(cToken.borrow(amount) == 0, "!borrow_up"); require(cToken.mint(IERC20(cToken.underlying()).balanceOf(address(this))) == 0, "!mint_up"); } // 3. Redeem collateral (ETH borrowed from DyDx) from Compound require(CETH.redeemUnderlying(wethBalance) == 0, "!redeem"); // 4. Wrap ETH into WETH IWETH(WETH).deposit{value: address(this).balance}(); // NOTE: after this, WETH will be taken by DyDx } function _getAccountInfo() internal view returns (Account.Info memory) { return Account.Info({owner: address(this), number: 1}); } function _getWithdrawAction(uint256 marketId, uint256 amount) internal view returns (Actions.ActionArgs memory) { return Actions.ActionArgs({ actionType: Actions.ActionType.Withdraw, accountId: 0, amount: Types.AssetAmount({ sign: false, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: amount }), primaryMarketId: marketId, secondaryMarketId: 0, otherAddress: address(this), otherAccountId: 0, data: "" }); } function _getCallAction(bytes memory data) internal view returns (Actions.ActionArgs memory) { return Actions.ActionArgs({ actionType: Actions.ActionType.Call, accountId: 0, amount: Types.AssetAmount({sign: false, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: 0}), primaryMarketId: 0, secondaryMarketId: 0, otherAddress: address(this), otherAccountId: 0, data: data }); } function _getDepositAction(uint256 marketId, uint256 amount) internal view returns (Actions.ActionArgs memory) { return Actions.ActionArgs({ actionType: Actions.ActionType.Deposit, accountId: 0, amount: Types.AssetAmount({ sign: true, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: amount }), primaryMarketId: marketId, secondaryMarketId: 0, otherAddress: address(this), otherAccountId: 0, data: "" }); } } // File: Strategy.sol /******************** * * A lender optimisation strategy for any erc20 asset * https://github.com/Grandthrax/yearnV2-generic-lender-strat * v0.4.2 * ********************* */ contract Strategy is BaseStrategy, ICallee { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; // @notice emitted when trying to do Flash Loan. flashLoan address is 0x00 when no flash loan used event Leverage(uint256 amountRequested, uint256 amountGiven, bool deficit, address flashLoan); // Comptroller address for compound.finance ComptrollerI private constant compound = ComptrollerI(0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B); //Only three tokens we use address private constant comp = 0xc00e94Cb662C3520282E6f5717214004A7f26888; address private constant weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; CErc20I public cToken; bool public useUniV3; // fee pool to use in UniV3 in basis points(default: 0.3% = 3000) uint24 public compToWethSwapFee; uint24 public wethToWantSwapFee; IUniswapV2Router02 public currentV2Router; IUniswapV2Router02 private constant UNI_V2_ROUTER = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); IUniswapV2Router02 private constant SUSHI_V2_ROUTER = IUniswapV2Router02(0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F); IUniswapV3Router private constant UNI_V3_ROUTER = IUniswapV3Router(0xE592427A0AEce92De3Edee1F18E0157C05861564); uint256 public collateralTarget; // total borrow / total supply ratio we are targeting (100% = 1e18) uint256 public blocksToLiquidationDangerZone; // minimum number of blocks before liquidation uint256 public minWant; // minimum amount of want to act on // Rewards handling bool public dontClaimComp; // enable/disables COMP claiming uint256 public minCompToSell; // minimum amount of COMP to be sold bool public DyDxActive; // To deactivate flash loan provider if needed bool public forceMigrate; constructor(address _vault, address _cToken) public BaseStrategy(_vault) { _initializeThis(_cToken); } function approveTokenMax(address token, address spender) internal { IERC20(token).safeApprove(spender, type(uint256).max); } // To receive ETH from compound and WETH contract receive() external payable {} function name() external override view returns (string memory){ return "GenLevCompV2"; } function _initializeThis(address _cToken) internal { cToken = CErc20I(address(_cToken)); currentV2Router = SUSHI_V2_ROUTER; //pre-set approvals approveTokenMax(comp, address(UNI_V2_ROUTER)); approveTokenMax(comp, address(SUSHI_V2_ROUTER)); approveTokenMax(comp, address(UNI_V3_ROUTER)); approveTokenMax(address(want), address(cToken)); approveTokenMax(weth, address(FlashLoanLib.SOLO)); // Enter Compound's ETH market to take it into account when using ETH as collateral address[] memory markets = new address[](2); markets[0] = address(FlashLoanLib.CETH); markets[1] = address(cToken); compound.enterMarkets(markets); //comp speed is amount to borrow or deposit (so half the total distribution for want) compToWethSwapFee = 3000; wethToWantSwapFee = 3000; // You can set these parameters on deployment to whatever you want maxReportDelay = 86400; // once per 24 hours profitFactor = 100; // multiple before triggering harvest minCompToSell = 0.1 ether; collateralTarget = 0.74 ether; blocksToLiquidationDangerZone = 46500; DyDxActive = true; } /* * Control Functions */ function setUniV3PathFees(uint24 _compToWethSwapFee, uint24 _wethToWantSwapFee) external management { compToWethSwapFee = _compToWethSwapFee; wethToWantSwapFee = _wethToWantSwapFee; } function setDontClaimComp(bool _dontClaimComp) external management { dontClaimComp = _dontClaimComp; } function setUseUniV3(bool _useUniV3) external management { useUniV3 = _useUniV3; } function setToggleV2Router() external management { currentV2Router = currentV2Router == SUSHI_V2_ROUTER ? UNI_V2_ROUTER : SUSHI_V2_ROUTER; } function setDyDx(bool _dydx) external management { DyDxActive = _dydx; } function setForceMigrate(bool _force) external onlyGovernance { forceMigrate = _force; } function setMinCompToSell(uint256 _minCompToSell) external management { minCompToSell = _minCompToSell; } function setMinWant(uint256 _minWant) external management { minWant = _minWant; } function setCollateralTarget(uint256 _collateralTarget) external management { (, uint256 collateralFactorMantissa, ) = compound.markets(address(cToken)); require(collateralFactorMantissa > _collateralTarget); collateralTarget = _collateralTarget; } /* * Base External Facing Functions */ /* * An accurate estimate for the total amount of assets (principle + return) * that this strategy is currently managing, denominated in terms of want tokens. */ function estimatedTotalAssets() public override view returns (uint256) { (uint256 deposits, uint256 borrows) = getCurrentPosition(); uint256 _claimableComp = predictCompAccrued(); uint256 currentComp = balanceOfToken(comp); // Use touch price. it doesnt matter if we are wrong as this is not used for decision making uint256 estimatedWant = priceCheck(comp, address(want),_claimableComp.add(currentComp)); uint256 conservativeWant = estimatedWant.mul(9).div(10); //10% pessimist return balanceOfToken(address(want)).add(deposits).add(conservativeWant).sub(borrows); } function balanceOfToken(address token) internal view returns (uint256) { return IERC20(token).balanceOf(address(this)); } //predicts our profit at next report function expectedReturn() public view returns (uint256) { uint256 estimateAssets = estimatedTotalAssets(); uint256 debt = vault.strategies(address(this)).totalDebt; if (debt > estimateAssets) { return 0; } else { return estimateAssets.sub(debt); } } /* * Provide a signal to the keeper that `tend()` should be called. * (keepers are always reimbursed by yEarn) * * NOTE: this call and `harvestTrigger` should never return `true` at the same time. * tendTrigger should be called with same gasCost as harvestTrigger */ function tendTrigger(uint256 gasCost) public override view returns (bool) { if (harvestTrigger(gasCost)) { //harvest takes priority return false; } return getblocksUntilLiquidation() <= blocksToLiquidationDangerZone; } //WARNING. manipulatable and simple routing. Only use for safe functions function priceCheck(address start, address end, uint256 _amount) public view returns (uint256) { if (_amount == 0) { return 0; } uint256[] memory amounts = currentV2Router.getAmountsOut(_amount, getTokenOutPathV2(start, end)); return amounts[amounts.length - 1]; } /***************** * Public non-base function ******************/ //Calculate how many blocks until we are in liquidation based on current interest rates //WARNING does not include compounding so the estimate becomes more innacurate the further ahead we look //equation. Compound doesn't include compounding for most blocks //((deposits*colateralThreshold - borrows) / (borrows*borrowrate - deposits*colateralThreshold*interestrate)); function getblocksUntilLiquidation() public view returns (uint256) { (, uint256 collateralFactorMantissa, ) = compound.markets(address(cToken)); (uint256 deposits, uint256 borrows) = getCurrentPosition(); uint256 borrrowRate = cToken.borrowRatePerBlock(); uint256 supplyRate = cToken.supplyRatePerBlock(); uint256 collateralisedDeposit1 = deposits.mul(collateralFactorMantissa).div(1e18); uint256 collateralisedDeposit = collateralisedDeposit1; uint256 denom1 = borrows.mul(borrrowRate); uint256 denom2 = collateralisedDeposit.mul(supplyRate); if (denom2 >= denom1) { return type(uint256).max; } else { uint256 numer = collateralisedDeposit.sub(borrows); uint256 denom = denom1.sub(denom2); //minus 1 for this block return numer.mul(1e18).div(denom); } } // This function makes a prediction on how much comp is accrued // It is not 100% accurate as it uses current balances in Compound to predict into the past function predictCompAccrued() public view returns (uint256) { (uint256 deposits, uint256 borrows) = getCurrentPosition(); if (deposits == 0) { return 0; // should be impossible to have 0 balance and positive comp accrued } uint256 distributionPerBlockSupply = compound.compSupplySpeeds(address(cToken)); uint256 distributionPerBlockBorrow = compound.compBorrowSpeeds(address(cToken)); uint256 totalBorrow = cToken.totalBorrows(); //total supply needs to be echanged to underlying using exchange rate uint256 totalSupplyCtoken = cToken.totalSupply(); uint256 totalSupply = totalSupplyCtoken.mul(cToken.exchangeRateStored()).div(1e18); uint256 blockShareSupply = 0; if(totalSupply > 0) { blockShareSupply = deposits.mul(distributionPerBlockSupply).div(totalSupply); } uint256 blockShareBorrow = 0; if(totalBorrow > 0) { blockShareBorrow = borrows.mul(distributionPerBlockBorrow).div(totalBorrow); } //how much we expect to earn per block uint256 blockShare = blockShareSupply.add(blockShareBorrow); //last time we ran harvest uint256 lastReport = vault.strategies(address(this)).lastReport; uint256 blocksSinceLast= (block.timestamp.sub(lastReport)).div(13); //roughly 13 seconds per block return blocksSinceLast.mul(blockShare); } //Returns the current position //WARNING - this returns just the balance at last time someone touched the cToken token. Does not accrue interst in between //cToken is very active so not normally an issue. function getCurrentPosition() public view returns (uint256 deposits, uint256 borrows) { (, uint256 ctokenBalance, uint256 borrowBalance, uint256 exchangeRate) = cToken.getAccountSnapshot(address(this)); borrows = borrowBalance; deposits = ctokenBalance.mul(exchangeRate).div(1e18); } //statechanging version function getLivePosition() public returns (uint256 deposits, uint256 borrows) { deposits = cToken.balanceOfUnderlying(address(this)); //we can use non state changing now because we updated state with balanceOfUnderlying call borrows = cToken.borrowBalanceStored(address(this)); } //Same warning as above function netBalanceLent() public view returns (uint256) { (uint256 deposits, uint256 borrows) = getCurrentPosition(); return deposits.sub(borrows); } /*********** * internal core logic *********** */ /* * A core method. * Called at beggining of harvest before providing report to owner * 1 - claim accrued comp * 2 - if enough to be worth it we sell * 3 - because we lose money on our loans we need to offset profit from comp. */ function prepareReturn(uint256 _debtOutstanding) internal override returns ( uint256 _profit, uint256 _loss, uint256 _debtPayment ) { _profit = 0; _loss = 0; //for clarity. also reduces bytesize if (balanceOfToken(address(cToken)) == 0) { uint256 wantBalance = balanceOfToken(address(want)); //no position to harvest //but we may have some debt to return //it is too expensive to free more debt in this method so we do it in adjust position _debtPayment = Math.min(wantBalance, _debtOutstanding); return (_profit, _loss, _debtPayment); } (uint256 deposits, uint256 borrows) = getLivePosition(); //claim comp accrued _claimComp(); //sell comp _disposeOfComp(); uint256 wantBalance = balanceOfToken(address(want)); uint256 investedBalance = deposits.sub(borrows); uint256 balance = investedBalance.add(wantBalance); uint256 debt = vault.strategies(address(this)).totalDebt; //Balance - Total Debt is profit if (balance > debt) { _profit = balance.sub(debt); if (wantBalance < _profit) { //all reserve is profit _profit = wantBalance; } else if (wantBalance > _profit.add(_debtOutstanding)) { _debtPayment = _debtOutstanding; } else { _debtPayment = wantBalance.sub(_profit); } } else { //we will lose money until we claim comp then we will make money //this has an unintended side effect of slowly lowering our total debt allowed _loss = debt.sub(balance); _debtPayment = Math.min(wantBalance, _debtOutstanding); } } /* * Second core function. Happens after report call. * * Similar to deposit function from V1 strategy */ function adjustPosition(uint256 _debtOutstanding) internal override { //emergency exit is dealt with in prepareReturn if (emergencyExit) { return; } //we are spending all our cash unless we have debt outstanding uint256 _wantBal = balanceOfToken(address(want)); if(_wantBal < _debtOutstanding){ //this is graceful withdrawal. dont use backup //we use more than 1 because withdrawunderlying causes problems with 1 token due to different decimals if(balanceOfToken(address(cToken)) > 1){ _withdrawSome(_debtOutstanding.sub(_wantBal)); } return; } (uint256 position, bool deficit) = _calculateDesiredPosition(_wantBal - _debtOutstanding, true); //if we are below minimun want change it is not worth doing //need to be careful in case this pushes to liquidation if (position > minWant) { //if dydx is not active we just try our best with basic leverage if (!DyDxActive) { uint i = 0; while(position > 0){ position = position.sub(_noFlashLoan(position, deficit)); if(i >= 6){ break; } i++; } } else { //if there is huge position to improve we want to do normal leverage. it is quicker if (position > want.balanceOf(address(FlashLoanLib.SOLO))) { position = position.sub(_noFlashLoan(position, deficit)); } //flash loan to position if(position > minWant){ doDyDxFlashLoan(deficit, position); } } } } /************* * Very important function * Input: amount we want to withdraw and whether we are happy to pay extra for Aave. * cannot be more than we have * Returns amount we were able to withdraw. notall if user has some balance left * * Deleverage position -> redeem our cTokens ******************** */ function _withdrawSome(uint256 _amount) internal returns (bool notAll) { (uint256 position, bool deficit) = _calculateDesiredPosition(_amount, false); //If there is no deficit we dont need to adjust position //if the position change is tiny do nothing if (deficit && position > minWant) { //we do a flash loan to give us a big gap. from here on out it is cheaper to use normal deleverage. Use Aave for extremely large loans if (DyDxActive) { position = position.sub(doDyDxFlashLoan(deficit, position)); } uint8 i = 0; //position will equal 0 unless we haven't been able to deleverage enough with flash loan //if we are not in deficit we dont need to do flash loan while (position > minWant.add(100)) { position = position.sub(_noFlashLoan(position, true)); i++; //A limit set so we don't run out of gas if (i >= 5) { notAll = true; break; } } } //now withdraw //if we want too much we just take max //This part makes sure our withdrawal does not force us into liquidation (uint256 depositBalance, uint256 borrowBalance) = getCurrentPosition(); uint256 tempColla = collateralTarget; uint256 reservedAmount = 0; if(tempColla == 0){ tempColla = 1e15; // 0.001 * 1e18. lower we have issues } reservedAmount = borrowBalance.mul(1e18).div(tempColla); if(depositBalance >= reservedAmount){ uint256 redeemable = depositBalance.sub(reservedAmount); if (redeemable < _amount) { cToken.redeemUnderlying(redeemable); } else { cToken.redeemUnderlying(_amount); } } if(collateralTarget == 0 && balanceOfToken(address(want)) > borrowBalance){ cToken.repayBorrow(borrowBalance); } } /*********** * This is the main logic for calculating how to change our lends and borrows * Input: balance. The net amount we are going to deposit/withdraw. * Input: dep. Is it a deposit or withdrawal * Output: position. The amount we want to change our current borrow position. * Output: deficit. True if we are reducing position size * * For instance deficit =false, position 100 means increase borrowed balance by 100 ****** */ function _calculateDesiredPosition(uint256 balance, bool dep) internal returns (uint256 position, bool deficit) { //we want to use statechanging for safety (uint256 deposits, uint256 borrows) = getLivePosition(); //When we unwind we end up with the difference between borrow and supply uint256 unwoundDeposit = deposits.sub(borrows); //we want to see how close to collateral target we are. //So we take our unwound deposits and add or remove the balance we are are adding/removing. //This gives us our desired future undwoundDeposit (desired supply) uint256 desiredSupply = 0; if (dep) { desiredSupply = unwoundDeposit.add(balance); } else { if(balance > unwoundDeposit) balance = unwoundDeposit; desiredSupply = unwoundDeposit.sub(balance); } //(ds *c)/(1-c) uint256 num = desiredSupply.mul(collateralTarget); uint256 den = uint256(1e18).sub(collateralTarget); uint256 desiredBorrow = num.div(den); if (desiredBorrow > 1e5) { //stop us going right up to the wire desiredBorrow = desiredBorrow.sub(1e5); } //now we see if we want to add or remove balance // if the desired borrow is less than our current borrow we are in deficit. so we want to reduce position if (desiredBorrow < borrows) { deficit = true; position = borrows.sub(desiredBorrow); //safemath check done in if statement } else { //otherwise we want to increase position deficit = false; position = desiredBorrow.sub(borrows); } } /* * Liquidate as many assets as possible to `want`, irregardless of slippage, * up to `_amount`. Any excess should be re-invested here as well. */ function liquidatePosition(uint256 _amountNeeded) internal override returns (uint256 _amountFreed, uint256 _loss) { uint256 _balance = balanceOfToken(address(want)); uint256 assets = netBalanceLent().add(_balance); uint256 debtOutstanding = vault.debtOutstanding(); if(debtOutstanding > assets){ _loss = debtOutstanding.sub(assets); } if (assets < _amountNeeded) { //if we cant afford to withdraw we take all we can //withdraw all we can (uint256 deposits, uint256 borrows) = getLivePosition(); //1 token causes rounding error with withdrawUnderlying if(balanceOfToken(address(cToken)) > 1){ _withdrawSome(deposits.sub(borrows)); } _amountFreed = Math.min(_amountNeeded, balanceOfToken(address(want))); } else { if (_balance < _amountNeeded) { _withdrawSome(_amountNeeded.sub(_balance)); //overflow error if we return more than asked for _amountFreed = Math.min(_amountNeeded, balanceOfToken(address(want))); }else{ _amountFreed = _amountNeeded; } } } function _claimComp() internal { if(dontClaimComp) { return; } CTokenI[] memory tokens = new CTokenI[](1); tokens[0] = cToken; compound.claimComp(address(this), tokens); } //sell comp function function _disposeOfComp() internal { uint256 _comp = balanceOfToken(comp); if (_comp < minCompToSell) { return; } if (useUniV3) { UNI_V3_ROUTER.exactInput( IUniswapV3Router.ExactInputParams( getTokenOutPathV3(comp, address(want)), address(this), now, _comp, 0 ) ); } else { currentV2Router.swapExactTokensForTokens( _comp, 0, getTokenOutPathV2(comp, address(want)), address(this), now ); } } function getTokenOutPathV2(address _tokenIn, address _tokenOut) internal pure returns (address[] memory _path) { bool isWeth = _tokenIn == address(weth) || _tokenOut == address(weth); _path = new address[](isWeth ? 2 : 3); _path[0] = _tokenIn; if (isWeth) { _path[1] = _tokenOut; } else { _path[1] = address(weth); _path[2] = _tokenOut; } } function getTokenOutPathV3(address _tokenIn, address _tokenOut) internal view returns (bytes memory _path) { if (address(want) == weth) { _path = abi.encodePacked( address(_tokenIn), compToWethSwapFee, address(weth) ); } else { _path = abi.encodePacked( address(_tokenIn), compToWethSwapFee, address(weth), wethToWantSwapFee, address(_tokenOut) ); } } //lets leave //if we can't deleverage in one go set collateralFactor to 0 and call harvest multiple times until delevered function prepareMigration(address _newStrategy) internal override { if(!forceMigrate){ (uint256 deposits, uint256 borrows) = getLivePosition(); _withdrawSome(deposits.sub(borrows)); (, , uint256 borrowBalance, ) = cToken.getAccountSnapshot(address(this)); require(borrowBalance < 10_000); IERC20 _comp = IERC20(comp); uint _compB = balanceOfToken(address(_comp)); if(_compB > 0){ _comp.safeTransfer(_newStrategy, _compB); } } } //Three functions covering normal leverage and deleverage situations // max is the max amount we want to increase our borrowed balance // returns the amount we actually did function _noFlashLoan(uint256 max, bool deficit) internal returns (uint256 amount) { //we can use non-state changing because this function is always called after _calculateDesiredPosition (uint256 lent, uint256 borrowed) = getCurrentPosition(); //if we have nothing borrowed then we can't deleverage any more if (borrowed == 0 && deficit) { return 0; } (, uint256 collateralFactorMantissa, ) = compound.markets(address(cToken)); if (deficit) { amount = _normalDeleverage(max, lent, borrowed, collateralFactorMantissa); } else { amount = _normalLeverage(max, lent, borrowed, collateralFactorMantissa); } emit Leverage(max, amount, deficit, address(0)); } //maxDeleverage is how much we want to reduce by function _normalDeleverage( uint256 maxDeleverage, uint256 lent, uint256 borrowed, uint256 collatRatio ) internal returns (uint256 deleveragedAmount) { uint256 theoreticalLent = 0; //collat ration should never be 0. if it is something is very wrong... but just incase if(collatRatio != 0){ theoreticalLent = borrowed.mul(1e18).div(collatRatio); } deleveragedAmount = lent.sub(theoreticalLent); if (deleveragedAmount >= borrowed) { deleveragedAmount = borrowed; } if (deleveragedAmount >= maxDeleverage) { deleveragedAmount = maxDeleverage; } uint256 exchangeRateStored = cToken.exchangeRateStored(); //redeemTokens = redeemAmountIn *1e18 / exchangeRate. must be more than 0 //a rounding error means we need another small addition if(deleveragedAmount.mul(1e18) >= exchangeRateStored && deleveragedAmount > 10){ deleveragedAmount = deleveragedAmount.sub(uint256(10)); cToken.redeemUnderlying(deleveragedAmount); //our borrow has been increased by no more than maxDeleverage cToken.repayBorrow(deleveragedAmount); } } //maxDeleverage is how much we want to increase by function _normalLeverage( uint256 maxLeverage, uint256 lent, uint256 borrowed, uint256 collatRatio ) internal returns (uint256 leveragedAmount) { uint256 theoreticalBorrow = lent.mul(collatRatio).div(1e18); leveragedAmount = theoreticalBorrow.sub(borrowed); if (leveragedAmount >= maxLeverage) { leveragedAmount = maxLeverage; } if(leveragedAmount > 10){ leveragedAmount = leveragedAmount.sub(uint256(10)); cToken.borrow(leveragedAmount); cToken.mint(balanceOfToken(address(want))); } } //emergency function that we can use to deleverage manually if something is broken function manualDeleverage(uint256 amount) external management{ require(cToken.redeemUnderlying(amount) == 0); require(cToken.repayBorrow(amount) == 0); } //emergency function that we can use to deleverage manually if something is broken function manualReleaseWant(uint256 amount) external onlyGovernance{ require(cToken.redeemUnderlying(amount) ==0); } function protectedTokens() internal override view returns (address[] memory) { } /****************** * Flash loan stuff ****************/ // Flash loan DXDY // amount desired is how much we are willing for position to change function doDyDxFlashLoan(bool deficit, uint256 amountDesired) internal returns (uint256) { return FlashLoanLib.doDyDxFlashLoan(deficit, amountDesired, address(want)); } //returns our current collateralisation ratio. Should be compared with collateralTarget function storedCollateralisation() public view returns (uint256 collat) { (uint256 lend, uint256 borrow) = getCurrentPosition(); if (lend == 0) { return 0; } collat = uint256(1e18).mul(borrow).div(lend); } //DyDx calls this function after doing flash loan function callFunction( address sender, Account.Info memory account, bytes memory data ) public override { (bool deficit, uint256 amount) = abi.decode(data, (bool, uint256)); require(msg.sender == address(FlashLoanLib.SOLO)); require(sender == address(this)); FlashLoanLib.loanLogic(deficit, amount, cToken); } // -- Internal Helper functions -- // function mgtm_check() internal { require(msg.sender == governance() || msg.sender == strategist); } modifier management() { mgtm_check(); _; } }
pre-set approvals Enter Compound's ETH market to take it into account when using ETH as collateralcomp speed is amount to borrow or deposit (so half the total distribution for want) You can set these parameters on deployment to whatever you want
function _initializeThis(address _cToken) internal { cToken = CErc20I(address(_cToken)); currentV2Router = SUSHI_V2_ROUTER; approveTokenMax(comp, address(UNI_V2_ROUTER)); approveTokenMax(comp, address(SUSHI_V2_ROUTER)); approveTokenMax(comp, address(UNI_V3_ROUTER)); approveTokenMax(address(want), address(cToken)); approveTokenMax(weth, address(FlashLoanLib.SOLO)); address[] memory markets = new address[](2); markets[0] = address(FlashLoanLib.CETH); markets[1] = address(cToken); compound.enterMarkets(markets); compToWethSwapFee = 3000; wethToWantSwapFee = 3000; minCompToSell = 0.1 ether; collateralTarget = 0.74 ether; blocksToLiquidationDangerZone = 46500; DyDxActive = true; }
5,925,077
./partial_match/1/0xdD518cc04A9138e88937F0541b06ABA3DAd71E61/sources/SALE_mtf.sol
Uses the token interface to check how many tokens the sale is allowed to sell
function allowanceOf() public view returns(uint256) { return token.allowanceOf(owner, this); }
2,820,046
./full_match/3/0x97150Bd5A5CB877042952A2719c07d2888280D96/sources/contracts/BlindAuction.sol
This is an "internal" function which means that it can only be called from the contract itself (or from derived contracts). Refund the previously highest bidder.
function placeBid(address bidder, uint value) internal returns (bool success) { if (value <= highestBid) { return false; } if (highestBidder != address(0)) { pendingReturns[highestBidder] += highestBid; } highestBid = value; highestBidder = bidder; return true; }
8,249,367
pragma solidity ^0.4.23; // File: openzeppelin-solidity/contracts/math/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting &#39;a&#39; not being zero, but the // benefit is lost if &#39;b&#39; is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval( address indexed owner, address indexed spender, uint256 value ); } // File: openzeppelin-solidity/contracts/crowdsale/Crowdsale.sol /** * @title Crowdsale * @dev Crowdsale is a base contract for managing a token crowdsale, * allowing investors to purchase tokens with ether. This contract implements * such functionality in its most fundamental form and can be extended to provide additional * functionality and/or custom behavior. * The external interface represents the basic interface for purchasing tokens, and conform * the base architecture for crowdsales. They are *not* intended to be modified / overriden. * The internal interface conforms the extensible and modifiable surface of crowdsales. Override * the methods to add functionality. Consider using &#39;super&#39; where appropiate to concatenate * behavior. */ contract Crowdsale { using SafeMath for uint256; // The token being sold ERC20 public token; // Address where funds are collected address public wallet; // How many token units a buyer gets per wei. // The rate is the conversion between wei and the smallest and indivisible token unit. // So, if you are using a rate of 1 with a DetailedERC20 token with 3 decimals called TOK // 1 wei will give you 1 unit, or 0.001 TOK. uint256 public rate; // Amount of wei raised uint256 public weiRaised; /** * Event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase( address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount ); /** * @param _rate Number of token units a buyer gets per wei * @param _wallet Address where collected funds will be forwarded to * @param _token Address of the token being sold */ constructor(uint256 _rate, address _wallet, ERC20 _token) public { require(_rate > 0); require(_wallet != address(0)); require(_token != address(0)); rate = _rate; wallet = _wallet; token = _token; } // ----------------------------------------- // Crowdsale external interface // ----------------------------------------- /** * @dev fallback function ***DO NOT OVERRIDE*** */ function () external payable { buyTokens(msg.sender); } /** * @dev low level token purchase ***DO NOT OVERRIDE*** * @param _beneficiary Address performing the token purchase */ function buyTokens(address _beneficiary) public payable { uint256 weiAmount = msg.value; _preValidatePurchase(_beneficiary, weiAmount); // calculate token amount to be created uint256 tokens = _getTokenAmount(weiAmount); // update state weiRaised = weiRaised.add(weiAmount); _processPurchase(_beneficiary, tokens); emit TokenPurchase( msg.sender, _beneficiary, weiAmount, tokens ); _updatePurchasingState(_beneficiary, weiAmount); _forwardFunds(); _postValidatePurchase(_beneficiary, weiAmount); } // ----------------------------------------- // Internal interface (extensible) // ----------------------------------------- /** * @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use super to concatenate validations. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _preValidatePurchase( address _beneficiary, uint256 _weiAmount ) internal { require(_beneficiary != address(0)); require(_weiAmount != 0); } /** * @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid conditions are not met. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _postValidatePurchase( address _beneficiary, uint256 _weiAmount ) internal { // optional override } /** * @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens. * @param _beneficiary Address performing the token purchase * @param _tokenAmount Number of tokens to be emitted */ function _deliverTokens( address _beneficiary, uint256 _tokenAmount ) internal { token.transfer(_beneficiary, _tokenAmount); } /** * @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens. * @param _beneficiary Address receiving the tokens * @param _tokenAmount Number of tokens to be purchased */ function _processPurchase( address _beneficiary, uint256 _tokenAmount ) internal { _deliverTokens(_beneficiary, _tokenAmount); } /** * @dev Override for extensions that require an internal state to check for validity (current user contributions, etc.) * @param _beneficiary Address receiving the tokens * @param _weiAmount Value in wei involved in the purchase */ function _updatePurchasingState( address _beneficiary, uint256 _weiAmount ) internal { // optional override } /** * @dev Override to extend the way in which ether is converted to tokens. * @param _weiAmount Value in wei to be converted into tokens * @return Number of tokens that can be purchased with the specified _weiAmount */ function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) { return _weiAmount.mul(rate); } /** * @dev Determines how ETH is stored/forwarded on purchases. */ function _forwardFunds() internal { wallet.transfer(msg.value); } } // File: openzeppelin-solidity/contracts/crowdsale/validation/TimedCrowdsale.sol /** * @title TimedCrowdsale * @dev Crowdsale accepting contributions only within a time frame. */ contract TimedCrowdsale is Crowdsale { using SafeMath for uint256; uint256 public openingTime; uint256 public closingTime; /** * @dev Reverts if not in crowdsale time range. */ modifier onlyWhileOpen { // solium-disable-next-line security/no-block-members require(block.timestamp >= openingTime && block.timestamp <= closingTime); _; } /** * @dev Constructor, takes crowdsale opening and closing times. * @param _openingTime Crowdsale opening time * @param _closingTime Crowdsale closing time */ constructor(uint256 _openingTime, uint256 _closingTime) public { // solium-disable-next-line security/no-block-members require(_openingTime >= block.timestamp); require(_closingTime >= _openingTime); openingTime = _openingTime; closingTime = _closingTime; } /** * @dev Checks whether the period in which the crowdsale is open has already elapsed. * @return Whether crowdsale period has elapsed */ function hasClosed() public view returns (bool) { // solium-disable-next-line security/no-block-members return block.timestamp > closingTime; } /** * @dev Extend parent behavior requiring to be within contributing period * @param _beneficiary Token purchaser * @param _weiAmount Amount of wei contributed */ function _preValidatePurchase( address _beneficiary, uint256 _weiAmount ) internal onlyWhileOpen { super._preValidatePurchase(_beneficiary, _weiAmount); } } // File: openzeppelin-solidity/contracts/crowdsale/distribution/PostDeliveryCrowdsale.sol /** * @title PostDeliveryCrowdsale * @dev Crowdsale that locks tokens from withdrawal until it ends. */ contract PostDeliveryCrowdsale is TimedCrowdsale { using SafeMath for uint256; mapping(address => uint256) public balances; /** * @dev Withdraw tokens only after crowdsale ends. */ function withdrawTokens() public { require(hasClosed()); uint256 amount = balances[msg.sender]; require(amount > 0); balances[msg.sender] = 0; _deliverTokens(msg.sender, amount); } /** * @dev Overrides parent by storing balances instead of issuing tokens right away. * @param _beneficiary Token purchaser * @param _tokenAmount Amount of tokens purchased */ function _processPurchase( address _beneficiary, uint256 _tokenAmount ) internal { balances[_beneficiary] = balances[_beneficiary].add(_tokenAmount); } } // File: openzeppelin-solidity/contracts/ownership/Ownable.sol /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } // File: openzeppelin-solidity/contracts/crowdsale/distribution/FinalizableCrowdsale.sol /** * @title FinalizableCrowdsale * @dev Extension of Crowdsale where an owner can do extra work * after finishing. */ contract FinalizableCrowdsale is TimedCrowdsale, Ownable { using SafeMath for uint256; bool public isFinalized = false; event Finalized(); /** * @dev Must be called after crowdsale ends, to do some extra finalization * work. Calls the contract&#39;s finalization function. */ function finalize() onlyOwner public { require(!isFinalized); require(hasClosed()); finalization(); emit Finalized(); isFinalized = true; } /** * @dev Can be overridden to add finalization logic. The overriding function * should call super.finalization() to ensure the chain of finalization is * executed entirely. */ function finalization() internal { } } // File: openzeppelin-solidity/contracts/crowdsale/distribution/utils/RefundVault.sol /** * @title RefundVault * @dev This contract is used for storing funds while a crowdsale * is in progress. Supports refunding the money if crowdsale fails, * and forwarding it if crowdsale is successful. */ contract RefundVault is Ownable { using SafeMath for uint256; enum State { Active, Refunding, Closed } mapping (address => uint256) public deposited; address public wallet; State public state; event Closed(); event RefundsEnabled(); event Refunded(address indexed beneficiary, uint256 weiAmount); /** * @param _wallet Vault address */ constructor(address _wallet) public { require(_wallet != address(0)); wallet = _wallet; state = State.Active; } /** * @param investor Investor address */ function deposit(address investor) onlyOwner public payable { require(state == State.Active); deposited[investor] = deposited[investor].add(msg.value); } function close() onlyOwner public { require(state == State.Active); state = State.Closed; emit Closed(); wallet.transfer(address(this).balance); } function enableRefunds() onlyOwner public { require(state == State.Active); state = State.Refunding; emit RefundsEnabled(); } /** * @param investor Investor address */ function refund(address investor) public { require(state == State.Refunding); uint256 depositedValue = deposited[investor]; deposited[investor] = 0; investor.transfer(depositedValue); emit Refunded(investor, depositedValue); } } // File: openzeppelin-solidity/contracts/crowdsale/distribution/RefundableCrowdsale.sol /** * @title RefundableCrowdsale * @dev Extension of Crowdsale contract that adds a funding goal, and * the possibility of users getting a refund if goal is not met. * Uses a RefundVault as the crowdsale&#39;s vault. */ contract RefundableCrowdsale is FinalizableCrowdsale { using SafeMath for uint256; // minimum amount of funds to be raised in weis uint256 public goal; // refund vault used to hold funds while crowdsale is running RefundVault public vault; /** * @dev Constructor, creates RefundVault. * @param _goal Funding goal */ constructor(uint256 _goal) public { require(_goal > 0); vault = new RefundVault(wallet); goal = _goal; } /** * @dev Investors can claim refunds here if crowdsale is unsuccessful */ function claimRefund() public { require(isFinalized); require(!goalReached()); vault.refund(msg.sender); } /** * @dev Checks whether funding goal was reached. * @return Whether funding goal was reached */ function goalReached() public view returns (bool) { return weiRaised >= goal; } /** * @dev vault finalization task, called when owner calls finalize() */ function finalization() internal { if (goalReached()) { vault.close(); } else { vault.enableRefunds(); } super.finalization(); } /** * @dev Overrides Crowdsale fund forwarding, sending funds to vault. */ function _forwardFunds() internal { vault.deposit.value(msg.value)(msg.sender); } } // File: openzeppelin-solidity/contracts/token/ERC20/BasicToken.sol /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } // File: openzeppelin-solidity/contracts/token/ERC20/StandardToken.sol /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender&#39;s allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval( address _spender, uint _addedValue ) public returns (bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval( address _spender, uint _subtractedValue ) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } // File: openzeppelin-solidity/contracts/token/ERC20/MintableToken.sol /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/openzeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } modifier hasMintPermission() { require(msg.sender == owner); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint( address _to, uint256 _amount ) hasMintPermission canMint public returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; emit MintFinished(); return true; } } // File: openzeppelin-solidity/contracts/crowdsale/emission/MintedCrowdsale.sol /** * @title MintedCrowdsale * @dev Extension of Crowdsale contract whose tokens are minted in each purchase. * Token ownership should be transferred to MintedCrowdsale for minting. */ contract MintedCrowdsale is Crowdsale { /** * @dev Overrides delivery by minting tokens upon purchase. * @param _beneficiary Token purchaser * @param _tokenAmount Number of tokens to be minted */ function _deliverTokens( address _beneficiary, uint256 _tokenAmount ) internal { require(MintableToken(token).mint(_beneficiary, _tokenAmount)); } } // File: openzeppelin-solidity/contracts/crowdsale/validation/CappedCrowdsale.sol /** * @title CappedCrowdsale * @dev Crowdsale with a limit for total contributions. */ contract CappedCrowdsale is Crowdsale { using SafeMath for uint256; uint256 public cap; /** * @dev Constructor, takes maximum amount of wei accepted in the crowdsale. * @param _cap Max amount of wei to be contributed */ constructor(uint256 _cap) public { require(_cap > 0); cap = _cap; } /** * @dev Checks whether the cap has been reached. * @return Whether the cap was reached */ function capReached() public view returns (bool) { return weiRaised >= cap; } /** * @dev Extend parent behavior requiring purchase to respect the funding cap. * @param _beneficiary Token purchaser * @param _weiAmount Amount of wei contributed */ function _preValidatePurchase( address _beneficiary, uint256 _weiAmount ) internal { super._preValidatePurchase(_beneficiary, _weiAmount); require(weiRaised.add(_weiAmount) <= cap); } } // File: openzeppelin-solidity/contracts/crowdsale/validation/IndividuallyCappedCrowdsale.sol /** * @title IndividuallyCappedCrowdsale * @dev Crowdsale with per-user caps. */ contract IndividuallyCappedCrowdsale is Crowdsale, Ownable { using SafeMath for uint256; mapping(address => uint256) public contributions; mapping(address => uint256) public caps; /** * @dev Sets a specific user&#39;s maximum contribution. * @param _beneficiary Address to be capped * @param _cap Wei limit for individual contribution */ function setUserCap(address _beneficiary, uint256 _cap) external onlyOwner { caps[_beneficiary] = _cap; } /** * @dev Sets a group of users&#39; maximum contribution. * @param _beneficiaries List of addresses to be capped * @param _cap Wei limit for individual contribution */ function setGroupCap( address[] _beneficiaries, uint256 _cap ) external onlyOwner { for (uint256 i = 0; i < _beneficiaries.length; i++) { caps[_beneficiaries[i]] = _cap; } } /** * @dev Returns the cap of a specific user. * @param _beneficiary Address whose cap is to be checked * @return Current cap for individual user */ function getUserCap(address _beneficiary) public view returns (uint256) { return caps[_beneficiary]; } /** * @dev Returns the amount contributed so far by a sepecific user. * @param _beneficiary Address of contributor * @return User contribution so far */ function getUserContribution(address _beneficiary) public view returns (uint256) { return contributions[_beneficiary]; } /** * @dev Extend parent behavior requiring purchase to respect the user&#39;s funding cap. * @param _beneficiary Token purchaser * @param _weiAmount Amount of wei contributed */ function _preValidatePurchase( address _beneficiary, uint256 _weiAmount ) internal { super._preValidatePurchase(_beneficiary, _weiAmount); require(contributions[_beneficiary].add(_weiAmount) <= caps[_beneficiary]); } /** * @dev Extend parent behavior to update user contributions * @param _beneficiary Token purchaser * @param _weiAmount Amount of wei contributed */ function _updatePurchasingState( address _beneficiary, uint256 _weiAmount ) internal { super._updatePurchasingState(_beneficiary, _weiAmount); contributions[_beneficiary] = contributions[_beneficiary].add(_weiAmount); } } // File: openzeppelin-solidity/contracts/crowdsale/validation/WhitelistedCrowdsale.sol /** * @title WhitelistedCrowdsale * @dev Crowdsale in which only whitelisted users can contribute. */ contract WhitelistedCrowdsale is Crowdsale, Ownable { mapping(address => bool) public whitelist; /** * @dev Reverts if beneficiary is not whitelisted. Can be used when extending this contract. */ modifier isWhitelisted(address _beneficiary) { require(whitelist[_beneficiary]); _; } /** * @dev Adds single address to whitelist. * @param _beneficiary Address to be added to the whitelist */ function addToWhitelist(address _beneficiary) external onlyOwner { whitelist[_beneficiary] = true; } /** * @dev Adds list of addresses to whitelist. Not overloaded due to limitations with truffle testing. * @param _beneficiaries Addresses to be added to the whitelist */ function addManyToWhitelist(address[] _beneficiaries) external onlyOwner { for (uint256 i = 0; i < _beneficiaries.length; i++) { whitelist[_beneficiaries[i]] = true; } } /** * @dev Removes single address from whitelist. * @param _beneficiary Address to be removed to the whitelist */ function removeFromWhitelist(address _beneficiary) external onlyOwner { whitelist[_beneficiary] = false; } /** * @dev Extend parent behavior requiring beneficiary to be in whitelist. * @param _beneficiary Token beneficiary * @param _weiAmount Amount of wei contributed */ function _preValidatePurchase( address _beneficiary, uint256 _weiAmount ) internal isWhitelisted(_beneficiary) { super._preValidatePurchase(_beneficiary, _weiAmount); } } // File: contracts/GBECrowdsale.sol /* * @title GBECrowdsale * @dev The crowdsale that will gain ownership and distrubute * the token * @param _rate Rate in the public sale * @param _wallet The address to which the funds will be forwarded to after the crowdsale ends * @param _cap The hard cap * @param _goal The soft cap * @param _minimumInvestment Minimum investment allowed in public sale * @param _openingTime The opening time as a unix timestamp * @param _closingTime The closing time as a unix timestamp * @param _token The address of the mintable token to be deployed */ contract GBECrowdsale is CappedCrowdsale, RefundableCrowdsale, MintedCrowdsale, WhitelistedCrowdsale { // solium-disable-line max-len uint256 public minimumInvestment; uint256 public initialRate; constructor( uint256 _rate, address _wallet, uint256 _cap, uint256 _goal, uint256 _minimumInvestment, uint256 _openingTime, uint256 _closingTime, MintableToken _token ) public Crowdsale(_rate, _wallet, _token) CappedCrowdsale(_cap) TimedCrowdsale(_openingTime, _closingTime) RefundableCrowdsale(_goal) { minimumInvestment = _minimumInvestment; initialRate = _rate; } /* * @title pushPrivateInvestment * @dev The function tracks a private investment made in currencies other than ETH. * For a _weiAmount calculated based on the ETH value of some other currency, a _tokenAmount * amount of tokens will be minted post crowdsale for the _beneficiary * @param _weiAmount The value in wei calculated based on the value of the external currency * @param _tokenAmount The amount to be minted * @param _beneficiary The beneficiary of the tokens */ function pushPrivateInvestment(uint256 _weiAmount, uint256 _tokenAmount, address _beneficiary) external onlyOwner { // solium-disable-next-line security/no-block-members require(block.timestamp <= closingTime); require(_weiAmount >= minimumInvestment, "Wei amount lower than minimum investment"); require(_beneficiary != address(0)); require(weiRaised.add(_weiAmount) <= cap); _deliverTokens(_beneficiary, _tokenAmount); // Wei added based on external value weiRaised = weiRaised.add(_weiAmount); // Every user that participated in private investments is whitelisted _addToWhitelist(_beneficiary); emit TokenPurchase( msg.sender, _beneficiary, _weiAmount, _tokenAmount ); } /* * @title changeRate * @dev The function sets the rate for exchanging ETH for tokens * Rate can be changed only if new rate value is greater than the old rate value * @param _newRate new rate value */ function changeRate(uint256 _newRate) external onlyOwner { // solium-disable-next-line security/no-block-members require(block.timestamp <= closingTime); require(_newRate >= initialRate, "New rate must be greater than initial rate"); rate = _newRate; } // ----------------------------------------- // Internal interface (extensible) // ----------------------------------------- /* * @dev Validation of an incoming purchase. Use require statements * to revert state when conditions are not met. Use super to concatenate validations. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal { require(_weiAmount != 0); require(_weiAmount >= minimumInvestment, "Wei amount lower than minimum investment"); super._preValidatePurchase(_beneficiary, _weiAmount); } /* * @dev Add the beneficiary to the whitelist. Used internally for private * investors since every private investor is automatically whitelisted. * minted and can be claimed post crowdsale * @param _beneficiary The address that will be whitelisted */ function _addToWhitelist(address _beneficiary) private { whitelist[_beneficiary] = true; } } // File: openzeppelin-solidity/contracts/token/ERC20/CappedToken.sol /** * @title Capped token * @dev Mintable token with a token cap. */ contract CappedToken is MintableToken { uint256 public cap; constructor(uint256 _cap) public { require(_cap > 0); cap = _cap; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint( address _to, uint256 _amount ) onlyOwner canMint public returns (bool) { require(totalSupply_.add(_amount) <= cap); return super.mint(_to, _amount); } } // File: contracts/GBEToken.sol /* * @title GBEToken * @dev Mintable ERC20 compliant token. */ contract GBEToken is CappedToken { string public constant name = "GBE Token"; // solium-disable-line uppercase string public constant symbol = "GBE"; // solium-disable-line uppercase uint8 public constant decimals = 18; // solium-disable-line uppercase // 4 * (10 ** 6) * (10 ** 18) 4M tokens uint256 public constant advisorsAmount = 4000000000000000000000000; // solium-disable-line uppercase // 21 * (10 ** 6) * (10 ** 18) 21M tokens uint256 public constant companyAmount = 21000000000000000000000000; // solium-disable-line uppercase // 2 * (10 ** 6) * (10 ** 18) 2M tokens uint256 public constant teamAmount = 2000000000000000000000000; // solium-disable-line uppercase address public constant advisorsWallet = 0xD9fFAAd95B151D6B50df0a3770B4481cA320F530; // solium-disable-line uppercase address public constant companyWallet = 0xFCcD1bD20aE0635D6AB5181cdA2c3de660f074C4; // solium-disable-line uppercase address public constant teamWallet = 0x27950EcE748A9a1A1F0AA6167Cd39893e7f39819; // solium-disable-line uppercase constructor(uint256 _cap) public CappedToken(_cap){ super.mint(advisorsWallet, advisorsAmount); super.mint(companyWallet, companyAmount); super.mint(teamWallet, teamAmount); } }
Add the beneficiary to the whitelist. Used internally for private investors since every private investor is automatically whitelisted. minted and can be claimed post crowdsale _beneficiary The address that will be whitelisted/
function _addToWhitelist(address _beneficiary) private { whitelist[_beneficiary] = true; }
2,305,788
./partial_match/1/0xEEEEEcf99b5d7e9c0bca6E2769E895d8F956BbAF/sources/ERC20.sol
Converts an unsigned uint256 into a signed int256. Requirements: - input must be less than or equal to maxInt256./ Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
function toInt256(uint256 value) internal pure returns (int256) { if (value > uint256(type(int256).max)) { revert SafeCastOverflowedUintToInt(value); } return int256(value); }
4,210,517
/** *Submitted for verification at Etherscan.io on 2022-03-07 */ // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC721/ERC721.sol) // MetaPiggyBanks.io pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } /** * @dev These functions deal with verification of Merkle Trees proofs. * * The proofs can be generated using the JavaScript library * https://github.com/miguelmota/merkletreejs[merkletreejs]. * Note: the hashing algorithm should be keccak256 and pair sorting should be enabled. * * See `test/utils/cryptography/MerkleProof.test.js` for some examples. * * WARNING: You should avoid using leaf values that are 64 bytes long prior to * hashing, or use a hash function other than keccak256 for hashing leaves. * This is because the concatenation of a sorted pair of internal nodes in * the merkle tree could be reinterpreted as a leaf value. */ library MerkleProof { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify( bytes32[] memory proof, bytes32 root, bytes32 leaf ) internal pure returns (bool) { return processProof(proof, leaf) == root; } /** * @dev Returns the rebuilt hash obtained by traversing a Merkle tree up * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt * hash matches the root of the tree. When processing the proof, the pairs * of leafs & pre-images are assumed to be sorted. * * _Available since v4.4._ */ function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = _efficientHash(computedHash, proofElement); } else { // Hash(current element of the proof + current computed hash) computedHash = _efficientHash(proofElement, computedHash); } } return computedHash; } function _efficientHash(bytes32 a, bytes32 b) private pure returns (bytes32 value) { assembly { mstore(0x00, a) mstore(0x20, b) value := keccak256(0x00, 0x40) } } } /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable, Ownable { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Token base URI string private _baseURI; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_, string memory baseURI_) { _name = name_; _symbol = symbol_; _baseURI = baseURI_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); return bytes(_baseURI).length > 0 ? string(abi.encodePacked(_baseURI, tokenId.toString())) : ""; } /** * @dev Set baseURI */ function setBaseURI(string memory baseURI_) public virtual onlyOwner { _baseURI = baseURI_; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual { if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { function balanceOf(address account) external view returns (uint256); function transfer(address to, uint256 amount) external returns (bool); } contract MetaPiggyBanks is ERC721("MetaPiggyBanks", "MPB", "https://metapiggybanks.io/api/metadata/") { using Counters for Counters.Counter; Counters.Counter private _tokenIds; Counters.Counter private _salesCounter; uint256 public publicMintStartAt = 1646780400; uint256 public whitelistMintStartAt = 1646773200; uint256 public maxSupply = 8888; uint256 public saleSupply = 800; uint256 public publicMintPrice = 0.0888 ether; uint256 public whitelistMintPrice = 0.0888 ether; uint256 public maxBatchMint = 2; bytes32 public merkleRoot = 0x0; uint256 public whitelistRound = 0; uint256 public whitelistLimitPerAccount = 2; mapping(uint256 => mapping(address => uint256)) public whitelistMinted; function setPublicMintStartAt(uint256 publicMintStartAt_) external onlyOwner { publicMintStartAt = publicMintStartAt_; } function setWhitelistMintStartAt(uint256 whitelistMintStartAt_) external onlyOwner { whitelistMintStartAt = whitelistMintStartAt_; } function setSaleSupply(uint256 saleSupply_) external onlyOwner { require(saleSupply_ <= maxSupply, "Sale supply can't be higher than max supply."); saleSupply = saleSupply_; } function setPublicMintPrice(uint256 publicMintPrice_) external onlyOwner { publicMintPrice = publicMintPrice_; } function setWhitelistMintPrice(uint256 whitelistMintPrice_) external onlyOwner { whitelistMintPrice = whitelistMintPrice_; } function setMaxBatchMint(uint256 maxBatchMint_) external onlyOwner { maxBatchMint = maxBatchMint_; } function setMerkleRoot(bytes32 merkleRoot_) external onlyOwner { merkleRoot = merkleRoot_; } function setWhitelistRound(uint256 whitelistRound_) external onlyOwner { whitelistRound = whitelistRound_; } function setWhitelistLimitPerAccount(uint256 whitelistLimitPerAccount_) external onlyOwner { whitelistLimitPerAccount = whitelistLimitPerAccount_; } function salesCounter() external view returns (uint256) { return _salesCounter.current(); } function mint(address to) external payable returns (uint256) { require(block.timestamp >= publicMintStartAt, "Public mint not started yet."); require(_salesCounter.current() < saleSupply, "Sale supply reached."); require(msg.value >= publicMintPrice, "Insufficient funds."); _salesCounter.increment(); return safeMint(to); } function batchMint(address to, uint256 amount) external payable returns (uint256[] memory) { require(block.timestamp >= publicMintStartAt, "Public mint not started yet."); require(_salesCounter.current() < saleSupply, "Sale supply reached."); require(_salesCounter.current() + amount <= saleSupply, "Not enough NFTs available for mint."); require(amount > 0 && amount <= maxBatchMint, "Invalid amount."); require(msg.value >= publicMintPrice * amount, "Insufficient funds."); uint256[] memory tokensMinted = new uint256[](amount); for (uint256 i = 0; i < amount; i++) { _salesCounter.increment(); tokensMinted[i] = safeMint(to); } return tokensMinted; } function whitelistMint(bytes32[] calldata merkleProof, uint256 amount) external payable returns (uint256[] memory) { require(block.timestamp > whitelistMintStartAt, "Whitelist mint not started yet."); require(amount > 0, "Invalid amount."); require(_salesCounter.current() + amount <= saleSupply, "Not enough NFTs available for mint."); require(msg.value >= whitelistMintPrice * amount, "Insufficient funds."); bytes32 leaf = keccak256(abi.encodePacked(_msgSender())); require(MerkleProof.verify(merkleProof, merkleRoot, leaf), "Invalid proof."); require(whitelistMinted[whitelistRound][_msgSender()] + amount <= whitelistLimitPerAccount, "Limit per account exceeded."); whitelistMinted[whitelistRound][_msgSender()] = whitelistMinted[whitelistRound][_msgSender()] + amount; uint256[] memory tokensMinted = new uint256[](amount); for (uint256 i = 0; i < amount; i++) { _salesCounter.increment(); tokensMinted[i] = safeMint(_msgSender()); } return tokensMinted; } function teamMint(address to) external onlyOwner returns (uint256) { return safeMint(to); } function teamBatchMint(address to, uint256 amount) external onlyOwner returns (uint256[] memory) { require(amount > 0, "Invalid amount."); uint256[] memory tokensMinted = new uint256[](amount); for (uint256 i = 0; i < amount; i++) { tokensMinted[i] = safeMint(to); } return tokensMinted; } function safeMint(address to) private returns (uint256) { require(_tokenIds.current() < maxSupply, "Mint supply reached."); _tokenIds.increment(); uint256 newId = _tokenIds.current(); _safeMint(to, newId); return newId; } function withdraw() external payable onlyOwner { (bool payment, ) = payable(owner()).call{value: address(this).balance}(""); require(payment); } function withdrawToken(address tokenAddress) external onlyOwner { IERC20 tokenContract = IERC20(tokenAddress); uint256 balance = tokenContract.balanceOf(address(this)); require(balance > 0, "Insufficient funds."); tokenContract.transfer(owner(), balance); } }
See {IERC721Metadata-tokenURI}./
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); return bytes(_baseURI).length > 0 ? string(abi.encodePacked(_baseURI, tokenId.toString())) : ""; }
2,462,250
./full_match/4/0x1Ba1DB48A7eFC6BFbdB214f75d9b32c0b402D719/sources/contracts/JBFundingCycleStore.sol
/ The distance of the current time to the start of the next possible funding cycle. If the returned mock cycle must not yet have started, the start time of the mock must be in the future. If the base funding cycle doesn't have a duration, no adjustment is necessary because the next cycle can start immediately. Derive what the start time should be. Derive what the number should be.
function _mockFundingCycleBasedOn(JBFundingCycle memory _baseFundingCycle, bool _allowMidCycle) private view returns (JBFundingCycle memory) { uint256 _mustStartAtOrAfter = !_allowMidCycle || _baseFundingCycle.duration == 0 ? block.timestamp + 1 : block.timestamp - _baseFundingCycle.duration + 1; uint256 _start = _deriveStartFrom(_baseFundingCycle, _mustStartAtOrAfter); uint256 _number = _deriveNumberFrom(_baseFundingCycle, _start); return JBFundingCycle( _number, _baseFundingCycle.configuration, _baseFundingCycle.basedOn, _start, _baseFundingCycle.duration, _deriveWeightFrom(_baseFundingCycle, _start), _baseFundingCycle.discountRate, _baseFundingCycle.ballot, _baseFundingCycle.metadata ); } Unpack a funding cycle's packed stored values into an easy-to-work-with funding cycle struct. @param _projectId The ID of the project to which the funding cycle belongs. @param _configuration The funding cycle configuration to get the full struct for. @return fundingCycle The funding cycle struct.
12,303,634
./partial_match/1/0x0649CFFa638931612649DfACE45bc8554e1be176/sources/Muntface_Decal.sol
Destroys `tokenId`. The approval is cleared when the token is burned. This is an internal function that does not check if the sender is authorized to operate on the token. Requirements: - `tokenId` must exist. Emits a {Transfer} event./ Update ownership in case tokenId was transferred by `_beforeTokenTransfer` hook Clear approvals Cannot overflow, as that would require more tokens to be burned/transferred out than the owner initially received through minting and transferring in.
function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId, 1); owner = ERC721.ownerOf(tokenId); delete _tokenApprovals[tokenId]; unchecked { _balances[owner] -= 1; } delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); _afterTokenTransfer(owner, address(0), tokenId, 1); }
3,697,531
pragma solidity ^0.5.0; contract ResolverBase { bytes4 private constant INTERFACE_META_ID = 0x01ffc9a7; function supportsInterface(bytes4 interfaceID) public pure returns(bool) { return interfaceID == INTERFACE_META_ID; } function isAuthorised(bytes32 node) internal view returns(bool); modifier authorised(bytes32 node) { require(isAuthorised(node)); _; } function bytesToAddress(bytes memory b) internal pure returns(address payable a) { require(b.length == 20); assembly { a := div(mload(add(b, 32)), exp(256, 12)) } } function addressToBytes(address a) internal pure returns(bytes memory b) { b = new bytes(20); assembly { mstore(add(b, 32), mul(a, exp(256, 12))) } } } pragma solidity >=0.5.0; interface ENS { // Logged when the owner of a node assigns a new owner to a subnode. event NewOwner(bytes32 indexed node, bytes32 indexed label, address owner); // Logged when the owner of a node transfers ownership to a new account. event Transfer(bytes32 indexed node, address owner); // Logged when the resolver for a node changes. event NewResolver(bytes32 indexed node, address resolver); // Logged when the TTL of a node changes event NewTTL(bytes32 indexed node, uint64 ttl); // Logged when an operator is added or removed. event ApprovalForAll(address indexed owner, address indexed operator, bool approved); function setRecord(bytes32 node, address owner, address resolver, uint64 ttl) external; function setSubnodeRecord(bytes32 node, bytes32 label, address owner, address resolver, uint64 ttl) external; function setSubnodeOwner(bytes32 node, bytes32 label, address owner) external returns(bytes32); function setResolver(bytes32 node, address resolver) external; function setOwner(bytes32 node, address owner) external; function setTTL(bytes32 node, uint64 ttl) external; function setApprovalForAll(address operator, bool approved) external; function owner(bytes32 node) external view returns (address); function resolver(bytes32 node) external view returns (address); function ttl(bytes32 node) external view returns (uint64); function recordExists(bytes32 node) external view returns (bool); function isApprovedForAll(address owner, address operator) external view returns (bool); } /** * The ENS registry contract. */ contract ENSRegistry is ENS { struct Record { address owner; address resolver; uint64 ttl; } mapping (bytes32 => Record) records; mapping (address => mapping(address => bool)) operators; // Permits modifications only by the owner of the specified node. modifier authorised(bytes32 node) { address owner = records[node].owner; require(owner == msg.sender || operators[owner][msg.sender]); _; } /** * @dev Constructs a new ENS registrar. */ constructor() public { records[0x0].owner = msg.sender; } /** * @dev Sets the record for a node. * @param node The node to update. * @param owner The address of the new owner. * @param resolver The address of the resolver. * @param ttl The TTL in seconds. */ function setRecord(bytes32 node, address owner, address resolver, uint64 ttl) external { setOwner(node, owner); _setResolverAndTTL(node, resolver, ttl); } /** * @dev Sets the record for a subnode. * @param node The parent node. * @param label The hash of the label specifying the subnode. * @param owner The address of the new owner. * @param resolver The address of the resolver. * @param ttl The TTL in seconds. */ function setSubnodeRecord(bytes32 node, bytes32 label, address owner, address resolver, uint64 ttl) external { bytes32 subnode = setSubnodeOwner(node, label, owner); _setResolverAndTTL(subnode, resolver, ttl); } /** * @dev Transfers ownership of a node to a new address. May only be called by the current owner of the node. * @param node The node to transfer ownership of. * @param owner The address of the new owner. */ function setOwner(bytes32 node, address owner) public authorised(node) { _setOwner(node, owner); emit Transfer(node, owner); } /** * @dev Transfers ownership of a subnode keccak256(node, label) to a new address. May only be called by the owner of the parent node. * @param node The parent node. * @param label The hash of the label specifying the subnode. * @param owner The address of the new owner. */ function setSubnodeOwner(bytes32 node, bytes32 label, address owner) public authorised(node) returns(bytes32) { bytes32 subnode = keccak256(abi.encodePacked(node, label)); _setOwner(subnode, owner); emit NewOwner(node, label, owner); return subnode; } /** * @dev Sets the resolver address for the specified node. * @param node The node to update. * @param resolver The address of the resolver. */ function setResolver(bytes32 node, address resolver) public authorised(node) { emit NewResolver(node, resolver); records[node].resolver = resolver; } /** * @dev Sets the TTL for the specified node. * @param node The node to update. * @param ttl The TTL in seconds. */ function setTTL(bytes32 node, uint64 ttl) public authorised(node) { emit NewTTL(node, ttl); records[node].ttl = ttl; } /** * @dev Enable or disable approval for a third party ("operator") to manage * all of `msg.sender`'s ENS records. Emits the ApprovalForAll event. * @param operator Address to add to the set of authorized operators. * @param approved True if the operator is approved, false to revoke approval. */ function setApprovalForAll(address operator, bool approved) external { operators[msg.sender][operator] = approved; emit ApprovalForAll(msg.sender, operator, approved); } /** * @dev Returns the address that owns the specified node. * @param node The specified node. * @return address of the owner. */ function owner(bytes32 node) public view returns (address) { address addr = records[node].owner; if (addr == address(this)) { return address(0x0); } return addr; } /** * @dev Returns the address of the resolver for the specified node. * @param node The specified node. * @return address of the resolver. */ function resolver(bytes32 node) public view returns (address) { return records[node].resolver; } /** * @dev Returns the TTL of a node, and any records associated with it. * @param node The specified node. * @return ttl of the node. */ function ttl(bytes32 node) public view returns (uint64) { return records[node].ttl; } /** * @dev Returns whether a record has been imported to the registry. * @param node The specified node. * @return Bool if record exists */ function recordExists(bytes32 node) public view returns (bool) { return records[node].owner != address(0x0); } /** * @dev Query if an address is an authorized operator for another address. * @param owner The address that owns the records. * @param operator The address that acts on behalf of the owner. * @return True if `operator` is an approved operator for `owner`, false otherwise. */ function isApprovedForAll(address owner, address operator) external view returns (bool) { return operators[owner][operator]; } function _setOwner(bytes32 node, address owner) internal { records[node].owner = owner; } function _setResolverAndTTL(bytes32 node, address resolver, uint64 ttl) internal { if(resolver != records[node].resolver) { records[node].resolver = resolver; emit NewResolver(node, resolver); } if(ttl != records[node].ttl) { records[node].ttl = ttl; emit NewTTL(node, ttl); } } } pragma solidity ^0.5.0; contract ABIResolver is ResolverBase { bytes4 constant private ABI_INTERFACE_ID = 0x2203ab56; event ABIChanged(bytes32 indexed node, uint256 indexed contentType); mapping(bytes32=>mapping(uint256=>bytes)) abis; /** * Sets the ABI associated with an ENS node. * Nodes may have one ABI of each content type. To remove an ABI, set it to * the empty string. * @param node The node to update. * @param contentType The content type of the ABI * @param data The ABI data. */ function setABI(bytes32 node, uint256 contentType, bytes calldata data) external authorised(node) { // Content types must be powers of 2 require(((contentType - 1) & contentType) == 0); abis[node][contentType] = data; emit ABIChanged(node, contentType); } /** * Returns the ABI associated with an ENS node. * Defined in EIP205. * @param node The ENS node to query * @param contentTypes A bitwise OR of the ABI formats accepted by the caller. * @return contentType The content type of the return value * @return data The ABI data */ function ABI(bytes32 node, uint256 contentTypes) external view returns (uint256, bytes memory) { mapping(uint256=>bytes) storage abiset = abis[node]; for (uint256 contentType = 1; contentType <= contentTypes; contentType <<= 1) { if ((contentType & contentTypes) != 0 && abiset[contentType].length > 0) { return (contentType, abiset[contentType]); } } return (0, bytes("")); } function supportsInterface(bytes4 interfaceID) public pure returns(bool) { return interfaceID == ABI_INTERFACE_ID || super.supportsInterface(interfaceID); } } pragma solidity ^0.5.0; contract AddrResolver is ResolverBase { bytes4 constant private ADDR_INTERFACE_ID = 0x3b3b57de; bytes4 constant private ADDRESS_INTERFACE_ID = 0xf1cb7e06; uint constant private COIN_TYPE_ETH = 60; event AddrChanged(bytes32 indexed node, address a); event AddressChanged(bytes32 indexed node, uint coinType, bytes newAddress); mapping(bytes32=>mapping(uint=>bytes)) _addresses; /** * Sets the address associated with an ENS node. * May only be called by the owner of that node in the ENS registry. * @param node The node to update. * @param a The address to set. */ function setAddr(bytes32 node, address a) external authorised(node) { setAddr(node, COIN_TYPE_ETH, addressToBytes(a)); } /** * Returns the address associated with an ENS node. * @param node The ENS node to query. * @return The associated address. */ function addr(bytes32 node) public view returns (address payable) { bytes memory a = addr(node, COIN_TYPE_ETH); if(a.length == 0) { return address(0); } return bytesToAddress(a); } function setAddr(bytes32 node, uint coinType, bytes memory a) public authorised(node) { emit AddressChanged(node, coinType, a); if(coinType == COIN_TYPE_ETH) { emit AddrChanged(node, bytesToAddress(a)); } _addresses[node][coinType] = a; } function addr(bytes32 node, uint coinType) public view returns(bytes memory) { return _addresses[node][coinType]; } function supportsInterface(bytes4 interfaceID) public pure returns(bool) { return interfaceID == ADDR_INTERFACE_ID || interfaceID == ADDRESS_INTERFACE_ID || super.supportsInterface(interfaceID); } } pragma solidity ^0.5.0; contract ContentHashResolver is ResolverBase { bytes4 constant private CONTENT_HASH_INTERFACE_ID = 0xbc1c58d1; event ContenthashChanged(bytes32 indexed node, bytes hash); mapping(bytes32=>bytes) hashes; /** * Sets the contenthash associated with an ENS node. * May only be called by the owner of that node in the ENS registry. * @param node The node to update. * @param hash The contenthash to set */ function setContenthash(bytes32 node, bytes calldata hash) external authorised(node) { hashes[node] = hash; emit ContenthashChanged(node, hash); } /** * Returns the contenthash associated with an ENS node. * @param node The ENS node to query. * @return The associated contenthash. */ function contenthash(bytes32 node) external view returns (bytes memory) { return hashes[node]; } function supportsInterface(bytes4 interfaceID) public pure returns(bool) { return interfaceID == CONTENT_HASH_INTERFACE_ID || super.supportsInterface(interfaceID); } } pragma solidity >0.4.23; library BytesUtils { /* * @dev Returns the keccak-256 hash of a byte range. * @param self The byte string to hash. * @param offset The position to start hashing at. * @param len The number of bytes to hash. * @return The hash of the byte range. */ function keccak(bytes memory self, uint offset, uint len) internal pure returns (bytes32 ret) { require(offset + len <= self.length); assembly { ret := keccak256(add(add(self, 32), offset), len) } } /* * @dev Returns a positive number if `other` comes lexicographically after * `self`, a negative number if it comes before, or zero if the * contents of the two bytes are equal. * @param self The first bytes to compare. * @param other The second bytes to compare. * @return The result of the comparison. */ function compare(bytes memory self, bytes memory other) internal pure returns (int) { return compare(self, 0, self.length, other, 0, other.length); } /* * @dev Returns a positive number if `other` comes lexicographically after * `self`, a negative number if it comes before, or zero if the * contents of the two bytes are equal. Comparison is done per-rune, * on unicode codepoints. * @param self The first bytes to compare. * @param offset The offset of self. * @param len The length of self. * @param other The second bytes to compare. * @param otheroffset The offset of the other string. * @param otherlen The length of the other string. * @return The result of the comparison. */ function compare(bytes memory self, uint offset, uint len, bytes memory other, uint otheroffset, uint otherlen) internal pure returns (int) { uint shortest = len; if (otherlen < len) shortest = otherlen; uint selfptr; uint otherptr; assembly { selfptr := add(self, add(offset, 32)) otherptr := add(other, add(otheroffset, 32)) } for (uint idx = 0; idx < shortest; idx += 32) { uint a; uint b; assembly { a := mload(selfptr) b := mload(otherptr) } if (a != b) { // Mask out irrelevant bytes and check again uint mask; if (shortest > 32) { mask = uint256(- 1); // aka 0xffffff.... } else { mask = ~(2 ** (8 * (32 - shortest + idx)) - 1); } uint diff = (a & mask) - (b & mask); if (diff != 0) return int(diff); } selfptr += 32; otherptr += 32; } return int(len) - int(otherlen); } /* * @dev Returns true if the two byte ranges are equal. * @param self The first byte range to compare. * @param offset The offset into the first byte range. * @param other The second byte range to compare. * @param otherOffset The offset into the second byte range. * @param len The number of bytes to compare * @return True if the byte ranges are equal, false otherwise. */ function equals(bytes memory self, uint offset, bytes memory other, uint otherOffset, uint len) internal pure returns (bool) { return keccak(self, offset, len) == keccak(other, otherOffset, len); } /* * @dev Returns true if the two byte ranges are equal with offsets. * @param self The first byte range to compare. * @param offset The offset into the first byte range. * @param other The second byte range to compare. * @param otherOffset The offset into the second byte range. * @return True if the byte ranges are equal, false otherwise. */ function equals(bytes memory self, uint offset, bytes memory other, uint otherOffset) internal pure returns (bool) { return keccak(self, offset, self.length - offset) == keccak(other, otherOffset, other.length - otherOffset); } /* * @dev Compares a range of 'self' to all of 'other' and returns True iff * they are equal. * @param self The first byte range to compare. * @param offset The offset into the first byte range. * @param other The second byte range to compare. * @return True if the byte ranges are equal, false otherwise. */ function equals(bytes memory self, uint offset, bytes memory other) internal pure returns (bool) { return self.length >= offset + other.length && equals(self, offset, other, 0, other.length); } /* * @dev Returns true if the two byte ranges are equal. * @param self The first byte range to compare. * @param other The second byte range to compare. * @return True if the byte ranges are equal, false otherwise. */ function equals(bytes memory self, bytes memory other) internal pure returns(bool) { return self.length == other.length && equals(self, 0, other, 0, self.length); } /* * @dev Returns the 8-bit number at the specified index of self. * @param self The byte string. * @param idx The index into the bytes * @return The specified 8 bits of the string, interpreted as an integer. */ function readUint8(bytes memory self, uint idx) internal pure returns (uint8 ret) { return uint8(self[idx]); } /* * @dev Returns the 16-bit number at the specified index of self. * @param self The byte string. * @param idx The index into the bytes * @return The specified 16 bits of the string, interpreted as an integer. */ function readUint16(bytes memory self, uint idx) internal pure returns (uint16 ret) { require(idx + 2 <= self.length); assembly { ret := and(mload(add(add(self, 2), idx)), 0xFFFF) } } /* * @dev Returns the 32-bit number at the specified index of self. * @param self The byte string. * @param idx The index into the bytes * @return The specified 32 bits of the string, interpreted as an integer. */ function readUint32(bytes memory self, uint idx) internal pure returns (uint32 ret) { require(idx + 4 <= self.length); assembly { ret := and(mload(add(add(self, 4), idx)), 0xFFFFFFFF) } } /* * @dev Returns the 32 byte value at the specified index of self. * @param self The byte string. * @param idx The index into the bytes * @return The specified 32 bytes of the string. */ function readBytes32(bytes memory self, uint idx) internal pure returns (bytes32 ret) { require(idx + 32 <= self.length); assembly { ret := mload(add(add(self, 32), idx)) } } /* * @dev Returns the 32 byte value at the specified index of self. * @param self The byte string. * @param idx The index into the bytes * @return The specified 32 bytes of the string. */ function readBytes20(bytes memory self, uint idx) internal pure returns (bytes20 ret) { require(idx + 20 <= self.length); assembly { ret := and(mload(add(add(self, 32), idx)), 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF000000000000000000000000) } } /* * @dev Returns the n byte value at the specified index of self. * @param self The byte string. * @param idx The index into the bytes. * @param len The number of bytes. * @return The specified 32 bytes of the string. */ function readBytesN(bytes memory self, uint idx, uint len) internal pure returns (bytes32 ret) { require(len <= 32); require(idx + len <= self.length); assembly { let mask := not(sub(exp(256, sub(32, len)), 1)) ret := and(mload(add(add(self, 32), idx)), mask) } } function memcpy(uint dest, uint src, uint len) private pure { // Copy word-length chunks while possible for (; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } // Copy remaining bytes uint mask = 256 ** (32 - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } } /* * @dev Copies a substring into a new byte string. * @param self The byte string to copy from. * @param offset The offset to start copying at. * @param len The number of bytes to copy. */ function substring(bytes memory self, uint offset, uint len) internal pure returns(bytes memory) { require(offset + len <= self.length); bytes memory ret = new bytes(len); uint dest; uint src; assembly { dest := add(ret, 32) src := add(add(self, 32), offset) } memcpy(dest, src, len); return ret; } // Maps characters from 0x30 to 0x7A to their base32 values. // 0xFF represents invalid characters in that range. bytes constant base32HexTable = hex'00010203040506070809FFFFFFFFFFFFFF0A0B0C0D0E0F101112131415161718191A1B1C1D1E1FFFFFFFFFFFFFFFFFFFFF0A0B0C0D0E0F101112131415161718191A1B1C1D1E1F'; /** * @dev Decodes unpadded base32 data of up to one word in length. * @param self The data to decode. * @param off Offset into the string to start at. * @param len Number of characters to decode. * @return The decoded data, left aligned. */ function base32HexDecodeWord(bytes memory self, uint off, uint len) internal pure returns(bytes32) { require(len <= 52); uint ret = 0; uint8 decoded; for(uint i = 0; i < len; i++) { bytes1 char = self[off + i]; require(char >= 0x30 && char <= 0x7A); decoded = uint8(base32HexTable[uint(uint8(char)) - 0x30]); require(decoded <= 0x20); if(i == len - 1) { break; } ret = (ret << 5) | decoded; } uint bitlen = len * 5; if(len % 8 == 0) { // Multiple of 8 characters, no padding ret = (ret << 5) | decoded; } else if(len % 8 == 2) { // Two extra characters - 1 byte ret = (ret << 3) | (decoded >> 2); bitlen -= 2; } else if(len % 8 == 4) { // Four extra characters - 2 bytes ret = (ret << 1) | (decoded >> 4); bitlen -= 4; } else if(len % 8 == 5) { // Five extra characters - 3 bytes ret = (ret << 4) | (decoded >> 1); bitlen -= 1; } else if(len % 8 == 7) { // Seven extra characters - 4 bytes ret = (ret << 2) | (decoded >> 3); bitlen -= 3; } else { revert(); } return bytes32(ret << (256 - bitlen)); } } pragma solidity >0.4.18; /** * @dev A library for working with mutable byte buffers in Solidity. * * Byte buffers are mutable and expandable, and provide a variety of primitives * for writing to them. At any time you can fetch a bytes object containing the * current contents of the buffer. The bytes object should not be stored between * operations, as it may change due to resizing of the buffer. */ library Buffer { /** * @dev Represents a mutable buffer. Buffers have a current value (buf) and * a capacity. The capacity may be longer than the current value, in * which case it can be extended without the need to allocate more memory. */ struct buffer { bytes buf; uint capacity; } /** * @dev Initializes a buffer with an initial capacity. * @param buf The buffer to initialize. * @param capacity The number of bytes of space to allocate the buffer. * @return The buffer, for chaining. */ function init(buffer memory buf, uint capacity) internal pure returns(buffer memory) { if (capacity % 32 != 0) { capacity += 32 - (capacity % 32); } // Allocate space for the buffer data buf.capacity = capacity; assembly { let ptr := mload(0x40) mstore(buf, ptr) mstore(ptr, 0) mstore(0x40, add(32, add(ptr, capacity))) } return buf; } /** * @dev Initializes a new buffer from an existing bytes object. * Changes to the buffer may mutate the original value. * @param b The bytes object to initialize the buffer with. * @return A new buffer. */ function fromBytes(bytes memory b) internal pure returns(buffer memory) { buffer memory buf; buf.buf = b; buf.capacity = b.length; return buf; } function resize(buffer memory buf, uint capacity) private pure { bytes memory oldbuf = buf.buf; init(buf, capacity); append(buf, oldbuf); } function max(uint a, uint b) private pure returns(uint) { if (a > b) { return a; } return b; } /** * @dev Sets buffer length to 0. * @param buf The buffer to truncate. * @return The original buffer, for chaining.. */ function truncate(buffer memory buf) internal pure returns (buffer memory) { assembly { let bufptr := mload(buf) mstore(bufptr, 0) } return buf; } /** * @dev Writes a byte string to a buffer. Resizes if doing so would exceed * the capacity of the buffer. * @param buf The buffer to append to. * @param off The start offset to write to. * @param data The data to append. * @param len The number of bytes to copy. * @return The original buffer, for chaining. */ function write(buffer memory buf, uint off, bytes memory data, uint len) internal pure returns(buffer memory) { require(len <= data.length); if (off + len > buf.capacity) { resize(buf, max(buf.capacity, len + off) * 2); } uint dest; uint src; assembly { // Memory address of the buffer data let bufptr := mload(buf) // Length of existing buffer data let buflen := mload(bufptr) // Start address = buffer address + offset + sizeof(buffer length) dest := add(add(bufptr, 32), off) // Update buffer length if we're extending it if gt(add(len, off), buflen) { mstore(bufptr, add(len, off)) } src := add(data, 32) } // Copy word-length chunks while possible for (; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } // Copy remaining bytes uint mask = 256 ** (32 - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } return buf; } /** * @dev Appends a byte string to a buffer. Resizes if doing so would exceed * the capacity of the buffer. * @param buf The buffer to append to. * @param data The data to append. * @param len The number of bytes to copy. * @return The original buffer, for chaining. */ function append(buffer memory buf, bytes memory data, uint len) internal pure returns (buffer memory) { return write(buf, buf.buf.length, data, len); } /** * @dev Appends a byte string to a buffer. Resizes if doing so would exceed * the capacity of the buffer. * @param buf The buffer to append to. * @param data The data to append. * @return The original buffer, for chaining. */ function append(buffer memory buf, bytes memory data) internal pure returns (buffer memory) { return write(buf, buf.buf.length, data, data.length); } /** * @dev Writes a byte to the buffer. Resizes if doing so would exceed the * capacity of the buffer. * @param buf The buffer to append to. * @param off The offset to write the byte at. * @param data The data to append. * @return The original buffer, for chaining. */ function writeUint8(buffer memory buf, uint off, uint8 data) internal pure returns(buffer memory) { if (off >= buf.capacity) { resize(buf, buf.capacity * 2); } assembly { // Memory address of the buffer data let bufptr := mload(buf) // Length of existing buffer data let buflen := mload(bufptr) // Address = buffer address + sizeof(buffer length) + off let dest := add(add(bufptr, off), 32) mstore8(dest, data) // Update buffer length if we extended it if eq(off, buflen) { mstore(bufptr, add(buflen, 1)) } } return buf; } /** * @dev Appends a byte to the buffer. Resizes if doing so would exceed the * capacity of the buffer. * @param buf The buffer to append to. * @param data The data to append. * @return The original buffer, for chaining. */ function appendUint8(buffer memory buf, uint8 data) internal pure returns(buffer memory) { return writeUint8(buf, buf.buf.length, data); } /** * @dev Writes up to 32 bytes to the buffer. Resizes if doing so would * exceed the capacity of the buffer. * @param buf The buffer to append to. * @param off The offset to write at. * @param data The data to append. * @param len The number of bytes to write (left-aligned). * @return The original buffer, for chaining. */ function write(buffer memory buf, uint off, bytes32 data, uint len) private pure returns(buffer memory) { if (len + off > buf.capacity) { resize(buf, (len + off) * 2); } uint mask = 256 ** len - 1; // Right-align data data = data >> (8 * (32 - len)); assembly { // Memory address of the buffer data let bufptr := mload(buf) // Address = buffer address + sizeof(buffer length) + off + len let dest := add(add(bufptr, off), len) mstore(dest, or(and(mload(dest), not(mask)), data)) // Update buffer length if we extended it if gt(add(off, len), mload(bufptr)) { mstore(bufptr, add(off, len)) } } return buf; } /** * @dev Writes a bytes20 to the buffer. Resizes if doing so would exceed the * capacity of the buffer. * @param buf The buffer to append to. * @param off The offset to write at. * @param data The data to append. * @return The original buffer, for chaining. */ function writeBytes20(buffer memory buf, uint off, bytes20 data) internal pure returns (buffer memory) { return write(buf, off, bytes32(data), 20); } /** * @dev Appends a bytes20 to the buffer. Resizes if doing so would exceed * the capacity of the buffer. * @param buf The buffer to append to. * @param data The data to append. * @return The original buffer, for chhaining. */ function appendBytes20(buffer memory buf, bytes20 data) internal pure returns (buffer memory) { return write(buf, buf.buf.length, bytes32(data), 20); } /** * @dev Appends a bytes32 to the buffer. Resizes if doing so would exceed * the capacity of the buffer. * @param buf The buffer to append to. * @param data The data to append. * @return The original buffer, for chaining. */ function appendBytes32(buffer memory buf, bytes32 data) internal pure returns (buffer memory) { return write(buf, buf.buf.length, data, 32); } /** * @dev Writes an integer to the buffer. Resizes if doing so would exceed * the capacity of the buffer. * @param buf The buffer to append to. * @param off The offset to write at. * @param data The data to append. * @param len The number of bytes to write (right-aligned). * @return The original buffer, for chaining. */ function writeInt(buffer memory buf, uint off, uint data, uint len) private pure returns(buffer memory) { if (len + off > buf.capacity) { resize(buf, (len + off) * 2); } uint mask = 256 ** len - 1; assembly { // Memory address of the buffer data let bufptr := mload(buf) // Address = buffer address + off + sizeof(buffer length) + len let dest := add(add(bufptr, off), len) mstore(dest, or(and(mload(dest), not(mask)), data)) // Update buffer length if we extended it if gt(add(off, len), mload(bufptr)) { mstore(bufptr, add(off, len)) } } return buf; } /** * @dev Appends a byte to the end of the buffer. Resizes if doing so would * exceed the capacity of the buffer. * @param buf The buffer to append to. * @param data The data to append. * @return The original buffer. */ function appendInt(buffer memory buf, uint data, uint len) internal pure returns(buffer memory) { return writeInt(buf, buf.buf.length, data, len); } } pragma solidity >0.4.23; /** * @dev RRUtils is a library that provides utilities for parsing DNS resource records. */ library RRUtils { using BytesUtils for *; using Buffer for *; /** * @dev Returns the number of bytes in the DNS name at 'offset' in 'self'. * @param self The byte array to read a name from. * @param offset The offset to start reading at. * @return The length of the DNS name at 'offset', in bytes. */ function nameLength(bytes memory self, uint offset) internal pure returns(uint) { uint idx = offset; while (true) { assert(idx < self.length); uint labelLen = self.readUint8(idx); idx += labelLen + 1; if (labelLen == 0) { break; } } return idx - offset; } /** * @dev Returns a DNS format name at the specified offset of self. * @param self The byte array to read a name from. * @param offset The offset to start reading at. * @return The name. */ function readName(bytes memory self, uint offset) internal pure returns(bytes memory ret) { uint len = nameLength(self, offset); return self.substring(offset, len); } /** * @dev Returns the number of labels in the DNS name at 'offset' in 'self'. * @param self The byte array to read a name from. * @param offset The offset to start reading at. * @return The number of labels in the DNS name at 'offset', in bytes. */ function labelCount(bytes memory self, uint offset) internal pure returns(uint) { uint count = 0; while (true) { assert(offset < self.length); uint labelLen = self.readUint8(offset); offset += labelLen + 1; if (labelLen == 0) { break; } count += 1; } return count; } /** * @dev An iterator over resource records. */ struct RRIterator { bytes data; uint offset; uint16 dnstype; uint16 class; uint32 ttl; uint rdataOffset; uint nextOffset; } /** * @dev Begins iterating over resource records. * @param self The byte string to read from. * @param offset The offset to start reading at. * @return An iterator object. */ function iterateRRs(bytes memory self, uint offset) internal pure returns (RRIterator memory ret) { ret.data = self; ret.nextOffset = offset; next(ret); } /** * @dev Returns true iff there are more RRs to iterate. * @param iter The iterator to check. * @return True iff the iterator has finished. */ function done(RRIterator memory iter) internal pure returns(bool) { return iter.offset >= iter.data.length; } /** * @dev Moves the iterator to the next resource record. * @param iter The iterator to advance. */ function next(RRIterator memory iter) internal pure { iter.offset = iter.nextOffset; if (iter.offset >= iter.data.length) { return; } // Skip the name uint off = iter.offset + nameLength(iter.data, iter.offset); // Read type, class, and ttl iter.dnstype = iter.data.readUint16(off); off += 2; iter.class = iter.data.readUint16(off); off += 2; iter.ttl = iter.data.readUint32(off); off += 4; // Read the rdata uint rdataLength = iter.data.readUint16(off); off += 2; iter.rdataOffset = off; iter.nextOffset = off + rdataLength; } /** * @dev Returns the name of the current record. * @param iter The iterator. * @return A new bytes object containing the owner name from the RR. */ function name(RRIterator memory iter) internal pure returns(bytes memory) { return iter.data.substring(iter.offset, nameLength(iter.data, iter.offset)); } /** * @dev Returns the rdata portion of the current record. * @param iter The iterator. * @return A new bytes object containing the RR's RDATA. */ function rdata(RRIterator memory iter) internal pure returns(bytes memory) { return iter.data.substring(iter.rdataOffset, iter.nextOffset - iter.rdataOffset); } /** * @dev Checks if a given RR type exists in a type bitmap. * @param self The byte string to read the type bitmap from. * @param offset The offset to start reading at. * @param rrtype The RR type to check for. * @return True if the type is found in the bitmap, false otherwise. */ function checkTypeBitmap(bytes memory self, uint offset, uint16 rrtype) internal pure returns (bool) { uint8 typeWindow = uint8(rrtype >> 8); uint8 windowByte = uint8((rrtype & 0xff) / 8); uint8 windowBitmask = uint8(uint8(1) << (uint8(7) - uint8(rrtype & 0x7))); for (uint off = offset; off < self.length;) { uint8 window = self.readUint8(off); uint8 len = self.readUint8(off + 1); if (typeWindow < window) { // We've gone past our window; it's not here. return false; } else if (typeWindow == window) { // Check this type bitmap if (len * 8 <= windowByte) { // Our type is past the end of the bitmap return false; } return (self.readUint8(off + windowByte + 2) & windowBitmask) != 0; } else { // Skip this type bitmap off += len + 2; } } return false; } function compareNames(bytes memory self, bytes memory other) internal pure returns (int) { if (self.equals(other)) { return 0; } uint off; uint otheroff; uint prevoff; uint otherprevoff; uint counts = labelCount(self, 0); uint othercounts = labelCount(other, 0); // Keep removing labels from the front of the name until both names are equal length while (counts > othercounts) { prevoff = off; off = progress(self, off); counts--; } while (othercounts > counts) { otherprevoff = otheroff; otheroff = progress(other, otheroff); othercounts--; } // Compare the last nonequal labels to each other while (counts > 0 && !self.equals(off, other, otheroff)) { prevoff = off; off = progress(self, off); otherprevoff = otheroff; otheroff = progress(other, otheroff); counts -= 1; } if (off == 0) { return -1; } if(otheroff == 0) { return 1; } return self.compare(prevoff + 1, self.readUint8(prevoff), other, otherprevoff + 1, other.readUint8(otherprevoff)); } function progress(bytes memory body, uint off) internal pure returns(uint) { return off + 1 + body.readUint8(off); } } pragma solidity ^0.5.0; contract DNSResolver is ResolverBase { using RRUtils for *; using BytesUtils for bytes; bytes4 constant private DNS_RECORD_INTERFACE_ID = 0xa8fa5682; bytes4 constant private DNS_ZONE_INTERFACE_ID = 0x5c47637c; // DNSRecordChanged is emitted whenever a given node/name/resource's RRSET is updated. event DNSRecordChanged(bytes32 indexed node, bytes name, uint16 resource, bytes record); // DNSRecordDeleted is emitted whenever a given node/name/resource's RRSET is deleted. event DNSRecordDeleted(bytes32 indexed node, bytes name, uint16 resource); // DNSZoneCleared is emitted whenever a given node's zone information is cleared. event DNSZoneCleared(bytes32 indexed node); // DNSZonehashChanged is emitted whenever a given node's zone hash is updated. event DNSZonehashChanged(bytes32 indexed node, bytes lastzonehash, bytes zonehash); // Zone hashes for the domains. // A zone hash is an EIP-1577 content hash in binary format that should point to a // resource containing a single zonefile. // node => contenthash mapping(bytes32=>bytes) private zonehashes; // Version the mapping for each zone. This allows users who have lost // track of their entries to effectively delete an entire zone by bumping // the version number. // node => version mapping(bytes32=>uint256) private versions; // The records themselves. Stored as binary RRSETs // node => version => name => resource => data mapping(bytes32=>mapping(uint256=>mapping(bytes32=>mapping(uint16=>bytes)))) private records; // Count of number of entries for a given name. Required for DNS resolvers // when resolving wildcards. // node => version => name => number of records mapping(bytes32=>mapping(uint256=>mapping(bytes32=>uint16))) private nameEntriesCount; /** * Set one or more DNS records. Records are supplied in wire-format. * Records with the same node/name/resource must be supplied one after the * other to ensure the data is updated correctly. For example, if the data * was supplied: * a.example.com IN A 1.2.3.4 * a.example.com IN A 5.6.7.8 * www.example.com IN CNAME a.example.com. * then this would store the two A records for a.example.com correctly as a * single RRSET, however if the data was supplied: * a.example.com IN A 1.2.3.4 * www.example.com IN CNAME a.example.com. * a.example.com IN A 5.6.7.8 * then this would store the first A record, the CNAME, then the second A * record which would overwrite the first. * * @param node the namehash of the node for which to set the records * @param data the DNS wire format records to set */ function setDNSRecords(bytes32 node, bytes calldata data) external authorised(node) { uint16 resource = 0; uint256 offset = 0; bytes memory name; bytes memory value; bytes32 nameHash; // Iterate over the data to add the resource records for (RRUtils.RRIterator memory iter = data.iterateRRs(0); !iter.done(); iter.next()) { if (resource == 0) { resource = iter.dnstype; name = iter.name(); nameHash = keccak256(abi.encodePacked(name)); value = bytes(iter.rdata()); } else { bytes memory newName = iter.name(); if (resource != iter.dnstype || !name.equals(newName)) { setDNSRRSet(node, name, resource, data, offset, iter.offset - offset, value.length == 0); resource = iter.dnstype; offset = iter.offset; name = newName; nameHash = keccak256(name); value = bytes(iter.rdata()); } } } if (name.length > 0) { setDNSRRSet(node, name, resource, data, offset, data.length - offset, value.length == 0); } } /** * Obtain a DNS record. * @param node the namehash of the node for which to fetch the record * @param name the keccak-256 hash of the fully-qualified name for which to fetch the record * @param resource the ID of the resource as per https://en.wikipedia.org/wiki/List_of_DNS_record_types * @return the DNS record in wire format if present, otherwise empty */ function dnsRecord(bytes32 node, bytes32 name, uint16 resource) public view returns (bytes memory) { return records[node][versions[node]][name][resource]; } /** * Check if a given node has records. * @param node the namehash of the node for which to check the records * @param name the namehash of the node for which to check the records */ function hasDNSRecords(bytes32 node, bytes32 name) public view returns (bool) { return (nameEntriesCount[node][versions[node]][name] != 0); } /** * Clear all information for a DNS zone. * @param node the namehash of the node for which to clear the zone */ function clearDNSZone(bytes32 node) public authorised(node) { versions[node]++; emit DNSZoneCleared(node); } /** * setZonehash sets the hash for the zone. * May only be called by the owner of that node in the ENS registry. * @param node The node to update. * @param hash The zonehash to set */ function setZonehash(bytes32 node, bytes calldata hash) external authorised(node) { bytes memory oldhash = zonehashes[node]; zonehashes[node] = hash; emit DNSZonehashChanged(node, oldhash, hash); } /** * zonehash obtains the hash for the zone. * @param node The ENS node to query. * @return The associated contenthash. */ function zonehash(bytes32 node) external view returns (bytes memory) { return zonehashes[node]; } function supportsInterface(bytes4 interfaceID) public pure returns(bool) { return interfaceID == DNS_RECORD_INTERFACE_ID || interfaceID == DNS_ZONE_INTERFACE_ID || super.supportsInterface(interfaceID); } function setDNSRRSet( bytes32 node, bytes memory name, uint16 resource, bytes memory data, uint256 offset, uint256 size, bool deleteRecord) private { uint256 version = versions[node]; bytes32 nameHash = keccak256(name); bytes memory rrData = data.substring(offset, size); if (deleteRecord) { if (records[node][version][nameHash][resource].length != 0) { nameEntriesCount[node][version][nameHash]--; } delete(records[node][version][nameHash][resource]); emit DNSRecordDeleted(node, name, resource); } else { if (records[node][version][nameHash][resource].length == 0) { nameEntriesCount[node][version][nameHash]++; } records[node][version][nameHash][resource] = rrData; emit DNSRecordChanged(node, name, resource, rrData); } } } pragma solidity ^0.5.0; contract InterfaceResolver is ResolverBase, AddrResolver { bytes4 constant private INTERFACE_INTERFACE_ID = bytes4(keccak256("interfaceImplementer(bytes32,bytes4)")); bytes4 private constant INTERFACE_META_ID = 0x01ffc9a7; event InterfaceChanged(bytes32 indexed node, bytes4 indexed interfaceID, address implementer); mapping(bytes32=>mapping(bytes4=>address)) interfaces; /** * Sets an interface associated with a name. * Setting the address to 0 restores the default behaviour of querying the contract at `addr()` for interface support. * @param node The node to update. * @param interfaceID The EIP 165 interface ID. * @param implementer The address of a contract that implements this interface for this node. */ function setInterface(bytes32 node, bytes4 interfaceID, address implementer) external authorised(node) { interfaces[node][interfaceID] = implementer; emit InterfaceChanged(node, interfaceID, implementer); } /** * Returns the address of a contract that implements the specified interface for this name. * If an implementer has not been set for this interfaceID and name, the resolver will query * the contract at `addr()`. If `addr()` is set, a contract exists at that address, and that * contract implements EIP165 and returns `true` for the specified interfaceID, its address * will be returned. * @param node The ENS node to query. * @param interfaceID The EIP 165 interface ID to check for. * @return The address that implements this interface, or 0 if the interface is unsupported. */ function interfaceImplementer(bytes32 node, bytes4 interfaceID) external view returns (address) { address implementer = interfaces[node][interfaceID]; if(implementer != address(0)) { return implementer; } address a = addr(node); if(a == address(0)) { return address(0); } (bool success, bytes memory returnData) = a.staticcall(abi.encodeWithSignature("supportsInterface(bytes4)", INTERFACE_META_ID)); if(!success || returnData.length < 32 || returnData[31] == 0) { // EIP 165 not supported by target return address(0); } (success, returnData) = a.staticcall(abi.encodeWithSignature("supportsInterface(bytes4)", interfaceID)); if(!success || returnData.length < 32 || returnData[31] == 0) { // Specified interface not supported by target return address(0); } return a; } function supportsInterface(bytes4 interfaceID) public pure returns(bool) { return interfaceID == INTERFACE_INTERFACE_ID || super.supportsInterface(interfaceID); } } pragma solidity ^0.5.0; contract NameResolver is ResolverBase { bytes4 constant private NAME_INTERFACE_ID = 0x691f3431; event NameChanged(bytes32 indexed node, string name); mapping(bytes32=>string) names; /** * Sets the name associated with an ENS node, for reverse records. * May only be called by the owner of that node in the ENS registry. * @param node The node to update. * @param name The name to set. */ function setName(bytes32 node, string calldata name) external authorised(node) { names[node] = name; emit NameChanged(node, name); } /** * Returns the name associated with an ENS node, for reverse records. * Defined in EIP181. * @param node The ENS node to query. * @return The associated name. */ function name(bytes32 node) external view returns (string memory) { return names[node]; } function supportsInterface(bytes4 interfaceID) public pure returns(bool) { return interfaceID == NAME_INTERFACE_ID || super.supportsInterface(interfaceID); } } pragma solidity ^0.5.0; contract PubkeyResolver is ResolverBase { bytes4 constant private PUBKEY_INTERFACE_ID = 0xc8690233; event PubkeyChanged(bytes32 indexed node, bytes32 x, bytes32 y); struct PublicKey { bytes32 x; bytes32 y; } mapping(bytes32=>PublicKey) pubkeys; /** * Sets the SECP256k1 public key associated with an ENS node. * @param node The ENS node to query * @param x the X coordinate of the curve point for the public key. * @param y the Y coordinate of the curve point for the public key. */ function setPubkey(bytes32 node, bytes32 x, bytes32 y) external authorised(node) { pubkeys[node] = PublicKey(x, y); emit PubkeyChanged(node, x, y); } /** * Returns the SECP256k1 public key associated with an ENS node. * Defined in EIP 619. * @param node The ENS node to query * @return x, y the X and Y coordinates of the curve point for the public key. */ function pubkey(bytes32 node) external view returns (bytes32 x, bytes32 y) { return (pubkeys[node].x, pubkeys[node].y); } function supportsInterface(bytes4 interfaceID) public pure returns(bool) { return interfaceID == PUBKEY_INTERFACE_ID || super.supportsInterface(interfaceID); } } pragma solidity ^0.5.0; contract TextResolver is ResolverBase { bytes4 constant private TEXT_INTERFACE_ID = 0x59d1d43c; event TextChanged(bytes32 indexed node, string indexed indexedKey, string key); mapping(bytes32=>mapping(string=>string)) texts; /** * Sets the text data associated with an ENS node and key. * May only be called by the owner of that node in the ENS registry. * @param node The node to update. * @param key The key to set. * @param value The text data value to set. */ function setText(bytes32 node, string calldata key, string calldata value) external authorised(node) { texts[node][key] = value; emit TextChanged(node, key, key); } /** * Returns the text data associated with an ENS node and key. * @param node The ENS node to query. * @param key The text data key to query. * @return The associated text data. */ function text(bytes32 node, string calldata key) external view returns (string memory) { return texts[node][key]; } function supportsInterface(bytes4 interfaceID) public pure returns(bool) { return interfaceID == TEXT_INTERFACE_ID || super.supportsInterface(interfaceID); } } pragma solidity ^0.5.0; /** * A simple resolver anyone can use; only allows the owner of a node to set its * address. */ contract PublicResolver is ABIResolver, AddrResolver, ContentHashResolver, DNSResolver, InterfaceResolver, NameResolver, PubkeyResolver, TextResolver { ENS ens; /** * A mapping of authorisations. An address that is authorised for a name * may make any changes to the name that the owner could, but may not update * the set of authorisations. * (node, owner, caller) => isAuthorised */ mapping(bytes32=>mapping(address=>mapping(address=>bool))) public authorisations; event AuthorisationChanged(bytes32 indexed node, address indexed owner, address indexed target, bool isAuthorised); constructor(ENS _ens) public { ens = _ens; } /** * @dev Sets or clears an authorisation. * Authorisations are specific to the caller. Any account can set an authorisation * for any name, but the authorisation that is checked will be that of the * current owner of a name. Thus, transferring a name effectively clears any * existing authorisations, and new authorisations can be set in advance of * an ownership transfer if desired. * * @param node The name to change the authorisation on. * @param target The address that is to be authorised or deauthorised. * @param isAuthorised True if the address should be authorised, or false if it should be deauthorised. */ function setAuthorisation(bytes32 node, address target, bool isAuthorised) external { authorisations[node][msg.sender][target] = isAuthorised; emit AuthorisationChanged(node, msg.sender, target, isAuthorised); } function isAuthorised(bytes32 node) internal view returns(bool) { address owner = ens.owner(node); return owner == msg.sender || authorisations[node][owner][msg.sender]; } }
Sets the ABI associated with an ENS node. Nodes may have one ABI of each content type. To remove an ABI, set it to the empty string. node The node to update. contentType The content type of the ABI data The ABI data./ Content types must be powers of 2
function setABI(bytes32 node, uint256 contentType, bytes calldata data) external authorised(node) { require(((contentType - 1) & contentType) == 0); abis[node][contentType] = data; emit ABIChanged(node, contentType); }
15,463
./full_match/1/0xEb57C7879C95ffdd2676748Caa7d36a83Cef8C53/sources/contracts/NestQueryV1.sol
Setup the parameters for queryings, one price for all token Parameters can be reset by set time to zero
function setParams(uint256 single, uint32 time, uint256 nestAmount) public onlyGovernance { (uint32 _singleFee, uint32 _time, uint32 _actFee, uint32 _res) = decode_4x32_256(paramsEncoded); _singleFee = uint32(single); _time = uint32(time); _actFee = uint32(nestAmount / 1e18); uint256 oldParamsEncoded = paramsEncoded; paramsEncoded = encode_4x32_256(_singleFee, _time, _actFee, _res); emit ParamsSetup(address(msg.sender), oldParamsEncoded, paramsEncoded); }
4,941,200
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; library AsciiPunkFactory { uint256 private constant TOP_COUNT = 55; uint256 private constant EYE_COUNT = 48; uint256 private constant NOSE_COUNT = 9; uint256 private constant MOUTH_COUNT = 32; function draw(uint256 seed) public pure returns (string memory) { uint256 rand = uint256(keccak256(abi.encodePacked(seed))); string memory top = _chooseTop(rand); string memory eyes = _chooseEyes(rand); string memory mouth = _chooseMouth(rand); string memory chin = unicode" │ │ \n" unicode" └──┘ │ \n"; string memory neck = unicode" │ │ \n" unicode" │ │ \n"; return string(abi.encodePacked(top, eyes, mouth, chin, neck)); } function _chooseTop(uint256 rand) internal pure returns (string memory) { string[TOP_COUNT] memory tops = [ unicode" ┌───┐ \n" unicode" │ ┼┐ \n" unicode" ├────┼┼ \n", unicode" ┌┬┬┬┬┐ \n" unicode" ╓┬┬┬┬╖ \n" unicode" ╙┴┴┴┴╜ \n", unicode" ╒════╕ \n" unicode" ┌┴────┴┐ \n" unicode" └┬────┬┘ \n", unicode" ╒════╕ \n" unicode" │□□□□│ \n" unicode" └┬────┬┘ \n", unicode" ╒════╕ \n" unicode" │ │ \n" unicode" └─┬────┬─┘ \n", unicode" ◙◙◙◙ \n" unicode" ▄████▄ \n" unicode" ┌────┐ \n", unicode" ┌───┐ \n" unicode"┌──┤ └┐ \n" unicode"└──┼────┤ \n", unicode" ┌───┐ \n" unicode" ┌┘ ├──┐\n" unicode" ├────┼──┘\n", unicode" ┌────┐/ \n" unicode"┌──┴────┴──┐\n" unicode"└──┬────┬──┘\n", unicode" ╒════╕ \n" unicode" ┌─┴────┴─┐ \n" unicode" └─┬────┬─┘ \n", unicode" ┌──────┐ \n" unicode" │▲▲▲▲▲▲│ \n" unicode" └┬────┬┘ \n", unicode" ┌┌────┐┐ \n" unicode" ││┌──┐││ \n" unicode" └┼┴──┴┼┘ \n", unicode" ┌────┐ \n" unicode" ┌┘─ │ \n" unicode" └┌────┐ \n", unicode" \n" unicode" ┌┬┬┬┬┐ \n" unicode" ├┴┴┴┴┤ \n", unicode" \n" unicode" ╓┬╥┐ \n" unicode" ┌╨┴╨┴┐ \n", unicode" \n" unicode" ╒╦╦╦╦╕ \n" unicode" ╞╩╩╩╩╡ \n", unicode" \n" unicode" \n" unicode" ┌┼┼┼┼┐ \n", unicode" \n" unicode" ││││ \n" unicode" ┌┼┼┼┼┐ \n", unicode" ╔ \n" unicode" ╔║ \n" unicode" ┌─╫╫─┐ \n", unicode" \n" unicode" ║║║║ \n" unicode" ┌╨╨╨╨┐ \n", unicode" \n" unicode" ▐▐▐▌▌▌ \n" unicode" ┌────┐ \n", unicode" \n" unicode" \\///// \n" unicode" ┌────┐ \n", unicode" ┐ ┌ \n" unicode" ┐││││┌ \n" unicode" ┌────┐ \n", unicode" ┌┐ ┐┌┐┌┐ \n" unicode" └└┐││┌┘ \n" unicode" ┌┴┴┴┴┐ \n", unicode" ┐┐┐┐┐ \n" unicode" └└└└└┐ \n" unicode" └└└└└┐ \n", unicode" \n" unicode" ││││││ \n" unicode" ┌────┐ \n", unicode" \n" unicode" ╓╓╓╓ \n" unicode" ┌╨╨╨╨┐ \n", unicode" ╔╔╗╗╗ \n" unicode" ╔╔╔╗╗╗╗ \n" unicode" ╔╝╝║ ╚╚╗ \n", unicode" ╔╔╔╔╔╗ \n" unicode" ╔╔╔╔╔╗║╗ \n" unicode" ╝║╨╨╨╨║╚ \n", unicode" ╔╔═╔═╔ \n" unicode" ╔╩╔╩╔╝ \n" unicode" ┌────┐ \n", unicode" \n" unicode" /// \n" unicode" ┌────┐ \n", unicode" ╔╗╔╗ \n" unicode" ╔╗╔╗╝ \n" unicode" ┌╔╝╔╝┐ \n", unicode" ╔╔╔╔╝ \n" unicode" ╔╝╔╝ \n" unicode" ┌╨╨╨─┐ \n", unicode" ╔╗ \n" unicode" ╔╔╔╗╝ \n" unicode" ┌╚╚╝╝┐ \n", unicode" ╔════╗ \n" unicode" ╔╚╚╚╝╝╝╗ \n" unicode" ╟┌────┐╢ \n", unicode" ╔═╗ \n" unicode" ╚╚╚╗ \n" unicode" ┌────┐ \n", unicode" \n" unicode" \n" unicode" ┌╨╨╨╨┐ \n", unicode" \n" unicode" ⌂⌂⌂⌂ \n" unicode" ┌────┐ \n", unicode" ┌────┐ \n" unicode" │ /└┐ \n" unicode" ├────┐/ \n", unicode" \n" unicode" (((((( \n" unicode" ┌────┐ \n", unicode" ┌┌┌┌┌┐ \n" unicode" ├┘┘┘┘┘ \n" unicode" ┌────┐ \n", unicode" «°┐ \n" unicode" │╪╕ \n" unicode" ┌└┼──┐ \n", unicode" <° °> § \n" unicode" \\'/ / \n" unicode" {())}} \n", unicode" ██████ \n" unicode" ██ ██ ██ \n" unicode" █ ██████ █ \n", unicode" ████ \n" unicode" ██◙◙██ \n" unicode" ┌─▼▼─┐ \n", unicode" ╓╖ ╓╖ \n" unicode" °╜╚╗╔╝╙° \n" unicode" ┌─╨╨─┐ \n", unicode" ± ±± ± \n" unicode" ◙◙◙◙◙◙ \n" unicode" ┌────┐ \n", unicode" ♫ ♪ \n" unicode" ♪ ♫ \n" unicode" ♪ ┌────┐ \n", unicode" /≡≡\\ \n" unicode" /≡≡≡≡\\ \n" unicode" /┌────┐\\ \n", unicode" \n" unicode" ♣♥♦♠♣♥ \n" unicode" ┌────┐ \n", unicode" [⌂] \n" unicode" │ \n" unicode" ┌────┐ \n", unicode" /\\/\\/\\/\\ \n" unicode" \\\\/\\/\\// \n" unicode" ┌────┐ \n", unicode" ↑↑↓↓ \n" unicode" ←→←→AB \n" unicode" ┌────┐ \n", unicode" ┌─┬┐ \n" unicode" ┌┘┌┘└┐ \n" unicode" ├─┴──┤ \n", unicode" ☼ ☼ \n" unicode" \\/ \n" unicode" ┌────┐ \n" ]; uint256 topId = rand % TOP_COUNT; return tops[topId]; } function _chooseEyes(uint256 rand) internal pure returns (string memory) { string[EYE_COUNT] memory leftEyes = [ unicode"◕", unicode"*", unicode"♥", unicode"X", unicode"⊙", unicode"˘", unicode"α", unicode"◉", unicode"☻", unicode"¬", unicode"^", unicode"═", unicode"┼", unicode"┬", unicode"■", unicode"─", unicode"û", unicode"╜", unicode"δ", unicode"│", unicode"┐", unicode"┌", unicode"┌", unicode"╤", unicode"/", unicode"\\", unicode"/", unicode"\\", unicode"╦", unicode"♥", unicode"♠", unicode"♦", unicode"╝", unicode"◄", unicode"►", unicode"◄", unicode"►", unicode"I", unicode"╚", unicode"╔", unicode"╙", unicode"╜", unicode"╓", unicode"╥", unicode"$", unicode"○", unicode"N", unicode"x" ]; string[EYE_COUNT] memory rightEyes = [ unicode"◕", unicode"*", unicode"♥", unicode"X", unicode"⊙", unicode"˘", unicode"α", unicode"◉", unicode"☻", unicode"¬", unicode"^", unicode"═", unicode"┼", unicode"┬", unicode"■", unicode"─", unicode"û", unicode"╜", unicode"δ", unicode"│", unicode"┐", unicode"┐", unicode"┌", unicode"╤", unicode"\\", unicode"/", unicode"/", unicode"\\", unicode"╦", unicode"♠", unicode"♣", unicode"♦", unicode"╝", unicode"►", unicode"◄", unicode"◄", unicode"◄", unicode"I", unicode"╚", unicode"╗", unicode"╜", unicode"╜", unicode"╓", unicode"╥", unicode"$", unicode"○", unicode"N", unicode"x" ]; uint256 eyeId = rand % EYE_COUNT; string memory leftEye = leftEyes[eyeId]; string memory rightEye = rightEyes[eyeId]; string memory nose = _chooseNose(rand); string memory forehead = unicode" │ ├┐ \n"; string memory leftFace = unicode" │"; string memory rightFace = unicode" └│ \n"; return string( abi.encodePacked( forehead, leftFace, leftEye, " ", rightEye, rightFace, nose ) ); } function _chooseMouth(uint256 rand) internal pure returns (string memory) { string[MOUTH_COUNT] memory mouths = [ unicode" │ │ \n" unicode" │── │ \n", unicode" │ │ \n" unicode" │δ │ \n", unicode" │ │ \n" unicode" │─┬ │ \n", unicode" │ │ \n" unicode" │(─) │ \n", unicode" │ │ \n" unicode" │[─] │ \n", unicode" │ │ \n" unicode" │<─> │ \n", unicode" │ │ \n" unicode" │╙─ │ \n", unicode" │ │ \n" unicode" │─╜ │ \n", unicode" │ │ \n" unicode" │└─┘ │ \n", unicode" │ │ \n" unicode" │┌─┐ │ \n", unicode" │ │ \n" unicode" │╓─ │ \n", unicode" │ │ \n" unicode" │─╖ │ \n", unicode" │ │ \n" unicode" │┼─┼ │ \n", unicode" │ │ \n" unicode" │──┼ │ \n", unicode" │ │ \n" unicode" │«─» │ \n", unicode" │ │ \n" unicode" │── │ \n", unicode" ∙ │ │ \n" unicode" ∙─── │ \n", unicode" ∙ │ │ \n" unicode" ∙───) │ \n", unicode" ∙ │ │ \n" unicode" ∙───] │ \n", unicode" │⌐¬ │ \n" unicode" √──── │ \n", unicode" │╓╖ │ \n" unicode" │── │ \n", unicode" │~~ │ \n" unicode" │/\\ │ \n", unicode" │ │ \n" unicode" │══ │ \n", unicode" │ │ \n" unicode" │▼▼ │ \n", unicode" │⌐¬ │ \n" unicode" │O │ \n", unicode" │ │ \n" unicode" │O │ \n", unicode" ∙ │⌐¬ │ \n" unicode" ∙─── │ \n", unicode" ∙ │⌐¬ │ \n" unicode" ∙───) │ \n", unicode" ∙ │⌐¬ │ \n" unicode" ∙───] │ \n", unicode" │⌐¬ │ \n" unicode" │── │ \n", unicode" │⌐-¬ │ \n" unicode" │ │ \n", unicode" │┌-┐ │ \n" unicode" ││ │ │ \n" ]; uint256 mouthId = rand % MOUTH_COUNT; return mouths[mouthId]; } function _chooseNose(uint256 rand) internal pure returns (string memory) { string[NOSE_COUNT] memory noses = [ unicode"└", unicode"╘", unicode"<", unicode"└", unicode"┌", unicode"^", unicode"└", unicode"┼", unicode"Γ" ]; uint256 noseId = rand % NOSE_COUNT; string memory nose = noses[noseId]; return string(abi.encodePacked(unicode" │ ", nose, unicode" └┘ \n")); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "./AsciiPunkFactory.sol"; import "./ERC721Metadata.sol"; import "./PaymentSplitter.sol"; contract AsciiPunks is ERC721Metadata, PaymentSplitter { using Address for address; using Strings for uint256; // EVENTS event Transfer( address indexed from, address indexed to, uint256 indexed tokenId ); event Approval( address indexed owner, address indexed approved, uint256 indexed tokenId ); event ApprovalForAll( address indexed owner, address indexed operator, bool approved ); event Generated(uint256 indexed index, address indexed a, string value); mapping(uint256 => uint256) internal idToSeed; mapping(uint256 => uint256) internal seedToId; mapping(uint256 => address) internal idToOwner; mapping(address => uint256[]) internal ownerToIds; mapping(uint256 => uint256) internal idToOwnerIndex; mapping(address => mapping(address => bool)) internal ownerToOperators; mapping(uint256 => address) internal idToApproval; uint256 internal numTokens = 0; uint256 public constant TOKEN_LIMIT = 2048; bool public hasSaleStarted = false; bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; modifier validNFToken(uint256 tokenId) { require( idToOwner[tokenId] != address(0), "ERC721: query for nonexistent token" ); _; } modifier canOperate(uint256 tokenId) { address owner = idToOwner[tokenId]; require( owner == _msgSender() || ownerToOperators[owner][_msgSender()], "ERC721: approve caller is not owner nor approved for all" ); _; } modifier canTransfer(uint256 tokenId) { address tokenOwner = idToOwner[tokenId]; require( tokenOwner == _msgSender() || idToApproval[tokenId] == _msgSender() || ownerToOperators[tokenOwner][_msgSender()], "ERC721: transfer caller is not owner nor approved" ); _; } constructor() { _registerInterface(_INTERFACE_ID_ERC721); _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } function createPunk(uint256 seed) external payable returns (string memory) { return _mint(_msgSender(), seed); } function calculatePrice() internal view returns (uint256) { uint256 price; if (numTokens < 256) { price = 50000000000000000; } else if (numTokens >= 256 && numTokens < 512) { price = 100000000000000000; } else if (numTokens >= 512 && numTokens < 1024) { price = 200000000000000000; } else if (numTokens >= 1024 && numTokens < 1536) { price = 300000000000000000; } else { price = 400000000000000000; } return price; } function _mint(address to, uint256 _seed) internal returns (string memory) { require(hasSaleStarted == true, "Sale hasn't started"); require(to != address(0), "ERC721: mint to the zero address"); require( numTokens < TOKEN_LIMIT, "ERC721: maximum number of tokens already minted" ); require(msg.value >= calculatePrice(), "ERC721: insufficient ether"); uint256 seed = uint256( keccak256(abi.encodePacked(_seed, block.timestamp, msg.sender, numTokens)) ); require(seedToId[seed] == 0, "ERC721: seed already used"); uint256 id = numTokens + 1; idToSeed[id] = seed; seedToId[seed] = id; string memory punk = AsciiPunkFactory.draw(idToSeed[id]); emit Generated(id, to, punk); numTokens = numTokens + 1; _registerToken(to, id); emit Transfer(address(0), to, id); return punk; } function _registerToken(address to, uint256 tokenId) internal { require(idToOwner[tokenId] == address(0)); idToOwner[tokenId] = to; ownerToIds[to].push(tokenId); uint256 length = ownerToIds[to].length; idToOwnerIndex[tokenId] = length - 1; } function draw(uint256 tokenId) external view validNFToken(tokenId) returns (string memory) { string memory uri = AsciiPunkFactory.draw(idToSeed[tokenId]); return uri; } function totalSupply() public view returns (uint256) { return numTokens; } function tokenByIndex(uint256 index) public view returns (uint256) { require(index < numTokens, "ERC721Enumerable: global index out of bounds"); return index; } function tokenOfOwnerByIndex(address owner, uint256 _index) external view returns (uint256) { require( _index < ownerToIds[owner].length, "ERC721Enumerable: owner index out of bounds" ); return ownerToIds[owner][_index]; } function balanceOf(address owner) external view returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return ownerToIds[owner].length; } function ownerOf(uint256 tokenId) external view returns (address) { return _ownerOf(tokenId); } function _ownerOf(uint256 tokenId) internal view validNFToken(tokenId) returns (address) { address owner = idToOwner[tokenId]; require(owner != address(0), "ERC721: query for nonexistent token"); return owner; } function transferFrom( address from, address to, uint256 tokenId ) external validNFToken(tokenId) canTransfer(tokenId) { address tokenOwner = idToOwner[tokenId]; require(tokenOwner == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _transfer(to, tokenId); } function _transfer(address to, uint256 tokenId) internal { address from = idToOwner[tokenId]; _clearApproval(tokenId); emit Approval(from, to, tokenId); _removeNFToken(from, tokenId); _registerToken(to, tokenId); emit Transfer(from, to, tokenId); } function _removeNFToken(address from, uint256 tokenId) internal { require(idToOwner[tokenId] == from); delete idToOwner[tokenId]; uint256 tokenToRemoveIndex = idToOwnerIndex[tokenId]; uint256 lastTokenIndex = ownerToIds[from].length - 1; if (lastTokenIndex != tokenToRemoveIndex) { uint256 lastToken = ownerToIds[from][lastTokenIndex]; ownerToIds[from][tokenToRemoveIndex] = lastToken; idToOwnerIndex[lastToken] = tokenToRemoveIndex; } ownerToIds[from].pop(); } function approve(address approved, uint256 tokenId) external validNFToken(tokenId) canOperate(tokenId) { address owner = idToOwner[tokenId]; require(approved != owner, "ERC721: approval to current owner"); idToApproval[tokenId] = approved; emit Approval(owner, approved, tokenId); } function _clearApproval(uint256 tokenId) private { if (idToApproval[tokenId] != address(0)) { delete idToApproval[tokenId]; } } function getApproved(uint256 tokenId) external view validNFToken(tokenId) returns (address) { return idToApproval[tokenId]; } function setApprovalForAll(address operator, bool approved) external { require(operator != _msgSender(), "ERC721: approve to caller"); ownerToOperators[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } function isApprovedForAll(address owner, address operator) external view returns (bool) { return ownerToOperators[owner][operator]; } function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external { _safeTransferFrom(from, to, tokenId, data); } function safeTransferFrom( address from, address to, uint256 tokenId ) external { _safeTransferFrom(from, to, tokenId, ""); } function _safeTransferFrom( address from, address to, uint256 tokenId, bytes memory data ) private validNFToken(tokenId) canTransfer(tokenId) { address tokenOwner = idToOwner[tokenId]; require(tokenOwner == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _transfer(to, tokenId); require( _checkOnERC721Received(from, to, tokenId, data), "ERC721: transfer to non ERC721Receiver implementer" ); } function tokenURI(uint256 tokenId) external view validNFToken(tokenId) returns (string memory) { string memory uri = _baseURI(); return bytes(uri).length > 0 ? string(abi.encodePacked(uri, tokenId.toString())) : ""; } function startSale() public onlyOwner { hasSaleStarted = true; } function pauseSale() public onlyOwner { hasSaleStarted = false; } function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; contract ERC165 { mapping(bytes4 => bool) private _supportedInterfaces; bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; constructor() { _registerInterface(_INTERFACE_ID_ERC165); } function supportsInterface(bytes4 interfaceId) external view returns (bool) { return _supportedInterfaces[interfaceId]; } function _registerInterface(bytes4 interfaceId) internal { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "./ERC165.sol"; contract ERC721Metadata is Ownable, ERC165 { bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; string private _baseTokenURI; string private _NFTName = "AsciiPunks"; string private _NFTSymbol = "ASC"; constructor() { _registerInterface(_INTERFACE_ID_ERC721_METADATA); _baseTokenURI = "https://api.asciipunks.com/punks/"; } function name() external view returns (string memory) { return _NFTName; } function symbol() external view returns (string memory) { return _NFTSymbol; } function setBaseURI(string calldata newBaseTokenURI) public onlyOwner { _baseTokenURI = newBaseTokenURI; } function baseURI() public view returns (string memory) { return _baseURI(); } function _baseURI() internal view returns (string memory) { return _baseTokenURI; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/utils/Context.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; /** * @title PaymentSplitter * @dev This contract allows to split Ether payments among a group of accounts. The sender does not need to be aware * that the Ether will be split in this way, since it is handled transparently by the contract. * * The split can be in equal parts or in any other arbitrary proportion. The way this is specified is by assigning each * account to a number of shares. Of all the Ether that this contract receives, each account will then be able to claim * an amount proportional to the percentage of total shares they were assigned. * * `PaymentSplitter` follows a _pull payment_ model. This means that payments are not automatically forwarded to the * accounts but kept in this contract, and the actual transfer is triggered as a separate step by calling the {release} * function. */ contract PaymentSplitter is Context { event PayeeAdded(address account, uint256 shares); event PaymentReleased(address to, uint256 amount); event PaymentReceived(address from, uint256 amount); uint256 private _totalShares; uint256 private _totalReleased; mapping(address => uint256) private _shares; mapping(address => uint256) private _released; address[] private _payees; /** * @dev Creates an instance of `PaymentSplitter` where each account in `payees` is assigned the number of shares at * the matching position in the `shares` array. * * All addresses in `payees` must be non-zero. Both arrays must have the same non-zero length, and there must be no * duplicates in `payees`. */ constructor() { address[2] memory initialPayees = [ address(0x9386efb02a55A1092dC19f0E68a9816DDaAbDb5b), address(0xF2353AD0930B9F7cf16b4b8300B843349581E817) ]; uint256[2] memory initialShares = [uint256(7), uint256(3)]; for (uint256 i = 0; i < initialPayees.length; i++) { _addPayee(initialPayees[i], initialShares[i]); } } /** * @dev The Ether received will be logged with {PaymentReceived} events. Note that these events are not fully * reliable: it's possible for a contract to receive Ether without triggering this function. This only affects the * reliability of the events, and not the actual splitting of Ether. * * To learn more about this see the Solidity documentation for * https://solidity.readthedocs.io/en/latest/contracts.html#fallback-function[fallback * functions]. */ receive() external payable { emit PaymentReceived(_msgSender(), msg.value); } /** * @dev Getter for the total shares held by payees. */ function totalShares() public view returns (uint256) { return _totalShares; } /** * @dev Getter for the total amount of Ether already released. */ function totalReleased() public view returns (uint256) { return _totalReleased; } /** * @dev Getter for the amount of shares held by an account. */ function shares(address account) public view returns (uint256) { return _shares[account]; } /** * @dev Getter for the amount of Ether already released to a payee. */ function released(address account) public view returns (uint256) { return _released[account]; } /** * @dev Getter for the address of the payee number `index`. */ function payee(uint256 index) public view returns (address) { return _payees[index]; } /** * @dev Triggers a transfer to `account` of the amount of Ether they are owed, according to their percentage of the * total shares and their previous withdrawals. */ function release(address payable account) public virtual { require(_shares[account] > 0, "PaymentSplitter: account has no shares"); uint256 totalReceived = address(this).balance + _totalReleased; uint256 payment = (totalReceived * _shares[account]) / _totalShares - _released[account]; require(payment != 0, "PaymentSplitter: account is not due payment"); _released[account] = _released[account] + payment; _totalReleased = _totalReleased + payment; Address.sendValue(account, payment); emit PaymentReleased(account, payment); } /** * @dev Add a new payee to the contract. * @param account The address of the payee to add. * @param shares_ The number of shares owned by the payee. */ function _addPayee(address account, uint256 shares_) private { require( account != address(0), "PaymentSplitter: account is the zero address" ); require(shares_ > 0, "PaymentSplitter: shares are 0"); require( _shares[account] == 0, "PaymentSplitter: account already has shares" ); _payees.push(account); _shares[account] = shares_; _totalShares = _totalShares + shares_; emit PayeeAdded(account, shares_); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./AsciiPunks/AsciiPunks.sol"; contract AsciiPunksNames { mapping(uint256 => string) names; AsciiPunks private punks; constructor(address payable _punksAddress) { punks = AsciiPunks(_punksAddress); } modifier validNFToken(uint256 tokenId) { address owner = punks.ownerOf(tokenId); require(owner != address(0), "ERC721: query for nonexistent token"); _; } function ownerOf(uint256 tokenId) public view returns (address) { address owner = punks.ownerOf(tokenId); return owner; } function setName(uint256 tokenId, string memory newName) external returns (string memory) { require(msg.sender == ownerOf(tokenId), 'This method is only callable by the owner of the token'); names[tokenId] = newName; return names[tokenId]; } function getName(uint256 tokenId) external view validNFToken(tokenId) returns (string memory) { string memory name = names[tokenId]; return name; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant alphabet = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = alphabet[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } }
Getter for the total shares held by payees./
function totalShares() public view returns (uint256) { return _totalShares; }
199,293
pragma solidity ^0.4.24; // File: openzeppelin-solidity/contracts/introspection/IERC165.sol /** * @title IERC165 * @dev https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md */ interface IERC165 { /** * @notice Query if a contract implements an interface * @param interfaceId The interface identifier, as specified in ERC-165 * @dev Interface identification is specified in ERC-165. This function * uses less than 30,000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: openzeppelin-solidity/contracts/introspection/ERC165.sol /** * @title ERC165 * @author Matt Condon (@shrugs) * @dev Implements ERC165 using a lookup table. */ contract ERC165 is IERC165 { bytes4 private constant _InterfaceId_ERC165 = 0x01ffc9a7; /** * 0x01ffc9a7 === * bytes4(keccak256('supportsInterface(bytes4)')) */ /** * @dev a mapping of interface id to whether or not it's supported */ mapping(bytes4 => bool) private _supportedInterfaces; /** * @dev A contract implementing SupportsInterfaceWithLookup * implement ERC165 itself */ constructor() internal { _registerInterface(_InterfaceId_ERC165); } /** * @dev implement supportsInterface(bytes4) using a lookup table */ function supportsInterface(bytes4 interfaceId) external view returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev internal method for registering an interface */ function _registerInterface(bytes4 interfaceId) internal { require(interfaceId != 0xffffffff); _supportedInterfaces[interfaceId] = true; } } // File: openzeppelin-solidity/contracts/token/ERC721/IERC721.sol /** * @title ERC721 Non-Fungible Token Standard basic interface * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract IERC721 is IERC165 { event Transfer( address indexed from, address indexed to, uint256 indexed tokenId ); event Approval( address indexed owner, address indexed approved, uint256 indexed tokenId ); event ApprovalForAll( address indexed owner, address indexed operator, bool approved ); function balanceOf(address owner) public view returns (uint256 balance); function ownerOf(uint256 tokenId) public view returns (address owner); function approve(address to, uint256 tokenId) public; function getApproved(uint256 tokenId) public view returns (address operator); function setApprovalForAll(address operator, bool _approved) public; function isApprovedForAll(address owner, address operator) public view returns (bool); function transferFrom(address from, address to, uint256 tokenId) public; function safeTransferFrom(address from, address to, uint256 tokenId) public; function safeTransferFrom( address from, address to, uint256 tokenId, bytes data ) public; } // File: openzeppelin-solidity/contracts/token/ERC721/IERC721Receiver.sol /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ contract IERC721Receiver { /** * @notice Handle the receipt of an NFT * @dev The ERC721 smart contract calls this function on the recipient * after a `safeTransfer`. This function MUST return the function selector, * otherwise the caller will revert the transaction. The selector to be * returned can be obtained as `this.onERC721Received.selector`. This * function MAY throw to revert and reject the transfer. * Note: the ERC721 contract address is always the message sender. * @param operator The address which called `safeTransferFrom` function * @param from The address which previously owned the token * @param tokenId The NFT identifier which is being transferred * @param data Additional data with no specified format * @return `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` */ function onERC721Received( address operator, address from, uint256 tokenId, bytes data ) public returns(bytes4); } // File: openzeppelin-solidity/contracts/math/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two numbers, 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 numbers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); // Solidity only automatically asserts when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, 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 numbers, 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 numbers 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; } } // File: openzeppelin-solidity/contracts/utils/Address.sol /** * Utility library of inline functions on addresses */ library Address { /** * Returns whether the target address is a contract * @dev This function will return false if invoked during the constructor of a contract, * as the code is not actually created until after the constructor finishes. * @param account address of the account to check * @return whether the target address is a contract */ function isContract(address account) internal view returns (bool) { uint256 size; // XXX Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address. // See https://ethereum.stackexchange.com/a/14016/36603 // for more details about how this works. // TODO Check this again before the Serenity release, because all addresses will be // contracts then. // solium-disable-next-line security/no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } } // File: openzeppelin-solidity/contracts/token/ERC721/ERC721.sol /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721 is ERC165, IERC721 { using SafeMath for uint256; using Address for address; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from token ID to owner mapping (uint256 => address) private _tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to number of owned token mapping (address => uint256) private _ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; bytes4 private constant _InterfaceId_ERC721 = 0x80ac58cd; /* * 0x80ac58cd === * bytes4(keccak256('balanceOf(address)')) ^ * bytes4(keccak256('ownerOf(uint256)')) ^ * bytes4(keccak256('approve(address,uint256)')) ^ * bytes4(keccak256('getApproved(uint256)')) ^ * bytes4(keccak256('setApprovalForAll(address,bool)')) ^ * bytes4(keccak256('isApprovedForAll(address,address)')) ^ * bytes4(keccak256('transferFrom(address,address,uint256)')) ^ * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) ^ * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) */ constructor() public { // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_InterfaceId_ERC721); } /** * @dev Gets the balance of the specified address * @param owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf(address owner) public view returns (uint256) { require(owner != address(0)); return _ownedTokensCount[owner]; } /** * @dev Gets the owner of the specified token ID * @param tokenId uint256 ID of the token to query the owner of * @return owner address currently marked as the owner of the given token ID */ function ownerOf(uint256 tokenId) public view returns (address) { address owner = _tokenOwner[tokenId]; require(owner != address(0)); return owner; } /** * @dev Approves another address to transfer the given token ID * The zero address indicates there is no approved address. * There can only be one approved address per token at a given time. * Can only be called by the token owner or an approved operator. * @param to address to be approved for the given token ID * @param tokenId uint256 ID of the token to be approved */ function approve(address to, uint256 tokenId) public { address owner = ownerOf(tokenId); require(to != owner); require(msg.sender == owner || isApprovedForAll(owner, msg.sender)); _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Gets the approved address for a token ID, or zero if no address set * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved(uint256 tokenId) public view returns (address) { require(_exists(tokenId)); return _tokenApprovals[tokenId]; } /** * @dev Sets or unsets the approval of a given operator * An operator is allowed to transfer all tokens of the sender on their behalf * @param to operator address to set the approval * @param approved representing the status of the approval to be set */ function setApprovalForAll(address to, bool approved) public { require(to != msg.sender); _operatorApprovals[msg.sender][to] = approved; emit ApprovalForAll(msg.sender, to, approved); } /** * @dev Tells whether an operator is approved by a given owner * @param owner owner address which you want to query the approval of * @param operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll( address owner, address operator ) public view returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev Transfers the ownership of a given token ID to another address * Usage of this method is discouraged, use `safeTransferFrom` whenever possible * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function transferFrom( address from, address to, uint256 tokenId ) public { require(_isApprovedOrOwner(msg.sender, tokenId)); require(to != address(0)); _clearApproval(from, tokenId); _removeTokenFrom(from, tokenId); _addTokenTo(to, tokenId); emit Transfer(from, to, tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function safeTransferFrom( address from, address to, uint256 tokenId ) public { // solium-disable-next-line arg-overflow safeTransferFrom(from, to, tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes _data ) public { transferFrom(from, to, tokenId); // solium-disable-next-line arg-overflow require(_checkOnERC721Received(from, to, tokenId, _data)); } /** * @dev Returns whether the specified token exists * @param tokenId uint256 ID of the token to query the existence of * @return whether the token exists */ function _exists(uint256 tokenId) internal view returns (bool) { address owner = _tokenOwner[tokenId]; return owner != address(0); } /** * @dev Returns whether the given spender can transfer a given token ID * @param spender address of the spender to query * @param tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function _isApprovedOrOwner( address spender, uint256 tokenId ) internal view returns (bool) { address owner = ownerOf(tokenId); // Disable solium check because of // https://github.com/duaraghav8/Solium/issues/175 // solium-disable-next-line operator-whitespace return ( spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender) ); } /** * @dev Internal function to mint a new token * Reverts if the given token ID already exists * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted by the msg.sender */ function _mint(address to, uint256 tokenId) internal { require(to != address(0)); _addTokenTo(to, tokenId); emit Transfer(address(0), to, tokenId); } /** * @dev Internal function to burn a specific token * Reverts if the token does not exist * @param tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address owner, uint256 tokenId) internal { _clearApproval(owner, tokenId); _removeTokenFrom(owner, tokenId); emit Transfer(owner, address(0), tokenId); } /** * @dev Internal function to add a token ID to the list of a given address * Note that this function is left internal to make ERC721Enumerable possible, but is not * intended to be called by custom derived contracts: in particular, it emits no Transfer event. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenTo(address to, uint256 tokenId) internal { require(_tokenOwner[tokenId] == address(0)); _tokenOwner[tokenId] = to; _ownedTokensCount[to] = _ownedTokensCount[to].add(1); } /** * @dev Internal function to remove a token ID from the list of a given address * Note that this function is left internal to make ERC721Enumerable possible, but is not * intended to be called by custom derived contracts: in particular, it emits no Transfer event, * and doesn't clear approvals. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFrom(address from, uint256 tokenId) internal { require(ownerOf(tokenId) == from); _ownedTokensCount[from] = _ownedTokensCount[from].sub(1); _tokenOwner[tokenId] = address(0); } /** * @dev Internal function to invoke `onERC721Received` on a target address * The call is not executed if the target address is not a contract * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes _data ) internal returns (bool) { if (!to.isContract()) { return true; } bytes4 retval = IERC721Receiver(to).onERC721Received( msg.sender, from, tokenId, _data); return (retval == _ERC721_RECEIVED); } /** * @dev Private function to clear current approval of a given token ID * Reverts if the given address is not indeed the owner of the token * @param owner owner of the token * @param tokenId uint256 ID of the token to be transferred */ function _clearApproval(address owner, uint256 tokenId) private { require(ownerOf(tokenId) == owner); if (_tokenApprovals[tokenId] != address(0)) { _tokenApprovals[tokenId] = address(0); } } } // File: contracts/library/token/ERC721Manager.sol /** * @title ERC721Manager * * @dev This library implements OpenZepellin's ERC721 implementation (as of 7/31/2018) as * an external library, in order to keep contract sizes smaller. * * Released under the MIT License. * * * The MIT License (MIT) * * Copyright (c) 2016 Smart Contract Solutions, Inc. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ library ERC721Manager { using SafeMath for uint256; // We define the events on both the library and the client, so that the events emitted here are detected // as if they had been emitted by the client event Transfer( address indexed _from, address indexed _to, uint256 indexed _tokenId ); event Approval( address indexed _owner, address indexed _approved, uint256 indexed _tokenId ); event ApprovalForAll( address indexed _owner, address indexed _operator, bool _approved ); struct ERC721Data { // List of supported interfaces mapping (bytes4 => bool) supportedInterfaces; // Mapping from token ID to owner mapping (uint256 => address) tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) tokenApprovals; // Mapping from owner to number of owned token mapping (address => uint256) ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) operatorApprovals; // Token name string name_; // Token symbol string symbol_; // Mapping from owner to list of owned token IDs mapping(address => uint256[]) ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) allTokensIndex; // Optional mapping for token URIs mapping(uint256 => string) tokenURIs; } // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `ERC721Receiver(0).onERC721Received.selector` bytes4 private constant ERC721_RECEIVED = 0x150b7a02; bytes4 private constant InterfaceId_ERC165 = 0x01ffc9a7; /** * 0x01ffc9a7 === * bytes4(keccak256('supportsInterface(bytes4)')) */ bytes4 private constant InterfaceId_ERC721 = 0x80ac58cd; /* * 0x80ac58cd === * bytes4(keccak256('balanceOf(address)')) ^ * bytes4(keccak256('ownerOf(uint256)')) ^ * bytes4(keccak256('approve(address,uint256)')) ^ * bytes4(keccak256('getApproved(uint256)')) ^ * bytes4(keccak256('setApprovalForAll(address,bool)')) ^ * bytes4(keccak256('isApprovedForAll(address,address)')) ^ * bytes4(keccak256('transferFrom(address,address,uint256)')) ^ * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) ^ * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) */ bytes4 private constant InterfaceId_ERC721Exists = 0x4f558e79; /* * 0x4f558e79 === * bytes4(keccak256('exists(uint256)')) */ bytes4 private constant InterfaceId_ERC721Enumerable = 0x780e9d63; /** * 0x780e9d63 === * bytes4(keccak256('totalSupply()')) ^ * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) ^ * bytes4(keccak256('tokenByIndex(uint256)')) */ bytes4 private constant InterfaceId_ERC721Metadata = 0x5b5e139f; /** * 0x5b5e139f === * bytes4(keccak256('name()')) ^ * bytes4(keccak256('symbol()')) ^ * bytes4(keccak256('tokenURI(uint256)')) */ function initialize(ERC721Data storage self, string _name, string _symbol) external { self.name_ = _name; self.symbol_ = _symbol; // register the supported interface to conform to ERC165 _registerInterface(self, InterfaceId_ERC165); // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(self, InterfaceId_ERC721); _registerInterface(self, InterfaceId_ERC721Exists); _registerInterface(self, InterfaceId_ERC721Enumerable); _registerInterface(self, InterfaceId_ERC721Metadata); } function _registerInterface(ERC721Data storage self, bytes4 _interfaceId) private { self.supportedInterfaces[_interfaceId] = true; } function supportsInterface(ERC721Data storage self, bytes4 _interfaceId) external view returns (bool) { return self.supportedInterfaces[_interfaceId]; } /** * @dev Gets the balance of the specified address * @param _owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf(ERC721Data storage self, address _owner) public view returns (uint256) { require(_owner != address(0)); return self.ownedTokensCount[_owner]; } /** * @dev Gets the owner of the specified token ID * @param _tokenId uint256 ID of the token to query the owner of * @return owner address currently marked as the owner of the given token ID */ function ownerOf(ERC721Data storage self, uint256 _tokenId) public view returns (address) { address owner = self.tokenOwner[_tokenId]; require(owner != address(0)); return owner; } /** * @dev Returns whether the specified token exists * @param _tokenId uint256 ID of the token to query the existence of * @return whether the token exists */ function exists(ERC721Data storage self, uint256 _tokenId) public view returns (bool) { address owner = self.tokenOwner[_tokenId]; return owner != address(0); } /** * @dev Approves another address to transfer the given token ID * The zero address indicates there is no approved address. * There can only be one approved address per token at a given time. * Can only be called by the token owner or an approved operator. * @param _to address to be approved for the given token ID * @param _tokenId uint256 ID of the token to be approved */ function approve(ERC721Data storage self, address _to, uint256 _tokenId) external { address owner = ownerOf(self, _tokenId); require(_to != owner); require(msg.sender == owner || isApprovedForAll(self, owner, msg.sender)); self.tokenApprovals[_tokenId] = _to; emit Approval(owner, _to, _tokenId); } /** * @dev Gets the approved address for a token ID, or zero if no address set * @param _tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved(ERC721Data storage self, uint256 _tokenId) public view returns (address) { return self.tokenApprovals[_tokenId]; } /** * @dev Sets or unsets the approval of a given operator * An operator is allowed to transfer all tokens of the sender on their behalf * @param _to operator address to set the approval * @param _approved representing the status of the approval to be set */ function setApprovalForAll(ERC721Data storage self, address _to, bool _approved) external { require(_to != msg.sender); self.operatorApprovals[msg.sender][_to] = _approved; emit ApprovalForAll(msg.sender, _to, _approved); } /** * @dev Tells whether an operator is approved by a given owner * @param _owner owner address which you want to query the approval of * @param _operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll( ERC721Data storage self, address _owner, address _operator ) public view returns (bool) { return self.operatorApprovals[_owner][_operator]; } /** * @dev Transfers the ownership of a given token ID to another address * Usage of this method is discouraged, use `safeTransferFrom` whenever possible * Requires the msg sender to be the owner, approved, or operator * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred */ function transferFrom( ERC721Data storage self, address _from, address _to, uint256 _tokenId ) public { require(isApprovedOrOwner(self, msg.sender, _tokenId)); require(_from != address(0)); require(_to != address(0)); _clearApproval(self, _from, _tokenId); _removeTokenFrom(self, _from, _tokenId); _addTokenTo(self, _to, _tokenId); emit Transfer(_from, _to, _tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * * Requires the msg sender to be the owner, approved, or operator * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred */ function safeTransferFrom( ERC721Data storage self, address _from, address _to, uint256 _tokenId ) external { // solium-disable-next-line arg-overflow safeTransferFrom(self, _from, _to, _tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg sender to be the owner, approved, or operator * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom( ERC721Data storage self, address _from, address _to, uint256 _tokenId, bytes _data ) public { transferFrom(self, _from, _to, _tokenId); // solium-disable-next-line arg-overflow require(_checkAndCallSafeTransfer(_from, _to, _tokenId, _data)); } /** * @dev Internal function to clear current approval of a given token ID * Reverts if the given address is not indeed the owner of the token * @param _owner owner of the token * @param _tokenId uint256 ID of the token to be transferred */ function _clearApproval(ERC721Data storage self, address _owner, uint256 _tokenId) internal { require(ownerOf(self, _tokenId) == _owner); if (self.tokenApprovals[_tokenId] != address(0)) { self.tokenApprovals[_tokenId] = address(0); } } /** * @dev Internal function to invoke `onERC721Received` on a target address * The call is not executed if the target address is not a contract * @param _from address representing the previous owner of the given token ID * @param _to target address that will receive the tokens * @param _tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return whether the call correctly returned the expected magic value */ function _checkAndCallSafeTransfer( address _from, address _to, uint256 _tokenId, bytes _data ) internal returns (bool) { if (!_isContract(_to)) { return true; } bytes4 retval = IERC721Receiver(_to).onERC721Received(msg.sender, _from, _tokenId, _data); return (retval == ERC721_RECEIVED); } /** * Returns whether the target address is a contract * @dev This function will return false if invoked during the constructor of a contract, * as the code is not actually created until after the constructor finishes. * @param _addr address to check * @return whether the target address is a contract */ function _isContract(address _addr) internal view returns (bool) { uint256 size; // XXX Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address. // See https://ethereum.stackexchange.com/a/14016/36603 // for more details about how this works. // TODO Check this again before the Serenity release, because all addresses will be // contracts then. // solium-disable-next-line security/no-inline-assembly assembly { size := extcodesize(_addr) } return size > 0; } /** * @dev Gets the token name * @return string representing the token name */ function name(ERC721Data storage self) external view returns (string) { return self.name_; } /** * @dev Gets the token symbol * @return string representing the token symbol */ function symbol(ERC721Data storage self) external view returns (string) { return self.symbol_; } /** * @dev Returns an URI for a given token ID * Throws if the token ID does not exist. May return an empty string. * @param _tokenId uint256 ID of the token to query */ function tokenURI(ERC721Data storage self, uint256 _tokenId) external view returns (string) { require(exists(self, _tokenId)); return self.tokenURIs[_tokenId]; } /** * @dev Gets the token ID at a given index of the tokens list of the requested owner * @param _owner address owning the tokens list to be accessed * @param _index uint256 representing the index to be accessed of the requested tokens list * @return uint256 token ID at the given index of the tokens list owned by the requested address */ function tokenOfOwnerByIndex( ERC721Data storage self, address _owner, uint256 _index ) external view returns (uint256) { require(_index < balanceOf(self, _owner)); return self.ownedTokens[_owner][_index]; } /** * @dev Gets the total amount of tokens stored by the contract * @return uint256 representing the total amount of tokens */ function totalSupply(ERC721Data storage self) external view returns (uint256) { return self.allTokens.length; } /** * @dev Gets the token ID at a given index of all the tokens in this contract * Reverts if the index is greater or equal to the total number of tokens * @param _index uint256 representing the index to be accessed of the tokens list * @return uint256 token ID at the given index of the tokens list */ function tokenByIndex(ERC721Data storage self, uint256 _index) external view returns (uint256) { require(_index < self.allTokens.length); return self.allTokens[_index]; } /** * @dev Function to set the token URI for a given token * Reverts if the token ID does not exist * @param _tokenId uint256 ID of the token to set its URI * @param _uri string URI to assign */ function setTokenURI(ERC721Data storage self, uint256 _tokenId, string _uri) external { require(exists(self, _tokenId)); self.tokenURIs[_tokenId] = _uri; } /** * @dev Internal function to add a token ID to the list of a given address * @param _to address representing the new owner of the given token ID * @param _tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenTo(ERC721Data storage self, address _to, uint256 _tokenId) internal { require(self.tokenOwner[_tokenId] == address(0)); self.tokenOwner[_tokenId] = _to; self.ownedTokensCount[_to] = self.ownedTokensCount[_to].add(1); uint256 length = self.ownedTokens[_to].length; self.ownedTokens[_to].push(_tokenId); self.ownedTokensIndex[_tokenId] = length; } /** * @dev Internal function to remove a token ID from the list of a given address * @param _from address representing the previous owner of the given token ID * @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFrom(ERC721Data storage self, address _from, uint256 _tokenId) internal { require(ownerOf(self, _tokenId) == _from); self.ownedTokensCount[_from] = self.ownedTokensCount[_from].sub(1); self.tokenOwner[_tokenId] = address(0); // To prevent a gap in the array, we store the last token in the index of the token to delete, and // then delete the last slot. uint256 tokenIndex = self.ownedTokensIndex[_tokenId]; uint256 lastTokenIndex = self.ownedTokens[_from].length.sub(1); uint256 lastToken = self.ownedTokens[_from][lastTokenIndex]; self.ownedTokens[_from][tokenIndex] = lastToken; self.ownedTokens[_from].length--; // ^ This also deletes the contents at the last position of the array // Note that this will handle single-element arrays. In that case, both tokenIndex and lastTokenIndex are going to // be zero. Then we can make sure that we will remove _tokenId from the ownedTokens list since we are first swapping // the lastToken to the first position, and then dropping the element placed in the last position of the list self.ownedTokensIndex[_tokenId] = 0; self.ownedTokensIndex[lastToken] = tokenIndex; } /** * @dev Function to mint a new token * Reverts if the given token ID already exists * @param _to address the beneficiary that will own the minted token * @param _tokenId uint256 ID of the token to be minted by the msg.sender */ function mint(ERC721Data storage self, address _to, uint256 _tokenId) external { require(_to != address(0)); _addTokenTo(self, _to, _tokenId); emit Transfer(address(0), _to, _tokenId); self.allTokensIndex[_tokenId] = self.allTokens.length; self.allTokens.push(_tokenId); } /** * @dev Function to burn a specific token * Reverts if the token does not exist * @param _owner owner of the token to burn * @param _tokenId uint256 ID of the token being burned by the msg.sender */ function burn(ERC721Data storage self, address _owner, uint256 _tokenId) external { _clearApproval(self, _owner, _tokenId); _removeTokenFrom(self, _owner, _tokenId); emit Transfer(_owner, address(0), _tokenId); // Clear metadata (if any) if (bytes(self.tokenURIs[_tokenId]).length != 0) { delete self.tokenURIs[_tokenId]; } // Reorg all tokens array uint256 tokenIndex = self.allTokensIndex[_tokenId]; uint256 lastTokenIndex = self.allTokens.length.sub(1); uint256 lastToken = self.allTokens[lastTokenIndex]; self.allTokens[tokenIndex] = lastToken; self.allTokens[lastTokenIndex] = 0; self.allTokens.length--; self.allTokensIndex[_tokenId] = 0; self.allTokensIndex[lastToken] = tokenIndex; } /** * @dev Returns whether the given spender can transfer a given token ID * @param _spender address of the spender to query * @param _tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function isApprovedOrOwner( ERC721Data storage self, address _spender, uint256 _tokenId ) public view returns (bool) { address owner = ownerOf(self, _tokenId); // Disable solium check because of // https://github.com/duaraghav8/Solium/issues/175 // solium-disable-next-line operator-whitespace return ( _spender == owner || getApproved(self, _tokenId) == _spender || isApprovedForAll(self, owner, _spender) ); } } // File: contracts/library/token/ERC721Token.sol /** * @title ERC721Token * * @dev This token interfaces with the OpenZepellin's ERC721 implementation (as of 7/31/2018) as * an external library, in order to keep contract sizes smaller. Intended for use with the * ERC721Manager.sol, also provided. * * Both files are released under the MIT License. * * * The MIT License (MIT) * * Copyright (c) 2016 Smart Contract Solutions, Inc. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ contract ERC721Token is ERC165, ERC721 { ERC721Manager.ERC721Data internal erc721Data; // We define the events on both the library and the client, so that the events emitted here are detected // as if they had been emitted by the client event Transfer( address indexed _from, address indexed _to, uint256 indexed _tokenId ); event Approval( address indexed _owner, address indexed _approved, uint256 indexed _tokenId ); event ApprovalForAll( address indexed _owner, address indexed _operator, bool _approved ); constructor(string _name, string _symbol) public { ERC721Manager.initialize(erc721Data, _name, _symbol); } function supportsInterface(bytes4 _interfaceId) external view returns (bool) { return ERC721Manager.supportsInterface(erc721Data, _interfaceId); } function balanceOf(address _owner) public view returns (uint256 _balance) { return ERC721Manager.balanceOf(erc721Data, _owner); } function ownerOf(uint256 _tokenId) public view returns (address _owner) { return ERC721Manager.ownerOf(erc721Data, _tokenId); } function exists(uint256 _tokenId) public view returns (bool _exists) { return ERC721Manager.exists(erc721Data, _tokenId); } function approve(address _to, uint256 _tokenId) public { ERC721Manager.approve(erc721Data, _to, _tokenId); } function getApproved(uint256 _tokenId) public view returns (address _operator) { return ERC721Manager.getApproved(erc721Data, _tokenId); } function setApprovalForAll(address _to, bool _approved) public { ERC721Manager.setApprovalForAll(erc721Data, _to, _approved); } function isApprovedForAll(address _owner, address _operator) public view returns (bool) { return ERC721Manager.isApprovedForAll(erc721Data, _owner, _operator); } function transferFrom(address _from, address _to, uint256 _tokenId) public { ERC721Manager.transferFrom(erc721Data, _from, _to, _tokenId); } function safeTransferFrom(address _from, address _to, uint256 _tokenId) public { ERC721Manager.safeTransferFrom(erc721Data, _from, _to, _tokenId); } function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes _data ) public { ERC721Manager.safeTransferFrom(erc721Data, _from, _to, _tokenId, _data); } function totalSupply() public view returns (uint256) { return ERC721Manager.totalSupply(erc721Data); } function tokenOfOwnerByIndex(address _owner, uint256 _index) public view returns (uint256 _tokenId) { return ERC721Manager.tokenOfOwnerByIndex(erc721Data, _owner, _index); } function tokenByIndex(uint256 _index) public view returns (uint256) { return ERC721Manager.tokenByIndex(erc721Data, _index); } function name() external view returns (string _name) { return erc721Data.name_; } function symbol() external view returns (string _symbol) { return erc721Data.symbol_; } function tokenURI(uint256 _tokenId) public view returns (string) { return ERC721Manager.tokenURI(erc721Data, _tokenId); } function _mint(address _to, uint256 _tokenId) internal { ERC721Manager.mint(erc721Data, _to, _tokenId); } function _burn(address _owner, uint256 _tokenId) internal { ERC721Manager.burn(erc721Data, _owner, _tokenId); } function _setTokenURI(uint256 _tokenId, string _uri) internal { ERC721Manager.setTokenURI(erc721Data, _tokenId, _uri); } function isApprovedOrOwner( address _spender, uint256 _tokenId ) public view returns (bool) { return ERC721Manager.isApprovedOrOwner(erc721Data, _spender, _tokenId); } } // File: contracts/library/data/PRNG.sol /** * Implementation of the xorshift128+ PRNG */ library PRNG { struct Data { uint64 s0; uint64 s1; } function next(Data storage self) external returns (uint64) { uint64 x = self.s0; uint64 y = self.s1; self.s0 = y; x ^= x << 23; // a self.s1 = x ^ y ^ (x >> 17) ^ (y >> 26); // b, c return self.s1 + y; } } // File: contracts/library/data/EnumerableSetAddress.sol /** * @title EnumerableSetAddress * @dev Library containing logic for an enumerable set of address values -- supports checking for presence, adding, * removing elements, and enumerating elements (without preserving order between mutable operations). */ library EnumerableSetAddress { struct Data { address[] elements; mapping(address => uint160) elementToIndex; } /** * @dev Returns whether the set contains a given element * * @param self Data storage Reference to set data * @param value address Value being checked for existence * @return bool */ function contains(Data storage self, address value) external view returns (bool) { uint160 mappingIndex = self.elementToIndex[value]; return (mappingIndex < self.elements.length) && (self.elements[mappingIndex] == value); } /** * @dev Adds a new element to the set. Element must not belong to set yet. * * @param self Data storage Reference to set data * @param value address Value being added */ function add(Data storage self, address value) external { uint160 mappingIndex = self.elementToIndex[value]; require(!((mappingIndex < self.elements.length) && (self.elements[mappingIndex] == value))); self.elementToIndex[value] = uint160(self.elements.length); self.elements.push(value); } /** * @dev Removes an element from the set. Element must already belong to set. * * @param self Data storage Reference to set data * @param value address Value being removed */ function remove(Data storage self, address value) external { uint160 currentElementIndex = self.elementToIndex[value]; require((currentElementIndex < self.elements.length) && (self.elements[currentElementIndex] == value)); uint160 lastElementIndex = uint160(self.elements.length - 1); address lastElement = self.elements[lastElementIndex]; self.elements[currentElementIndex] = lastElement; self.elements[lastElementIndex] = 0; self.elements.length--; self.elementToIndex[lastElement] = currentElementIndex; self.elementToIndex[value] = 0; } /** * @dev Gets the number of elements on the set. * * @param self Data storage Reference to set data * @return uint160 */ function size(Data storage self) external view returns (uint160) { return uint160(self.elements.length); } /** * @dev Gets the N-th element from the set, 0-indexed. Note that the ordering is not necessarily consistent * before and after add, remove operations. * * @param self Data storage Reference to set data * @param index uint160 0-indexed position of the element being queried * @return address */ function get(Data storage self, uint160 index) external view returns (address) { return self.elements[index]; } /** * @dev Mark the set as empty (not containing any further elements). * * @param self Data storage Reference to set data */ function clear(Data storage self) external { self.elements.length = 0; } /** * @dev Copy all data from a source set to a target set * * @param source Data storage Reference to source data * @param target Data storage Reference to target data */ function copy(Data storage source, Data storage target) external { uint160 numElements = uint160(source.elements.length); target.elements.length = numElements; for (uint160 index = 0; index < numElements; index++) { address element = source.elements[index]; target.elements[index] = element; target.elementToIndex[element] = index; } } /** * @dev Adds all elements from another set into this set, if they are not already present * * @param self Data storage Reference to set being edited * @param other Data storage Reference to set items are being added from */ function addAll(Data storage self, Data storage other) external { uint160 numElements = uint160(other.elements.length); for (uint160 index = 0; index < numElements; index++) { address value = other.elements[index]; uint160 mappingIndex = self.elementToIndex[value]; if (!((mappingIndex < self.elements.length) && (self.elements[mappingIndex] == value))) { self.elementToIndex[value] = uint160(self.elements.length); self.elements.push(value); } } } } // File: contracts/library/data/EnumerableSet256.sol /** * @title EnumerableSet256 * @dev Library containing logic for an enumerable set of uint256 values -- supports checking for presence, adding, * removing elements, and enumerating elements (without preserving order between mutable operations). */ library EnumerableSet256 { struct Data { uint256[] elements; mapping(uint256 => uint256) elementToIndex; } /** * @dev Returns whether the set contains a given element * * @param self Data storage Reference to set data * @param value uint256 Value being checked for existence * @return bool */ function contains(Data storage self, uint256 value) external view returns (bool) { uint256 mappingIndex = self.elementToIndex[value]; return (mappingIndex < self.elements.length) && (self.elements[mappingIndex] == value); } /** * @dev Adds a new element to the set. Element must not belong to set yet. * * @param self Data storage Reference to set data * @param value uint256 Value being added */ function add(Data storage self, uint256 value) external { uint256 mappingIndex = self.elementToIndex[value]; require(!((mappingIndex < self.elements.length) && (self.elements[mappingIndex] == value))); self.elementToIndex[value] = uint256(self.elements.length); self.elements.push(value); } /** * @dev Removes an element from the set. Element must already belong to set yet. * * @param self Data storage Reference to set data * @param value uint256 Value being added */ function remove(Data storage self, uint256 value) external { uint256 currentElementIndex = self.elementToIndex[value]; require((currentElementIndex < self.elements.length) && (self.elements[currentElementIndex] == value)); uint256 lastElementIndex = uint256(self.elements.length - 1); uint256 lastElement = self.elements[lastElementIndex]; self.elements[currentElementIndex] = lastElement; self.elements[lastElementIndex] = 0; self.elements.length--; self.elementToIndex[lastElement] = currentElementIndex; self.elementToIndex[value] = 0; } /** * @dev Gets the number of elements on the set. * * @param self Data storage Reference to set data * @return uint256 */ function size(Data storage self) external view returns (uint256) { return uint256(self.elements.length); } /** * @dev Gets the N-th element from the set, 0-indexed. Note that the ordering is not necessarily consistent * before and after add, remove operations. * * @param self Data storage Reference to set data * @param index uint256 0-indexed position of the element being queried * @return uint256 */ function get(Data storage self, uint256 index) external view returns (uint256) { return self.elements[index]; } /** * @dev Mark the set as empty (not containing any further elements). * * @param self Data storage Reference to set data */ function clear(Data storage self) external { self.elements.length = 0; } } // File: contracts/library/data/URIDistribution.sol /** * @title URIDistribution * @dev Library responsible for maintaining a weighted distribution of URIs */ library URIDistribution { struct Data { uint16[] cumulativeWeights; mapping(uint16 => string) uris; } /** * @dev Adds a URI to the distribution, with a given weight * * @param self Data storage Distribution data reference * @param weight uint16 Relative distribution weight * @param uri string URI to be stored */ function addURI(Data storage self, uint16 weight, string uri) external { if (weight == 0) return; if (self.cumulativeWeights.length == 0) { self.cumulativeWeights.push(weight); } else { self.cumulativeWeights.push(self.cumulativeWeights[uint16(self.cumulativeWeights.length - 1)] + weight); } self.uris[uint16(self.cumulativeWeights.length - 1)] = uri; } /** * @dev Gets an URI from the distribution, with the given random seed * * @param self Data storage Distribution data reference * @param seed uint64 * @return string */ function getURI(Data storage self, uint64 seed) external view returns (string) { uint16 n = uint16(self.cumulativeWeights.length); uint16 modSeed = uint16(seed % uint64(self.cumulativeWeights[n - 1])); uint16 left = 0; uint16 right = n; uint16 mid; while (left < right) { mid = uint16((uint24(left) + uint24(right)) / 2); if (self.cumulativeWeights[mid] <= modSeed) { left = mid + 1; } else { right = mid; } } return self.uris[left]; } } // File: contracts/library/game/GameDataLib.sol /** * @title GameDataLib * * Library containing data structures and logic for game entities. */ library GameDataLib { /** Data structures */ struct Butterfly { // data encoding butterfly appearance uint64 gene; // time this butterfly was created uint64 createdTimestamp; // last time this butterfly changed owner uint64 lastTimestamp; // set of owners, current and former EnumerableSetAddress.Data previousAddresses; } struct Heart { // ID of butterfly that generated this heart uint256 butterflyId; // time this heart was generated uint64 snapshotTimestamp; // set of owners, current and former, at time heart was generated EnumerableSetAddress.Data previousAddresses; } struct Flower { // Whether this address has ever claimed a butterfly bool isClaimed; // Data encoding flower appearance uint64 gene; // Data encoding the garden's timezone uint64 gardenTimezone; // Data encoding the creation timestamp uint64 createdTimestamp; // index of the flower registration uint160 flowerIndex; } struct URIMappingData { URIDistribution.Data flowerURIs; string whiteFlowerURI; URIDistribution.Data butterflyLiveURIs; URIDistribution.Data butterflyDeadURIs; URIDistribution.Data heartURIs; } // possible types of NFT enum TokenType { Butterfly, Heart } struct Data { // global pseudo-randomization seed PRNG.Data seed; // next ID available for token generation uint256 nextId; // token type data mapping (uint256 => TokenType) tokenToType; mapping (uint8 => mapping (address => EnumerableSet256.Data)) typedOwnedTokens; mapping (uint8 => EnumerableSet256.Data) typedTokens; // token data mapping (uint256 => Butterfly) butterflyData; mapping (uint256 => Heart) heartData; // owner data mapping (address => Flower) flowerData; address[] claimedFlowers; // URI mapping data URIMappingData uriMappingData; } /** Viewer methods */ /** * @dev Gets game information associated with a specific butterfly. * Requires ID to be a valid butterfly. * * @param self Data storage Reference to game data * @param butterflyId uint256 ID of butterfly being queried * * @return gene uint64 * @return createdTimestamp uint64 * @return lastTimestamp uint64 * @return numOwners uint160 */ function getButterflyInfo( Data storage self, uint256 butterflyId ) external view returns ( uint64 gene, uint64 createdTimestamp, uint64 lastTimestamp, uint160 numOwners ) { Butterfly storage butterfly = self.butterflyData[butterflyId]; require(butterfly.createdTimestamp != 0); gene = butterfly.gene; createdTimestamp = butterfly.createdTimestamp; lastTimestamp = butterfly.lastTimestamp; numOwners = uint160(butterfly.previousAddresses.elements.length); } /** * @dev Gets game information associated with a specific heart. * Requires ID to be a valid heart. * * @param self Data storage Reference to game data * @param heartId uint256 ID of heart being queried * * @return butterflyId uint256 * @return gene uint64 * @return snapshotTimestamp uint64 * @return numOwners uint160 */ function getHeartInfo( Data storage self, uint256 heartId ) external view returns ( uint256 butterflyId, uint64 gene, uint64 snapshotTimestamp, uint160 numOwners ) { Heart storage heart = self.heartData[heartId]; require(heart.snapshotTimestamp != 0); butterflyId = heart.butterflyId; gene = self.butterflyData[butterflyId].gene; snapshotTimestamp = heart.snapshotTimestamp; numOwners = uint160(heart.previousAddresses.elements.length); } /** * @dev Gets game information associated with a specific flower. * * @param self Data storage Reference to game data * @param flowerAddress address Address of the flower being queried * * @return isClaimed bool * @return gene uint64 * @return gardenTimezone uint64 * @return createdTimestamp uint64 * @return flowerIndex uint160 */ function getFlowerInfo( Data storage self, address flowerAddress ) external view returns ( bool isClaimed, uint64 gene, uint64 gardenTimezone, uint64 createdTimestamp, uint160 flowerIndex ) { Flower storage flower = self.flowerData[flowerAddress]; isClaimed = flower.isClaimed; if (isClaimed) { gene = flower.gene; gardenTimezone = flower.gardenTimezone; createdTimestamp = flower.createdTimestamp; flowerIndex = flower.flowerIndex; } } /** * @dev Returns the N-th owner associated with a butterfly. * Requires ID to be a valid butterfly, and owner index to be smaller than the number of owners. * * @param self Data storage Reference to game data * @param butterflyId uint256 ID of butterfly being queried * @param index uint160 Index of owner being queried * * @return address */ function getButterflyOwnerByIndex( Data storage self, uint256 butterflyId, uint160 index ) external view returns (address) { Butterfly storage butterfly = self.butterflyData[butterflyId]; require(butterfly.createdTimestamp != 0); return butterfly.previousAddresses.elements[index]; } /** * @dev Returns the N-th owner associated with a heart's snapshot. * Requires ID to be a valid butterfly, and owner index to be smaller than the number of owners. * * @param self Data storage Reference to game data * @param heartId uint256 ID of heart being queried * @param index uint160 Index of owner being queried * * @return address */ function getHeartOwnerByIndex( Data storage self, uint256 heartId, uint160 index ) external view returns (address) { Heart storage heart = self.heartData[heartId]; require(heart.snapshotTimestamp != 0); return heart.previousAddresses.elements[index]; } /** * @dev Determines whether the game logic allows a transfer of a butterfly to another address. * Conditions: * - The receiver address must have already claimed a butterfly * - The butterfly's last timestamp is within the last 24 hours * - The receiver address must have never claimed *this* butterfly * OR * - The receiver is 0x0 * * @param self Data storage Reference to game data * @param butterflyId uint256 ID of butterfly being queried * @param receiver address Address of potential receiver * @param currentTimestamp uint64 */ function canReceiveButterfly( Data storage self, uint256 butterflyId, address receiver, uint64 currentTimestamp ) public view returns (bool) { Butterfly storage butterfly = self.butterflyData[butterflyId]; // butterfly must exist if (butterfly.createdTimestamp == 0) return false; // can always transfer to 0 (destroying it) if (receiver == address(0x0)) return true; // butterfly must have been last updated on the last day if (currentTimestamp < butterfly.lastTimestamp || currentTimestamp - butterfly.lastTimestamp > 1 days) return false; // receiver must have already claimed Flower storage flower = self.flowerData[receiver]; if (!flower.isClaimed) return false; // receiver must have never owned this butterfly return !EnumerableSetAddress.contains(butterfly.previousAddresses, receiver); } /** Editor methods */ /** * @dev Claims a flower and an initial butterfly for a given address. * Requires address to have not claimed previously * * @param self Data storage Reference to game data * @param claimer address Address making the claim * @param gardenTimezone uint64 * @param currentTimestamp uint64 * * @return butterflyId uint256 ID for the new butterfly */ function claim( Data storage self, address claimer, uint64 gardenTimezone, uint64 currentTimestamp ) external returns (uint256 butterflyId) { Flower storage flower = self.flowerData[claimer]; // require address has not claimed before require(!flower.isClaimed); // assert no overflow on IDs require(self.nextId + 1 != 0); // get butterfly ID butterflyId = self.nextId; // assert ID is not being reused Butterfly storage butterfly = self.butterflyData[butterflyId]; require(butterfly.createdTimestamp == 0); // update counter self.nextId++; // update flower data flower.isClaimed = true; flower.gardenTimezone = gardenTimezone; flower.createdTimestamp = currentTimestamp; flower.gene = PRNG.next(self.seed); flower.flowerIndex = uint160(self.claimedFlowers.length); // update butterfly data butterfly.gene = PRNG.next(self.seed); butterfly.createdTimestamp = currentTimestamp; butterfly.lastTimestamp = currentTimestamp; EnumerableSetAddress.add(butterfly.previousAddresses, claimer); // update butterfly token data self.tokenToType[butterflyId] = TokenType.Butterfly; // register butterfly token EnumerableSet256.add(self.typedOwnedTokens[uint8(TokenType.Butterfly)][claimer], butterflyId); EnumerableSet256.add(self.typedTokens[uint8(TokenType.Butterfly)], butterflyId); // register address self.claimedFlowers.push(claimer); } /** * @dev Logs a transfer of a butterfly between two addresses, leaving a heart behind. * * Conditions: * - The receiver address must have already claimed a butterfly * - The butterfly's last timestamp is within the last 24 hours * * @param self Data storage Reference to game data * @param butterflyId uint256 ID of butterfly being queried * @param sender Address of sender * @param receiver address Address of potential receiver * @param currentTimestamp uint64 * * @return heartId uint256 ID for the new heart */ function transferButterfly( Data storage self, uint256 butterflyId, address sender, address receiver, uint64 currentTimestamp ) external returns (uint256 heartId) { // require transfer conditions to be satisfied require(canReceiveButterfly(self, butterflyId, receiver, currentTimestamp)); // require no overflow on IDs require(self.nextId + 1 != 0); // get heart ID heartId = self.nextId; // assert ID is not being reused Heart storage heart = self.heartData[heartId]; require(heart.snapshotTimestamp == 0); // update counter self.nextId++; // update heart data heart.butterflyId = butterflyId; heart.snapshotTimestamp = currentTimestamp; Butterfly storage butterfly = self.butterflyData[butterflyId]; // update heart token heartId self.tokenToType[heartId] = TokenType.Heart; // update butterfly data butterfly.lastTimestamp = currentTimestamp; EnumerableSetAddress.add(butterfly.previousAddresses, receiver); // update heart addresses EnumerableSetAddress.copy(butterfly.previousAddresses, heart.previousAddresses); // update butterfly register EnumerableSet256.remove(self.typedOwnedTokens[uint8(TokenType.Butterfly)][sender], butterflyId); EnumerableSet256.add(self.typedOwnedTokens[uint8(TokenType.Butterfly)][receiver], butterflyId); // update heart register EnumerableSet256.add(self.typedOwnedTokens[uint8(TokenType.Heart)][sender], heartId); EnumerableSet256.add(self.typedTokens[uint8(TokenType.Heart)], heartId); } /** * @dev Logs a transfer of a heart between two addresses * * @param self Data storage Reference to game data * @param heartId uint256 ID of heart being queried * @param sender Address of sender * @param receiver address Address of potential receiver */ function transferHeart( Data storage self, uint256 heartId, address sender, address receiver ) external { // update heart register EnumerableSet256.remove(self.typedOwnedTokens[uint8(TokenType.Heart)][sender], heartId); EnumerableSet256.add(self.typedOwnedTokens[uint8(TokenType.Heart)][receiver], heartId); } /** * @dev Returns the total number of tokens for a given type, owned by a specific address * * @param self Data storage Reference to game data * @param tokenType uint8 * @param _owner address * * @return uint256 */ function typedBalanceOf(Data storage self, uint8 tokenType, address _owner) public view returns (uint256) { return self.typedOwnedTokens[tokenType][_owner].elements.length; } /** * @dev Returns the total number of tokens for a given type * * @param self Data storage Reference to game data * @param tokenType uint8 * * @return uint256 */ function typedTotalSupply(Data storage self, uint8 tokenType) public view returns (uint256) { return self.typedTokens[tokenType].elements.length; } /** * @dev Returns the I-th token of a specific type owned by an index * * @param self Data storage Reference to game data * @param tokenType uint8 * @param _owner address * @param _index uint256 * * @return uint256 */ function typedTokenOfOwnerByIndex( Data storage self, uint8 tokenType, address _owner, uint256 _index ) external view returns (uint256) { return self.typedOwnedTokens[tokenType][_owner].elements[_index]; } /** * @dev Returns the I-th token of a specific type * * @param self Data storage Reference to game data * @param tokenType uint8 * @param _index uint256 * * @return uint256 */ function typedTokenByIndex( Data storage self, uint8 tokenType, uint256 _index ) external view returns (uint256) { return self.typedTokens[tokenType].elements[_index]; } /** * @dev Gets the total number of claimed flowers * * @param self Data storage Reference to game data * @return uint160 */ function totalFlowers(Data storage self) external view returns (uint160) { return uint160(self.claimedFlowers.length); } /** * @dev Gets the address of the N-th flower * * @param self Data storage Reference to game data * @return address */ function getFlowerByIndex(Data storage self, uint160 index) external view returns (address) { return self.claimedFlowers[index]; } /** Admin methods **/ /** * @dev Registers a new flower URI with the corresponding weight * * @param self Data storage Reference to game data * @param weight uint16 Relative weight for the occurrence of this URI * @param uri string */ function addFlowerURI(Data storage self, uint16 weight, string uri) external { URIDistribution.addURI(self.uriMappingData.flowerURIs, weight, uri); } /** * @dev Registers the flower URI for address 0 * * @param self Data storage Reference to game data * @param uri string */ function setWhiteFlowerURI(Data storage self, string uri) external { self.uriMappingData.whiteFlowerURI = uri; } /** * @dev Gets the flower URI for address 0 * * @param self Data storage Reference to game data * @return string */ function getWhiteFlowerURI(Data storage self) external view returns (string) { return self.uriMappingData.whiteFlowerURI; } /** * @dev Registers a new butterfly URI with the corresponding weight * * @param self Data storage Reference to game data * @param weight uint16 Relative weight for the occurrence of this URI * @param liveUri string * @param deadUri string * @param heartUri string */ function addButterflyURI(Data storage self, uint16 weight, string liveUri, string deadUri, string heartUri) external { URIDistribution.addURI(self.uriMappingData.butterflyLiveURIs, weight, liveUri); URIDistribution.addURI(self.uriMappingData.butterflyDeadURIs, weight, deadUri); URIDistribution.addURI(self.uriMappingData.heartURIs, weight, heartUri); } /** * @dev Returns the URI mapped to a particular flower. * Requires flower to be claimed / exist. * * @param self Data storage Reference to game data * @param flowerAddress address Flower being queried * @return string */ function getFlowerURI(Data storage self, address flowerAddress) external view returns (string) { Flower storage flower = self.flowerData[flowerAddress]; require(flower.isClaimed); return URIDistribution.getURI(self.uriMappingData.flowerURIs, flower.gene); } /** * @dev Returns the URI mapped to a particular butterfly -- selecting the URI for it being alive * or dead based on the current timestamp. * Requires butterfly to exist. * * @param self Data storage Reference to game data * @param erc721Data ERC721Manager.ERC721Data storage Reference to ownership data * @param butterflyId uint256 ID of the butterfly being queried * @param currentTimestamp uint64 * @return string */ function getButterflyURI( Data storage self, ERC721Manager.ERC721Data storage erc721Data, uint256 butterflyId, uint64 currentTimestamp ) external view returns (string) { Butterfly storage butterfly = self.butterflyData[butterflyId]; require(butterfly.createdTimestamp != 0); if (erc721Data.tokenOwner[butterflyId] == 0 || currentTimestamp < butterfly.lastTimestamp || currentTimestamp - butterfly.lastTimestamp > 1 days) { return URIDistribution.getURI(self.uriMappingData.butterflyDeadURIs, butterfly.gene); } return URIDistribution.getURI(self.uriMappingData.butterflyLiveURIs, butterfly.gene); } /** * @dev Returns the URI for a particular butterfly gene -- useful for seeing the butterfly "as it was" * when it dropped a heart * * @param self Daata storage Reference to game data * @param gene uint64 * @param isAlive bool * @return string */ function getButterflyURIFromGene( Data storage self, uint64 gene, bool isAlive ) external view returns (string) { if (isAlive) { return URIDistribution.getURI(self.uriMappingData.butterflyLiveURIs, gene); } return URIDistribution.getURI(self.uriMappingData.butterflyDeadURIs, gene); } /** * @dev Returns the URI mapped to hearts * * @param self Data storage Reference to game data * @param heartId uint256 ID of heart being queried * @return string */ function getHeartURI(Data storage self, uint256 heartId) external view returns (string) { Heart storage heart = self.heartData[heartId]; require(heart.snapshotTimestamp != 0); uint64 gene = self.butterflyData[heart.butterflyId].gene; return URIDistribution.getURI(self.uriMappingData.heartURIs, gene); } } // File: openzeppelin-solidity/contracts/ownership/Ownable.sol /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address 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. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit 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; } } // File: contracts\game\Main.sol /** * @title Main * * Main contract for LittleButterflies. Implements the ERC721 EIP for Non-Fungible Tokens. */ contract Main is ERC721Token, Ownable { GameDataLib.Data internal data; // Set our token name and symbol constructor() ERC721Token("LittleButterfly", "BFLY") public { // initialize PRNG values data.seed.s0 = uint64(now); data.seed.s1 = uint64(msg.sender); } /** Token viewer methods **/ /** * @dev Gets game information associated with a specific butterfly. * Requires ID to be a valid butterfly. * * @param butterflyId uint256 ID of butterfly being queried * * @return gene uint64 * @return createdTimestamp uint64 * @return lastTimestamp uint64 * @return numOwners uint160 */ function getButterflyInfo(uint256 butterflyId) public view returns ( uint64 gene, uint64 createdTimestamp, uint64 lastTimestamp, uint160 numOwners ) { (gene, createdTimestamp, lastTimestamp, numOwners) = GameDataLib.getButterflyInfo(data, butterflyId); } /** * @dev Returns the N-th owner associated with a butterfly. * Requires ID to be a valid butterfly, and owner index to be smaller than the number of owners. * * @param butterflyId uint256 ID of butterfly being queried * @param index uint160 Index of owner being queried * * @return address */ function getButterflyOwnerByIndex( uint256 butterflyId, uint160 index ) external view returns (address) { return GameDataLib.getButterflyOwnerByIndex(data, butterflyId, index); } /** * @dev Gets game information associated with a specific heart. * Requires ID to be a valid heart. * * @param heartId uint256 ID of heart being queried * * @return butterflyId uint256 * @return gene uint64 * @return snapshotTimestamp uint64 * @return numOwners uint160 */ function getHeartInfo(uint256 heartId) public view returns ( uint256 butterflyId, uint64 gene, uint64 snapshotTimestamp, uint160 numOwners ) { (butterflyId, gene, snapshotTimestamp, numOwners) = GameDataLib.getHeartInfo(data, heartId); } /** * @dev Returns the N-th owner associated with a heart's snapshot. * Requires ID to be a valid butterfly, and owner index to be smaller than the number of owners. * * @param heartId uint256 ID of heart being queried * @param index uint160 Index of owner being queried * * @return address */ function getHeartOwnerByIndex( uint256 heartId, uint160 index ) external view returns (address) { return GameDataLib.getHeartOwnerByIndex(data, heartId, index); } /** * @dev Gets game information associated with a specific flower. * * @param flowerAddress address Address of the flower being queried * * @return isClaimed bool * @return gene uint64 * @return gardenTimezone uint64 * @return createdTimestamp uint64 * @return flowerIndex uint160 */ function getFlowerInfo( address flowerAddress ) external view returns ( bool isClaimed, uint64 gene, uint64 gardenTimezone, uint64 createdTimestamp, uint160 flowerIndex ) { (isClaimed, gene, gardenTimezone, createdTimestamp, flowerIndex) = GameDataLib.getFlowerInfo(data, flowerAddress); } /** * @dev Determines whether the game logic allows a transfer of a butterfly to another address. * Conditions: * - The receiver address must have already claimed a butterfly * - The butterfly's last timestamp is within the last 24 hours * - The receiver address must have never claimed *this* butterfly * * @param butterflyId uint256 ID of butterfly being queried * @param receiver address Address of potential receiver */ function canReceiveButterfly( uint256 butterflyId, address receiver ) external view returns (bool) { return GameDataLib.canReceiveButterfly(data, butterflyId, receiver, uint64(now)); } /** Override token methods **/ /** * @dev Override the default ERC721 transferFrom implementation in order to check game conditions and * generate side effects */ function transferFrom(address _from, address _to, uint256 _tokenId) public { _setupTransferFrom(_from, _to, _tokenId, uint64(now)); ERC721Manager.transferFrom(erc721Data, _from, _to, _tokenId); } /** * @dev Override the default ERC721 safeTransferFrom implementation in order to check game conditions and * generate side effects */ function safeTransferFrom(address _from, address _to, uint256 _tokenId) public { _setupTransferFrom(_from, _to, _tokenId, uint64(now)); ERC721Manager.safeTransferFrom(erc721Data, _from, _to, _tokenId); } /** * @dev Override the default ERC721 safeTransferFrom implementation in order to check game conditions and * generate side effects */ function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes _data ) public { _setupTransferFrom(_from, _to, _tokenId, uint64(now)); ERC721Manager.safeTransferFrom(erc721Data, _from, _to, _tokenId, _data); } /** * @dev Execute before transfer, preventing token transfer in some circumstances. * Requirements: * - Caller is owner, approved, or operator for the token * - To has claimed a token before * - Token is a Heart, or Token's last activity was in the last 24 hours * * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param currentTimestamp uint64 */ function _setupTransferFrom( address from, address to, uint256 tokenId, uint64 currentTimestamp ) private { if (data.tokenToType[tokenId] == GameDataLib.TokenType.Butterfly) { // try to do transfer and mint a heart uint256 heartId = GameDataLib.transferButterfly(data, tokenId, from, to, currentTimestamp); ERC721Manager.mint(erc721Data, from, heartId); } else { GameDataLib.transferHeart(data, tokenId, from, to); } } /** * @dev Overrides the default tokenURI method to lookup from the stored table of URIs -- rather than * storing a copy of the URI for each instance * * @param _tokenId uint256 * @return string */ function tokenURI(uint256 _tokenId) public view returns (string) { if (data.tokenToType[_tokenId] == GameDataLib.TokenType.Heart) { return GameDataLib.getHeartURI(data, _tokenId); } return GameDataLib.getButterflyURI(data, erc721Data, _tokenId, uint64(now)); } /** * @dev Returns the URI mapped to a particular account / flower * * @param accountAddress address * @return string */ function accountURI(address accountAddress) public view returns (string) { return GameDataLib.getFlowerURI(data, accountAddress); } /** * @dev Returns the URI mapped to account 0 * * @return string */ function accountZeroURI() public view returns (string) { return GameDataLib.getWhiteFlowerURI(data); } /** * @dev Returns the URI for a particular butterfly gene -- useful for seeing the butterfly "as it was" * when it dropped a heart * * @param gene uint64 * @param isAlive bool * @return string */ function getButterflyURIFromGene(uint64 gene, bool isAlive) public view returns (string) { return GameDataLib.getButterflyURIFromGene(data, gene, isAlive); } /** Extra token methods **/ /** * @dev Claims a flower and an initial butterfly for a given address. * Requires address to have not claimed previously * * @param gardenTimezone uint64 */ function claim(uint64 gardenTimezone) external { address claimer = msg.sender; // claim a butterfly uint256 butterflyId = GameDataLib.claim(data, claimer, gardenTimezone, uint64(now)); // mint its token ERC721Manager.mint(erc721Data, claimer, butterflyId); } /** * @dev Burns a token. Caller must be owner or approved. * * @param _tokenId uint256 ID of token to burn */ function burn(uint256 _tokenId) public { require(ERC721Manager.isApprovedOrOwner(erc721Data, msg.sender, _tokenId)); address _owner = ERC721Manager.ownerOf(erc721Data, _tokenId); _setupTransferFrom(_owner, address(0x0), _tokenId, uint64(now)); ERC721Manager.burn(erc721Data, _owner, _tokenId); } /** * @dev Returns the total number of tokens for a given type, owned by a specific address * * @param tokenType uint8 * @param _owner address * * @return uint256 */ function typedBalanceOf(uint8 tokenType, address _owner) public view returns (uint256) { return GameDataLib.typedBalanceOf(data, tokenType, _owner); } /** * @dev Returns the total number of tokens for a given type * * @param tokenType uint8 * * @return uint256 */ function typedTotalSupply(uint8 tokenType) public view returns (uint256) { return GameDataLib.typedTotalSupply(data, tokenType); } /** * @dev Returns the I-th token of a specific type owned by an index * * @param tokenType uint8 * @param _owner address * @param _index uint256 * * @return uint256 */ function typedTokenOfOwnerByIndex( uint8 tokenType, address _owner, uint256 _index ) external view returns (uint256) { return GameDataLib.typedTokenOfOwnerByIndex(data, tokenType, _owner, _index); } /** * @dev Returns the I-th token of a specific type * * @param tokenType uint8 * @param _index uint256 * * @return uint256 */ function typedTokenByIndex( uint8 tokenType, uint256 _index ) external view returns (uint256) { return GameDataLib.typedTokenByIndex(data, tokenType, _index); } /** * @dev Gets the total number of claimed flowers * * @return uint160 */ function totalFlowers() external view returns (uint160) { return GameDataLib.totalFlowers(data); } /** * @dev Gets the address of the N-th flower * * @return address */ function getFlowerByIndex(uint160 index) external view returns (address) { return GameDataLib.getFlowerByIndex(data, index); } /** Admin setup methods */ /* * Methods intended for initial contract setup, to be called at deployment. * Call renounceOwnership() to make the contract have no owner after setup is complete. */ /** * @dev Registers a new flower URI with the corresponding weight * * @param weight uint16 Relative weight for the occurrence of this URI * @param uri string */ function addFlowerURI(uint16 weight, string uri) external onlyOwner { GameDataLib.addFlowerURI(data, weight, uri); } /** * @dev Registers the flower URI for address 0 * * @param uri string */ function setWhiteFlowerURI(string uri) external onlyOwner { GameDataLib.setWhiteFlowerURI(data, uri); } /** * @dev Registers a new butterfly URI with the corresponding weight * * @param weight uint16 Relative weight for the occurrence of this URI * @param liveUri string * @param deadUri string * @param heartUri string */ function addButterflyURI(uint16 weight, string liveUri, string deadUri, string heartUri) external onlyOwner { GameDataLib.addButterflyURI(data, weight, liveUri, deadUri, heartUri); } }
Returns the URI mapped to a particular butterfly -- selecting the URI for it being alive or dead based on the current timestamp. Requires butterfly to exist. self Data storage Reference to game data erc721Data ERC721Manager.ERC721Data storage Reference to ownership data butterflyId uint256 ID of the butterfly being queried currentTimestamp uint64 return string/
function getButterflyURI( Data storage self, ERC721Manager.ERC721Data storage erc721Data, uint256 butterflyId, uint64 currentTimestamp ) external view returns (string) { Butterfly storage butterfly = self.butterflyData[butterflyId]; require(butterfly.createdTimestamp != 0); if (erc721Data.tokenOwner[butterflyId] == 0 || currentTimestamp < butterfly.lastTimestamp || currentTimestamp - butterfly.lastTimestamp > 1 days) { return URIDistribution.getURI(self.uriMappingData.butterflyDeadURIs, butterfly.gene); } return URIDistribution.getURI(self.uriMappingData.butterflyLiveURIs, butterfly.gene); }
7,284,080
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // Emmet for natspac in VS Code : nat_contract /// @title Solidity basic operations /// @author Jake Sung /// @notice You can learn how solidity function and variable works /// @dev Check out emmets contract MyOperator { // state variables uint8 a = 8; uint8 b = 16; uint8 c = 33; uint8 newValue; uint8 getA = getter_a(); /// @notice : read only function(functions with view) function getter_a() public view returns (uint8){ return a; } /// @notice : assign new value function MyCalc2() public { newValue = c % a ; // update the state variable to 1 // basic operations b++; b += a; } /// @notice : local scope variable function MyLocals() public view { bool result = false; if (a < b) { result = true; } if (a == b) { result = true; } if (a != b) { result = false; } if (a < b && c > b) { result = false; } } function MyIternary() public view { uint8 testing = 0; newValue > 100 ? testing = 10 : testing = 0; } }
: read only function(functions with view)
function getter_a() public view returns (uint8){ return a; }
12,639,001
pragma solidity ^0.6.0; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol"; import "./cryptoblades.sol"; import "./characters.sol"; import "./weapons.sol"; import "./Promos.sol"; import "./util.sol"; import "./items/RaidTrinket.sol"; import "./items/KeyLootbox.sol"; import "./items/Junk.sol"; contract Raid1 is Initializable, AccessControlUpgradeable { /* Actual raids reimplementation Figured the old contract may have a lot of redundant variables and it's already deployed Maybe the raid interface isn't the way to go Either way it's probably fine to lay out the new one in a single file and compare The idea is to store all participants and raid details using an indexed mapping system And players get to claim their rewards as a derivative of a raid completion seed that a safe verifiable random source will provide (ideally) It may be better to convert the mappings using raidIndex into a struct Need to test gas impact or if stack limits are any different */ using ABDKMath64x64 for int128; using ABDKMath64x64 for uint256; bytes32 public constant GAME_ADMIN = keccak256("GAME_ADMIN"); uint8 public constant STATUS_UNSTARTED = 0; uint8 public constant STATUS_STARTED = 1; uint8 public constant STATUS_WON = 2; uint8 public constant STATUS_LOST = 3; uint8 public constant STATUS_PAUSED = 4; // in case of emergency // leaving link 0 empty intentionally uint256 public constant LINK_TRINKET = 1; uint256 public constant LINK_KEYBOX = 2; uint256 public constant LINK_JUNK = 3; uint256 public constant NUMBERPARAMETER_AUTO_DURATION = 1; uint256 public constant NUMBERPARAMETER_AUTO_BOSSPOWER_PERCENT = uint256(keccak256("BOSSPOWER_PERCENT")); CryptoBlades public game; Characters public characters; Weapons public weapons; Promos public promos; struct Raider { address owner; uint256 charID; uint256 wepID; uint24 power; uint24 traitsCWS;//char trait, wep trait, wep statpattern, unused for now } uint64 public staminaCost; uint64 public durabilityCost; int128 public joinCost; uint16 public xpReward; uint256 public raidIndex; // all (first) keys are raidIndex mapping(uint256 => uint8) public raidStatus; mapping(uint256 => uint256) public raidEndTime; mapping(uint256 => uint256) public raidSeed; mapping(uint256 => uint8) public raidBossTrait; mapping(uint256 => uint256) public raidBossPower; mapping(uint256 => uint256) public raidPlayerPower; mapping(uint256 => Raider[]) public raidParticipants; mapping(uint256 => mapping(address => uint256[])) public raidParticipantIndices; mapping(uint256 => mapping(address => bool)) public raidRewardClaimed; // link interface // the idea is to avoid littering the contract with variables for each type of reward mapping(uint256 => address) public links; // parameters to avoid littering the contract with more state vars mapping(uint256 => uint256) public numberParameters; event RaidStarted(uint256 indexed raidIndex, uint8 bossTrait, uint256 bossPower, uint256 endTime); event RaidJoined(uint256 raidIndex, address indexed user, uint256 indexed character, uint256 indexed weapon, uint256 skillPaid); event RaidCompleted(uint256 indexed raidIndex, uint8 outcome, uint256 bossRoll, uint256 playerRoll); // reward specific events for analytics event RewardClaimed(uint256 indexed raidIndex, address indexed user, uint256 characterCount); event RewardedXpBonus(uint256 indexed raidIndex, address indexed user, uint256 indexed charID, uint16 amount); event RewardedDustLB(uint256 indexed raidIndex, address indexed user, uint32 amount); event RewardedDust4B(uint256 indexed raidIndex, address indexed user, uint32 amount); event RewardedDust5B(uint256 indexed raidIndex, address indexed user, uint32 amount); event RewardedWeapon(uint256 indexed raidIndex, address indexed user, uint8 stars, uint256 indexed tokenID); event RewardedJunk(uint256 indexed raidIndex, address indexed user, uint8 stars, uint256 indexed tokenID); event RewardedTrinket(uint256 indexed raidIndex, address indexed user, uint8 stars, uint256 effect, uint256 indexed tokenID); event RewardedKeyBox(uint256 indexed raidIndex, address indexed user, uint256 indexed tokenID); function initialize(address gameContract) public initializer { __AccessControl_init_unchained(); _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setupRole(GAME_ADMIN, msg.sender); game = CryptoBlades(gameContract); characters = Characters(game.characters()); weapons = Weapons(game.weapons()); promos = Promos(game.promos()); staminaCost = 200; // 5 mins each, or 16.666 hours durabilityCost = 20; // 50 mins each, or 16.666 hours joinCost = 0;// free (was going to be 10 USD) xpReward = 128 * 2; // 13 hour 20 min worth of fight xp, but we had double xp active on launch } modifier restricted() { _restricted(); _; } function _restricted() internal view { require(hasRole(GAME_ADMIN, msg.sender), "Not game admin"); } function doRaidAuto() public restricted { uint256 seed = uint256(keccak256(abi.encodePacked(blockhash(block.number - 1)))); uint256 power = ABDKMath64x64.divu(numberParameters[NUMBERPARAMETER_AUTO_BOSSPOWER_PERCENT],100) .mulu(raidPlayerPower[raidIndex]); uint8 trait = uint8(seed % 4); uint256 duration = numberParameters[NUMBERPARAMETER_AUTO_DURATION]; if(duration == 0) { duration = 480; // 8 hrs } doRaidWithSeed(power, trait, duration, seed); } function doRaid(uint256 bossPower, uint8 bossTrait, uint256 durationMinutes) public restricted { doRaidWithSeed(bossPower, bossTrait, durationMinutes, uint256(keccak256(abi.encodePacked(blockhash(block.number - 1))))); } function doRaidWithSeed(uint256 bossPower, uint8 bossTrait, uint256 durationMinutes, uint256 seed) public restricted { require(raidStatus[raidIndex] != STATUS_PAUSED, "Raid paused"); if(raidStatus[raidIndex] == STATUS_STARTED && raidParticipants[raidIndex].length > 0) { completeRaidWithSeed(seed); } startRaid(bossPower, bossTrait, durationMinutes); } function startRaid(uint256 bossPower, uint8 bossTrait, uint256 durationMinutes) public restricted { raidStatus[raidIndex] = STATUS_STARTED; raidBossPower[raidIndex] = bossPower; raidBossTrait[raidIndex] = bossTrait; uint256 endTime = now + (durationMinutes * 1 minutes); raidEndTime[raidIndex] = endTime; emit RaidStarted(raidIndex, bossTrait, bossPower, endTime); } function joinRaid(uint256 characterID, uint256 weaponID) public { require(characters.canRaid(msg.sender, characterID)); require(weapons.canRaid(msg.sender, weaponID)); /*require(characters.ownerOf(characterID) == msg.sender); require(weapons.ownerOf(weaponID) == msg.sender); require(characters.getStaminaPoints(characterID) > 0, "You cannot join with 0 character stamina"); require(weapons.getDurabilityPoints(weaponID) > 0, "You cannot join with 0 weapon durability");*/ require(raidStatus[raidIndex] == STATUS_STARTED, "Cannot join raid right now!"); require(raidEndTime[raidIndex] > now, "It is too late to join this raid!"); uint256[] memory raiderIndices = raidParticipantIndices[raidIndex][msg.sender]; for(uint i = 0; i < raiderIndices.length; i++) { require(raidParticipants[raidIndex][raiderIndices[i]].wepID != weaponID, "This weapon is already used in the raid"); require(raidParticipants[raidIndex][raiderIndices[i]].charID != characterID, "This character is already participating"); } (uint8 charTrait, uint24 basePowerLevel, /*uint64 timestamp*/) = unpackFightData(characters.getFightDataAndDrainStamina( characterID, uint8(staminaCost), true) ); (/*int128 weaponMultTarget*/, int128 weaponMultFight, uint24 weaponBonusPower, /*uint8 weaponTrait*/) = weapons.getFightDataAndDrainDurability(weaponID, charTrait, uint8(durabilityCost), true); uint24 power = getPlayerFinalPower( getPlayerPower(basePowerLevel, weaponMultFight, weaponBonusPower), charTrait, raidBossTrait[raidIndex] ); raidPlayerPower[raidIndex] += power; //uint8 wepStatPattern = weapons.getStatPattern(weaponID); raidParticipantIndices[raidIndex][msg.sender].push(raidParticipants[raidIndex].length); raidParticipants[raidIndex].push(Raider( msg.sender, characterID, weaponID, power, 0//uint24(charTrait) | (uint24(weaponTrait) << 8) | ((uint24(wepStatPattern)) << 16)//traitCWS )); uint256 joinCostPaid = 0; if(joinCost > 0) { joinCostPaid = game.usdToSkill(joinCost); game.payContractTokenOnly(msg.sender, joinCostPaid); } emit RaidJoined(raidIndex, msg.sender, characterID, weaponID, joinCostPaid); } function setRaidStatus(uint256 index, uint8 status) public restricted { // only use if absolutely necessary raidStatus[index] = status; } function completeRaid() public restricted { completeRaidWithSeed(uint256(keccak256(abi.encodePacked(blockhash(block.number - 1))))); } function completeRaidWithSeed(uint256 seed) internal { raidSeed[raidIndex] = seed; raidEndTime[raidIndex] = now; uint256 bossPower = raidBossPower[raidIndex]; // we could also not include bossPower in the roll to have slightly higher chances of failure // with bosspower added to roll ceiling the likelyhood of a win is: playerPower / bossPower uint256 roll = RandomUtil.randomSeededMinMax(0,raidPlayerPower[raidIndex]+bossPower, seed); uint8 outcome = roll >= bossPower ? STATUS_WON : STATUS_LOST; raidStatus[raidIndex] = outcome; if(outcome == STATUS_WON) { // since we pay out exactly one trinket per raid, we might as well do it here Raider memory trinketWinner = raidParticipants[raidIndex][seed % raidParticipants[raidIndex].length]; uint8 trinketStars = getTrinketStarsFromSeed(seed); uint256 trinketEffect = (seed / 100) % 5; uint tokenID = RaidTrinket(links[LINK_TRINKET]).mint( trinketWinner.owner, trinketStars, trinketEffect ); emit RewardedTrinket(raidIndex, trinketWinner.owner, trinketStars, trinketEffect, tokenID); } emit RaidCompleted(raidIndex, outcome, bossPower, roll); raidIndex++; } function getTrinketStarsFromSeed(uint256 seed) private pure returns(uint8 stars) { uint256 roll = seed % 100; if(roll < 1) { return 4; // 5* at 1% } else if(roll < 6) { // 4* at 5% return 3; } else if(roll < 21) { // 3* at 15% return 2; } else if(roll < 56) { // 2* at 35% return 1; } else { return 0; // 1* at 44% } } function unpackFightData(uint96 playerData) public pure returns (uint8 charTrait, uint24 basePowerLevel, uint64 timestamp) { charTrait = uint8(playerData & 0xFF); basePowerLevel = uint24((playerData >> 8) & 0xFFFFFF); timestamp = uint64((playerData >> 32) & 0xFFFFFFFFFFFFFFFF); } function getPlayerPower( uint24 basePower, int128 weaponMultiplier, uint24 bonusPower ) public pure returns(uint24) { return uint24(weaponMultiplier.mulu(basePower) + bonusPower); } function isTraitEffectiveAgainst(uint8 attacker, uint8 defender) public pure returns (bool) { return (((attacker + 1) % 4) == defender); // Thanks to Tourist } function getPlayerFinalPower(uint24 playerPower, uint8 charTrait, uint8 bossTrait) public pure returns(uint24) { if(isTraitEffectiveAgainst(charTrait, bossTrait)) return uint24(ABDKMath64x64.divu(1075,1000).mulu(uint256(playerPower))); return playerPower; } function claimReward(uint256 claimRaidIndex) public { // NOTE: this function is stack limited //claimRaidIndex can act as a version integer if future rewards change bool victory = raidStatus[claimRaidIndex] == STATUS_WON; require(victory || raidStatus[claimRaidIndex] == STATUS_LOST, "Raid not over"); require(raidRewardClaimed[claimRaidIndex][msg.sender] == false, "Already claimed"); uint256[] memory raiderIndices = raidParticipantIndices[claimRaidIndex][msg.sender]; require(raiderIndices.length > 0, "None of your characters participated"); uint256 earlyBonusCutoff = raidParticipants[claimRaidIndex].length/2+1; // first half of players // we grab raider info (power) and give out xp and raid stats for(uint i = 0; i < raiderIndices.length; i++) { uint256 raiderIndex = raiderIndices[i]; Raider memory raider = raidParticipants[claimRaidIndex][raiderIndex]; int128 earlyMultiplier = ABDKMath64x64.fromUInt(1).add( raiderIndex < earlyBonusCutoff ? ABDKMath64x64.divu(1,10).mul( // early bonus, 10% (earlyBonusCutoff-raiderIndex).divu(earlyBonusCutoff) ) : ABDKMath64x64.fromUInt(0) ); if(victory) { distributeRewards( claimRaidIndex, raiderIndex, ABDKMath64x64.divu(earlyMultiplier.mulu(raider.power), raidPlayerPower[claimRaidIndex]/raidParticipants[claimRaidIndex].length) ); } characters.processRaidParticipation(raider.charID, victory, uint16(earlyMultiplier.mulu(xpReward))); } raidRewardClaimed[claimRaidIndex][msg.sender] = true; emit RewardClaimed(claimRaidIndex, msg.sender, raiderIndices.length); } function distributeRewards( uint256 claimRaidIndex, uint256 raiderIndex, int128 comparedToAverage ) private { // at most 2 types of rewards // common: Lb dust, 1-3 star junk, 3 star wep // rare: 4-5b dust, 4-5 star wep, 4-5 star junk, keybox // chances are a bit generous compared to weapon mints because stamina cost equals lost skill // That being said these rates stink if the oracle is 3x lower than real value. uint256 seed = uint256(keccak256(abi.encodePacked(raidSeed[claimRaidIndex], raiderIndex, uint256(msg.sender)))); uint256 commonRoll = RandomUtil.randomSeededMinMax(1, 15 + comparedToAverage.mulu(85), seed); if(commonRoll > 20) { // Expected: ~75% (at least 25% at bottom, 90+% past 65% power) uint mod = seed % 10; if(mod < 2) { // 1 star junk, 2 out of 10 (20%) distributeJunk(msg.sender, claimRaidIndex, 0); } else if(mod < 4) { // 2 star junk, 2 out of 10 (20%) distributeJunk(msg.sender, claimRaidIndex, 1); } else if(mod < 6) { // 2 star weapon, 2 out of 10 (20%) distributeWeapon(msg.sender, claimRaidIndex, seed, 1); } else if(mod == 6) { // 3 star junk, 1 out of 10 (10%) distributeJunk(msg.sender, claimRaidIndex, 2); } else if(mod == 7) { // 1x LB Dust, 1 out of 10 (10%) distributeLBDust(msg.sender, claimRaidIndex, 1); } else if(mod == 8) { // 2x LB Dust, 1 out of 10 (10%) distributeLBDust(msg.sender, claimRaidIndex, 2); } else { // 3 star weapon, 1 out of 10 (10%) distributeWeapon(msg.sender, claimRaidIndex, seed, 2); } } uint256 rareRoll = RandomUtil.randomSeededMinMax(1, 950 + comparedToAverage.mulu(50), seed + 1); if(rareRoll > 950) { // Expected: ~5% (0.72% at bottom, 15% at top, 8.43% middle) uint mod = (seed / 10) % 20; if(mod < 8) { // key box, 8 out of 20 (40%) distributeKeyBox(msg.sender, claimRaidIndex); } else if(mod == 8) { // 5 star sword, 1 out of 20 (5%) distributeWeapon(msg.sender, claimRaidIndex, seed, 4); } else if(mod == 9) { // 5 star junk, 1 out of 20 (5%) distributeJunk(msg.sender, claimRaidIndex, 4); } else if(mod < 14) { // 4 star sword, 4 out of 20 (20%) distributeWeapon(msg.sender, claimRaidIndex, seed, 3); } else if(mod == 14) { // 1x 4B Dust, 1 out of 20 (5%) distribute4BDust(msg.sender, claimRaidIndex, 1); } else if(mod == 15) { // 1x 5B Dust, 1 out of 20 (5%) distribute5BDust(msg.sender, claimRaidIndex, 1); } else { // 4 star junk, 4 out of 20 (20%) distributeJunk(msg.sender, claimRaidIndex, 3); } } uint256 bonusXpRoll = RandomUtil.randomSeededMinMax(1, 2000, seed + 2); // 0.05% per point if(bonusXpRoll <= 100) { // 5% for any bonus xp result if(bonusXpRoll > 50) { // 2.5% for +25% xp distributeBonusXp(msg.sender, claimRaidIndex, raiderIndex, uint16(ABDKMath64x64.divu(25,100).mulu(xpReward))); } else if(bonusXpRoll > 20) { // 1.5% for +150% xp distributeBonusXp(msg.sender, claimRaidIndex, raiderIndex, uint16(ABDKMath64x64.divu(150,100).mulu(xpReward))); } else if(bonusXpRoll > 10) { // 0.5% for +275% xp distributeBonusXp(msg.sender, claimRaidIndex, raiderIndex, uint16(ABDKMath64x64.divu(275,100).mulu(xpReward))); } else if(bonusXpRoll > 4) { // 0.3% for +525% xp distributeBonusXp(msg.sender, claimRaidIndex, raiderIndex, uint16(ABDKMath64x64.divu(525,100).mulu(xpReward))); } else if(bonusXpRoll > 1) { // 0.15% for +1150% xp distributeBonusXp(msg.sender, claimRaidIndex, raiderIndex, uint16(ABDKMath64x64.divu(1150,100).mulu(xpReward))); } else { // 0.05% for +2400% xp distributeBonusXp(msg.sender, claimRaidIndex, raiderIndex, uint16(ABDKMath64x64.divu(2400,100).mulu(xpReward))); } } } function distributeBonusXp(address claimant, uint256 claimRaidIndex, uint256 raiderIndex, uint16 amount) private { uint256 charID = raidParticipants[claimRaidIndex][raiderIndex].charID; characters.gainXp(charID, amount); emit RewardedXpBonus(claimRaidIndex, claimant, charID, amount); } function distributeKeyBox(address claimant, uint256 claimRaidIndex) private { uint tokenID = KeyLootbox(links[LINK_KEYBOX]).mint(claimant); emit RewardedKeyBox(claimRaidIndex, claimant, tokenID); } function distributeJunk(address claimant, uint256 claimRaidIndex, uint8 stars) private { uint tokenID = Junk(links[LINK_JUNK]).mint(claimant, stars); emit RewardedJunk(claimRaidIndex, claimant, stars, tokenID); } function distributeWeapon(address claimant, uint256 claimRaidIndex, uint256 seed, uint8 stars) private { uint tokenID = weapons.mintWeaponWithStars(claimant, stars, seed / 100, 100); emit RewardedWeapon(claimRaidIndex, claimant, stars, tokenID); } function distributeLBDust(address claimant, uint256 claimRaidIndex, uint32 amount) private { weapons.incrementDustSupplies(claimant, amount, 0, 0); emit RewardedDustLB(claimRaidIndex, claimant, amount); } function distribute4BDust(address claimant, uint256 claimRaidIndex, uint32 amount) private { weapons.incrementDustSupplies(claimant, 0, amount, 0); emit RewardedDust4B(claimRaidIndex, claimant, amount); } function distribute5BDust(address claimant, uint256 claimRaidIndex, uint32 amount) private { weapons.incrementDustSupplies(claimant, 0, 0, amount); emit RewardedDust5B(claimRaidIndex, claimant, amount); } function registerLink(address addr, uint256 index) public restricted { links[index] = addr; } function setStaminaPointCost(uint8 points) public restricted { staminaCost = points; } function setDurabilityPointCost(uint8 points) public restricted { durabilityCost = points; } function setJoinCostInCents(uint256 cents) public restricted { joinCost = ABDKMath64x64.divu(cents, 100); } function getJoinCostInSkill() public view returns(uint256) { return game.usdToSkill(joinCost); } function setXpReward(uint16 xp) public restricted { xpReward = xp; } function setNumberParameter(uint256 paramIndex, uint256 value) public restricted { numberParameters[paramIndex] = value; } function getNumberParameter(uint256 paramIndex) public view returns(uint256) { return numberParameters[paramIndex]; } function getRaidStatus(uint256 index) public view returns(uint8) { return raidStatus[index]; } function getRaidEndTime(uint256 index) public view returns(uint256) { return raidEndTime[index]; } function getRaidBossTrait(uint256 index) public view returns(uint8) { return raidBossTrait[index]; } function getRaidBossPower(uint256 index) public view returns(uint256) { return raidBossPower[index]; } function getRaidPlayerPower(uint256 index) public view returns(uint256) { return raidPlayerPower[index]; } function getRaidParticipantCount(uint256 index) public view returns(uint256) { return raidParticipants[index].length; } function getEligibleRewardIndexes(uint256 startIndex, uint256 endIndex) public view returns(uint256[] memory) { uint indexCount = 0; for(uint i = startIndex; i <= endIndex; i++) { if(isEligibleForReward(i)) { indexCount++; } } uint256[] memory result = new uint256[](indexCount); uint currentIndex = 0; for(uint i = startIndex; i <= endIndex; i++) { if(isEligibleForReward(i)) { result[currentIndex++] = i; } } return result; } function isEligibleForReward(uint256 index) public view returns(bool) { uint8 status = raidStatus[index]; return (status == STATUS_WON || status == STATUS_LOST) && raidParticipantIndices[index][msg.sender].length > 0 && raidRewardClaimed[index][msg.sender] == false; } function getParticipatingCharacters() public view returns(uint256[] memory) { uint256[] memory indices = raidParticipantIndices[raidIndex][msg.sender]; uint256[] memory chars = new uint256[](indices.length); for(uint i = 0; i < indices.length; i++) { chars[i] = raidParticipants[raidIndex][indices[i]].charID; } return chars; } function getParticipatingWeapons() public view returns(uint256[] memory) { uint256[] memory indices = raidParticipantIndices[raidIndex][msg.sender]; uint256[] memory weps = new uint256[](indices.length); for(uint i = 0; i < indices.length; i++) { weps[i] = raidParticipants[raidIndex][indices[i]].wepID; } return weps; } function getAccountsRaiderIndexes(uint256 index) public view returns(uint256[] memory){ return raidParticipantIndices[index][msg.sender]; } function getAccountsPower(uint256 index) public view returns(uint256) { uint256 totalAccountPower = 0; uint256[] memory raiderIndexes = getAccountsRaiderIndexes(index); for(uint256 i = 0; i < raiderIndexes.length; i++) { totalAccountPower += raidParticipants[index][raiderIndexes[i]].power; } return totalAccountPower; } function canJoinRaid(uint256 characterID, uint256 weaponID) public view returns(bool) { return isRaidStarted() && haveEnoughEnergy(characterID, weaponID) && !isCharacterRaiding(characterID) && !isWeaponRaiding(weaponID); } function haveEnoughEnergy(uint256 characterID, uint256 weaponID) public view returns(bool) { return characters.getStaminaPoints(characterID) > 0 && weapons.getDurabilityPoints(weaponID) > 0; } function isRaidStarted() public view returns(bool) { return raidStatus[raidIndex] == STATUS_STARTED && raidEndTime[raidIndex] > now; } function isWeaponRaiding(uint256 weaponID) public view returns(bool) { uint256[] memory raiderIndices = raidParticipantIndices[raidIndex][msg.sender]; for(uint i = 0; i < raiderIndices.length; i++) { if(raidParticipants[raidIndex][raiderIndices[i]].wepID == weaponID) { return true; } } return false; } function isCharacterRaiding(uint256 characterID) public view returns(bool) { uint256[] memory raiderIndices = raidParticipantIndices[raidIndex][msg.sender]; for(uint i = 0; i < raiderIndices.length; i++) { if(raidParticipants[raidIndex][raiderIndices[i]].charID == characterID) { return true; } } return false; } function getLinkAddress(uint256 linkIndex) public view returns (address) { return links[linkIndex]; } function getRaidData() public view returns( uint256 index, uint256 endTime, uint256 raiderCount, uint256 playerPower, uint256 bossPower, uint8 trait, uint8 status, uint256 joinSkill, uint64 stamina, uint64 durability, uint64 xp, uint256 accountPower ) { index = raidIndex; endTime = raidEndTime[raidIndex]; raiderCount = getRaidParticipantCount(raidIndex); playerPower = getRaidPlayerPower(raidIndex); bossPower = getRaidBossPower(raidIndex); trait = getRaidBossTrait(raidIndex); status = getRaidStatus(raidIndex); joinSkill = getJoinCostInSkill(); stamina = staminaCost; durability = durabilityCost; xp = xpReward; accountPower = getAccountsPower(raidIndex); } }
require(characters.ownerOf(characterID) == msg.sender);
function joinRaid(uint256 characterID, uint256 weaponID) public { require(characters.canRaid(msg.sender, characterID)); require(weapons.canRaid(msg.sender, weaponID)); require(weapons.ownerOf(weaponID) == msg.sender); require(characters.getStaminaPoints(characterID) > 0, "You cannot join with 0 character stamina"); require(weapons.getDurabilityPoints(weaponID) > 0, "You cannot join with 0 weapon durability");*/ require(raidStatus[raidIndex] == STATUS_STARTED, "Cannot join raid right now!"); require(raidEndTime[raidIndex] > now, "It is too late to join this raid!"); uint256[] memory raiderIndices = raidParticipantIndices[raidIndex][msg.sender]; for(uint i = 0; i < raiderIndices.length; i++) { require(raidParticipants[raidIndex][raiderIndices[i]].wepID != weaponID, "This weapon is already used in the raid"); require(raidParticipants[raidIndex][raiderIndices[i]].charID != characterID, "This character is already participating"); } (uint8 charTrait, uint24 basePowerLevel, /*uint64 timestamp*/) = unpackFightData(characters.getFightDataAndDrainStamina( characterID, uint8(staminaCost), true) ); (/*int128 weaponMultTarget*/, int128 weaponMultFight, uint24 weaponBonusPower, uint24 power = getPlayerFinalPower( getPlayerPower(basePowerLevel, weaponMultFight, weaponBonusPower), charTrait, raidBossTrait[raidIndex] ); raidPlayerPower[raidIndex] += power; raidParticipants[raidIndex].push(Raider( msg.sender, characterID, weaponID, power, )); uint256 joinCostPaid = 0; if(joinCost > 0) { joinCostPaid = game.usdToSkill(joinCost); game.payContractTokenOnly(msg.sender, joinCostPaid); } emit RaidJoined(raidIndex, msg.sender, characterID, weaponID, joinCostPaid); }
1,752,064
// SPDX-License-Identifier: MIT // File: erc-payable-token/contracts/token/ERC1363/IERC1363Spender.sol pragma solidity ^0.8.0; /** * @title IERC1363Spender Interface * @author Vittorio Minacori (https://github.com/vittominacori) * @dev Interface for any contract that wants to support approveAndCall * from ERC1363 token contracts as defined in * https://eips.ethereum.org/EIPS/eip-1363 */ interface IERC1363Spender { /** * @notice Handle the approval of ERC1363 tokens * @dev Any ERC1363 smart contract calls this function on the recipient * after an `approve`. This function MAY throw to revert and reject the * approval. Return of other than the magic value MUST result in the * transaction being reverted. * Note: the token contract address is always the message sender. * @param sender address The address which called `approveAndCall` function * @param amount uint256 The amount of tokens to be spent * @param data bytes Additional data with no specified format * @return `bytes4(keccak256("onApprovalReceived(address,uint256,bytes)"))` unless throwing */ function onApprovalReceived( address sender, uint256 amount, bytes calldata data ) external returns (bytes4); } // File: erc-payable-token/contracts/token/ERC1363/IERC1363Receiver.sol pragma solidity ^0.8.0; /** * @title IERC1363Receiver Interface * @author Vittorio Minacori (https://github.com/vittominacori) * @dev Interface for any contract that wants to support transferAndCall or transferFromAndCall * from ERC1363 token contracts as defined in * https://eips.ethereum.org/EIPS/eip-1363 */ interface IERC1363Receiver { /** * @notice Handle the receipt of ERC1363 tokens * @dev Any ERC1363 smart contract calls this function on the recipient * after a `transfer` or a `transferFrom`. This function MAY throw to revert and reject the * transfer. Return of other than the magic value MUST result in the * transaction being reverted. * Note: the token contract address is always the message sender. * @param operator address The address which called `transferAndCall` or `transferFromAndCall` function * @param sender address The address which are token transferred from * @param amount uint256 The amount of tokens transferred * @param data bytes Additional data with no specified format * @return `bytes4(keccak256("onTransferReceived(address,address,uint256,bytes)"))` unless throwing */ function onTransferReceived( address operator, address sender, uint256 amount, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts/utils/introspection/IERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/utils/introspection/ERC165Checker.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165Checker.sol) pragma solidity ^0.8.0; /** * @dev Library used to query support of an interface declared via {IERC165}. * * Note that these functions return the actual result of the query: they do not * `revert` if an interface is not supported. It is up to the caller to decide * what to do in these cases. */ library ERC165Checker { // As per the EIP-165 spec, no interface should ever match 0xffffffff bytes4 private constant _INTERFACE_ID_INVALID = 0xffffffff; /** * @dev Returns true if `account` supports the {IERC165} interface, */ function supportsERC165(address account) internal view returns (bool) { // Any contract that implements ERC165 must explicitly indicate support of // InterfaceId_ERC165 and explicitly indicate non-support of InterfaceId_Invalid return _supportsERC165Interface(account, type(IERC165).interfaceId) && !_supportsERC165Interface(account, _INTERFACE_ID_INVALID); } /** * @dev Returns true if `account` supports the interface defined by * `interfaceId`. Support for {IERC165} itself is queried automatically. * * See {IERC165-supportsInterface}. */ function supportsInterface(address account, bytes4 interfaceId) internal view returns (bool) { // query support of both ERC165 as per the spec and support of _interfaceId return supportsERC165(account) && _supportsERC165Interface(account, interfaceId); } /** * @dev Returns a boolean array where each value corresponds to the * interfaces passed in and whether they're supported or not. This allows * you to batch check interfaces for a contract where your expectation * is that some interfaces may not be supported. * * See {IERC165-supportsInterface}. * * _Available since v3.4._ */ function getSupportedInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool[] memory) { // an array of booleans corresponding to interfaceIds and whether they're supported or not bool[] memory interfaceIdsSupported = new bool[](interfaceIds.length); // query support of ERC165 itself if (supportsERC165(account)) { // query support of each interface in interfaceIds for (uint256 i = 0; i < interfaceIds.length; i++) { interfaceIdsSupported[i] = _supportsERC165Interface(account, interfaceIds[i]); } } return interfaceIdsSupported; } /** * @dev Returns true if `account` supports all the interfaces defined in * `interfaceIds`. Support for {IERC165} itself is queried automatically. * * Batch-querying can lead to gas savings by skipping repeated checks for * {IERC165} support. * * See {IERC165-supportsInterface}. */ function supportsAllInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool) { // query support of ERC165 itself if (!supportsERC165(account)) { return false; } // query support of each interface in _interfaceIds for (uint256 i = 0; i < interfaceIds.length; i++) { if (!_supportsERC165Interface(account, interfaceIds[i])) { return false; } } // all interfaces supported return true; } /** * @notice Query if a contract implements an interface, does not check ERC165 support * @param account The address of the contract to query for support of an interface * @param interfaceId The interface identifier, as specified in ERC-165 * @return true if the contract at account indicates support of the interface with * identifier interfaceId, false otherwise * @dev Assumes that account contains a contract that supports ERC165, otherwise * the behavior of this method is undefined. This precondition can be checked * with {supportsERC165}. * Interface identification is specified in ERC-165. */ function _supportsERC165Interface(address account, bytes4 interfaceId) private view returns (bool) { bytes memory encodedParams = abi.encodeWithSelector(IERC165.supportsInterface.selector, interfaceId); (bool success, bytes memory result) = account.staticcall{gas: 30000}(encodedParams); if (result.length < 32) return false; return success && abi.decode(result, (bool)); } } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/contracts/security/ReentrancyGuard.sol // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // File: @openzeppelin/contracts/utils/Address.sol // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol // OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: erc-payable-token/contracts/token/ERC1363/IERC1363.sol pragma solidity ^0.8.0; /** * @title IERC1363 Interface * @author Vittorio Minacori (https://github.com/vittominacori) * @dev Interface for a Payable Token contract as defined in * https://eips.ethereum.org/EIPS/eip-1363 */ interface IERC1363 is IERC20, IERC165 { /** * @notice Transfer tokens from `msg.sender` to another address and then call `onTransferReceived` on receiver * @param recipient address The address which you want to transfer to * @param amount uint256 The amount of tokens to be transferred * @return true unless throwing */ function transferAndCall(address recipient, uint256 amount) external returns (bool); /** * @notice Transfer tokens from `msg.sender` to another address and then call `onTransferReceived` on receiver * @param recipient address The address which you want to transfer to * @param amount uint256 The amount of tokens to be transferred * @param data bytes Additional data with no specified format, sent in call to `recipient` * @return true unless throwing */ function transferAndCall( address recipient, uint256 amount, bytes calldata data ) external returns (bool); /** * @notice Transfer tokens from one address to another and then call `onTransferReceived` on receiver * @param sender address The address which you want to send tokens from * @param recipient address The address which you want to transfer to * @param amount uint256 The amount of tokens to be transferred * @return true unless throwing */ function transferFromAndCall( address sender, address recipient, uint256 amount ) external returns (bool); /** * @notice Transfer tokens from one address to another and then call `onTransferReceived` on receiver * @param sender address The address which you want to send tokens from * @param recipient address The address which you want to transfer to * @param amount uint256 The amount of tokens to be transferred * @param data bytes Additional data with no specified format, sent in call to `recipient` * @return true unless throwing */ function transferFromAndCall( address sender, address recipient, uint256 amount, bytes calldata data ) external returns (bool); /** * @notice Approve the passed address to spend the specified amount of tokens on behalf of msg.sender * and then call `onApprovalReceived` on spender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param spender address The address which will spend the funds * @param amount uint256 The amount of tokens to be spent */ function approveAndCall(address spender, uint256 amount) external returns (bool); /** * @notice Approve the passed address to spend the specified amount of tokens on behalf of msg.sender * and then call `onApprovalReceived` on spender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param spender address The address which will spend the funds * @param amount uint256 The amount of tokens to be spent * @param data bytes Additional data with no specified format, sent in call to `spender` */ function approveAndCall( address spender, uint256 amount, bytes calldata data ) external returns (bool); } // File: @openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol // OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: @openzeppelin/contracts/utils/math/Math.sol // OpenZeppelin Contracts v4.4.1 (utils/math/Math.sol) pragma solidity ^0.8.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow. return (a & b) + (a ^ b) / 2; } /** * @dev Returns the ceiling of the division of two numbers. * * This differs from standard division with `/` in that it rounds up instead * of rounding down. */ function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b - 1) / b can overflow on addition, so we distribute. return a / b + (a % b == 0 ? 0 : 1); } } // File: @openzeppelin/contracts/utils/Context.sol // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: erc-payable-token/contracts/payment/ERC1363Payable.sol pragma solidity ^0.8.0; /** * @title ERC1363Payable * @author Vittorio Minacori (https://github.com/vittominacori) * @dev Implementation proposal of a contract that wants to accept ERC1363 payments */ contract ERC1363Payable is IERC1363Receiver, IERC1363Spender, ERC165, Context { using ERC165Checker for address; /** * @dev Emitted when `amount` tokens are moved from one account (`sender`) to * this by operator (`operator`) using {transferAndCall} or {transferFromAndCall}. */ event TokensReceived(address indexed operator, address indexed sender, uint256 amount, bytes data); /** * @dev Emitted when the allowance of this for a `sender` is set by * a call to {approveAndCall}. `amount` is the new allowance. */ event TokensApproved(address indexed sender, uint256 amount, bytes data); // The ERC1363 token accepted IERC1363 private _acceptedToken; /** * @param acceptedToken_ Address of the token being accepted */ constructor(IERC1363 acceptedToken_) { require(address(acceptedToken_) != address(0), "ERC1363Payable: acceptedToken is zero address"); require(acceptedToken_.supportsInterface(type(IERC1363).interfaceId)); _acceptedToken = acceptedToken_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165) returns (bool) { return interfaceId == type(IERC1363Receiver).interfaceId || interfaceId == type(IERC1363Spender).interfaceId || super.supportsInterface(interfaceId); } /* * @dev Note: remember that the token contract address is always the message sender. * @param operator The address which called `transferAndCall` or `transferFromAndCall` function * @param sender The address which are token transferred from * @param amount The amount of tokens transferred * @param data Additional data with no specified format */ function onTransferReceived( address operator, address sender, uint256 amount, bytes memory data ) public override returns (bytes4) { require(_msgSender() == address(_acceptedToken), "ERC1363Payable: acceptedToken is not message sender"); emit TokensReceived(operator, sender, amount, data); _transferReceived(operator, sender, amount, data); return IERC1363Receiver(this).onTransferReceived.selector; } /* * @dev Note: remember that the token contract address is always the message sender. * @param sender The address which called `approveAndCall` function * @param amount The amount of tokens to be spent * @param data Additional data with no specified format */ function onApprovalReceived( address sender, uint256 amount, bytes memory data ) public override returns (bytes4) { require(_msgSender() == address(_acceptedToken), "ERC1363Payable: acceptedToken is not message sender"); emit TokensApproved(sender, amount, data); _approvalReceived(sender, amount, data); return IERC1363Spender(this).onApprovalReceived.selector; } /** * @dev The ERC1363 token accepted */ function acceptedToken() public view returns (IERC1363) { return _acceptedToken; } /** * @dev Called after validating a `onTransferReceived`. Override this method to * make your stuffs within your contract. * @param operator The address which called `transferAndCall` or `transferFromAndCall` function * @param sender The address which are token transferred from * @param amount The amount of tokens transferred * @param data Additional data with no specified format */ function _transferReceived( address operator, address sender, uint256 amount, bytes memory data ) internal virtual { // optional override } /** * @dev Called after validating a `onApprovalReceived`. Override this method to * make your stuffs within your contract. * @param sender The address which called `approveAndCall` function * @param amount The amount of tokens to be spent * @param data Additional data with no specified format */ function _approvalReceived( address sender, uint256 amount, bytes memory data ) internal virtual { // optional override } } // File: @openzeppelin/contracts/security/Pausable.sol // OpenZeppelin Contracts v4.4.1 (security/Pausable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // File: @openzeppelin/contracts/access/Ownable.sol // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: contracts/ExenoTokenStaking.sol pragma solidity 0.8.4; /** * @notice Staking utilizing a payable token (ERC1363) * No tokens are burnt or minted, whereas staked tokens are stored in this contract * Interest payouts are done from the wallet account (thus prior allowance is needed) * Note: Multiple staking contracts can be deployed simultaneously */ contract ExenoTokenStaking is Ownable, Pausable, ReentrancyGuard, ERC1363Payable { using SafeERC20 for IERC1363; // The tokens being staked IERC1363 public immutable token; // Source of interest payouts address public immutable wallet; /** * Interest rate per annum * Expressed as 10**4, e.g. 1285 means 0.1285 or 12.85% */ uint256 public annualizedInterestRate; /** * Rebase period, expressed in hours * 24 means rebasing every day, 168 means rebasing every week, etc */ uint256 public immutable rebasePeriodInHours; // Mode of calculating start time for new stakes StakeStartMode public stakeStartMode; // Date when this staking contract is terminated uint256 public endDate; // The total amount of currently staked tokens uint256 public totalTokensStaked; // Available options for `stakeStartMode` enum StakeStartMode { IMMEDIATE, NEAREST_FULL_HOUR, NEAREST_MIDNIGHT, NEAREST_1AM, NEAREST_NOON, NEAREST_1PM } // Represents a single staking deposit struct Stake { address user; uint256 timestamp; uint256 amount; } // Represents a stakeholder with active stakes struct Stakeholder { address user; uint256 totalAmount; Stake[] stakes; } // Represents a financial record for a single stake struct Record { uint256 timestamp; uint256 amount; uint256 interest; uint256 claimable; uint256 nextRebaseClaimable; uint256 nextRebaseTimestamp; } // Represents all records owned by a stakeholder struct StakingStatus { uint256 timestamp; uint256 totalAmount; Record[] records; } /** * Contains all stakes done with this contract * The stakes for each address are stored at an index which can be found using the `stakes` mapping */ Stakeholder[] internal _stakeholders; // Keeps track of the index for the stakers in the stakes array mapping(address => uint256) internal _stakeMap; // Triggered whenever someone stakes tokens event Staked( address indexed user, uint256 amount ); // Triggered whenever someone unstakes tokens event Unstaked( address indexed user, uint256 amount, uint256 payout ); // Triggered when interest-rate is updated event UpdateAnnualizedInterestRate( uint256 previousRate, uint256 currentRate ); // Triggered when start-mode is updated event UpdateStakeStartMode( StakeStartMode previousMode, StakeStartMode currentMode ); // Triggered when end-date is updated event ExtendEndDate( uint256 previousEndDate, uint256 currentEndDate ); modifier validAddress(address a) { require(a != address(0), "ExenoTokenStaking: address cannot be zero"); require(a != address(this), "ExenoTokenStaking: invalid address"); _; } constructor( IERC1363 _token, uint256 _annualizedInterestRate, uint256 _rebasePeriodInHours, uint8 _stakeStartMode, address _wallet, uint256 _endDate ) ERC1363Payable(_token) validAddress(_wallet) { require(_annualizedInterestRate > 0, "ExenoTokenStaking: invalid annualized interest rate"); require(_rebasePeriodInHours > 0, "ExenoTokenStaking: invalid rebase period"); require(_stakeStartMode <= uint256(StakeStartMode.NEAREST_1PM), "ExenoTokenStaking: invalid stake start mode"); require(_endDate > block.timestamp, "ExenoTokenStaking: end-date cannot be in the past"); token = _token; annualizedInterestRate = _annualizedInterestRate; rebasePeriodInHours = _rebasePeriodInHours; stakeStartMode = StakeStartMode(_stakeStartMode); wallet = _wallet; endDate = _endDate; // Index 0 indicates a non-existing stakeholder _stakeholders.push(); } /** * @dev When tokens are sent to this contract with `transferAndCall` a new stake is created for the sender * @param sender The address performing the action * @param amount The amount of tokens transferred */ function _transferReceived(address, address sender, uint256 amount, bytes memory) internal override validAddress(sender) { _stake(sender, amount); } /** * @dev Adds a stakeholder to the `_stakeholders` array * @param stakeholder The stakeholder to be added */ function _addStakeholder(address stakeholder) internal validAddress(stakeholder) returns(uint256) { // Push a empty item to make space for the new stakeholder _stakeholders.push(); // Calculate the index of the last item in the array uint256 userIndex = _stakeholders.length - 1; // Assign the address to the new index _stakeholders[userIndex].user = stakeholder; // Add index to the map _stakeMap[stakeholder] = userIndex; return userIndex; } /** * @dev Creates a new stake for a sender * @param stakeholder Who is staking * @param amount Amount of tokens to be staked */ function _stake(address stakeholder, uint256 amount) internal validAddress(stakeholder) whenNotPaused { require(amount > 0, "ExenoTokenStaking: amount cannot be zero"); require(endDate > block.timestamp, "ExenoTokenStaking: end-date is expired"); // Make sure tokens have been received assert(_checkBalanceIntegrity(totalTokensStaked + amount)); // Mappings in Solidity creates all values, so we can just check the address uint256 userIndex = _stakeMap[stakeholder]; // Check if the stakeholder already has a staked index or if its the first time if (userIndex == 0) { // This stakeholder stakes for the first time // We need to add him to the stakeHolders and also map it into the index of the stakes // The index returned will be the index of the stakeholder in the _stakeholders array userIndex = _addStakeholder(stakeholder); } // Use the index to push a new stake _stakeholders[userIndex].stakes.push( Stake(stakeholder, _calculateStartTimestamp(), amount) ); // Track the total amount of staked tokens for the user _stakeholders[userIndex].totalAmount += amount; // Track the total balance of staked tokens for all users totalTokensStaked += amount; // Emit an event that the stake has occurred emit Staked(stakeholder, amount); } /** * @dev Unstaking logic * @param userIndex Who is unstaking * @param stakeIndex Index of the stake is the users stake counter, starting at 0 for the first stake * @param amount Amount of tokens to be unstaked from stakeIndex * @return Amount of tokens to be paid as interest payout */ function _unstake(uint256 userIndex, uint256 stakeIndex, uint256 amount) internal returns(uint256) { // Calculate duration (,uint256 recentRebaseDuration,,) = _calculateDuration( _stakeholders[userIndex].stakes[stakeIndex].timestamp); // Calculate payout uint256 payout = _calculatePayout(recentRebaseDuration, amount); // Reduce the stake by subtracting the unstaked amount _stakeholders[userIndex].stakes[stakeIndex].amount -= amount; // Track the total amount of staked tokens for the user _stakeholders[userIndex].totalAmount -= amount; // Track the balance of staked tokens for all users totalTokensStaked -= amount; return payout; } /** * @dev Purging logic for the stakes array * It should be applied after `_unstake` is called * @param userIndex User whose stakes are to be purged */ function _purge(uint256 userIndex) internal { Stake[] storage stakes = _stakeholders[userIndex].stakes; uint256 i; //index of the current stake in the loop uint256 j; //index of the nearest non-zero stake // Loop through all stakes while (i < stakes.length && j < stakes.length) { // Amount equal zero indicates that a stake can be revmoved if (stakes[i].amount == 0) { // Find the nearest non-zero stake if (j == 0) j = i + 1; while (j < stakes.length && stakes[j].amount == 0) { j++; } // If it's found, use it to replace the current stake and then delete it if (j < stakes.length) { stakes[i] = stakes[j]; delete stakes[j]; } j++; } i++; } // If stakes have been shifted, permanently remove the deleted ones if (j > i) { // At this stage all deleted stakes are at the end of the array for (uint256 k = 0; k < j - i; k++) { assert(stakes[stakes.length - 1].amount == 0); stakes.pop(); } } } function _checkBalanceIntegrity(uint256 expectedBalance) internal view returns(bool) { return token.balanceOf(address(this)) >= expectedBalance; } /** * @dev Calculates start time for a new stake * @return startTimestamp */ function _calculateStartTimestamp() internal view virtual returns(uint256) { if (stakeStartMode == StakeStartMode.IMMEDIATE) { return block.timestamp; } uint256 startTimestamp = block.timestamp; if (stakeStartMode == StakeStartMode.NEAREST_FULL_HOUR) { // Reverse time to the top of the hour and then add 1 hour startTimestamp = startTimestamp / 1 hours * 1 hours + 1 hours; } else if (stakeStartMode == StakeStartMode.NEAREST_MIDNIGHT) { // Reverse time to 00:00 UTC and then add 1 day startTimestamp = startTimestamp / 1 days * 1 days + 1 days; } else if (stakeStartMode == StakeStartMode.NEAREST_1AM) { // Reverse time to 00:00 UTC and then add 1 hour startTimestamp = startTimestamp / 1 days * 1 days + 1 hours; } else if (stakeStartMode == StakeStartMode.NEAREST_NOON) { // Reverse time to 00:00 UTC and then add 12 hours startTimestamp = startTimestamp / 1 days * 1 days + 12 hours; } else if (stakeStartMode == StakeStartMode.NEAREST_1PM) { // Reverse time to 00:00 UTC and then add 13 hours startTimestamp = startTimestamp / 1 days * 1 days + 13 hours; } // Shift by 1 day if the new start is earlier than the current time if (startTimestamp < block.timestamp) { startTimestamp += 1 days; assert(startTimestamp >= block.timestamp); } return startTimestamp; } /** * @dev Calculates durations for different scenarios * @param startTimestamp When staking started * @return actualDuration Actual duration, expressed in hours * @return recentRebaseDuration Recent rebase duration, expressed in hours * @return nextRebaseDuration Next rebase duration, expressed in hours * @return nextRebaseTimestamp Next rebase timestamp expressed in hours */ function _calculateDuration(uint256 startTimestamp) internal view virtual returns( uint256 actualDuration, uint256 recentRebaseDuration, uint256 nextRebaseDuration, uint256 nextRebaseTimestamp ) { // We assume the stake is going to be terminated now uint256 endTimestamp = block.timestamp; // In case endDate has already happened, allow endTimestamp to extend one extra rebase period if (endDate < endTimestamp) { endTimestamp = Math.min(endTimestamp, endDate + rebasePeriodInHours * 1 hours); } // Actual duration of the stake, expressed in hours actualDuration = 0; // When the stake is already started, actualDuration becomes non-zero if (startTimestamp < endTimestamp) { actualDuration = (endTimestamp - startTimestamp) / 1 hours; } // Duration of the most recent rebase, expressed in hours recentRebaseDuration = (actualDuration / rebasePeriodInHours) * rebasePeriodInHours; // If no additional interest can be accrued, reduce actualDuration to recentRebaseDuration if (endTimestamp < block.timestamp) { actualDuration = recentRebaseDuration; } // Duration of the next rebase, expressed in hours nextRebaseDuration = 0; nextRebaseTimestamp = 0; // If this in not the last rebase, set nextRebaseDuration by extending recentRebaseDuration by one rebase period if (startTimestamp + recentRebaseDuration * 1 hours < endDate) { nextRebaseDuration = recentRebaseDuration + rebasePeriodInHours; nextRebaseTimestamp = startTimestamp + nextRebaseDuration * 1 hours; } } /** * @dev Calculates interest payout * @param duration Duration expressed in hours * @param amount Amount of tokens staked * @return Actual or potential payout */ function _calculatePayout(uint256 duration, uint256 amount) internal view virtual returns(uint256) { return duration * amount * annualizedInterestRate / 365 / 24 / 10**4; } function pause() external onlyOwner { _pause(); } function unpause() external onlyOwner { _unpause(); } /** * @notice Sets a new annualized-interest-rate * @param newAnnualizedInterestRate New value for the rate */ function updateAnnualizedInterestRate(uint256 newAnnualizedInterestRate) external onlyOwner { require(newAnnualizedInterestRate > 0, "ExenoTokenStaking: invalid annualized interest rate"); emit UpdateAnnualizedInterestRate(annualizedInterestRate, newAnnualizedInterestRate); annualizedInterestRate = newAnnualizedInterestRate; } /** * @notice Sets a new stake-start-mode * @param newStakeStartValue New value for the mode */ function updateStakeStartMode(uint8 newStakeStartValue) external onlyOwner { require(newStakeStartValue <= uint256(StakeStartMode.NEAREST_1PM), "ExenoTokenStaking: invalid stake start mode"); StakeStartMode newStakeStartMode = StakeStartMode(newStakeStartValue); emit UpdateStakeStartMode(stakeStartMode, newStakeStartMode); stakeStartMode = newStakeStartMode; } /** * @notice Sets a new end-date under the following conditions: * (1) the existing end-date has not expired yet * (2) the new end-date is later then existing end-date * @param newEndDate New value for the end-date */ function extendEndDate(uint256 newEndDate) external onlyOwner { require(newEndDate > block.timestamp, "ExenoTokenStaking: new end-date cannot be in the past"); require(newEndDate > endDate, "ExenoTokenStaking: new end-date cannot be prior to existing end-date"); require(endDate > block.timestamp, "ExenoTokenStaking: cannot set a new end-date as existing end-date is expired"); emit ExtendEndDate(endDate, newEndDate); endDate = newEndDate; } /** * @notice Generates a staking status report for a given stakeholder * @param stakeholder For whom is the report * @return StakingStatus report */ function getStakingStatus(address stakeholder) external view validAddress(stakeholder) returns(StakingStatus memory) { Stake[] memory stakes = _stakeholders[_stakeMap[stakeholder]].stakes; Record[] memory records = new Record[](stakes.length); for (uint256 i = 0; i < stakes.length; i++) { uint256 timestamp = stakes[i].timestamp; records[i].timestamp = timestamp; ( uint256 actualDuration, uint256 recentRebaseDuration, uint256 nextRebaseDuration, uint256 nextRebaseTimestamp ) = _calculateDuration(timestamp); uint256 amount = stakes[i].amount; records[i].amount = amount; records[i].interest = _calculatePayout(actualDuration, amount); records[i].claimable = _calculatePayout(recentRebaseDuration, amount); records[i].nextRebaseClaimable = _calculatePayout(nextRebaseDuration, amount); records[i].nextRebaseTimestamp = nextRebaseTimestamp; } StakingStatus memory status = StakingStatus(block.timestamp, _stakeholders[_stakeMap[stakeholder]].totalAmount, records); return status; } /** * @notice Returns the number of stakeholders * @return Number of stakeholders */ function getNumberOfStakeholders() external view returns(uint256) { return _stakeholders.length - 1; } /** * @notice Shows the current amount of tokens available for payouts * @return Owner's balance and this contract's allowance */ function checkAvailableFunds() external view returns(uint256, uint256) { return (token.balanceOf(wallet), token.allowance(wallet, address(this))); } /** * @notice Withdraws stake from a given staking index and makes appropriate transfers * @param amount Amount to unstake, zero indicates maximum available * @param stakeIndex Index of the stake is the users stake counter, starting at 0 for the first stake * @param skipPayout Whether to give up interest payout (do not use it unless you have to) */ function unstake(uint256 amount, uint256 stakeIndex, bool skipPayout) external nonReentrant { address stakeholder = msg.sender; uint256 userIndex = _stakeMap[stakeholder]; Stake[] memory stakes = _stakeholders[userIndex].stakes; require(stakes.length > 0, "ExenoTokenStaking: this account has never made any staking"); require(stakeIndex < stakes.length, "ExenoTokenStaking: provided index is out of range"); Stake memory currentStake = stakes[stakeIndex]; if (amount > 0) { require(currentStake.amount >= amount, "ExenoTokenStaking: there is not enough stake on the provided index for the requested amount"); } else { // Amount equal to zero indicates that the entire index needs to be unstaked require(currentStake.amount > 0, "ExenoTokenStaking: there is not enough stake on the provided index for the requested amount"); amount = currentStake.amount; } // Unstake and calculate the payout uint256 payout = _unstake(userIndex, stakeIndex, amount); // Reduce payout to zero in case we don't need it if (skipPayout) payout = 0; require(token.balanceOf(wallet) >= payout, "ExenoTokenStaking: not enough balance for payout"); require(token.allowance(wallet, address(this)) >= payout, "ExenoTokenStaking: not enough allowance for payout"); assert(_checkBalanceIntegrity(totalTokensStaked)); // Apply purging right after unstaking to eliminate empty stakes _purge(userIndex); // Return staked tokens to the stakeholder token.safeTransfer(stakeholder, amount); // Send payout to the stakeholder if (payout > 0) { token.safeTransferFrom(wallet, stakeholder, payout); } assert(_checkBalanceIntegrity(totalTokensStaked)); // Emit an event that unstaking has occurred emit Unstaked(stakeholder, amount, payout); } /** * @notice Withdraws stake by applying the FIFO rule - no staking index needs to be provided * @param amount Amount to unstake, zero indicates maximum available */ function unstakeFifo(uint256 amount) external nonReentrant { address stakeholder = msg.sender; uint256 userIndex = _stakeMap[stakeholder]; Stake[] memory stakes = _stakeholders[userIndex].stakes; require(stakes.length > 0, "ExenoTokenStaking: this account has never made any staking"); // Amount equal to zero indicates that all indexes need to be unstaked if (amount == 0) { amount = _stakeholders[userIndex].totalAmount; require(amount > 0, "ExenoTokenStaking: not enough stake on all indexes for the requested amount"); } // FIFO unstaking loop uint256 amountLeft = amount; uint256 payout = 0; uint256 index = 0; while (amountLeft > 0 && index < stakes.length) { uint256 bite = Math.min(stakes[index].amount, amountLeft); payout += _unstake(userIndex, index, bite); amountLeft -= bite; index++; } require(amountLeft == 0, "ExenoTokenStaking: not enough stake on all indexes for the requested amount"); require(token.balanceOf(wallet) >= payout, "ExenoTokenStaking: not enough balance for payout"); require(token.allowance(wallet, address(this)) >= payout, "ExenoTokenStaking: not enough allowance for payout"); assert(_checkBalanceIntegrity(totalTokensStaked)); // Apply purging after the entire unstaking loop _purge(userIndex); // Return staked tokens to the stakeholder token.safeTransfer(stakeholder, amount); // Send payout to the stakeholder token.safeTransferFrom(wallet, stakeholder, payout); assert(_checkBalanceIntegrity(totalTokensStaked)); // Emit an event that unstaking has occurred emit Unstaked(stakeholder, amount, payout); } }
Calculates durations for different scenarios startTimestamp When staking started return actualDuration Actual duration, expressed in hours return recentRebaseDuration Recent rebase duration, expressed in hours return nextRebaseDuration Next rebase duration, expressed in hours return nextRebaseTimestamp Next rebase timestamp expressed in hours/ We assume the stake is going to be terminated now In case endDate has already happened, allow endTimestamp to extend one extra rebase period When the stake is already started, actualDuration becomes non-zero If no additional interest can be accrued, reduce actualDuration to recentRebaseDuration If this in not the last rebase, set nextRebaseDuration by extending recentRebaseDuration by one rebase period
function _calculateDuration(uint256 startTimestamp) internal view virtual returns( uint256 actualDuration, uint256 recentRebaseDuration, uint256 nextRebaseDuration, uint256 nextRebaseTimestamp ) { uint256 endTimestamp = block.timestamp; if (endDate < endTimestamp) { endTimestamp = Math.min(endTimestamp, endDate + rebasePeriodInHours * 1 hours); } if (startTimestamp < endTimestamp) { actualDuration = (endTimestamp - startTimestamp) / 1 hours; } if (endTimestamp < block.timestamp) { actualDuration = recentRebaseDuration; } nextRebaseTimestamp = 0; if (startTimestamp + recentRebaseDuration * 1 hours < endDate) { nextRebaseDuration = recentRebaseDuration + rebasePeriodInHours; nextRebaseTimestamp = startTimestamp + nextRebaseDuration * 1 hours; } }
1,685,548
pragma solidity ^0.4.15; /* Copyright 2017, Roderik van der Veer (SettleMint) Copyright 2017, Jorge Izquierdo (Aragon Foundation) Copyright 2017, Jordi Baylina (Giveth) Based on MiniMeToken.sol from https://github.com/Giveth/minime Original contract from https://github.com/aragon/aragon-network-token/blob/master/contracts/interface/Controlled.sol */ contract Controlled { /// @notice The address of the controller is the only address that can call /// a function with this modifier modifier onlyController { require(msg.sender == controller); _; } address public controller; function Controlled() { controller = msg.sender;} /// @notice Changes the controller of the contract /// @param _newController The new controller of the contract function changeController(address _newController) onlyController { controller = _newController; } } /* Abstract contract for the full ERC 20 Token standard https://github.com/ethereum/EIPs/issues/20 Copyright 2017, Jordi Baylina (Giveth) Original contract from https://github.com/status-im/status-network-token/blob/master/contracts/ERC20Token.sol */ contract ERC20Token { /* This is a slight change to the ERC20 base standard. function totalSupply() constant returns (uint256 supply); is replaced with: uint256 public totalSupply; This automatically creates a getter function for the totalSupply. This is moved to the base contract since public getter functions are not currently recognised as an implementation of the matching abstract function by the compiler. */ /// total amount of tokens function totalSupply() constant returns (uint256 balance); /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) constant returns (uint256 balance); /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) returns (bool success); /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) returns (bool success); /// @notice `msg.sender` approves `_spender` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of tokens to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) returns (bool success); /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) constant returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract MiniMeTokenI is ERC20Token, Controlled { string public name; //The Token&#39;s name: e.g. DigixDAO Tokens uint8 public decimals; //Number of decimals of the smallest unit string public symbol; //An identifier: e.g. REP string public version = "MMT_0.1"; //An arbitrary versioning scheme /////////////////// // ERC20 Methods /////////////////// /// @notice `msg.sender` approves `_spender` to send `_amount` tokens on /// its behalf, and then a function is triggered in the contract that is /// being approved, `_spender`. This allows users to use their tokens to /// interact with contracts in one function call instead of two /// @param _spender The address of the contract able to transfer the tokens /// @param _amount The amount of tokens to be approved for transfer /// @return True if the function call was successful function approveAndCall( address _spender, uint256 _amount, bytes _extraData ) returns (bool success); //////////////// // Query balance and totalSupply in History //////////////// /// @dev Queries the balance of `_owner` at a specific `_blockNumber` /// @param _owner The address from which the balance will be retrieved /// @param _blockNumber The block number when the balance is queried /// @return The balance at `_blockNumber` function balanceOfAt( address _owner, uint _blockNumber ) constant returns (uint); /// @notice Total amount of tokens at a specific `_blockNumber`. /// @param _blockNumber The block number when the totalSupply is queried /// @return The total amount of tokens at `_blockNumber` function totalSupplyAt(uint _blockNumber) constant returns(uint); //////////////// // Clone Token Method //////////////// /// @notice Creates a new clone token with the initial distribution being /// this token at `_snapshotBlock` /// @param _cloneTokenName Name of the clone token /// @param _cloneDecimalUnits Number of decimals of the smallest unit /// @param _cloneTokenSymbol Symbol of the clone token /// @param _snapshotBlock Block when the distribution of the parent token is /// copied to set the initial distribution of the new clone token; /// if the block is zero than the actual block, the current block is used /// @param _transfersEnabled True if transfers are allowed in the clone /// @return The address of the new MiniMeToken Contract function createCloneToken( string _cloneTokenName, uint8 _cloneDecimalUnits, string _cloneTokenSymbol, uint _snapshotBlock, bool _transfersEnabled ) returns(address); //////////////// // Generate and destroy tokens //////////////// /// @notice Generates `_amount` tokens that are assigned to `_owner` /// @param _owner The address that will be assigned the new tokens /// @param _amount The quantity of tokens generated /// @return True if the tokens are generated correctly function generateTokens(address _owner, uint _amount) returns (bool); /// @notice Burns `_amount` tokens from `_owner` /// @param _owner The address that will lose the tokens /// @param _amount The quantity of tokens to burn /// @return True if the tokens are burned correctly function destroyTokens(address _owner, uint _amount) returns (bool); //////////////// // Enable tokens transfers //////////////// /// @notice Enables token holders to transfer their tokens freely if true /// @param _transfersEnabled True if transfers are allowed in the clone function enableTransfers(bool _transfersEnabled); ////////// // Safety Methods ////////// /// @notice This method can be used by the controller to extract mistakenly /// sent tokens to this contract. /// @param _token The address of the token contract that you want to recover /// set to 0 in case you want to extract ether. function claimTokens(address _token); //////////////// // Events //////////////// event ClaimedTokens(address indexed _token, address indexed _controller, uint _amount); event NewCloneToken(address indexed _cloneToken, uint _snapshotBlock); } /* Copyright 2017, Jorge Izquierdo (Aragon Foundation) Copyright 2017, Jordi Baylina (Giveth) Based on MiniMeToken.sol from https://github.com/Giveth/minime Original contract from https://github.com/aragon/aragon-network-token/blob/master/contracts/interface/Controller.sol */ /// @dev The token controller contract must implement these functions contract TokenController { /// @notice Called when `_owner` sends ether to the MiniMe Token contract /// @param _owner The address that sent the ether to create tokens /// @return True if the ether is accepted, false if it throws function proxyPayment(address _owner) payable returns(bool); /// @notice Notifies the controller about a token transfer allowing the /// controller to react if desired /// @param _from The origin of the transfer /// @param _to The destination of the transfer /// @param _amount The amount of the transfer /// @return False if the controller does not authorize the transfer function onTransfer(address _from, address _to, uint _amount) returns(bool); /// @notice Notifies the controller about an approval allowing the /// controller to react if desired /// @param _owner The address that calls `approve()` /// @param _spender The spender in the `approve()` call /// @param _amount The amount in the `approve()` call /// @return False if the controller does not authorize the approval function onApprove(address _owner, address _spender, uint _amount) returns(bool); } /* Copyright 2017, Jordi Baylina (Giveth) Original contract from https://github.com/aragon/aragon-network-token/blob/master/contracts/interface/ApproveAndCallReceiver.sol */ contract ApproveAndCallReceiver { function receiveApproval( address _from, uint256 _amount, address _token, bytes _data ); } /* Copyright 2017, Anton Egorov (Mothership Foundation) Copyright 2017, Jordi Baylina (Giveth) Based on MineMeToken.sol from https://github.com/Giveth/minime Original contract from https://github.com/status-im/status-network-token/blob/master/contracts/MiniMeToken.sol */ /// @title MiniMeToken Contract /// @author Jordi Baylina /// @dev This token contract&#39;s goal is to make it easy for anyone to clone this /// token using the token distribution at a given block, this will allow DAO&#39;s /// and DApps to upgrade their features in a decentralized manner without /// affecting the original token /// @dev It is ERC20 compliant, but still needs to under go further testing. /// @dev The actual token contract, the default controller is the msg.sender /// that deploys the contract, so usually this token will be deployed by a /// token controller contract, which Giveth will call a "Campaign" contract MiniMeToken is MiniMeTokenI { string public name; //The Token&#39;s name: e.g. DigixDAO Tokens uint8 public decimals; //Number of decimals of the smallest unit string public symbol; //An identifier: e.g. REP string public version = "MMT_0.1"; //An arbitrary versioning scheme /// @dev `Checkpoint` is the structure that attaches a block number to a /// given value, the block number attached is the one that last changed the /// value struct Checkpoint { // `fromBlock` is the block number that the value was generated from uint128 fromBlock; // `value` is the amount of tokens at a specific block number uint128 value; } // `parentToken` is the Token address that was cloned to produce this token; // it will be 0x0 for a token that was not cloned MiniMeToken public parentToken; // `parentSnapShotBlock` is the block number from the Parent Token that was // used to determine the initial distribution of the Clone Token uint public parentSnapShotBlock; // `creationBlock` is the block number that the Clone Token was created uint public creationBlock; // `balances` is the map that tracks the balance of each address, in this // contract when the balance changes the block number that the change // occurred is also included in the map mapping (address => Checkpoint[]) balances; // `allowed` tracks any extra transfer rights as in all ERC20 tokens mapping (address => mapping (address => uint256)) allowed; // Tracks the history of the `totalSupply` of the token Checkpoint[] totalSupplyHistory; // Flag that determines if the token is transferable or not. bool public transfersEnabled; // The factory used to create new clone tokens MiniMeTokenFactory public tokenFactory; //////////////// // Constructor //////////////// /// @notice Constructor to create a MiniMeToken /// @param _tokenFactory The address of the MiniMeTokenFactory contract that /// will create the Clone token contracts, the token factory needs to be /// deployed first /// @param _parentToken Address of the parent token, set to 0x0 if it is a /// new token /// @param _parentSnapShotBlock Block of the parent token that will /// determine the initial distribution of the clone token, set to 0 if it /// is a new token /// @param _tokenName Name of the new token /// @param _decimalUnits Number of decimals of the new token /// @param _tokenSymbol Token Symbol for the new token /// @param _transfersEnabled If true, tokens will be able to be transferred function MiniMeToken( address _tokenFactory, address _parentToken, uint _parentSnapShotBlock, string _tokenName, uint8 _decimalUnits, string _tokenSymbol, bool _transfersEnabled ) { tokenFactory = MiniMeTokenFactory(_tokenFactory); name = _tokenName; // Set the name decimals = _decimalUnits; // Set the decimals symbol = _tokenSymbol; // Set the symbol parentToken = MiniMeToken(_parentToken); parentSnapShotBlock = _parentSnapShotBlock; transfersEnabled = _transfersEnabled; creationBlock = block.number; } /////////////////// // ERC20 Methods /////////////////// /// @notice Send `_amount` tokens to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _amount The amount of tokens to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _amount) returns (bool success) { require(transfersEnabled); return doTransfer(msg.sender, _to, _amount); } /// @notice Send `_amount` tokens to `_to` from `_from` on the condition it /// is approved by `_from` /// @param _from The address holding the tokens being transferred /// @param _to The address of the recipient /// @param _amount The amount of tokens to be transferred /// @return True if the transfer was successful function transferFrom(address _from, address _to, uint256 _amount) returns (bool success) { // The controller of this contract can move tokens around at will, // this is important to recognize! Confirm that you trust the // controller of this contract, which in most situations should be // another open source smart contract or 0x0 if (msg.sender != controller) { require(transfersEnabled); // The standard ERC 20 transferFrom functionality if (allowed[_from][msg.sender] < _amount) { return false; } allowed[_from][msg.sender] -= _amount; } return doTransfer(_from, _to, _amount); } /// @dev This is the actual transfer function in the token contract, it can /// only be called by other functions in this contract. /// @param _from The address holding the tokens being transferred /// @param _to The address of the recipient /// @param _amount The amount of tokens to be transferred /// @return True if the transfer was successful function doTransfer(address _from, address _to, uint _amount) internal returns(bool) { if (_amount == 0) { return true; } require(parentSnapShotBlock < block.number); // Do not allow transfer to 0x0 or the token contract itself require((_to != 0) && (_to != address(this))); // If the amount being transfered is more than the balance of the // account the transfer returns false var previousBalanceFrom = balanceOfAt(_from, block.number); if (previousBalanceFrom < _amount) { return false; } // Alerts the token controller of the transfer if (isContract(controller)) { bool onTransfer = TokenController(controller).onTransfer(_from, _to, _amount); require(onTransfer); } // First update the balance array with the new value for the address // sending the tokens updateValueAtNow(balances[_from], previousBalanceFrom - _amount); // Then update the balance array with the new value for the address // receiving the tokens var previousBalanceTo = balanceOfAt(_to, block.number); require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow updateValueAtNow(balances[_to], previousBalanceTo + _amount); // An event to make the transfer easy to find on the blockchain Transfer(_from, _to, _amount); return true; } /// @param _owner The address that&#39;s balance is being requested /// @return The balance of `_owner` at the current block function balanceOf(address _owner) constant returns (uint256 balance) { return balanceOfAt(_owner, block.number); } /// @notice `msg.sender` approves `_spender` to spend `_amount` tokens on /// its behalf. This is a modified version of the ERC20 approve function /// to be a little bit safer /// @param _spender The address of the account able to transfer the tokens /// @param _amount The amount of tokens to be approved for transfer /// @return True if the approval was successful function approve(address _spender, uint256 _amount) returns (bool success) { require(transfersEnabled); // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender,0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_amount == 0) || (allowed[msg.sender][_spender] == 0)); // Alerts the token controller of the approve function call if (isContract(controller)) { bool onApprove = TokenController(controller).onApprove(msg.sender, _spender, _amount); require(onApprove); } allowed[msg.sender][_spender] = _amount; Approval(msg.sender, _spender, _amount); return true; } /// @dev This function makes it easy to read the `allowed[]` map /// @param _owner The address of the account that owns the token /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens of _owner that _spender is allowed /// to spend function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /// @notice `msg.sender` approves `_spender` to send `_amount` tokens on /// its behalf, and then a function is triggered in the contract that is /// being approved, `_spender`. This allows users to use their tokens to /// interact with contracts in one function call instead of two /// @param _spender The address of the contract able to transfer the tokens /// @param _amount The amount of tokens to be approved for transfer /// @return True if the function call was successful function approveAndCall(address _spender, uint256 _amount, bytes _extraData) returns (bool success) { require(approve(_spender, _amount)); ApproveAndCallReceiver(_spender).receiveApproval( msg.sender, _amount, this, _extraData ); return true; } /// @dev This function makes it easy to get the total number of tokens /// @return The total number of tokens function totalSupply() constant returns (uint) { return totalSupplyAt(block.number); } //////////////// // Query balance and totalSupply in History //////////////// /// @dev Queries the balance of `_owner` at a specific `_blockNumber` /// @param _owner The address from which the balance will be retrieved /// @param _blockNumber The block number when the balance is queried /// @return The balance at `_blockNumber` function balanceOfAt(address _owner, uint _blockNumber) constant returns (uint) { // These next few lines are used when the balance of the token is // requested before a check point was ever created for this token, it // requires that the `parentToken.balanceOfAt` be queried at the // genesis block for that token as this contains initial balance of // this token if ((balances[_owner].length == 0) || (balances[_owner][0].fromBlock > _blockNumber)) { if (address(parentToken) != 0) { return parentToken.balanceOfAt(_owner, min(_blockNumber, parentSnapShotBlock)); } else { // Has no parent return 0; } // This will return the expected balance during normal situations } else { return getValueAt(balances[_owner], _blockNumber); } } /// @notice Total amount of tokens at a specific `_blockNumber`. /// @param _blockNumber The block number when the totalSupply is queried /// @return The total amount of tokens at `_blockNumber` function totalSupplyAt(uint _blockNumber) constant returns(uint) { // These next few lines are used when the totalSupply of the token is // requested before a check point was ever created for this token, it // requires that the `parentToken.totalSupplyAt` be queried at the // genesis block for this token as that contains totalSupply of this // token at this block number. if ((totalSupplyHistory.length == 0) || (totalSupplyHistory[0].fromBlock > _blockNumber)) { if (address(parentToken) != 0) { return parentToken.totalSupplyAt(min(_blockNumber, parentSnapShotBlock)); } else { return 0; } // This will return the expected totalSupply during normal situations } else { return getValueAt(totalSupplyHistory, _blockNumber); } } //////////////// // Clone Token Method //////////////// /// @notice Creates a new clone token with the initial distribution being /// this token at `_snapshotBlock` /// @param _cloneTokenName Name of the clone token /// @param _cloneDecimalUnits Number of decimals of the smallest unit /// @param _cloneTokenSymbol Symbol of the clone token /// @param _snapshotBlock Block when the distribution of the parent token is /// copied to set the initial distribution of the new clone token; /// if the block is zero than the actual block, the current block is used /// @param _transfersEnabled True if transfers are allowed in the clone /// @return The address of the new MiniMeToken Contract function createCloneToken( string _cloneTokenName, uint8 _cloneDecimalUnits, string _cloneTokenSymbol, uint _snapshotBlock, bool _transfersEnabled ) returns(address) { if (_snapshotBlock == 0) { _snapshotBlock = block.number; } MiniMeToken cloneToken = tokenFactory.createCloneToken( this, _snapshotBlock, _cloneTokenName, _cloneDecimalUnits, _cloneTokenSymbol, _transfersEnabled ); cloneToken.changeController(msg.sender); // An event to make the token easy to find on the blockchain NewCloneToken(address(cloneToken), _snapshotBlock); return address(cloneToken); } //////////////// // Generate and destroy tokens //////////////// /// @notice Generates `_amount` tokens that are assigned to `_owner` /// @param _owner The address that will be assigned the new tokens /// @param _amount The quantity of tokens generated /// @return True if the tokens are generated correctly function generateTokens(address _owner, uint _amount) onlyController returns (bool) { uint curTotalSupply = totalSupply(); require(curTotalSupply + _amount >= curTotalSupply); // Check for overflow uint previousBalanceTo = balanceOf(_owner); require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow updateValueAtNow(totalSupplyHistory, curTotalSupply + _amount); updateValueAtNow(balances[_owner], previousBalanceTo + _amount); Transfer(0, _owner, _amount); return true; } /// @notice Burns `_amount` tokens from `_owner` /// @param _owner The address that will lose the tokens /// @param _amount The quantity of tokens to burn /// @return True if the tokens are burned correctly function destroyTokens(address _owner, uint _amount) onlyController returns (bool) { uint curTotalSupply = totalSupply(); require(curTotalSupply >= _amount); uint previousBalanceFrom = balanceOf(_owner); require(previousBalanceFrom >= _amount); updateValueAtNow(totalSupplyHistory, curTotalSupply - _amount); updateValueAtNow(balances[_owner], previousBalanceFrom - _amount); Transfer(_owner, 0, _amount); return true; } //////////////// // Enable tokens transfers //////////////// /// @notice Enables token holders to transfer their tokens freely if true /// @param _transfersEnabled True if transfers are allowed in the clone function enableTransfers(bool _transfersEnabled) onlyController { transfersEnabled = _transfersEnabled; } //////////////// // Internal helper functions to query and set a value in a snapshot array //////////////// /// @dev `getValueAt` retrieves the number of tokens at a given block number /// @param checkpoints The history of values being queried /// @param _block The block number to retrieve the value at /// @return The number of tokens being queried function getValueAt(Checkpoint[] storage checkpoints, uint _block) constant internal returns (uint) { if (checkpoints.length == 0) { return 0; } // Shortcut for the actual value if (_block >= checkpoints[checkpoints.length-1].fromBlock) return checkpoints[checkpoints.length-1].value; if (_block < checkpoints[0].fromBlock) { return 0; } // Binary search of the value in the array uint min = 0; uint max = checkpoints.length-1; while (max > min) { uint mid = (max + min + 1) / 2; if (checkpoints[mid].fromBlock<=_block) { min = mid; } else { max = mid-1; } } return checkpoints[min].value; } /// @dev `updateValueAtNow` used to update the `balances` map and the /// `totalSupplyHistory` /// @param checkpoints The history of data being updated /// @param _value The new number of tokens function updateValueAtNow(Checkpoint[] storage checkpoints, uint _value) internal { if ((checkpoints.length == 0) || (checkpoints[checkpoints.length - 1].fromBlock < block.number)) { Checkpoint storage newCheckPoint = checkpoints[checkpoints.length++]; newCheckPoint.fromBlock = uint128(block.number); newCheckPoint.value = uint128(_value); } else { Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length-1]; oldCheckPoint.value = uint128(_value); } } /// @dev Internal function to determine if an address is a contract /// @param _addr The address being queried /// @return True if `_addr` is a contract function isContract(address _addr) constant internal returns(bool) { uint size; if (_addr == 0) { return false; } assembly { size := extcodesize(_addr) } return size>0; } /// @dev Helper function to return a min betwen the two uints function min(uint a, uint b) internal returns (uint) { return a < b ? a : b; } /// @notice The fallback function: If the contract&#39;s controller has not been /// set to 0, then the `proxyPayment` method is called which relays the /// ether and creates tokens as described in the token controller contract function () payable { require(isContract(controller)); bool proxyPayment = TokenController(controller).proxyPayment.value(msg.value)(msg.sender); require(proxyPayment); } ////////// // Safety Methods ////////// /// @notice This method can be used by the controller to extract mistakenly /// sent tokens to this contract. /// @param _token The address of the token contract that you want to recover /// set to 0 in case you want to extract ether. function claimTokens(address _token) onlyController { if (_token == 0x0) { controller.transfer(this.balance); return; } MiniMeToken token = MiniMeToken(_token); uint balance = token.balanceOf(this); token.transfer(controller, balance); ClaimedTokens(_token, controller, balance); } //////////////// // Events //////////////// event ClaimedTokens(address indexed _token, address indexed _controller, uint _amount); event Transfer(address indexed _from, address indexed _to, uint256 _amount); event NewCloneToken(address indexed _cloneToken, uint _snapshotBlock); event Approval( address indexed _owner, address indexed _spender, uint256 _amount ); } //////////////// // MiniMeTokenFactory //////////////// /// @dev This contract is used to generate clone contracts from a contract. /// In solidity this is the way to create a contract from a contract of the /// same class contract MiniMeTokenFactory { /// @notice Update the DApp by creating a new token with new functionalities /// the msg.sender becomes the controller of this clone token /// @param _parentToken Address of the token being cloned /// @param _snapshotBlock Block of the parent token that will /// determine the initial distribution of the clone token /// @param _tokenName Name of the new token /// @param _decimalUnits Number of decimals of the new token /// @param _tokenSymbol Token Symbol for the new token /// @param _transfersEnabled If true, tokens will be able to be transferred /// @return The address of the new token contract function createCloneToken( address _parentToken, uint _snapshotBlock, string _tokenName, uint8 _decimalUnits, string _tokenSymbol, bool _transfersEnabled ) returns (MiniMeToken) { MiniMeToken newToken = new MiniMeToken( this, _parentToken, _snapshotBlock, _tokenName, _decimalUnits, _tokenSymbol, _transfersEnabled ); newToken.changeController(msg.sender); return newToken; } } contract DataBrokerDaoToken is MiniMeToken { function DataBrokerDaoToken(address _tokenFactory) MiniMeToken( _tokenFactory, 0x0, // no parent token 0, // no snapshot block number from parent "DataBroker DAO Token", // Token name 18, // Decimals "DATA", // Symbol true // Enable transfers ) {} } pragma solidity ^0.4.15; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal constant returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return c; } function sub(uint256 a, uint256 b) internal constant returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract EarlyTokenSale is TokenController, Controlled { using SafeMath for uint256; // In UNIX time format - http://www.unixtimestamp.com/ uint256 public startFundingTime; uint256 public endFundingTime; // 15% of tokens hard cap, at 1200 tokens per ETH // 225,000,000*0.15 => 33,750,000 / 1200 => 28,125 ETH uint256 constant public maximumFunding = 28125 ether; uint256 constant public tokensPerEther = 1200; uint256 constant public maxGasPrice = 50000000000; // antispam uint256 constant public maxCallFrequency = 100; mapping (address => uint256) public lastCallBlock; // total amount raised in wei uint256 public totalCollected; // the tokencontract for the DataBrokerDAO DataBrokerDaoToken public tokenContract; // the funds end up in this address address public vaultAddress; bool public paused; bool public finalized = false; /// @param _startFundingTime The UNIX time that the EarlyTokenSale will be able to start receiving funds /// @param _endFundingTime The UNIX time that the EarlyTokenSale will stop being able to receive funds /// @param _vaultAddress The address that will store the donated funds /// @param _tokenAddress Address of the token contract this contract controls function EarlyTokenSale( uint _startFundingTime, uint _endFundingTime, address _vaultAddress, address _tokenAddress ) { require(_endFundingTime > now); require(_endFundingTime >= _startFundingTime); require(_vaultAddress != 0); require(_tokenAddress != 0); startFundingTime = _startFundingTime; endFundingTime = _endFundingTime; tokenContract = DataBrokerDaoToken(_tokenAddress); vaultAddress = _vaultAddress; paused = false; } /// @dev The fallback function is called when ether is sent to the contract, it /// simply calls `doPayment()` with the address that sent the ether as the /// `_owner`. Payable is a required solidity modifier for functions to receive /// ether, without this modifier functions will throw if ether is sent to them function () payable notPaused { doPayment(msg.sender); } /// @notice `proxyPayment()` allows the caller to send ether to the EarlyTokenSale and /// have the tokens created in an address of their choosing /// @param _owner The address that will hold the newly created tokens function proxyPayment(address _owner) payable notPaused returns(bool success) { return doPayment(_owner); } /// @notice Notifies the controller about a transfer, for this EarlyTokenSale all /// transfers are allowed by default and no extra notifications are needed /// @param _from The origin of the transfer /// @param _to The destination of the transfer /// @param _amount The amount of the transfer /// @return False if the controller does not authorize the transfer function onTransfer(address _from, address _to, uint _amount) returns(bool success) { if ( _from == vaultAddress ) { return true; } return false; } /// @notice Notifies the controller about an approval, for this EarlyTokenSale all /// approvals are allowed by default and no extra notifications are needed /// @param _owner The address that calls `approve()` /// @param _spender The spender in the `approve()` call /// @param _amount The amount in the `approve()` call /// @return False if the controller does not authorize the approval function onApprove(address _owner, address _spender, uint _amount) returns(bool success) { if ( _owner == vaultAddress ) { return true; } return false; } /// @dev `doPayment()` is an internal function that sends the ether that this /// contract receives to the `vault` and creates tokens in the address of the /// `_owner` assuming the EarlyTokenSale is still accepting funds /// @param _owner The address that will hold the newly created tokens function doPayment(address _owner) internal returns(bool success) { require(tx.gasprice <= maxGasPrice); // Antispam // do not allow contracts to game the system require(!isContract(msg.sender)); // limit the amount of contributions to once per 100 blocks require(getBlockNumber().sub(lastCallBlock[msg.sender]) >= maxCallFrequency); lastCallBlock[msg.sender] = getBlockNumber(); // First check that the EarlyTokenSale is allowed to receive this donation if (msg.sender != controller) { require(startFundingTime <= now); } require(endFundingTime > now); require(tokenContract.controller() != 0); require(msg.value > 0); require(totalCollected.add(msg.value) <= maximumFunding); // Track how much the EarlyTokenSale has collected totalCollected = totalCollected.add(msg.value); //Send the ether to the vault require(vaultAddress.send(msg.value)); // Creates an equal amount of tokens as ether sent. The new tokens are created in the `_owner` address require(tokenContract.generateTokens(_owner, tokensPerEther.mul(msg.value))); return true; } /// @dev Internal function to determine if an address is a contract /// @param _addr The address being queried /// @return True if `_addr` is a contract function isContract(address _addr) constant internal returns (bool) { if (_addr == 0) { return false; } uint256 size; assembly { size := extcodesize(_addr) } return (size > 0); } /// @notice `finalizeSale()` ends the EarlyTokenSale. It will generate the platform and team tokens /// and set the controller to the referral fee contract. /// @dev `finalizeSale()` can only be called after the end of the funding period or if the maximum amount is raised. function finalizeSale() onlyController { require(now > endFundingTime || totalCollected >= maximumFunding); require(!finalized); uint256 reservedTokens = 225000000 * 0.35 * 10**18; if (!tokenContract.generateTokens(vaultAddress, reservedTokens)) { revert(); } finalized = true; } ////////// // Testing specific methods ////////// /// @notice This function is overridden by the tests. function getBlockNumber() internal constant returns (uint256) { return block.number; } ////////// // Safety Methods ////////// /// @notice This method can be used by the controller to extract mistakenly /// sent tokens to this contract. /// @param _token The address of the token contract that you want to recover /// set to 0 in case you want to extract ether. function claimTokens(address _token) onlyController { if (_token == 0x0) { controller.transfer(this.balance); return; } ERC20Token token = ERC20Token(_token); uint balance = token.balanceOf(this); token.transfer(controller, balance); ClaimedTokens(_token, controller, balance); } event ClaimedTokens(address indexed _token, address indexed _controller, uint _amount); /// @notice Pauses the contribution if there is any issue function pauseContribution() onlyController { paused = true; } /// @notice Resumes the contribution function resumeContribution() onlyController { paused = false; } modifier notPaused() { require(!paused); _; } }
Notifies the controller about a transfer, for this EarlyTokenSale all transfers are allowed by default and no extra notifications are needed _from The origin of the transfer _to The destination of the transfer _amount The amount of the transfer return False if the controller does not authorize the transfer
function onTransfer(address _from, address _to, uint _amount) returns(bool success) { if ( _from == vaultAddress ) { return true; } return false; }
10,662,354
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./ShackledStructs.sol"; import "./ShackledRenderer.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; contract ShackledIcons is ERC721Enumerable, Ownable { string public currentBaseURI; mapping(uint256 => bytes32) public tokenHashes; constructor() ERC721("ShackledIcons", "ICON") {} /** * @dev Mint token ids to a particular address */ function mint(address to, uint256 tokenId) public onlyOwner { require( tokenHashes[tokenId] != 0x0, "Cannot mint a token that doesn't exist" ); _safeMint(to, tokenId); } function storeTokenHash(uint256 tokenId, bytes32 tokenHash) public onlyOwner { tokenHashes[tokenId] = tokenHash; } function getRenderParamsHash( ShackledStructs.RenderParams calldata renderParams ) public pure returns (bytes32) { return keccak256( abi.encodePacked( abi.encodePacked( renderParams.faces, renderParams.verts, renderParams.cols ), abi.encodePacked( renderParams.objPosition, renderParams.objScale, renderParams.backgroundColor, renderParams.perspCamera, renderParams.backfaceCulling, renderParams.invert, renderParams.wireframe ), _getLightingParamsHash(renderParams.lightingParams) ) ); } function _getLightingParamsHash( ShackledStructs.LightingParams calldata lightingParams ) internal pure returns (bytes32) { return keccak256( abi.encodePacked( lightingParams.applyLighting, lightingParams.lightAmbiPower, lightingParams.lightDiffPower, lightingParams.lightSpecPower, lightingParams.inverseShininess, lightingParams.lightPos, lightingParams.lightColSpec, lightingParams.lightColDiff, lightingParams.lightColAmbi ) ); } function render( uint256 tokenId, int256 canvasDim_, ShackledStructs.RenderParams calldata renderParams ) public view returns (string memory) { bytes32 tokenHash = getRenderParamsHash(renderParams); require(tokenHash == tokenHashes[tokenId], "Token hash mismatch"); return ShackledRenderer.render(renderParams, canvasDim_, true); } function setBaseURI(string memory baseURI_) public onlyOwner { currentBaseURI = baseURI_; } function _baseURI() internal view virtual override returns (string memory) { return currentBaseURI; } } // SPDX-License-Identifier: Unlicense pragma solidity ^0.8.0; library ShackledStructs { struct Metadata { string colorScheme; /// name of the color scheme string geomSpec; /// name of the geometry specification uint256 nPrisms; /// number of prisms made string pseudoSymmetry; /// horizontal, vertical, diagonal string wireframe; /// enabled or disabled string inversion; /// enabled or disabled } struct RenderParams { uint256[3][] faces; /// index of verts and colorss used for each face (triangle) int256[3][] verts; /// x, y, z coordinates used in the geometry int256[3][] cols; /// colors of each vert int256[3] objPosition; /// position to place the object int256 objScale; /// scalar for the object int256[3][2] backgroundColor; /// color of the background (gradient) LightingParams lightingParams; /// parameters for the lighting bool perspCamera; /// true = perspective camera, false = orthographic bool backfaceCulling; /// whether to implement backface culling (saves gas!) bool invert; /// whether to invert colors in the final encoding stage bool wireframe; /// whether to only render edges } /// struct for testing lighting struct LightingParams { bool applyLighting; /// true = apply lighting, false = don't apply lighting int256 lightAmbiPower; /// power of the ambient light int256 lightDiffPower; /// power of the diffuse light int256 lightSpecPower; /// power of the specular light uint256 inverseShininess; /// shininess of the material int256[3] lightPos; /// position of the light int256[3] lightColSpec; /// color of the specular light int256[3] lightColDiff; /// color of the diffuse light int256[3] lightColAmbi; /// color of the ambient light } } // // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.0; import "./ShackledCoords.sol"; import "./ShackledRasteriser.sol"; import "./ShackledUtils.sol"; import "./ShackledStructs.sol"; library ShackledRenderer { uint256 constant outputHeight = 512; uint256 constant outputWidth = 512; /** @dev take any geometry, render it, and return a bitmap image inside an SVG this can be called to render the Shackled art collection (the output of ShackledGenesis.sol) or any other custom made geometry */ function render( ShackledStructs.RenderParams memory renderParams, int256 canvasDim, bool returnSVG ) public view returns (string memory) { /// prepare the fragments int256[12][3][] memory trisFragments = prepareGeometryForRender( renderParams, canvasDim ); /// run Bresenham's line algorithm to rasterize the fragments int256[12][] memory fragments = ShackledRasteriser.rasterise( trisFragments, canvasDim, renderParams.wireframe ); fragments = ShackledRasteriser.depthTesting(fragments, canvasDim); if (renderParams.lightingParams.applyLighting) { /// apply lighting (Blinn phong) fragments = ShackledRasteriser.lightScene( fragments, renderParams.lightingParams ); } /// get the background int256[5][] memory background = ShackledRasteriser.getBackground( canvasDim, renderParams.backgroundColor ); /// place each fragment in an encoded bitmap string memory encodedBitmap = ShackledUtils.getEncodedBitmap( fragments, background, canvasDim, renderParams.invert ); if (returnSVG) { /// insert the bitmap into an encoded svg (to be accepted by OpenSea) return ShackledUtils.getSVGContainer( encodedBitmap, canvasDim, outputHeight, outputWidth ); } else { return encodedBitmap; } } /** @dev prepare the triangles and colors for rasterization */ function prepareGeometryForRender( ShackledStructs.RenderParams memory renderParams, int256 canvasDim ) internal view returns (int256[12][3][] memory) { /// convert geometry and colors from PLY standard into Shackled format /// create the final triangles and colors that will be rendered /// by pulling the numbers out of the faces array /// and using them to index into the verts and colors arrays /// make copies of each coordinate and color int256[3][3][] memory tris = new int256[3][3][]( renderParams.faces.length ); int256[3][3][] memory trisCols = new int256[3][3][]( renderParams.faces.length ); for (uint256 i = 0; i < renderParams.faces.length; i++) { for (uint256 j = 0; j < 3; j++) { for (uint256 k = 0; k < 3; k++) { /// copy the values from verts and cols arrays /// using the faces lookup array to index into them tris[i][j][k] = renderParams.verts[ renderParams.faces[i][j] ][k]; trisCols[i][j][k] = renderParams.cols[ renderParams.faces[i][j] ][k]; } } } /// convert the fragments from model to world space int256[3][] memory vertsWorldSpace = ShackledCoords .convertToWorldSpaceWithModelTransform( tris, renderParams.objScale, renderParams.objPosition ); /// convert the vertices back to triangles in world space int256[3][3][] memory trisWorldSpace = ShackledUtils .unflattenVertsToTris(vertsWorldSpace); /// implement backface culling if (renderParams.backfaceCulling) { (trisWorldSpace, trisCols) = ShackledCoords.backfaceCulling( trisWorldSpace, trisCols ); } /// update vertsWorldSpace vertsWorldSpace = ShackledUtils.flattenTris(trisWorldSpace); /// convert the fragments from world to camera space int256[3][] memory vertsCameraSpace = ShackledCoords .convertToCameraSpaceViaVertexShader( vertsWorldSpace, canvasDim, renderParams.perspCamera ); /// convert the vertices back to triangles in camera space int256[3][3][] memory trisCameraSpace = ShackledUtils .unflattenVertsToTris(vertsCameraSpace); int256[12][3][] memory trisFragments = ShackledRasteriser .initialiseFragments( trisCameraSpace, trisWorldSpace, trisCols, canvasDim ); return trisFragments; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Enumerable.sol) pragma solidity ^0.8.0; import "../ERC721.sol"; import "./IERC721Enumerable.sol"; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.0; import "./ShackledUtils.sol"; import "./ShackledMath.sol"; library ShackledCoords { /** @dev scale and translate the verts this can be effectively disabled with a scale of 1 and translate of [0, 0, 0] */ function convertToWorldSpaceWithModelTransform( int256[3][3][] memory tris, int256 scale, int256[3] memory position ) external view returns (int256[3][] memory) { int256[3][] memory verts = ShackledUtils.flattenTris(tris); // Scale model matrices are easy, just multiply through by the scale value int256[3][] memory scaledVerts = new int256[3][](verts.length); for (uint256 i = 0; i < verts.length; i++) { scaledVerts[i][0] = verts[i][0] * scale + position[0]; scaledVerts[i][1] = verts[i][1] * scale + position[1]; scaledVerts[i][2] = verts[i][2] * scale + position[2]; } return scaledVerts; } /** @dev run backfaceCulling to save future operations on faces that aren't seen by the camera*/ function backfaceCulling( int256[3][3][] memory trisWorldSpace, int256[3][3][] memory trisCols ) external view returns ( int256[3][3][] memory culledTrisWorldSpace, int256[3][3][] memory culledTrisCols ) { culledTrisWorldSpace = new int256[3][3][](trisWorldSpace.length); culledTrisCols = new int256[3][3][](trisCols.length); uint256 nextIx; for (uint256 i = 0; i < trisWorldSpace.length; i++) { int256[3] memory v1 = trisWorldSpace[i][0]; int256[3] memory v2 = trisWorldSpace[i][1]; int256[3] memory v3 = trisWorldSpace[i][2]; int256[3] memory norm = ShackledMath.crossProduct( ShackledMath.vector3Sub(v1, v2), ShackledMath.vector3Sub(v2, v3) ); /// since shackled has a static positioned camera at the origin, /// the points are already in view space, relaxing the backfaceCullingCond int256 backfaceCullingCond = ShackledMath.vector3Dot(v1, norm); if (backfaceCullingCond < 0) { culledTrisWorldSpace[nextIx] = trisWorldSpace[i]; culledTrisCols[nextIx] = trisCols[i]; nextIx++; } } /// remove any empty slots uint256 nToCull = culledTrisWorldSpace.length - nextIx; /// cull uneeded tris assembly { mstore( culledTrisWorldSpace, sub(mload(culledTrisWorldSpace), nToCull) ) } /// cull uneeded cols assembly { mstore(culledTrisCols, sub(mload(culledTrisCols), nToCull)) } } /**@dev calculate verts in camera space */ function convertToCameraSpaceViaVertexShader( int256[3][] memory vertsWorldSpace, int256 canvasDim, bool perspCamera ) external view returns (int256[3][] memory) { // get the camera matrix as a numerator and denominator int256[4][4][2] memory cameraMatrix; if (perspCamera) { cameraMatrix = getCameraMatrixPersp(); } else { cameraMatrix = getCameraMatrixOrth(canvasDim); } int256[4][4] memory nM = cameraMatrix[0]; // camera matrix numerator int256[4][4] memory dM = cameraMatrix[1]; // camera matrix denominator int256[3][] memory verticesCameraSpace = new int256[3][]( vertsWorldSpace.length ); for (uint256 i = 0; i < vertsWorldSpace.length; i++) { // Convert from 3D to 4D homogenous coordinate system int256[3] memory vert = vertsWorldSpace[i]; // Make a copy of vert ("homoVertex") int256[] memory hv = new int256[](vert.length + 1); for (uint256 j = 0; j < vert.length; j++) { hv[j] = vert[j]; } // Insert 1 at final position in copy of vert hv[hv.length - 1] = 1; int256 x = ((hv[0] * nM[0][0]) / dM[0][0]) + ((hv[1] * nM[0][1]) / dM[0][1]) + ((hv[2] * nM[0][2]) / dM[0][2]) + (nM[0][3] / dM[0][3]); int256 y = ((hv[0] * nM[1][0]) / dM[1][0]) + ((hv[1] * nM[1][1]) / dM[1][1]) + ((hv[2] * nM[1][2]) / dM[1][2]) + (nM[1][3] / dM[1][0]); int256 z = ((hv[0] * nM[2][0]) / dM[2][0]) + ((hv[1] * nM[2][1]) / dM[2][1]) + ((hv[2] * nM[2][2]) / dM[2][2]) + (nM[2][3] / dM[2][3]); int256 w = ((hv[0] * nM[3][0]) / dM[3][0]) + ((hv[1] * nM[3][1]) / dM[3][1]) + ((hv[2] * nM[3][2]) / dM[3][2]) + (nM[3][3] / dM[3][3]); if (w != 1) { x = (x * 1e3) / w; y = (y * 1e3) / w; z = (z * 1e3) / w; } // Turn it back into a 3-vector // Add it to the ordered list verticesCameraSpace[i] = [x, y, z]; } return verticesCameraSpace; } /** @dev generate an orthographic camera matrix */ function getCameraMatrixOrth(int256 canvasDim) internal pure returns (int256[4][4][2] memory) { int256 canvasHalf = canvasDim / 2; // Left, right, top, bottom int256 r = ShackledMath.abs(canvasHalf); int256 l = -canvasHalf; int256 t = ShackledMath.abs(canvasHalf); int256 b = -canvasHalf; // Z settings (near and far) /// multiplied by 1e3 int256 n = 1; int256 f = 1024; // Get the orthographic transform matrix // as a numerator and denominator int256[4][4] memory cameraMatrixNum = [ [int256(2), 0, 0, -(r + l)], [int256(0), 2, 0, -(t + b)], [int256(0), 0, -2, -(f + n)], [int256(0), 0, 0, 1] ]; int256[4][4] memory cameraMatrixDen = [ [int256(r - l), 1, 1, (r - l)], [int256(1), (t - b), 1, (t - b)], [int256(1), 1, (f - n), (f - n)], [int256(1), 1, 1, 1] ]; int256[4][4][2] memory cameraMatrix = [ cameraMatrixNum, cameraMatrixDen ]; return cameraMatrix; } /** @dev generate a perspective camera matrix */ function getCameraMatrixPersp() internal pure returns (int256[4][4][2] memory) { // Z settings (near and far) /// multiplied by 1e3 int256 n = 500; int256 f = 501; // Get the perspective transform matrix // as a numerator and denominator // parameter = 1 / tan(fov in degrees / 2) // 0.1763 = 1 / tan(160 / 2) // 1.428 = 1 / tan(70 / 2) // 1.732 = 1 / tan(60 / 2) // 2.145 = 1 / tan(50 / 2) int256[4][4] memory cameraMatrixNum = [ [int256(2145), 0, 0, 0], [int256(0), 2145, 0, 0], [int256(0), 0, f, -f * n], [int256(0), 0, 1, 0] ]; int256[4][4] memory cameraMatrixDen = [ [int256(1000), 1, 1, 1], [int256(1), 1000, 1, 1], [int256(1), 1, f - n, f - n], [int256(1), 1, 1, 1] ]; int256[4][4][2] memory cameraMatrix = [ cameraMatrixNum, cameraMatrixDen ]; return cameraMatrix; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.0; import "./ShackledUtils.sol"; import "./ShackledMath.sol"; import "./ShackledStructs.sol"; library ShackledRasteriser { /// define some constant lighting parameters int256 constant fidelity = int256(100); /// an extra paramater to improve numeric resolution int256 constant lightAmbiPower = int256(1); // Base light colour // was 0.5 int256 constant lightDiffPower = int256(3e9); // Diffused light on surface relative strength int256 constant lightSpecPower = int256(1e7); // Specular reflection on surface relative strength uint256 constant inverseShininess = 10; // 'sharpness' of specular light on surface /// define a scale factor to use in lerp to avoid rounding errors int256 constant lerpScaleFactor = 1e3; /// storing variables used in the fragment lighting struct LightingVars { int256[3] fragCol; int256[3] fragNorm; int256[3] fragPos; int256[3] V; int256 vMag; int256[3] N; int256 nMag; int256[3] L; int256 lMag; int256 falloff; int256 lnDot; int256 lambertian; } /// store variables used in Bresenham's line algorithm struct BresenhamsVars { int256 x; int256 y; int256 dx; int256 dy; int256 sx; int256 sy; int256 err; int256 e2; } /// store variables used when running the scanline algorithm struct ScanlineVars { int256 left; int256 right; int256[12] leftFrag; int256[12] rightFrag; int256 dx; int256 ir; int256 newFragRow; int256 newFragCol; } /** @dev initialise the fragments fragments are defined as: [ canvas_x, canvas_y, depth, col_x, col_y, col_z, normal_x, normal_y, normal_z, world_x, world_y, world_z ] */ function initialiseFragments( int256[3][3][] memory trisCameraSpace, int256[3][3][] memory trisWorldSpace, int256[3][3][] memory trisCols, int256 canvasDim ) external view returns (int256[12][3][] memory) { /// make an array containing the fragments of each triangle (groups of 3 frags) int256[12][3][] memory trisFragments = new int256[12][3][]( trisCameraSpace.length ); // First convert from camera space to screen space within each triangle for (uint256 t = 0; t < trisCameraSpace.length; t++) { int256[3][3] memory tri = trisCameraSpace[t]; /// initialise an array for three fragments, each of len 9 int256[12][3] memory triFragments; // First calculate the fragments that belong to defined vertices for (uint256 v = 0; v < 3; v++) { int256[12] memory fragment; // first convert to screen space // mapping from -1e3 -> 1e3 to account for the original geom being on order of 1e3 fragment[0] = ShackledMath.mapRangeToRange( tri[v][0], -1e3, 1e3, 0, canvasDim ); fragment[1] = ShackledMath.mapRangeToRange( tri[v][1], -1e3, 1e3, 0, canvasDim ); fragment[2] = tri[v][2]; // Now calculate the normal using the cross product of the edge vectors. This needs to be // done in world space coordinates int256[3] memory thisV = trisWorldSpace[t][(v + 0) % 3]; int256[3] memory nextV = trisWorldSpace[t][(v + 1) % 3]; int256[3] memory prevV = trisWorldSpace[t][(v + 2) % 3]; int256[3] memory norm = ShackledMath.crossProduct( ShackledMath.vector3Sub(prevV, thisV), ShackledMath.vector3Sub(thisV, nextV) ); // Now attach the colour (in 0 -> 255 space) fragment[3] = (trisCols[t][v][0]); fragment[4] = (trisCols[t][v][1]); fragment[5] = (trisCols[t][v][2]); // And the normal (inverted) fragment[6] = -norm[0]; fragment[7] = -norm[1]; fragment[8] = -norm[2]; // And the world position of this vertex to the frag fragment[9] = thisV[0]; fragment[10] = thisV[1]; fragment[11] = thisV[2]; // These are just the fragments attached to // the given vertices triFragments[v] = fragment; } trisFragments[t] = triFragments; } return trisFragments; } /** @dev rasterize fragments onto a canvas */ function rasterise( int256[12][3][] memory trisFragments, int256 canvasDim, bool wireframe ) external view returns (int256[12][] memory) { /// determine the upper limits of the inner Bresenham's result uint256 canvasHypot = uint256(ShackledMath.hypot(canvasDim, canvasDim)); /// initialise a new array /// for each trisFragments we will get 3 results from bresenhams /// maximum of 1 per pixel (canvasDim**2) int256[12][] memory fragments = new int256[12][]( 3 * uint256(canvasDim)**2 ); uint256 nextFragmentsIx = 0; for (uint256 t = 0; t < trisFragments.length; t++) { // prepare the variables required int256[12] memory fa; int256[12] memory fb; uint256 nextBresTriFragmentIx = 0; /// create an array to hold the bresenham results /// this may cause an out of bounds error if there are a very large number of fragments /// (e.g. many that are 'off screen') int256[12][] memory bresTriFragments = new int256[12][]( canvasHypot * 10 ); // for each pair of fragments, run bresenhams and extend bresTriFragments with the output // this replaces the three push(...modified_bresenhams_algorhtm) statements in JS for (uint256 i = 0; i < 3; i++) { if (i == 0) { fa = trisFragments[t][0]; fb = trisFragments[t][1]; } else if (i == 1) { fa = trisFragments[t][1]; fb = trisFragments[t][2]; } else { fa = trisFragments[t][2]; fb = trisFragments[t][0]; } // run the bresenhams algorithm ( bresTriFragments, nextBresTriFragmentIx ) = runBresenhamsAlgorithm( fa, fb, canvasDim, bresTriFragments, nextBresTriFragmentIx ); } bresTriFragments = ShackledUtils.clipArray12ToLength( bresTriFragments, nextBresTriFragmentIx ); if (wireframe) { /// only store the edges for (uint256 j = 0; j < bresTriFragments.length; j++) { fragments[nextFragmentsIx] = bresTriFragments[j]; nextFragmentsIx++; } } else { /// fill the triangle (fragments, nextFragmentsIx) = runScanline( bresTriFragments, fragments, nextFragmentsIx, canvasDim ); } } fragments = ShackledUtils.clipArray12ToLength( fragments, nextFragmentsIx ); return fragments; } /** @dev run Bresenham's line algorithm on a pair of fragments */ function runBresenhamsAlgorithm( int256[12] memory f1, int256[12] memory f2, int256 canvasDim, int256[12][] memory bresTriFragments, uint256 nextBresTriFragmentIx ) internal view returns (int256[12][] memory, uint256) { /// initiate a new set of vars BresenhamsVars memory vars; int256[12] memory fa; int256[12] memory fb; /// determine which fragment has a greater magnitude /// and set it as the destination (always order a given pair of edges the same) if ( (f1[0]**2 + f1[1]**2 + f1[2]**2) < (f2[0]**2 + f2[1]**2 + f2[2]**2) ) { fa = f1; fb = f2; } else { fa = f2; fb = f1; } vars.x = fa[0]; vars.y = fa[1]; vars.dx = ShackledMath.abs(fb[0] - fa[0]); vars.dy = -ShackledMath.abs(fb[1] - fa[1]); int256 mag = ShackledMath.hypot(vars.dx, -vars.dy); if (fa[0] < fb[0]) { vars.sx = 1; } else { vars.sx = -1; } if (fa[1] < fb[1]) { vars.sy = 1; } else { vars.sy = -1; } vars.err = vars.dx + vars.dy; vars.e2 = 0; // get the bresenhams output for this fragment pair (fa & fb) if (mag == 0) { bresTriFragments[nextBresTriFragmentIx] = fa; bresTriFragments[nextBresTriFragmentIx + 1] = fb; nextBresTriFragmentIx += 2; } else { // when mag is not 0, // the length of the result will be max of upperLimitInner // but will be clipped to remove any empty slots (bresTriFragments, nextBresTriFragmentIx) = bresenhamsInner( vars, mag, fa, fb, canvasDim, bresTriFragments, nextBresTriFragmentIx ); } return (bresTriFragments, nextBresTriFragmentIx); } /** @dev run the inner loop of Bresenham's line algorithm on a pair of fragments * (preventing stack too deep) */ function bresenhamsInner( BresenhamsVars memory vars, int256 mag, int256[12] memory fa, int256[12] memory fb, int256 canvasDim, int256[12][] memory bresTriFragments, uint256 nextBresTriFragmentIx ) internal view returns (int256[12][] memory, uint256) { // define variables to be used in the inner loop int256 ir; int256 h; /// loop through all fragments while (!(vars.x == fb[0] && vars.y == fb[1])) { /// get hypotenuse length of fragment a h = ShackledMath.hypot(fa[0] - vars.x, fa[1] - vars.y); assembly { ir := div(mul(lerpScaleFactor, h), mag) } // only add the fragment if it falls within the canvas /// create a new fragment by linear interpolation between a and b int256[12] memory newFragment = ShackledMath.vector12Lerp( fa, fb, ir, lerpScaleFactor ); newFragment[0] = vars.x; newFragment[1] = vars.y; /// save this fragment bresTriFragments[nextBresTriFragmentIx] = newFragment; ++nextBresTriFragmentIx; /// update variables to use in next iteration vars.e2 = 2 * vars.err; if (vars.e2 >= vars.dy) { vars.err += vars.dy; vars.x += vars.sx; } if (vars.e2 <= vars.dx) { vars.err += vars.dx; vars.y += vars.sy; } } /// save fragment 2 bresTriFragments[nextBresTriFragmentIx] = fb; ++nextBresTriFragmentIx; return (bresTriFragments, nextBresTriFragmentIx); } /** @dev run the scan line algorithm to fill the raster */ function runScanline( int256[12][] memory bresTriFragments, int256[12][] memory fragments, uint256 nextFragmentsIx, int256 canvasDim ) internal view returns (int256[12][] memory, uint256) { /// make a 2d array with length = num of output rows ( int256[][] memory rowFragIndices, uint256[] memory nextIxFragRows ) = getRowFragIndices(bresTriFragments, canvasDim); /// initialise a struct to hold the scanline vars ScanlineVars memory slVars; // Now iterate through the list of fragments that live in a single row for (uint256 i = 0; i < rowFragIndices.length; i++) { /// Get the left most fragment slVars.left = 4096; /// Get the right most fragment slVars.right = -4096; /// loop through the fragments in this row /// and check that a fragment was written to this row for (uint256 j = 0; j < nextIxFragRows[i]; j++) { /// What's the current fragment that we're looking at int256 fragX = bresTriFragments[uint256(rowFragIndices[i][j])][ 0 ]; // if it's lefter than our current most left frag then its the new left frag if (fragX < slVars.left) { slVars.left = fragX; slVars.leftFrag = bresTriFragments[ uint256(rowFragIndices[i][j]) ]; } // if it's righter than our current most right frag then its the new right frag if (fragX > slVars.right) { slVars.right = fragX; slVars.rightFrag = bresTriFragments[ uint256(rowFragIndices[i][j]) ]; } } /// now we need to scan from the left to the right fragment /// and interpolate as we go slVars.dx = slVars.right - slVars.left + 1; /// get the row that we're on slVars.newFragRow = slVars.leftFrag[1]; /// check that the new frag's row will be in the canvas bounds if (slVars.newFragRow >= 0 && slVars.newFragRow < canvasDim) { if (slVars.dx > int256(0)) { for (int256 j = 0; j < slVars.dx; j++) { /// calculate the column of the new fragment (its position in the scan) slVars.newFragCol = slVars.leftFrag[0] + j; /// check that the new frag's column will be in the canvas bounds if ( slVars.newFragCol >= 0 && slVars.newFragCol < canvasDim ) { slVars.ir = (j * lerpScaleFactor) / slVars.dx; /// make a new fragment by linear interpolation between left and right frags fragments[nextFragmentsIx] = ShackledMath .vector12Lerp( slVars.leftFrag, slVars.rightFrag, slVars.ir, lerpScaleFactor ); /// update its position fragments[nextFragmentsIx][0] = slVars.newFragCol; fragments[nextFragmentsIx][1] = slVars.newFragRow; nextFragmentsIx++; } } } } } return (fragments, nextFragmentsIx); } /** @dev get the row indices of each fragment in preparation for the scanline alg */ function getRowFragIndices( int256[12][] memory bresTriFragments, int256 canvasDim ) internal view returns (int256[][] memory, uint256[] memory nextIxFragRows) { uint256 canvasDimUnsigned = uint256(canvasDim); // define the length of each outer array so we can push items into it using nextIxFragRows int256[][] memory rowFragIndices = new int256[][](canvasDimUnsigned); // the inner rows can't be longer than bresTriFragments for (uint256 i = 0; i < canvasDimUnsigned; i++) { rowFragIndices[i] = new int256[](bresTriFragments.length); } // make an array the tracks for each row how many items have been pushed into it uint256[] memory nextIxFragRows = new uint256[](canvasDimUnsigned); for (uint256 f = 0; f < bresTriFragments.length; f++) { // get the row index uint256 rowIx = uint256(bresTriFragments[f][1]); // canvas_y if (rowIx >= 0 && rowIx < canvasDimUnsigned) { // get the ix of the next item to be added to the row rowFragIndices[rowIx][nextIxFragRows[rowIx]] = int256(f); ++nextIxFragRows[rowIx]; } } return (rowFragIndices, nextIxFragRows); } /** @dev run depth-testing on all fragments */ function depthTesting(int256[12][] memory fragments, int256 canvasDim) external view returns (int256[12][] memory) { uint256 canvasDimUnsigned = uint256(canvasDim); /// create a 2d array to hold the zValues of the fragments int256[][] memory zValues = ShackledMath.get2dArray( canvasDimUnsigned, canvasDimUnsigned, 0 ); /// create a 2d array to hold the fragIndex of the fragments /// as their depth is compared int256[][] memory fragIndex = ShackledMath.get2dArray( canvasDimUnsigned, canvasDimUnsigned, -1 /// -1 so we can check if a fragment was written to this location ); int256[12][] memory culledFrags = new int256[12][](fragments.length); uint256 nextFragIx = 0; /// iterate through all fragments /// and store the index of the fragment with the largest z value /// at each x, y coordinate for (uint256 i = 0; i < fragments.length; i++) { int256[12] memory frag = fragments[i]; /// x and y must be uint for indexing uint256 fragX = uint256(frag[0]); uint256 fragY = uint256(frag[1]); // console.log("checking frag", i, "z:"); // console.logInt(frag[2]); if ( (fragX < canvasDimUnsigned) && (fragY < canvasDimUnsigned) && fragX >= 0 && fragY >= 0 ) { // if this is the first fragment seen at (fragX, fragY), ie if fragIndex == 0, add it // or if this frag is closer (lower z value) than the current frag at (fragX, fragY), add it if ( fragIndex[fragX][fragY] == -1 || frag[2] >= zValues[fragX][fragY] ) { zValues[fragX][fragY] = frag[2]; fragIndex[fragX][fragY] = int256(i); } } } /// save only the fragments with prefered z values for (uint256 x = 0; x < canvasDimUnsigned; x++) { for (uint256 y = 0; y < canvasDimUnsigned; y++) { int256 fragIx = fragIndex[x][y]; /// ensure we have a valid index if (fragIndex[x][y] != -1) { culledFrags[nextFragIx] = fragments[uint256(fragIx)]; nextFragIx++; } } } return ShackledUtils.clipArray12ToLength(culledFrags, nextFragIx); } /** @dev apply lighting to the scene and update fragments accordingly */ function lightScene( int256[12][] memory fragments, ShackledStructs.LightingParams memory lp ) external view returns (int256[12][] memory) { /// create a struct for the variables to prevent stack too deep LightingVars memory lv; // calculate a constant lighting vector and its magniture lv.L = lp.lightPos; lv.lMag = ShackledMath.vector3Len(lv.L); for (uint256 f = 0; f < fragments.length; f++) { /// get the fragment's color, norm and position lv.fragCol = [fragments[f][3], fragments[f][4], fragments[f][5]]; lv.fragNorm = [fragments[f][6], fragments[f][7], fragments[f][8]]; lv.fragPos = [fragments[f][9], fragments[f][10], fragments[f][11]]; /// calculate the direction to camera / viewer and its magnitude lv.V = ShackledMath.vector3MulScalar(lv.fragPos, -1); lv.vMag = ShackledMath.vector3Len(lv.V); /// calculate the direction of the fragment normaland its magnitude lv.N = lv.fragNorm; lv.nMag = ShackledMath.vector3Len(lv.N); /// calculate the light vector per-fragment // lv.L = ShackledMath.vector3Sub(lp.lightPos, lv.fragPos); // lv.lMag = ShackledMath.vector3Len(lv.L); lv.falloff = lv.lMag**2; /// lighting intensity fall over the scene lv.lnDot = ShackledMath.vector3Dot(lv.L, lv.N); /// implement double-side rendering to account for flipped normals lv.lambertian = ShackledMath.abs(lv.lnDot); int256 specular; if (lv.lambertian > 0) { int256[3] memory normedL = ShackledMath.vector3NormX( lv.L, fidelity ); int256[3] memory normedV = ShackledMath.vector3NormX( lv.V, fidelity ); int256[3] memory H = ShackledMath.vector3Add(normedL, normedV); int256 hnDot = int256( ShackledMath.vector3Dot( ShackledMath.vector3NormX(H, fidelity), ShackledMath.vector3NormX(lv.N, fidelity) ) ); specular = calculateSpecular( lp.lightSpecPower, hnDot, fidelity, lp.inverseShininess ); } // Calculate the colour and write it into the fragment int256[3] memory colAmbi = ShackledMath.vector3Add( lv.fragCol, ShackledMath.vector3MulScalar( lp.lightColAmbi, lp.lightAmbiPower ) ); /// finalise and color the diffuse lighting int256[3] memory colDiff = ShackledMath.vector3MulScalar( lp.lightColDiff, ((lp.lightDiffPower * lv.lambertian) / (lv.lMag * lv.nMag)) / lv.falloff ); /// finalise and color the specular lighting int256[3] memory colSpec = ShackledMath.vector3DivScalar( ShackledMath.vector3MulScalar(lp.lightColSpec, specular), lv.falloff ); // add up the colour components int256[3] memory col = ShackledMath.vector3Add( ShackledMath.vector3Add(colAmbi, colDiff), colSpec ); /// update the fragment's colour in place fragments[f][3] = col[0]; fragments[f][4] = col[1]; fragments[f][5] = col[2]; } return fragments; } /** @dev calculate the specular lighting parameter */ function calculateSpecular( int256 lightSpecPower, int256 hnDot, int256 fidelity, uint256 inverseShininess ) internal pure returns (int256 specular) { int256 specAngle = hnDot > int256(0) ? hnDot : int256(0); assembly { specular := sdiv( mul(lightSpecPower, exp(specAngle, inverseShininess)), exp(fidelity, mul(inverseShininess, 2)) ) } } /** @dev get background gradient that fills the canvas */ function getBackground( int256 canvasDim, int256[3][2] memory backgroundColor ) external view returns (int256[5][] memory) { int256[5][] memory background = new int256[5][](uint256(canvasDim**2)); int256 w = canvasDim; uint256 nextIx = 0; for (int256 i = 0; i < canvasDim; i++) { for (int256 j = 0; j < canvasDim; j++) { // / write coordinates of background pixel background[nextIx][0] = j; /// x background[nextIx][1] = i; /// y // / write colours of background pixel // / get weighted average of top and bottom color according to row (i) background[nextIx][2] = /// r ((backgroundColor[0][0] * i) + (backgroundColor[1][0] * (w - i))) / w; background[nextIx][3] = /// g ((backgroundColor[0][1] * i) + (backgroundColor[1][1] * (w - i))) / w; background[nextIx][4] = /// b ((backgroundColor[0][2] * i) + (backgroundColor[1][2] * (w - i))) / w; ++nextIx; } } return background; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.0; import "./ShackledStructs.sol"; library ShackledUtils { string internal constant TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; /** @dev Flatten 3d tris array into 2d verts */ function flattenTris(int256[3][3][] memory tris) internal pure returns (int256[3][] memory) { /// initialize a dynamic in-memory array int256[3][] memory flattened = new int256[3][](3 * tris.length); for (uint256 i = 0; i < tris.length; i++) { /// tris.length == N // add values to specific index, as cannot push to array in memory flattened[(i * 3) + 0] = tris[i][0]; flattened[(i * 3) + 1] = tris[i][1]; flattened[(i * 3) + 2] = tris[i][2]; } return flattened; } /** @dev Unflatten 2d verts array into 3d tries (inverse of flattenTris function) */ function unflattenVertsToTris(int256[3][] memory verts) internal pure returns (int256[3][3][] memory) { /// initialize an array with length = 1/3 length of verts int256[3][3][] memory tris = new int256[3][3][](verts.length / 3); for (uint256 i = 0; i < verts.length; i += 3) { tris[i / 3] = [verts[i], verts[i + 1], verts[i + 2]]; } return tris; } /** @dev clip an array to a certain length (to trim empty tail slots) */ function clipArray12ToLength(int256[12][] memory arr, uint256 desiredLen) internal pure returns (int256[12][] memory) { uint256 nToCull = arr.length - desiredLen; assembly { mstore(arr, sub(mload(arr), nToCull)) } return arr; } /** @dev convert an unsigned int to a string */ function uint2str(uint256 _i) internal pure returns (string memory _uintAsString) { if (_i == 0) { return "0"; } uint256 j = _i; uint256 len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint256 k = len; while (_i != 0) { k = k - 1; uint8 temp = (48 + uint8(_i - (_i / 10) * 10)); bytes1 b1 = bytes1(temp); bstr[k] = b1; _i /= 10; } return string(bstr); } /** @dev get the hex encoding of various powers of 2 (canvas size options) */ function getHex(uint256 _i) internal pure returns (bytes memory _hex) { if (_i == 8) { return hex"08_00_00_00"; } else if (_i == 16) { return hex"10_00_00_00"; } else if (_i == 32) { return hex"20_00_00_00"; } else if (_i == 64) { return hex"40_00_00_00"; } else if (_i == 128) { return hex"80_00_00_00"; } else if (_i == 256) { return hex"00_01_00_00"; } else if (_i == 512) { return hex"00_02_00_00"; } } /** @dev create an svg container for a bitmap (for display on svg-only platforms) */ function getSVGContainer( string memory encodedBitmap, int256 canvasDim, uint256 outputHeight, uint256 outputWidth ) internal view returns (string memory) { uint256 canvasDimUnsigned = uint256(canvasDim); // construct some elements in memory prior to return string to avoid stack too deep bytes memory imgSize = abi.encodePacked( "width='", ShackledUtils.uint2str(canvasDimUnsigned), "' height='", ShackledUtils.uint2str(canvasDimUnsigned), "'" ); bytes memory canvasSize = abi.encodePacked( "width='", ShackledUtils.uint2str(outputWidth), "' height='", ShackledUtils.uint2str(outputHeight), "'" ); bytes memory scaleStartTag = abi.encodePacked( "<g transform='scale(", ShackledUtils.uint2str(outputWidth / canvasDimUnsigned), ")'>" ); return string( abi.encodePacked( "data:image/svg+xml;base64,", Base64.encode( abi.encodePacked( "<svg xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' ", "shape-rendering='crispEdges' ", canvasSize, ">", scaleStartTag, "<image ", imgSize, " style='image-rendering: pixelated; image-rendering: crisp-edges;' ", "href='", encodedBitmap, "'/></g></svg>" ) ) ) ); } /** @dev converts raw metadata into */ function getAttributes(ShackledStructs.Metadata memory metadata) internal pure returns (bytes memory) { return abi.encodePacked( "{", '"Structure": "', metadata.geomSpec, '", "Chroma": "', metadata.colorScheme, '", "Pseudosymmetry": "', metadata.pseudoSymmetry, '", "Wireframe": "', metadata.wireframe, '", "Inversion": "', metadata.inversion, '", "Prisms": "', uint2str(metadata.nPrisms), '"}' ); } /** @dev create and encode the token's metadata */ function getEncodedMetadata( string memory image, ShackledStructs.Metadata memory metadata, uint256 tokenId ) internal view returns (string memory) { /// get attributes and description here to avoid stack too deep string memory description = '"description": "Shackled is the first general-purpose 3D renderer' " running on the Ethereum blockchain." ' Each piece represents a leap forward in on-chain computer graphics, and the collection itself is an NFT first."'; return string( abi.encodePacked( "data:application/json;base64,", Base64.encode( bytes( string( abi.encodePacked( '{"name": "Shackled Genesis #', uint2str(tokenId), '", ', description, ', "attributes":', getAttributes(metadata), ', "image":"', image, '"}' ) ) ) ) ) ); } // fragment = // [ canvas_x, canvas_y, depth, col_x, col_y, col_z, normal_x, normal_y, normal_z, world_x, world_y, world_z ], /** @dev get an encoded 2d bitmap by combining the object and background fragments */ function getEncodedBitmap( int256[12][] memory fragments, int256[5][] memory background, int256 canvasDim, bool invert ) internal view returns (string memory) { uint256 canvasDimUnsigned = uint256(canvasDim); bytes memory fileHeader = abi.encodePacked( hex"42_4d", // BM hex"36_04_00_00", // size of the bitmap file in bytes (14 (file header) + 40 (info header) + size of raw data (1024)) hex"00_00_00_00", // 2x2 bytes reserved hex"36_00_00_00" // offset of pixels in bytes ); bytes memory infoHeader = abi.encodePacked( hex"28_00_00_00", // size of the header in bytes (40) getHex(canvasDimUnsigned), // width in pixels 32 getHex(canvasDimUnsigned), // height in pixels 32 hex"01_00", // number of color plans (must be 1) hex"18_00", // number of bits per pixel (24) hex"00_00_00_00", // type of compression (none) hex"00_04_00_00", // size of the raw bitmap data (1024) hex"C4_0E_00_00", // horizontal resolution hex"C4_0E_00_00", // vertical resolution hex"00_00_00_00", // number of used colours hex"05_00_00_00" // number of important colours ); bytes memory headers = abi.encodePacked(fileHeader, infoHeader); /// create a container for the bitmap's bytes bytes memory bytesArray = new bytes(3 * canvasDimUnsigned**2); /// write the background first so it is behind the fragments bytesArray = writeBackgroundToBytesArray( background, bytesArray, canvasDimUnsigned, invert ); bytesArray = writeFragmentsToBytesArray( fragments, bytesArray, canvasDimUnsigned, invert ); return string( abi.encodePacked( "data:image/bmp;base64,", Base64.encode(BytesUtils.MergeBytes(headers, bytesArray)) ) ); } /** @dev write the fragments to the bytes array */ function writeFragmentsToBytesArray( int256[12][] memory fragments, bytes memory bytesArray, uint256 canvasDimUnsigned, bool invert ) internal pure returns (bytes memory) { /// loop through each fragment /// and write it's color into bytesArray in its canvas equivelant position for (uint256 i = 0; i < fragments.length; i++) { /// check if x and y are both greater than 0 if ( uint256(fragments[i][0]) >= 0 && uint256(fragments[i][1]) >= 0 ) { /// calculating the starting bytesArray ix for this fragment's colors uint256 flatIx = ((canvasDimUnsigned - uint256(fragments[i][1]) - 1) * canvasDimUnsigned + (canvasDimUnsigned - uint256(fragments[i][0]) - 1)) * 3; /// red uint256 r = fragments[i][3] > 255 ? 255 : uint256(fragments[i][3]); /// green uint256 g = fragments[i][4] > 255 ? 255 : uint256(fragments[i][4]); /// blue uint256 b = fragments[i][5] > 255 ? 255 : uint256(fragments[i][5]); if (invert) { r = 255 - r; g = 255 - g; b = 255 - b; } bytesArray[flatIx + 0] = bytes1(uint8(b)); bytesArray[flatIx + 1] = bytes1(uint8(g)); bytesArray[flatIx + 2] = bytes1(uint8(r)); } } return bytesArray; } /** @dev write the fragments to the bytes array using a separate function from above to account for variable input size */ function writeBackgroundToBytesArray( int256[5][] memory background, bytes memory bytesArray, uint256 canvasDimUnsigned, bool invert ) internal pure returns (bytes memory) { /// loop through each fragment /// and write it's color into bytesArray in its canvas equivelant position for (uint256 i = 0; i < background.length; i++) { /// check if x and y are both greater than 0 if ( uint256(background[i][0]) >= 0 && uint256(background[i][1]) >= 0 ) { /// calculating the starting bytesArray ix for this fragment's colors uint256 flatIx = (uint256(background[i][1]) * canvasDimUnsigned + uint256(background[i][0])) * 3; // red uint256 r = background[i][2] > 255 ? 255 : uint256(background[i][2]); /// green uint256 g = background[i][3] > 255 ? 255 : uint256(background[i][3]); // blue uint256 b = background[i][4] > 255 ? 255 : uint256(background[i][4]); if (invert) { r = 255 - r; g = 255 - g; b = 255 - b; } bytesArray[flatIx + 0] = bytes1(uint8(b)); bytesArray[flatIx + 1] = bytes1(uint8(g)); bytesArray[flatIx + 2] = bytes1(uint8(r)); } } return bytesArray; } } /// [MIT License] /// @title Base64 /// @notice Provides a function for encoding some bytes in base64 /// @author Brecht Devos <[email protected]> library Base64 { bytes internal constant TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; /// @notice Encodes some bytes to the base64 representation function encode(bytes memory data) internal view returns (string memory) { uint256 len = data.length; if (len == 0) return ""; // multiply by 4/3 rounded up uint256 encodedLen = 4 * ((len + 2) / 3); // Add some extra buffer at the end bytes memory result = new bytes(encodedLen + 32); bytes memory table = TABLE; assembly { let tablePtr := add(table, 1) let resultPtr := add(result, 32) for { let i := 0 } lt(i, len) { } { i := add(i, 3) let input := and(mload(add(data, i)), 0xffffff) let out := mload(add(tablePtr, and(shr(18, input), 0x3F))) out := shl(8, out) out := add( out, and(mload(add(tablePtr, and(shr(12, input), 0x3F))), 0xFF) ) out := shl(8, out) out := add( out, and(mload(add(tablePtr, and(shr(6, input), 0x3F))), 0xFF) ) out := shl(8, out) out := add( out, and(mload(add(tablePtr, and(input, 0x3F))), 0xFF) ) out := shl(224, out) mstore(resultPtr, out) resultPtr := add(resultPtr, 4) } switch mod(len, 3) case 1 { mstore(sub(resultPtr, 2), shl(240, 0x3d3d)) } case 2 { mstore(sub(resultPtr, 1), shl(248, 0x3d)) } mstore(result, encodedLen) } return string(result); } } library BytesUtils { function char(bytes1 b) internal view returns (bytes1 c) { if (uint8(b) < 10) return bytes1(uint8(b) + 0x30); else return bytes1(uint8(b) + 0x57); } function bytes32string(bytes32 b32) internal view returns (string memory out) { bytes memory s = new bytes(64); for (uint32 i = 0; i < 32; i++) { bytes1 b = bytes1(b32[i]); bytes1 hi = bytes1(uint8(b) / 16); bytes1 lo = bytes1(uint8(b) - 16 * uint8(hi)); s[i * 2] = char(hi); s[i * 2 + 1] = char(lo); } out = string(s); } function hach(string memory value) internal view returns (string memory) { return bytes32string(sha256(abi.encodePacked(value))); } function MergeBytes(bytes memory a, bytes memory b) internal pure returns (bytes memory c) { // Store the length of the first array uint256 alen = a.length; // Store the length of BOTH arrays uint256 totallen = alen + b.length; // Count the loops required for array a (sets of 32 bytes) uint256 loopsa = (a.length + 31) / 32; // Count the loops required for array b (sets of 32 bytes) uint256 loopsb = (b.length + 31) / 32; assembly { let m := mload(0x40) // Load the length of both arrays to the head of the new bytes array mstore(m, totallen) // Add the contents of a to the array for { let i := 0 } lt(i, loopsa) { i := add(1, i) } { mstore( add(m, mul(32, add(1, i))), mload(add(a, mul(32, add(1, i)))) ) } // Add the contents of b to the array for { let i := 0 } lt(i, loopsb) { i := add(1, i) } { mstore( add(m, add(mul(32, add(1, i)), alen)), mload(add(b, mul(32, add(1, i)))) ) } mstore(0x40, add(m, add(32, totallen))) c := m } } } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.0; library ShackledMath { /** @dev Get the minimum of two numbers */ function min(int256 a, int256 b) internal pure returns (int256) { return a < b ? a : b; } /** @dev Get the maximum of two numbers */ function max(int256 a, int256 b) internal pure returns (int256) { return a > b ? a : b; } /** @dev perform a modulo operation, with support for negative numbers */ function mod(int256 n, int256 m) internal pure returns (int256) { if (n < 0) { return ((n % m) + m) % m; } else { return n % m; } } /** @dev 'randomly' select n numbers between 0 and m (useful for getting a randomly sampled index) */ function randomIdx( bytes32 seedModifier, uint256 n, // number of elements to select uint256 m // max value of elements ) internal pure returns (uint256[] memory) { uint256[] memory result = new uint256[](n); for (uint256 i = 0; i < n; i++) { result[i] = uint256(keccak256(abi.encodePacked(seedModifier, i))) % m; } return result; } /** @dev create a 2d array and fill with a single value */ function get2dArray( uint256 m, uint256 q, int256 value ) internal pure returns (int256[][] memory) { /// Create a matrix of values with dimensions (m, q) int256[][] memory rows = new int256[][](m); for (uint256 i = 0; i < m; i++) { int256[] memory row = new int256[](q); for (uint256 j = 0; j < q; j++) { row[j] = value; } rows[i] = row; } return rows; } /** @dev get the absolute of a number */ function abs(int256 x) internal pure returns (int256) { assembly { if slt(x, 0) { x := sub(0, x) } } return x; } /** @dev get the square root of a number */ function sqrt(int256 y) internal pure returns (int256 z) { assembly { if sgt(y, 3) { z := y let x := add(div(y, 2), 1) for { } slt(x, z) { } { z := x x := div(add(div(y, x), x), 2) } } if and(slt(y, 4), sgt(y, 0)) { z := 1 } } } /** @dev get the hypotenuse of a triangle given the length of 2 sides */ function hypot(int256 x, int256 y) internal pure returns (int256) { int256 sumsq; assembly { let xsq := mul(x, x) let ysq := mul(y, y) sumsq := add(xsq, ysq) } return sqrt(sumsq); } /** @dev addition between two vectors (size 3) */ function vector3Add(int256[3] memory v1, int256[3] memory v2) internal pure returns (int256[3] memory result) { assembly { mstore(result, add(mload(v1), mload(v2))) mstore( add(result, 0x20), add(mload(add(v1, 0x20)), mload(add(v2, 0x20))) ) mstore( add(result, 0x40), add(mload(add(v1, 0x40)), mload(add(v2, 0x40))) ) } } /** @dev subtraction between two vectors (size 3) */ function vector3Sub(int256[3] memory v1, int256[3] memory v2) internal pure returns (int256[3] memory result) { assembly { mstore(result, sub(mload(v1), mload(v2))) mstore( add(result, 0x20), sub(mload(add(v1, 0x20)), mload(add(v2, 0x20))) ) mstore( add(result, 0x40), sub(mload(add(v1, 0x40)), mload(add(v2, 0x40))) ) } } /** @dev multiply a vector (size 3) by a constant */ function vector3MulScalar(int256[3] memory v, int256 a) internal pure returns (int256[3] memory result) { assembly { mstore(result, mul(mload(v), a)) mstore(add(result, 0x20), mul(mload(add(v, 0x20)), a)) mstore(add(result, 0x40), mul(mload(add(v, 0x40)), a)) } } /** @dev divide a vector (size 3) by a constant */ function vector3DivScalar(int256[3] memory v, int256 a) internal pure returns (int256[3] memory result) { assembly { mstore(result, sdiv(mload(v), a)) mstore(add(result, 0x20), sdiv(mload(add(v, 0x20)), a)) mstore(add(result, 0x40), sdiv(mload(add(v, 0x40)), a)) } } /** @dev get the length of a vector (size 3) */ function vector3Len(int256[3] memory v) internal pure returns (int256) { int256 res; assembly { let x := mload(v) let y := mload(add(v, 0x20)) let z := mload(add(v, 0x40)) res := add(add(mul(x, x), mul(y, y)), mul(z, z)) } return sqrt(res); } /** @dev scale and then normalise a vector (size 3) */ function vector3NormX(int256[3] memory v, int256 fidelity) internal pure returns (int256[3] memory result) { int256 l = vector3Len(v); assembly { mstore(result, sdiv(mul(fidelity, mload(add(v, 0x40))), l)) mstore( add(result, 0x20), sdiv(mul(fidelity, mload(add(v, 0x20))), l) ) mstore(add(result, 0x40), sdiv(mul(fidelity, mload(v)), l)) } } /** @dev get the dot-product of two vectors (size 3) */ function vector3Dot(int256[3] memory v1, int256[3] memory v2) internal view returns (int256 result) { assembly { result := add( add( mul(mload(v1), mload(v2)), mul(mload(add(v1, 0x20)), mload(add(v2, 0x20))) ), mul(mload(add(v1, 0x40)), mload(add(v2, 0x40))) ) } } /** @dev get the cross product of two vectors (size 3) */ function crossProduct(int256[3] memory v1, int256[3] memory v2) internal pure returns (int256[3] memory result) { assembly { mstore( result, sub( mul(mload(add(v1, 0x20)), mload(add(v2, 0x40))), mul(mload(add(v1, 0x40)), mload(add(v2, 0x20))) ) ) mstore( add(result, 0x20), sub( mul(mload(add(v1, 0x40)), mload(v2)), mul(mload(v1), mload(add(v2, 0x40))) ) ) mstore( add(result, 0x40), sub( mul(mload(v1), mload(add(v2, 0x20))), mul(mload(add(v1, 0x20)), mload(v2)) ) ) } } /** @dev linearly interpolate between two vectors (size 12) */ function vector12Lerp( int256[12] memory v1, int256[12] memory v2, int256 ir, int256 scaleFactor ) internal view returns (int256[12] memory result) { int256[12] memory vd = vector12Sub(v2, v1); // loop through all 12 items assembly { let ix for { let i := 0 } lt(i, 0xC) { // (i < 12) i := add(i, 1) } { /// get index of the next element ix := mul(i, 0x20) /// store into the result array mstore( add(result, ix), add( // v1[i] + (ir * vd[i]) / 1e3 mload(add(v1, ix)), sdiv(mul(ir, mload(add(vd, ix))), 1000) ) ) } } } /** @dev subtraction between two vectors (size 12) */ function vector12Sub(int256[12] memory v1, int256[12] memory v2) internal view returns (int256[12] memory result) { // loop through all 12 items assembly { let ix for { let i := 0 } lt(i, 0xC) { // (i < 12) i := add(i, 1) } { /// get index of the next element ix := mul(i, 0x20) /// store into the result array mstore( add(result, ix), sub( // v1[ix] - v2[ix] mload(add(v1, ix)), mload(add(v2, ix)) ) ) } } } /** @dev map a number from one range into another */ function mapRangeToRange( int256 num, int256 inMin, int256 inMax, int256 outMin, int256 outMax ) internal pure returns (int256 res) { assembly { res := add( sdiv( mul(sub(outMax, outMin), sub(num, inMin)), sub(inMax, inMin) ), outMin ) } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); _afterTokenTransfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); _afterTokenTransfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); _afterTokenTransfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol) pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: UNLICENSED pragma solidity >=0.6.0; import "../contracts/ShackledCoords.sol"; contract XShackledCoords { constructor() {} function xconvertToWorldSpaceWithModelTransform(int256[3][3][] calldata tris,int256 scale,int256[3] calldata position) external view returns (int256[3][] memory) { return ShackledCoords.convertToWorldSpaceWithModelTransform(tris,scale,position); } function xbackfaceCulling(int256[3][3][] calldata trisWorldSpace,int256[3][3][] calldata trisCols) external view returns (int256[3][3][] memory, int256[3][3][] memory) { return ShackledCoords.backfaceCulling(trisWorldSpace,trisCols); } function xconvertToCameraSpaceViaVertexShader(int256[3][] calldata vertsWorldSpace,int256 canvasDim,bool perspCamera) external view returns (int256[3][] memory) { return ShackledCoords.convertToCameraSpaceViaVertexShader(vertsWorldSpace,canvasDim,perspCamera); } function xgetCameraMatrixOrth(int256 canvasDim) external pure returns (int256[4][4][2] memory) { return ShackledCoords.getCameraMatrixOrth(canvasDim); } function xgetCameraMatrixPersp() external pure returns (int256[4][4][2] memory) { return ShackledCoords.getCameraMatrixPersp(); } } // SPDX-License-Identifier: UNLICENSED pragma solidity >=0.6.0; import "../contracts/ShackledIcons.sol"; contract XShackledIcons is ShackledIcons { constructor() {} function x_getLightingParamsHash(ShackledStructs.LightingParams calldata lightingParams) external pure returns (bytes32) { return super._getLightingParamsHash(lightingParams); } function x_baseURI() external view returns (string memory) { return super._baseURI(); } function x_transferOwnership(address newOwner) external { return super._transferOwnership(newOwner); } function x_beforeTokenTransfer(address from,address to,uint256 tokenId) external { return super._beforeTokenTransfer(from,to,tokenId); } function x_safeTransfer(address from,address to,uint256 tokenId,bytes calldata _data) external { return super._safeTransfer(from,to,tokenId,_data); } function x_exists(uint256 tokenId) external view returns (bool) { return super._exists(tokenId); } function x_isApprovedOrOwner(address spender,uint256 tokenId) external view returns (bool) { return super._isApprovedOrOwner(spender,tokenId); } function x_safeMint(address to,uint256 tokenId) external { return super._safeMint(to,tokenId); } function x_safeMint(address to,uint256 tokenId,bytes calldata _data) external { return super._safeMint(to,tokenId,_data); } function x_mint(address to,uint256 tokenId) external { return super._mint(to,tokenId); } function x_burn(uint256 tokenId) external { return super._burn(tokenId); } function x_transfer(address from,address to,uint256 tokenId) external { return super._transfer(from,to,tokenId); } function x_approve(address to,uint256 tokenId) external { return super._approve(to,tokenId); } function x_setApprovalForAll(address owner,address operator,bool approved) external { return super._setApprovalForAll(owner,operator,approved); } function x_afterTokenTransfer(address from,address to,uint256 tokenId) external { return super._afterTokenTransfer(from,to,tokenId); } function x_msgSender() external view returns (address) { return super._msgSender(); } function x_msgData() external view returns (bytes memory) { return super._msgData(); } } // SPDX-License-Identifier: UNLICENSED pragma solidity >=0.6.0; import "../contracts/ShackledMath.sol"; contract XShackledMath { constructor() {} function xmin(int256 a,int256 b) external pure returns (int256) { return ShackledMath.min(a,b); } function xmax(int256 a,int256 b) external pure returns (int256) { return ShackledMath.max(a,b); } function xmod(int256 n,int256 m) external pure returns (int256) { return ShackledMath.mod(n,m); } function xrandomIdx(bytes32 seedModifier,uint256 n,uint256 m) external pure returns (uint256[] memory) { return ShackledMath.randomIdx(seedModifier,n,m); } function xget2dArray(uint256 m,uint256 q,int256 value) external pure returns (int256[][] memory) { return ShackledMath.get2dArray(m,q,value); } function xabs(int256 x) external pure returns (int256) { return ShackledMath.abs(x); } function xsqrt(int256 y) external pure returns (int256) { return ShackledMath.sqrt(y); } function xhypot(int256 x,int256 y) external pure returns (int256) { return ShackledMath.hypot(x,y); } function xvector3Add(int256[3] calldata v1,int256[3] calldata v2) external pure returns (int256[3] memory) { return ShackledMath.vector3Add(v1,v2); } function xvector3Sub(int256[3] calldata v1,int256[3] calldata v2) external pure returns (int256[3] memory) { return ShackledMath.vector3Sub(v1,v2); } function xvector3MulScalar(int256[3] calldata v,int256 a) external pure returns (int256[3] memory) { return ShackledMath.vector3MulScalar(v,a); } function xvector3DivScalar(int256[3] calldata v,int256 a) external pure returns (int256[3] memory) { return ShackledMath.vector3DivScalar(v,a); } function xvector3Len(int256[3] calldata v) external pure returns (int256) { return ShackledMath.vector3Len(v); } function xvector3NormX(int256[3] calldata v,int256 fidelity) external pure returns (int256[3] memory) { return ShackledMath.vector3NormX(v,fidelity); } function xvector3Dot(int256[3] calldata v1,int256[3] calldata v2) external view returns (int256) { return ShackledMath.vector3Dot(v1,v2); } function xcrossProduct(int256[3] calldata v1,int256[3] calldata v2) external pure returns (int256[3] memory) { return ShackledMath.crossProduct(v1,v2); } function xvector12Lerp(int256[12] calldata v1,int256[12] calldata v2,int256 ir,int256 scaleFactor) external view returns (int256[12] memory) { return ShackledMath.vector12Lerp(v1,v2,ir,scaleFactor); } function xvector12Sub(int256[12] calldata v1,int256[12] calldata v2) external view returns (int256[12] memory) { return ShackledMath.vector12Sub(v1,v2); } function xmapRangeToRange(int256 num,int256 inMin,int256 inMax,int256 outMin,int256 outMax) external pure returns (int256) { return ShackledMath.mapRangeToRange(num,inMin,inMax,outMin,outMax); } } // SPDX-License-Identifier: UNLICENSED pragma solidity >=0.6.0; import "../contracts/ShackledRasteriser.sol"; contract XShackledRasteriser { constructor() {} function xinitialiseFragments(int256[3][3][] calldata trisCameraSpace,int256[3][3][] calldata trisWorldSpace,int256[3][3][] calldata trisCols,int256 canvasDim) external view returns (int256[12][3][] memory) { return ShackledRasteriser.initialiseFragments(trisCameraSpace,trisWorldSpace,trisCols,canvasDim); } function xrasterise(int256[12][3][] calldata trisFragments,int256 canvasDim,bool wireframe) external view returns (int256[12][] memory) { return ShackledRasteriser.rasterise(trisFragments,canvasDim,wireframe); } function xrunBresenhamsAlgorithm(int256[12] calldata f1,int256[12] calldata f2,int256 canvasDim,int256[12][] calldata bresTriFragments,uint256 nextBresTriFragmentIx) external view returns (int256[12][] memory, uint256) { return ShackledRasteriser.runBresenhamsAlgorithm(f1,f2,canvasDim,bresTriFragments,nextBresTriFragmentIx); } function xbresenhamsInner(ShackledRasteriser.BresenhamsVars calldata vars,int256 mag,int256[12] calldata fa,int256[12] calldata fb,int256 canvasDim,int256[12][] calldata bresTriFragments,uint256 nextBresTriFragmentIx) external view returns (int256[12][] memory, uint256) { return ShackledRasteriser.bresenhamsInner(vars,mag,fa,fb,canvasDim,bresTriFragments,nextBresTriFragmentIx); } function xrunScanline(int256[12][] calldata bresTriFragments,int256[12][] calldata fragments,uint256 nextFragmentsIx,int256 canvasDim) external view returns (int256[12][] memory, uint256) { return ShackledRasteriser.runScanline(bresTriFragments,fragments,nextFragmentsIx,canvasDim); } function xgetRowFragIndices(int256[12][] calldata bresTriFragments,int256 canvasDim) external view returns (int256[][] memory, uint256[] memory) { return ShackledRasteriser.getRowFragIndices(bresTriFragments,canvasDim); } function xdepthTesting(int256[12][] calldata fragments,int256 canvasDim) external view returns (int256[12][] memory) { return ShackledRasteriser.depthTesting(fragments,canvasDim); } function xlightScene(int256[12][] calldata fragments,ShackledStructs.LightingParams calldata lp) external view returns (int256[12][] memory) { return ShackledRasteriser.lightScene(fragments,lp); } function xcalculateSpecular(int256 lightSpecPower,int256 hnDot,int256 fidelity,uint256 inverseShininess) external pure returns (int256) { return ShackledRasteriser.calculateSpecular(lightSpecPower,hnDot,fidelity,inverseShininess); } function xgetBackground(int256 canvasDim,int256[3][2] calldata backgroundColor) external view returns (int256[5][] memory) { return ShackledRasteriser.getBackground(canvasDim,backgroundColor); } } // SPDX-License-Identifier: UNLICENSED pragma solidity >=0.6.0; import "../contracts/ShackledRenderer.sol"; contract XShackledRenderer { constructor() {} function xrender(ShackledStructs.RenderParams calldata renderParams,int256 canvasDim,bool returnSVG) external view returns (string memory) { return ShackledRenderer.render(renderParams,canvasDim,returnSVG); } function xprepareGeometryForRender(ShackledStructs.RenderParams calldata renderParams,int256 canvasDim) external view returns (int256[12][3][] memory) { return ShackledRenderer.prepareGeometryForRender(renderParams,canvasDim); } } // SPDX-License-Identifier: UNLICENSED pragma solidity >=0.6.0; import "../contracts/ShackledStructs.sol"; contract XShackledStructs { constructor() {} } // SPDX-License-Identifier: UNLICENSED pragma solidity >=0.6.0; import "../contracts/ShackledUtils.sol"; contract XShackledUtils { constructor() {} function xflattenTris(int256[3][3][] calldata tris) external pure returns (int256[3][] memory) { return ShackledUtils.flattenTris(tris); } function xunflattenVertsToTris(int256[3][] calldata verts) external pure returns (int256[3][3][] memory) { return ShackledUtils.unflattenVertsToTris(verts); } function xclipArray12ToLength(int256[12][] calldata arr,uint256 desiredLen) external pure returns (int256[12][] memory) { return ShackledUtils.clipArray12ToLength(arr,desiredLen); } function xuint2str(uint256 _i) external pure returns (string memory) { return ShackledUtils.uint2str(_i); } function xgetHex(uint256 _i) external pure returns (bytes memory) { return ShackledUtils.getHex(_i); } function xgetSVGContainer(string calldata encodedBitmap,int256 canvasDim,uint256 outputHeight,uint256 outputWidth) external view returns (string memory) { return ShackledUtils.getSVGContainer(encodedBitmap,canvasDim,outputHeight,outputWidth); } function xgetAttributes(ShackledStructs.Metadata calldata metadata) external pure returns (bytes memory) { return ShackledUtils.getAttributes(metadata); } function xgetEncodedMetadata(string calldata image,ShackledStructs.Metadata calldata metadata,uint256 tokenId) external view returns (string memory) { return ShackledUtils.getEncodedMetadata(image,metadata,tokenId); } function xgetEncodedBitmap(int256[12][] calldata fragments,int256[5][] calldata background,int256 canvasDim,bool invert) external view returns (string memory) { return ShackledUtils.getEncodedBitmap(fragments,background,canvasDim,invert); } function xwriteFragmentsToBytesArray(int256[12][] calldata fragments,bytes calldata bytesArray,uint256 canvasDimUnsigned,bool invert) external pure returns (bytes memory) { return ShackledUtils.writeFragmentsToBytesArray(fragments,bytesArray,canvasDimUnsigned,invert); } function xwriteBackgroundToBytesArray(int256[5][] calldata background,bytes calldata bytesArray,uint256 canvasDimUnsigned,bool invert) external pure returns (bytes memory) { return ShackledUtils.writeBackgroundToBytesArray(background,bytesArray,canvasDimUnsigned,invert); } } contract XBase64 { constructor() {} function xencode(bytes calldata data) external view returns (string memory) { return Base64.encode(data); } } contract XBytesUtils { constructor() {} function xchar(bytes1 b) external view returns (bytes1) { return BytesUtils.char(b); } function xbytes32string(bytes32 b32) external view returns (string memory) { return BytesUtils.bytes32string(b32); } function xhach(string calldata value) external view returns (string memory) { return BytesUtils.hach(value); } function xMergeBytes(bytes calldata a,bytes calldata b) external pure returns (bytes memory) { return BytesUtils.MergeBytes(a,b); } }
converts raw metadata into /
function getAttributes(ShackledStructs.Metadata memory metadata) internal pure returns (bytes memory) { return abi.encodePacked( "{", '"Structure": "', metadata.geomSpec, '", "Chroma": "', metadata.colorScheme, '", "Pseudosymmetry": "', metadata.pseudoSymmetry, '", "Wireframe": "', metadata.wireframe, '", "Inversion": "', metadata.inversion, '", "Prisms": "', uint2str(metadata.nPrisms), '"}' ); }
278,775
//Address: 0x076719c05961a0c3398e558e2199085d32717ca6 //Contract name: Compliance //Balance: 0 Ether //Verification Date: 1/30/2018 //Transacion Count: 1 // CODE STARTS HERE pragma solidity ^0.4.18; /* Polymath compliance protocol is intended to ensure regulatory compliance in the jurisdictions that security tokens are being offered in. The compliance protocol allows security tokens remain interoperable so that anyone can build on top of the Polymath platform and extend it's functionality. */ interface ICompliance { /** * @dev `setRegsitrarAddress` This function set the SecurityTokenRegistrar contract address. * @param _STRegistrar It is the `this` reference of STR contract * @return bool */ function setRegsitrarAddress(address _STRegistrar) public returns (bool); /** * @dev `createTemplate` is a simple function to create a new compliance template * @param _offeringType The name of the security being issued * @param _issuerJurisdiction The jurisdiction id of the issuer * @param _accredited Accreditation status required for investors * @param _KYC KYC provider used by the template * @param _details Details of the offering requirements * @param _expires Timestamp of when the template will expire * @param _fee Amount of POLY to use the template (held in escrow until issuance) * @param _quorum Minimum percent of shareholders which need to vote to freeze * @param _vestingPeriod Length of time to vest funds */ function createTemplate( string _offeringType, bytes32 _issuerJurisdiction, bool _accredited, address _KYC, bytes32 _details, uint256 _expires, uint256 _fee, uint8 _quorum, uint256 _vestingPeriod ) public; /** * @dev Propose a bid for a security token issuance * @param _securityToken The security token being bid on * @param _template The unique template address * @return bool success */ function proposeTemplate( address _securityToken, address _template ) public returns (bool success); /** * @dev Propose a Security Token Offering Contract for an issuance * @param _securityToken The security token being bid on * @param _stoContract The security token offering contract address * @return bool success */ function proposeOfferingContract( address _securityToken, address _stoContract ) public returns (bool success); /** * @dev Cancel a Template proposal if the bid hasn't been accepted * @param _securityToken The security token being bid on * @param _templateProposalIndex The template proposal array index * @return bool success */ function cancelTemplateProposal( address _securityToken, uint256 _templateProposalIndex ) public returns (bool success); /** * @dev Set the STO contract by the issuer. * @param _STOAddress address of the STO contract deployed over the network. * @param _fee fee to be paid in poly to use that contract * @param _vestingPeriod no. of days investor binded to hold the Security token * @param _quorum Minimum percent of shareholders which need to vote to freeze */ function setSTO ( address _STOAddress, uint256 _fee, uint256 _vestingPeriod, uint8 _quorum ) public returns (bool success); /** * @dev Cancel a STO contract proposal if the bid hasn't been accepted * @param _securityToken The security token being bid on * @param _offeringProposalIndex The offering proposal array index * @return bool success */ function cancelOfferingProposal( address _securityToken, uint256 _offeringProposalIndex ) public returns (bool success); /** * @dev `updateTemplateReputation` is a constant function that updates the history of a security token template usage to keep track of previous uses * @param _template The unique template id * @param _templateIndex The array index of the template proposal */ function updateTemplateReputation (address _template, uint8 _templateIndex) external returns (bool success); /** * @dev `updateOfferingReputation` is a constant function that updates the history of a security token offering contract to keep track of previous uses * @param _stoContract The smart contract address of the STO contract * @param _offeringProposalIndex The array index of the security token offering proposal */ function updateOfferingReputation (address _stoContract, uint8 _offeringProposalIndex) external returns (bool success); /** * @dev Get template details by the proposal index * @param _securityTokenAddress The security token ethereum address * @param _templateIndex The array index of the template being checked * @return Template struct */ function getTemplateByProposal(address _securityTokenAddress, uint8 _templateIndex) view public returns ( address _template ); /** * @dev Get security token offering smart contract details by the proposal index * @param _securityTokenAddress The security token ethereum address * @param _offeringProposalIndex The array index of the STO contract being checked * @return Contract struct */ function getOfferingByProposal(address _securityTokenAddress, uint8 _offeringProposalIndex) view public returns ( address stoContract, address auditor, uint256 vestingPeriod, uint8 quorum, uint256 fee ); } /// ERC Token Standard #20 Interface (https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md) interface IERC20 { function balanceOf(address _owner) public view returns (uint256 balance); function transfer(address _to, uint256 _value) public returns (bool success); function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); function approve(address _spender, uint256 _value) public returns (bool success); function allowance(address _owner, address _spender) public view returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } interface ICustomers { /** * @dev Allow new provider applications * @param _providerAddress The provider's public key address * @param _name The provider's name * @param _details A SHA256 hash of the new providers details * @param _fee The fee charged for customer verification */ function newProvider(address _providerAddress, string _name, bytes32 _details, uint256 _fee) public returns (bool success); /** * @dev Change a providers fee * @param _newFee The new fee of the provider */ function changeFee(uint256 _newFee) public returns (bool success); /** * @dev Verify an investor * @param _customer The customer's public key address * @param _countryJurisdiction The country urisdiction code of the customer * @param _divisionJurisdiction The subdivision jurisdiction code of the customer * @param _role The type of customer - investor:1, delegate:2, issuer:3, marketmaker:4, etc. * @param _accredited Whether the customer is accredited or not (only applied to investors) * @param _expires The time the verification expires */ function verifyCustomer( address _customer, bytes32 _countryJurisdiction, bytes32 _divisionJurisdiction, uint8 _role, bool _accredited, uint256 _expires ) public returns (bool success); /////////////////// /// GET Functions ////////////////// /** * @dev Get customer attestation data by KYC provider and customer ethereum address * @param _provider Address of the KYC provider. * @param _customer Address of the customer ethereum address */ function getCustomer(address _provider, address _customer) public constant returns ( bytes32, bytes32, bool, uint8, bool, uint256 ); /** * Get provider details and fee by ethereum address * @param _providerAddress Address of the KYC provider */ function getProvider(address _providerAddress) public constant returns ( string name, uint256 joined, bytes32 details, uint256 fee ); } /* Polymath customer registry is used to ensure regulatory compliance of the investors, provider, and issuers. The customers registry is a central place where ethereum addresses can be whitelisted to purchase certain security tokens based on their verifications by providers. */ /** * @title Customers * @dev Contract use to register the user on the Platform platform */ contract Customers is ICustomers { string public VERSION = "1"; IERC20 POLY; // Instance of the POLY token struct Customer { // Structure use to store the details of the customers bytes32 countryJurisdiction; // Customers country jurisdiction as ex - ISO3166 bytes32 divisionJurisdiction; // Customers sub-division jurisdiction as ex - ISO3166 uint256 joined; // Timestamp when customer register uint8 role; // role of the customer bool verified; // Boolean variable to check the status of the customer whether it is verified or not bool accredited; // Accrediation status of the customer bytes32 proof; // Proof for customer uint256 expires; // Timestamp when customer verification expires } mapping(address => mapping(address => Customer)) public customers; // Customers (kyc provider address => customer address) struct Provider { // KYC/Accreditation Provider string name; // Name of the provider uint256 joined; // Timestamp when provider register bytes32 details; // Details of provider uint256 fee; // Fee charged by the KYC providers } mapping(address => Provider) public providers; // KYC/Accreditation Providers // Notifications event LogNewProvider(address providerAddress, string name, bytes32 details); event LogCustomerVerified(address customer, address provider, uint8 role); // Modifier modifier onlyProvider() { require(providers[msg.sender].details != 0x0); _; } /** * @dev Constructor */ function Customers(address _polyTokenAddress) public { POLY = IERC20(_polyTokenAddress); } /** * @dev Allow new provider applications * @param _providerAddress The provider's public key address * @param _name The provider's name * @param _details A SHA256 hash of the new providers details * @param _fee The fee charged for customer verification */ function newProvider(address _providerAddress, string _name, bytes32 _details, uint256 _fee) public returns (bool success) { require(_providerAddress != address(0)); require(_details != 0x0); require(providers[_providerAddress].details == 0x0); providers[_providerAddress] = Provider(_name, now, _details, _fee); LogNewProvider(_providerAddress, _name, _details); return true; } /** * @dev Change a providers fee * @param _newFee The new fee of the provider */ function changeFee(uint256 _newFee) public returns (bool success) { require(providers[msg.sender].details != 0x0); providers[msg.sender].fee = _newFee; return true; } /** * @dev Verify an investor * @param _customer The customer's public key address * @param _countryJurisdiction The jurisdiction country code of the customer * @param _divisionJurisdiction The jurisdiction subdivision code of the customer * @param _role The type of customer - investor:1, delegate:2, issuer:3, marketmaker:4, etc. * @param _accredited Whether the customer is accredited or not (only applied to investors) * @param _expires The time the verification expires */ function verifyCustomer( address _customer, bytes32 _countryJurisdiction, bytes32 _divisionJurisdiction, uint8 _role, bool _accredited, uint256 _expires ) public onlyProvider returns (bool success) { require(_expires > now); require(POLY.transferFrom(_customer, msg.sender, providers[msg.sender].fee)); customers[msg.sender][_customer].countryJurisdiction = _countryJurisdiction; customers[msg.sender][_customer].divisionJurisdiction = _divisionJurisdiction; customers[msg.sender][_customer].role = _role; customers[msg.sender][_customer].accredited = _accredited; customers[msg.sender][_customer].expires = _expires; customers[msg.sender][_customer].verified = true; LogCustomerVerified(_customer, msg.sender, _role); return true; } /////////////////// /// GET Functions ////////////////// /** * @dev Get customer attestation data by KYC provider and customer ethereum address * @param _provider Address of the KYC provider. * @param _customer Address of the customer ethereum address */ function getCustomer(address _provider, address _customer) public constant returns ( bytes32, bytes32, bool, uint8, bool, uint256 ) { return ( customers[_provider][_customer].countryJurisdiction, customers[_provider][_customer].divisionJurisdiction, customers[_provider][_customer].accredited, customers[_provider][_customer].role, customers[_provider][_customer].verified, customers[_provider][_customer].expires ); } /** * Get provider details and fee by ethereum address * @param _providerAddress Address of the KYC provider */ function getProvider(address _providerAddress) public constant returns ( string name, uint256 joined, bytes32 details, uint256 fee ) { return ( providers[_providerAddress].name, providers[_providerAddress].joined, providers[_providerAddress].details, providers[_providerAddress].fee ); } } interface ITemplate { /** * @dev `addJurisdiction` allows the adding of new jurisdictions to a template * @param _allowedJurisdictions An array of jurisdictions * @param _allowed An array of whether the jurisdiction is allowed to purchase the security or not */ function addJurisdiction(bytes32[] _allowedJurisdictions, bool[] _allowed) public; /** * @dev `addDivisionJurisdiction` allows the adding of new jurisdictions to a template * @param _blockedDivisionJurisdictions An array of jurisdictions * @param _blocked An array of whether the jurisdiction is allowed to purchase the security or not */ function addDivisionJurisdiction(bytes32[] _blockedDivisionJurisdictions, bool[] _blocked) public; /** * @dev `addRole` allows the adding of new roles to be added to whitelist * @param _allowedRoles User roles that can purchase the security */ function addRoles(uint8[] _allowedRoles) public; /** * @notice `updateDetails` * @param _details details of the template need to change * @return allowed boolean variable */ function updateDetails(bytes32 _details) public returns (bool allowed); /** * @dev `finalizeTemplate` is used to finalize template.full compliance process/requirements * @return success */ function finalizeTemplate() public returns (bool success); /** * @dev `checkTemplateRequirements` is a constant function that checks if templates requirements are met * @param _countryJurisdiction The ISO-3166 code of the investors country jurisdiction * @param _divisionJurisdiction The ISO-3166 code of the investors subdivision jurisdiction * @param _accredited Whether the investor is accredited or not * @param _role role of the user * @return allowed boolean variable */ function checkTemplateRequirements( bytes32 _countryJurisdiction, bytes32 _divisionJurisdiction, bool _accredited, uint8 _role ) public constant returns (bool allowed); /** * @dev getTemplateDetails is a constant function that gets template details * @return bytes32 details, bool finalized */ function getTemplateDetails() view public returns (bytes32, bool); /** * @dev `getUsageFees` is a function to get all the details on template usage fees * @return uint256 fee, uint8 quorum, uint256 vestingPeriod, address owner, address KYC */ function getUsageDetails() view public returns (uint256, uint8, uint256, address, address); } /* Polymath compliance template is intended to ensure regulatory compliance in the jurisdictions that security tokens are being offered in. The compliance template allows security tokens to enforce purchase restrictions on chain and keep a log of documents for future auditing purposes. */ /** * @title Template * @dev Template details used for the security token offering to ensure the regulatory compliance */ contract Template is ITemplate { string public VERSION = "1"; address public owner; // Address of the owner of template string public offeringType; // Name of the security being issued bytes32 public issuerJurisdiction; // Variable contains the jurisdiction of the issuer of the template mapping(bytes32 => bool) public allowedJurisdictions; // Mapping that contains the allowed staus of Jurisdictions mapping(bytes32 => bool) public blockedDivisionJurisdictions; // Mapping that contains the allowed staus of Jurisdictions mapping(uint8 => bool) public allowedRoles; // Mapping that contains the allowed status of Roles bool public accredited; // Variable that define the required level of accrediation for the investor address public KYC; // Address of the KYC provider bytes32 details; // Details of the offering requirements bool finalized; // Variable to know the status of the template (complete - true, not complete - false) uint256 public expires; // Timestamp when template expires uint256 fee; // Amount of POLY to use the template (held in escrow until issuance) uint8 quorum; // Minimum percent of shareholders which need to vote to freeze uint256 vestingPeriod; // Length of time to vest funds event DetailsUpdated(bytes32 _prevDetails, bytes32 _newDetails, uint _updateDate); function Template ( address _owner, string _offeringType, bytes32 _issuerJurisdiction, bool _accredited, address _KYC, bytes32 _details, uint256 _expires, uint256 _fee, uint8 _quorum, uint256 _vestingPeriod ) public { require(_KYC != address(0) && _owner != address(0)); require(_fee > 0); require(_details.length > 0 && _expires > now && _issuerJurisdiction.length > 0); require(_quorum > 0 && _quorum <= 100); require(_vestingPeriod > 0); owner = _owner; offeringType = _offeringType; issuerJurisdiction = _issuerJurisdiction; accredited = _accredited; KYC = _KYC; details = _details; finalized = false; expires = _expires; fee = _fee; quorum = _quorum; vestingPeriod = _vestingPeriod; } /** * @dev `addJurisdiction` allows the adding of new jurisdictions to a template * @param _allowedJurisdictions An array of jurisdictions * @param _allowed An array of whether the jurisdiction is allowed to purchase the security or not */ function addJurisdiction(bytes32[] _allowedJurisdictions, bool[] _allowed) public { require(owner == msg.sender); require(_allowedJurisdictions.length == _allowed.length); require(!finalized); for (uint i = 0; i < _allowedJurisdictions.length; ++i) { allowedJurisdictions[_allowedJurisdictions[i]] = _allowed[i]; } } /** * @dev `addJurisdiction` allows the adding of new jurisdictions to a template * @param _blockedDivisionJurisdictions An array of subdivision jurisdictions * @param _blocked An array of whether the subdivision jurisdiction is blocked to purchase the security or not */ function addDivisionJurisdiction(bytes32[] _blockedDivisionJurisdictions, bool[] _blocked) public { require(owner == msg.sender); require(_blockedDivisionJurisdictions.length == _blocked.length); require(!finalized); for (uint i = 0; i < _blockedDivisionJurisdictions.length; ++i) { blockedDivisionJurisdictions[_blockedDivisionJurisdictions[i]] = _blocked[i]; } } /** * @dev `addRole` allows the adding of new roles to be added to whitelist * @param _allowedRoles User roles that can purchase the security */ function addRoles(uint8[] _allowedRoles) public { require(owner == msg.sender); require(!finalized); for (uint i = 0; i < _allowedRoles.length; ++i) { allowedRoles[_allowedRoles[i]] = true; } } /** * @notice `updateDetails` * @param _details details of the template need to change * @return allowed boolean variable */ function updateDetails(bytes32 _details) public returns (bool allowed) { require(_details != 0x0); require(owner == msg.sender); bytes32 prevDetails = details; details = _details; DetailsUpdated(prevDetails, details, now); return true; } /** * @dev `finalizeTemplate` is used to finalize template.full compliance process/requirements * @return success */ function finalizeTemplate() public returns (bool success) { require(owner == msg.sender); finalized = true; return true; } /** * @dev `checkTemplateRequirements` is a constant function that checks if templates requirements are met * @param _countryJurisdiction The ISO-3166 code of the investors country jurisdiction * @param _divisionJurisdiction The ISO-3166 code of the investors subdivision jurisdiction * @param _accredited Whether the investor is accredited or not * @param _role role of the user * @return allowed boolean variable */ function checkTemplateRequirements( bytes32 _countryJurisdiction, bytes32 _divisionJurisdiction, bool _accredited, uint8 _role ) public constant returns (bool allowed) { require(_countryJurisdiction != 0x0); require(allowedJurisdictions[_countryJurisdiction] || !blockedDivisionJurisdictions[_divisionJurisdiction]); require(allowedRoles[_role]); if (accredited) { require(_accredited); } return true; } /** * @dev getTemplateDetails is a constant function that gets template details * @return bytes32 details, bool finalized */ function getTemplateDetails() view public returns (bytes32, bool) { require(expires > now); return (details, finalized); } /** * @dev `getUsageFees` is a function to get all the details on template usage fees * @return uint256 fee, uint8 quorum, uint256 vestingPeriod, address owner, address KYC */ function getUsageDetails() view public returns (uint256, uint8, uint256, address, address) { return (fee, quorum, vestingPeriod, owner, KYC); } } interface ISecurityToken { /** * @dev Set default security token parameters * @param _name Name of the security token * @param _ticker Ticker name of the security * @param _totalSupply Total amount of tokens being created * @param _decimals Decimals for token * @param _owner Ethereum address of the security token owner * @param _maxPoly Amount of maximum poly issuer want to raise * @param _lockupPeriod Length of time raised POLY will be locked up for dispute * @param _quorum Percent of initial investors required to freeze POLY raise * @param _polyTokenAddress Ethereum address of the POLY token contract * @param _polyCustomersAddress Ethereum address of the PolyCustomers contract * @param _polyComplianceAddress Ethereum address of the PolyCompliance contract */ function SecurityToken( string _name, string _ticker, uint256 _totalSupply, uint8 _decimals, address _owner, uint256 _maxPoly, uint256 _lockupPeriod, uint8 _quorum, address _polyTokenAddress, address _polyCustomersAddress, address _polyComplianceAddress ) public; /** * @dev `selectTemplate` Select a proposed template for the issuance * @param _templateIndex Array index of the delegates proposed template * @return bool success */ function selectTemplate(uint8 _templateIndex) public returns (bool success); /** * @dev Update compliance proof hash for the issuance * @param _newMerkleRoot New merkle root hash of the compliance Proofs * @param _complianceProof Compliance Proof hash * @return bool success */ function updateComplianceProof( bytes32 _newMerkleRoot, bytes32 _complianceProof ) public returns (bool success); /** * @dev `selectOfferingProposal` Select an security token offering proposal for the issuance * @param _offeringProposalIndex Array index of the STO proposal * @return bool success */ function selectOfferingProposal ( uint8 _offeringProposalIndex ) public returns (bool success); /** * @dev Start the offering by sending all the tokens to STO contract * @return bool */ function startOffering() external returns (bool success); /** * @dev Add a verified address to the Security Token whitelist * @param _whitelistAddress Address attempting to join ST whitelist * @return bool success */ function addToWhitelist(uint8 KYCProviderIndex, address _whitelistAddress) public returns (bool success); /** * @dev Allow POLY allocations to be withdrawn by owner, delegate, and the STO auditor at appropriate times * @return bool success */ function withdrawPoly() public returns (bool success); /** * @dev Vote to freeze the fee of a certain network participant * @param _recipient The fee recipient being protested * @return bool success */ function voteToFreeze(address _recipient) public returns (bool success); /** * @dev `issueSecurityTokens` is used by the STO to keep track of STO investors * @param _contributor The address of the person whose contributing * @param _amountOfSecurityTokens The amount of ST to pay out. * @param _polyContributed The amount of POLY paid for the security tokens. */ function issueSecurityTokens(address _contributor, uint256 _amountOfSecurityTokens, uint256 _polyContributed) public returns (bool success); /// Get token details function getTokenDetails() view public returns (address, address, bytes32, address, address); /** * @dev Trasfer tokens from one address to another * @param _to Ethereum public address to transfer tokens to * @param _value Amount of tokens to send * @return bool success */ function transfer(address _to, uint256 _value) public returns (bool success); /** * @dev Allows contracts to transfer tokens on behalf of token holders * @param _from Address to transfer tokens from * @param _to Address to send tokens to * @param _value Number of tokens to transfer * @return bool success */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); /** * @dev `balanceOf` used to get the balance of shareholders * @param _owner The address from which the balance will be retrieved * @return The balance */ function balanceOf(address _owner) public constant returns (uint256 balance); /** * @dev Approve transfer of tokens manually * @param _spender Address to approve transfer to * @param _value Amount of tokens to approve for transfer * @return bool success */ function approve(address _spender, uint256 _value) public returns (bool success); /** * @dev Use to get the allowance provided to the spender * @param _owner The address of the account owning tokens * @param _spender The address of the account able to transfer the tokens * @return Amount of remaining tokens allowed to spent */ function allowance(address _owner, address _spender) public constant returns (uint256 remaining); } interface ISTRegistrar { /** * @dev Creates a new Security Token and saves it to the registry * @param _name Name of the security token * @param _ticker Ticker name of the security * @param _totalSupply Total amount of tokens being created * @param _owner Ethereum public key address of the security token owner * @param _maxPoly Amount of maximum poly issuer want to raise * @param _host The host of the security token wizard * @param _fee Fee being requested by the wizard host * @param _type Type of security being tokenized * @param _lockupPeriod Length of time raised POLY will be locked up for dispute * @param _quorum Percent of initial investors required to freeze POLY raise */ function createSecurityToken ( string _name, string _ticker, uint256 _totalSupply, uint8 _decimals, address _owner, uint256 _maxPoly, address _host, uint256 _fee, uint8 _type, uint256 _lockupPeriod, uint8 _quorum ) external; } /** * SafeMath <https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/math/SafeMath.sol/> * Copyright (c) 2016 Smart Contract Solutions, Inc. * Released under the MIT License (MIT) */ /// @title Math operations with safety checks library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } function max64(uint64 a, uint64 b) internal pure returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal pure returns (uint64) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } } contract STO20 { uint256 public startTime; uint256 public endTime; /** * @dev Initializes the STO with certain params * @dev _tokenAddress Address of the security token * @param _startTime Given in UNIX time this is the time that the offering will begin * @param _endTime Given in UNIX time this is the time that the offering will end */ function securityTokenOffering( address _tokenAddress, uint256 _startTime, uint256 _endTime ) external ; } /** * @title SecurityToken * @dev Contract (A Blueprint) that contains the functionalities of the security token */ contract SecurityToken is IERC20 { using SafeMath for uint256; string public VERSION = "1"; IERC20 public POLY; // Instance of the POLY token contract ICompliance public PolyCompliance; // Instance of the Compliance contract ITemplate public Template; // Instance of the Template contract ICustomers public PolyCustomers; // Instance of the Customers contract STO20 public STO; // ERC20 Fields string public name; // Name of the security token uint8 public decimals; // Decimals for the security token it should be 0 as standard string public symbol; // Symbol of the security token address public owner; // Address of the owner of the security token uint256 public totalSupply; // Total number of security token generated mapping(address => mapping(address => uint256)) allowed; // Mapping as same as in ERC20 token mapping(address => uint256) balances; // Array used to store the balances of the security token holders // Template address public delegate; // Address who create the template bytes32 public merkleRoot; // address public KYC; // Address of the KYC provider which aloowed the roles and jurisdictions in the template // Security token shareholders struct Shareholder { // Structure that contains the data of the shareholders address verifier; // verifier - address of the KYC oracle bool allowed; // allowed - whether the shareholder is allowed to transfer or recieve the security token uint8 role; // role - role of the shareholder {1,2,3,4} } mapping(address => Shareholder) public shareholders; // Mapping that holds the data of the shareholder corresponding to investor address // STO bool public isSTOProposed = false; bool public hasOfferingStarted = false; uint256 public maxPoly; // The start and end time of the STO uint256 public startSTO; // Timestamp when Security Token Offering will be start uint256 public endSTO; // Timestamp when Security Token Offering contract will ends // POLY allocations struct Allocation { // Structure that contains the allocation of the POLY for stakeholders uint256 amount; // stakeholders - delegate, issuer(owner), auditor uint256 vestingPeriod; uint8 quorum; uint256 yayVotes; uint256 yayPercent; bool frozen; } mapping(address => mapping(address => bool)) public voted; // Voting mapping mapping(address => Allocation) public allocations; // Mapping that contains the data of allocation corresponding to stakeholder address // Security Token Offering statistics mapping(address => uint256) public contributedToSTO; // Mapping for tracking the POLY contribution by the contributor uint256 public tokensIssuedBySTO = 0; // Flag variable to track the security token issued by the offering contract // Notifications event LogTemplateSet(address indexed _delegateAddress, address _template, address indexed _KYC); event LogUpdatedComplianceProof(bytes32 _merkleRoot, bytes32 _complianceProofHash); event LogSetSTOContract(address _STO, address indexed _STOtemplate, address indexed _auditor, uint256 _startTime, uint256 _endTime); event LogNewWhitelistedAddress(address _KYC, address _shareholder, uint8 _role); event LogNewBlacklistedAddress(address _KYC, address _shareholder); event LogVoteToFreeze(address _recipient, uint256 _yayPercent, uint8 _quorum, bool _frozen); event LogTokenIssued(address indexed _contributor, uint256 _stAmount, uint256 _polyContributed, uint256 _timestamp); //Modifiers modifier onlyOwner() { require (msg.sender == owner); _; } modifier onlyDelegate() { require (msg.sender == delegate); _; } modifier onlyOwnerOrDelegate() { require (msg.sender == delegate || msg.sender == owner); _; } modifier onlySTO() { require (msg.sender == address(STO)); _; } modifier onlyShareholder() { require (shareholders[msg.sender].allowed); _; } /** * @dev Set default security token parameters * @param _name Name of the security token * @param _ticker Ticker name of the security * @param _totalSupply Total amount of tokens being created * @param _owner Ethereum address of the security token owner * @param _maxPoly Amount of maximum poly issuer want to raise * @param _lockupPeriod Length of time raised POLY will be locked up for dispute * @param _quorum Percent of initial investors required to freeze POLY raise * @param _polyTokenAddress Ethereum address of the POLY token contract * @param _polyCustomersAddress Ethereum address of the PolyCustomers contract * @param _polyComplianceAddress Ethereum address of the PolyCompliance contract */ function SecurityToken( string _name, string _ticker, uint256 _totalSupply, uint8 _decimals, address _owner, uint256 _maxPoly, uint256 _lockupPeriod, uint8 _quorum, address _polyTokenAddress, address _polyCustomersAddress, address _polyComplianceAddress ) public { decimals = _decimals; name = _name; symbol = _ticker; owner = _owner; maxPoly = _maxPoly; totalSupply = _totalSupply; balances[_owner] = _totalSupply; POLY = IERC20(_polyTokenAddress); PolyCustomers = ICustomers(_polyCustomersAddress); PolyCompliance = ICompliance(_polyComplianceAddress); allocations[owner] = Allocation(0, _lockupPeriod, _quorum, 0, 0, false); Transfer(0x0, _owner, _totalSupply); } /* function initialiseBalances(uint256) */ /** * @dev `selectTemplate` Select a proposed template for the issuance * @param _templateIndex Array index of the delegates proposed template * @return bool success */ function selectTemplate(uint8 _templateIndex) public onlyOwner returns (bool success) { require(!isSTOProposed); address _template = PolyCompliance.getTemplateByProposal(this, _templateIndex); require(_template != address(0)); Template = ITemplate(_template); var (_fee, _quorum, _vestingPeriod, _delegate, _KYC) = Template.getUsageDetails(); require(POLY.balanceOf(this) >= _fee); allocations[_delegate] = Allocation(_fee, _vestingPeriod, _quorum, 0, 0, false); delegate = _delegate; KYC = _KYC; PolyCompliance.updateTemplateReputation(_template, _templateIndex); LogTemplateSet(_delegate, _template, _KYC); return true; } /** * @dev Update compliance proof hash for the issuance * @param _newMerkleRoot New merkle root hash of the compliance Proofs * @param _merkleRoot Compliance Proof hash * @return bool success */ function updateComplianceProof( bytes32 _newMerkleRoot, bytes32 _merkleRoot ) public onlyOwnerOrDelegate returns (bool success) { merkleRoot = _newMerkleRoot; LogUpdatedComplianceProof(merkleRoot, _merkleRoot); return true; } /** * @dev `selectOfferingProposal` Select an security token offering proposal for the issuance * @param _offeringProposalIndex Array index of the STO proposal * @return bool success */ function selectOfferingProposal (uint8 _offeringProposalIndex) public onlyDelegate returns (bool success) { require(!isSTOProposed); var (_stoContract, _auditor, _vestingPeriod, _quorum, _fee) = PolyCompliance.getOfferingByProposal(this, _offeringProposalIndex); require(_stoContract != address(0)); require(merkleRoot != 0x0); require(delegate != address(0)); require(POLY.balanceOf(this) >= allocations[delegate].amount.add(_fee)); STO = STO20(_stoContract); require(STO.startTime() > now && STO.endTime() > STO.startTime()); allocations[_auditor] = Allocation(_fee, _vestingPeriod, _quorum, 0, 0, false); shareholders[address(STO)] = Shareholder(this, true, 5); startSTO = STO.startTime(); endSTO = STO.endTime(); isSTOProposed = !isSTOProposed; PolyCompliance.updateOfferingReputation(_stoContract, _offeringProposalIndex); LogSetSTOContract(STO, _stoContract, _auditor, startSTO, endSTO); return true; } /** * @dev Start the offering by sending all the tokens to STO contract * @return bool */ function startOffering() onlyOwner external returns (bool success) { require(isSTOProposed); require(!hasOfferingStarted); uint256 tokenAmount = this.balanceOf(msg.sender); require(tokenAmount == totalSupply); balances[STO] = balances[STO].add(tokenAmount); balances[msg.sender] = balances[msg.sender].sub(tokenAmount); hasOfferingStarted = true; Transfer(owner, STO, tokenAmount); return true; } /** * @dev Add a verified address to the Security Token whitelist * The Issuer can add an address to the whitelist by themselves by * creating their own KYC provider and using it to verify the accounts * they want to add to the whitelist. * @param _whitelistAddress Address attempting to join ST whitelist * @return bool success */ function addToWhitelist(address _whitelistAddress) onlyOwner public returns (bool success) { var (countryJurisdiction, divisionJurisdiction, accredited, role, verified, expires) = PolyCustomers.getCustomer(KYC, _whitelistAddress); require(verified && expires > now); require(Template.checkTemplateRequirements(countryJurisdiction, divisionJurisdiction, accredited, role)); shareholders[_whitelistAddress] = Shareholder(msg.sender, true, role); LogNewWhitelistedAddress(msg.sender, _whitelistAddress, role); return true; } /** * @dev Add a verified address to the Security Token blacklist * @param _blacklistAddress Address being added to the blacklist * @return bool success */ function addToBlacklist(address _blacklistAddress) onlyOwner public returns (bool success) { require(shareholders[_blacklistAddress].allowed); shareholders[_blacklistAddress].allowed = false; LogNewBlacklistedAddress(msg.sender, _blacklistAddress); return true; } /** * @dev Allow POLY allocations to be withdrawn by owner, delegate, and the STO auditor at appropriate times * @return bool success */ function withdrawPoly() public returns (bool success) { if (delegate == address(0)) { return POLY.transfer(owner, POLY.balanceOf(this)); } require(now > endSTO + allocations[msg.sender].vestingPeriod); require(!allocations[msg.sender].frozen); require(allocations[msg.sender].amount > 0); require(POLY.transfer(msg.sender, allocations[msg.sender].amount)); allocations[msg.sender].amount = 0; return true; } /** * @dev Vote to freeze the fee of a certain network participant * @param _recipient The fee recipient being protested * @return bool success */ function voteToFreeze(address _recipient) public onlyShareholder returns (bool success) { require(delegate != address(0)); require(now > endSTO); require(now < endSTO.add(allocations[_recipient].vestingPeriod)); require(!voted[msg.sender][_recipient]); voted[msg.sender][_recipient] = true; allocations[_recipient].yayVotes = allocations[_recipient].yayVotes.add(contributedToSTO[msg.sender]); allocations[_recipient].yayPercent = allocations[_recipient].yayVotes.mul(100).div(allocations[owner].amount); if (allocations[_recipient].yayPercent >= allocations[_recipient].quorum) { allocations[_recipient].frozen = true; } LogVoteToFreeze(_recipient, allocations[_recipient].yayPercent, allocations[_recipient].quorum, allocations[_recipient].frozen); return true; } /** * @dev `issueSecurityTokens` is used by the STO to keep track of STO investors * @param _contributor The address of the person whose contributing * @param _amountOfSecurityTokens The amount of ST to pay out. * @param _polyContributed The amount of POLY paid for the security tokens. */ function issueSecurityTokens(address _contributor, uint256 _amountOfSecurityTokens, uint256 _polyContributed) public onlySTO returns (bool success) { // Check whether the offering active or not require(hasOfferingStarted); // The _contributor being issued tokens must be in the whitelist require(shareholders[_contributor].allowed); // Tokens may only be issued while the STO is running require(now >= startSTO && now <= endSTO); // In order to issue the ST, the _contributor first pays in POLY require(POLY.transferFrom(_contributor, this, _polyContributed)); // ST being issued can't be higher than the totalSupply require(tokensIssuedBySTO.add(_amountOfSecurityTokens) <= totalSupply); // POLY contributed can't be higher than maxPoly set by STO require(maxPoly >= allocations[owner].amount.add(_polyContributed)); // Update ST balances (transfers ST from STO to _contributor) balances[STO] = balances[STO].sub(_amountOfSecurityTokens); balances[_contributor] = balances[_contributor].add(_amountOfSecurityTokens); // ERC20 Transfer event Transfer(STO, _contributor, _amountOfSecurityTokens); // Update the amount of tokens issued by STO tokensIssuedBySTO = tokensIssuedBySTO.add(_amountOfSecurityTokens); // Update the amount of POLY a contributor has contributed and allocated to the owner contributedToSTO[_contributor] = contributedToSTO[_contributor].add(_polyContributed); allocations[owner].amount = allocations[owner].amount.add(_polyContributed); LogTokenIssued(_contributor, _amountOfSecurityTokens, _polyContributed, now); return true; } // Get token details function getTokenDetails() view public returns (address, address, bytes32, address, address) { return (Template, delegate, merkleRoot, STO, KYC); } /////////////////////////////////////////////// Customized ERC20 Functions //////////////////////////////////////////////////////////// /** * @dev Trasfer tokens from one address to another * @param _to Ethereum public address to transfer tokens to * @param _value Amount of tokens to send * @return bool success */ function transfer(address _to, uint256 _value) public returns (bool success) { if (shareholders[_to].allowed && shareholders[msg.sender].allowed && balances[msg.sender] >= _value && _value > 0) { balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } else { return false; } } /** * @dev Allows contracts to transfer tokens on behalf of token holders * @param _from Address to transfer tokens from * @param _to Address to send tokens to * @param _value Number of tokens to transfer * @return bool success */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { if (shareholders[_to].allowed && shareholders[_from].allowed && balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) { uint256 _allowance = allowed[_from][msg.sender]; balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = _allowance.sub(_value); balances[_to] = balances[_to].add(_value); Transfer(_from, _to, _value); return true; } else { return false; } } /** * @dev `balanceOf` used to get the balance of shareholders * @param _owner The address from which the balance will be retrieved * @return The balance */ function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; } /** * @dev Approve transfer of tokens manually * @param _spender Address to approve transfer to * @param _value Amount of tokens to approve for transfer * @return bool success */ function approve(address _spender, uint256 _value) public returns (bool success) { require(_value != 0); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Use to get the allowance provided to the spender * @param _owner The address of the account owning tokens * @param _spender The address of the account able to transfer the tokens * @return Amount of remaining tokens allowed to spent */ function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } } /* The Polymath Security Token Registrar provides a way to lookup security token details from a single place and allows wizard creators to earn POLY fees by uploading to the registrar. */ /** * @title SecurityTokenRegistrar * @dev Contract use to register the security token on Polymath platform */ contract SecurityTokenRegistrar is ISTRegistrar { string public VERSION = "1"; SecurityToken securityToken; address public polyTokenAddress; // Address of POLY token address public polyCustomersAddress; // Address of the polymath-core Customers contract address address public polyComplianceAddress; // Address of the polymath-core Compliance contract address // Security Token struct SecurityTokenData { // A structure that contains the specific info of each ST uint256 totalSupply; // created ever using the Polymath platform address owner; uint8 decimals; string ticker; uint8 securityType; } mapping(address => SecurityTokenData) securityTokens; // Array contains the details of security token corresponds to security token address mapping(string => address) tickers; // Mapping of ticker name to Security Token event LogNewSecurityToken(string ticker, address securityTokenAddress, address owner, address host, uint256 fee, uint8 _type); /** * @dev Constructor use to set the essentials addresses to facilitate * the creation of the security token */ function SecurityTokenRegistrar( address _polyTokenAddress, address _polyCustomersAddress, address _polyComplianceAddress ) public { polyTokenAddress = _polyTokenAddress; polyCustomersAddress = _polyCustomersAddress; polyComplianceAddress = _polyComplianceAddress; // Creating the instance of the compliance contract and assign the STR contract // address (this) into the compliance contract Compliance PolyCompliance = Compliance(polyComplianceAddress); require(PolyCompliance.setRegsitrarAddress(this)); } /** * @dev Creates a new Security Token and saves it to the registry * @param _name Name of the security token * @param _ticker Ticker name of the security * @param _totalSupply Total amount of tokens being created * @param _decimals Decimals value for token * @param _owner Ethereum public key address of the security token owner * @param _maxPoly Amount of maximum poly issuer want to raise * @param _host The host of the security token wizard * @param _fee Fee being requested by the wizard host * @param _type Type of security being tokenized * @param _lockupPeriod Length of time raised POLY will be locked up for dispute * @param _quorum Percent of initial investors required to freeze POLY raise */ function createSecurityToken ( string _name, string _ticker, uint256 _totalSupply, uint8 _decimals, address _owner, uint256 _maxPoly, address _host, uint256 _fee, uint8 _type, uint256 _lockupPeriod, uint8 _quorum ) external { require(_totalSupply > 0 && _maxPoly > 0 && _fee > 0); require(tickers[_ticker] == 0x0); require(_lockupPeriod >= now); require(_owner != address(0) && _host != address(0)); require(bytes(_name).length > 0 && bytes(_ticker).length > 0); IERC20 POLY = IERC20(polyTokenAddress); POLY.transferFrom(msg.sender, _host, _fee); address newSecurityTokenAddress = initialiseSecurityToken(_name, _ticker, _totalSupply, _decimals, _owner, _maxPoly, _type, _lockupPeriod, _quorum); LogNewSecurityToken(_ticker, newSecurityTokenAddress, _owner, _host, _fee, _type); } function initialiseSecurityToken( string _name, string _ticker, uint256 _totalSupply, uint8 _decimals, address _owner, uint256 _maxPoly, uint8 _type, uint256 _lockupPeriod, uint8 _quorum ) internal returns (address) { address newSecurityTokenAddress = new SecurityToken( _name, _ticker, _totalSupply, _decimals, _owner, _maxPoly, _lockupPeriod, _quorum, polyTokenAddress, polyCustomersAddress, polyComplianceAddress ); tickers[_ticker] = newSecurityTokenAddress; securityTokens[newSecurityTokenAddress] = SecurityTokenData( _totalSupply, _owner, _decimals, _ticker, _type ); return newSecurityTokenAddress; } ////////////////////////////// ///////// Get Functions ////////////////////////////// /** * @dev Get security token address by ticker name * @param _ticker Symbol of the Scurity token * @return address _ticker */ function getSecurityTokenAddress(string _ticker) public constant returns (address) { return tickers[_ticker]; } /** * @dev Get Security token details by its ethereum address * @param _STAddress Security token address */ function getSecurityTokenData(address _STAddress) public constant returns ( uint256 totalSupply, address owner, uint8 decimals, string ticker, uint8 securityType ) { return ( securityTokens[_STAddress].totalSupply, securityTokens[_STAddress].owner, securityTokens[_STAddress].decimals, securityTokens[_STAddress].ticker, securityTokens[_STAddress].securityType ); } } /* Polymath compliance protocol is intended to ensure regulatory compliance in the jurisdictions that security tokens are being offered in. The compliance protocol allows security tokens remain interoperable so that anyone can build on top of the Polymath platform and extend it's functionality. */ /** * @title Compilance * @dev Regulatory details offered by the security token */ contract Compliance is ICompliance { string public VERSION = "1"; ITemplate template; SecurityTokenRegistrar public STRegistrar; struct TemplateReputation { // Structure contains the compliance template details address owner; // Address of the template owner uint256 totalRaised; // Total amount raised by the issuers that used the template uint256 timesUsed; // How many times template will be used as the compliance regulator for different security token uint256 expires; // Timestamp when template get expire address[] usedBy; // Array of security token addresses that used the particular template } mapping(address => TemplateReputation) public templates; // Mapping used for storing the template past records corresponds to template address mapping(address => address[]) public templateProposals; // Template proposals for a specific security token struct Offering { // Smart contract proposals for a specific security token offering address auditor; uint256 fee; uint256 vestingPeriod; uint8 quorum; address[] usedBy; } mapping(address => Offering) offerings; // Mapping used for storing the Offering detials corresponds to offering contract address mapping(address => address[]) public offeringProposals; // Security token contract proposals for a specific security token Customers public PolyCustomers; // Instance of the Compliance contract uint256 public constant MINIMUM_VESTING_PERIOD = 60 * 60 * 24 * 100; // 100 Day minimum vesting period for POLY earned // Notifications event LogTemplateCreated(address indexed _creator, address _template, string _offeringType); event LogNewTemplateProposal(address indexed _securityToken, address _template, address _delegate, uint _templateProposalIndex); event LogCancelTemplateProposal(address indexed _securityToken, address _template, uint _templateProposalIndex); event LogNewContractProposal(address indexed _securityToken, address _offeringContract, address _delegate, uint _offeringProposalIndex); event LogCancelContractProposal(address indexed _securityToken, address _offeringContract, uint _offeringProposalIndex); /* @param _polyCustomersAddress The address of the Polymath Customers contract */ function Compliance(address _polyCustomersAddress) public { PolyCustomers = Customers(_polyCustomersAddress); } /** * @dev `setRegsitrarAddress` This function set the SecurityTokenRegistrar contract address. * @param _STRegistrar It is the `this` reference of STR contract * @return bool */ function setRegsitrarAddress(address _STRegistrar) public returns (bool) { require(STRegistrar == address(0)); STRegistrar = SecurityTokenRegistrar(_STRegistrar); return true; } /** * @dev `createTemplate` is a simple function to create a new compliance template * @param _offeringType The name of the security being issued * @param _issuerJurisdiction The jurisdiction id of the issuer * @param _accredited Accreditation status required for investors * @param _KYC KYC provider used by the template * @param _details Details of the offering requirements * @param _expires Timestamp of when the template will expire * @param _fee Amount of POLY to use the template (held in escrow until issuance) * @param _quorum Minimum percent of shareholders which need to vote to freeze * @param _vestingPeriod Length of time to vest funds */ function createTemplate( string _offeringType, bytes32 _issuerJurisdiction, bool _accredited, address _KYC, bytes32 _details, uint256 _expires, uint256 _fee, uint8 _quorum, uint256 _vestingPeriod ) public { require(_KYC != address(0)); require(_vestingPeriod >= MINIMUM_VESTING_PERIOD); address _template = new Template( msg.sender, _offeringType, _issuerJurisdiction, _accredited, _KYC, _details, _expires, _fee, _quorum, _vestingPeriod ); templates[_template] = TemplateReputation({ owner: msg.sender, totalRaised: 0, timesUsed: 0, expires: _expires, usedBy: new address[](0) }); LogTemplateCreated(msg.sender, _template, _offeringType); } /** * @dev Propose a bid for a security token issuance * @param _securityToken The security token being bid on * @param _template The unique template address * @return bool success */ function proposeTemplate( address _securityToken, address _template ) public returns (bool success) { // Verifying that provided _securityToken is generated by securityTokenRegistrar only var (totalSupply, owner,,) = STRegistrar.getSecurityTokenData(_securityToken); require(totalSupply > 0 && owner != address(0)); // Require that template has not expired, that the caller is the // owner of the template and that the template has been finalized require(templates[_template].expires > now); require(templates[_template].owner == msg.sender); // Creating the instance of template to avail the function calling template = Template(_template); var (,finalized) = template.getTemplateDetails(); require(finalized); //Get a reference of the template contract and add it to the templateProposals array templateProposals[_securityToken].push(_template); LogNewTemplateProposal(_securityToken, _template, msg.sender,templateProposals[_securityToken].length -1); return true; } /** * @dev Cancel a Template proposal if the bid hasn't been accepted * @param _securityToken The security token being bid on * @param _templateProposalIndex The template proposal array index * @return bool success */ function cancelTemplateProposal( address _securityToken, uint256 _templateProposalIndex ) public returns (bool success) { address proposedTemplate = templateProposals[_securityToken][_templateProposalIndex]; require(templates[proposedTemplate].owner == msg.sender); var (chosenTemplate,,,,) = ISecurityToken(_securityToken).getTokenDetails(); require(chosenTemplate != proposedTemplate); templateProposals[_securityToken][_templateProposalIndex] = address(0); LogCancelTemplateProposal(_securityToken, proposedTemplate, _templateProposalIndex); return true; } /** * @dev Set the STO contract by the issuer. * @param _STOAddress address of the STO contract deployed over the network. * @param _fee fee to be paid in poly to use that contract * @param _vestingPeriod no. of days investor binded to hold the Security token * @param _quorum Minimum percent of shareholders which need to vote to freeze */ function setSTO ( address _STOAddress, uint256 _fee, uint256 _vestingPeriod, uint8 _quorum ) public returns (bool success) { require(offerings[_STOAddress].auditor == address(0)); require(_STOAddress != address(0)); require(_quorum > 0 && _quorum <= 100); require(_vestingPeriod >= MINIMUM_VESTING_PERIOD); require(_fee > 0); offerings[_STOAddress].auditor = msg.sender; offerings[_STOAddress].fee = _fee; offerings[_STOAddress].vestingPeriod = _vestingPeriod; offerings[_STOAddress].quorum = _quorum; return true; } /** * @dev Propose a Security Token Offering Contract for an issuance * @param _securityToken The security token being bid on * @param _stoContract The security token offering contract address * @return bool success */ function proposeOfferingContract( address _securityToken, address _stoContract ) public returns (bool success) { // Verifying that provided _securityToken is generated by securityTokenRegistrar only var (totalSupply, owner,,) = STRegistrar.getSecurityTokenData(_securityToken); require(totalSupply > 0 && owner != address(0)); var (,,,,KYC) = ISecurityToken(_securityToken).getTokenDetails(); var (,,, verified, expires) = PolyCustomers.getCustomer(KYC, offerings[_stoContract].auditor); require(offerings[_stoContract].auditor == msg.sender); require(verified); require(expires > now); offeringProposals[_securityToken].push(_stoContract); LogNewContractProposal(_securityToken, _stoContract, msg.sender,offeringProposals[_securityToken].length -1); return true; } /** * @dev Cancel a STO contract proposal if the bid hasn't been accepted * @param _securityToken The security token being bid on * @param _offeringProposalIndex The offering proposal array index * @return bool success */ function cancelOfferingProposal( address _securityToken, uint256 _offeringProposalIndex ) public returns (bool success) { address proposedOffering = offeringProposals[_securityToken][_offeringProposalIndex]; require(offerings[proposedOffering].auditor == msg.sender); var (,,,,chosenOffering) = ISecurityToken(_securityToken).getTokenDetails(); require(chosenOffering != proposedOffering); offeringProposals[_securityToken][_offeringProposalIndex] = address(0); LogCancelContractProposal(_securityToken, proposedOffering, _offeringProposalIndex); return true; } /** * @dev `updateTemplateReputation` is a constant function that updates the history of a security token template usage to keep track of previous uses * @param _template The unique template id * @param _templateIndex The array index of the template proposal */ function updateTemplateReputation (address _template, uint8 _templateIndex) external returns (bool success) { require(templateProposals[msg.sender][_templateIndex] == _template); templates[_template].usedBy.push(msg.sender); return true; } /** * @dev `updateOfferingReputation` is a constant function that updates the history of a security token offering contract to keep track of previous uses * @param _stoContract The smart contract address of the STO contract * @param _offeringProposalIndex The array index of the security token offering proposal */ function updateOfferingReputation (address _stoContract, uint8 _offeringProposalIndex) external returns (bool success) { require(offeringProposals[msg.sender][_offeringProposalIndex] == _stoContract); offerings[_stoContract].usedBy.push(msg.sender); return true; } /** * @dev Get template details by the proposal index * @param _securityTokenAddress The security token ethereum address * @param _templateIndex The array index of the template being checked * @return Template struct */ function getTemplateByProposal(address _securityTokenAddress, uint8 _templateIndex) view public returns ( address _template ){ return templateProposals[_securityTokenAddress][_templateIndex]; } /** * @dev Get an array containing the address of all template proposals for a given ST * @param _securityTokenAddress The security token ethereum address * @return Template proposals array */ function getAllTemplateProposals(address _securityTokenAddress) view public returns (address[]){ return templateProposals[_securityTokenAddress]; } /** * @dev Get security token offering smart contract details by the proposal index * @param _securityTokenAddress The security token ethereum address * @param _offeringProposalIndex The array index of the STO contract being checked * @return Contract struct */ function getOfferingByProposal(address _securityTokenAddress, uint8 _offeringProposalIndex) view public returns ( address stoContract, address auditor, uint256 vestingPeriod, uint8 quorum, uint256 fee ){ address _stoContract = offeringProposals[_securityTokenAddress][_offeringProposalIndex]; return ( _stoContract, offerings[_stoContract].auditor, offerings[_stoContract].vestingPeriod, offerings[_stoContract].quorum, offerings[_stoContract].fee ); } /** * @dev Get an array containing the address of all offering proposals for a given ST * @param _securityTokenAddress The security token ethereum address * @return Offering proposals array */ function getAllOfferingProposals(address _securityTokenAddress) view public returns (address[]){ return offeringProposals[_securityTokenAddress]; } }
Allows contracts to transfer tokens on behalf of token holders _from Address to transfer tokens from _to Address to send tokens to _value Number of tokens to transfer return bool success/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { if (shareholders[_to].allowed && shareholders[_from].allowed && balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) { uint256 _allowance = allowed[_from][msg.sender]; balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = _allowance.sub(_value); balances[_to] = balances[_to].add(_value); Transfer(_from, _to, _value); return true; return false; } } else { }
885,162
pragma solidity 0.5.10; import "./BlockRewardAuRaBase.sol"; import "../interfaces/IBlockRewardAuRaCoins.sol"; contract BlockRewardAuRaCoins is BlockRewardAuRaBase, IBlockRewardAuRaCoins { // ============================================== Constants ======================================================= /// @dev Inflation rate per staking epoch. Calculated as follows: /// 2.5% annual rate * 48 staking weeks per staking year / 100 * 10**18 /// This assumes that 1 staking epoch = 1 week /// i.e. Inflation Rate = 2.5/48/100 * 1 ether /// Recalculate it for different annual rate and/or different staking epoch duration. uint256 public constant NATIVE_COIN_INFLATION_RATE = 520833333333333; // =============================================== Setters ======================================================== /// @dev Called by the `StakingAuRa.claimReward` function to transfer native coins /// from the balance of the `BlockRewardAuRa` contract to the specified address as a reward. /// @param _nativeCoins The amount of native coins to transfer as a reward. /// @param _to The target address to transfer the amounts to. function transferReward(uint256 _nativeCoins, address payable _to) external onlyStakingContract { _transferNativeReward(_nativeCoins, _to); } // =============================================== Getters ======================================================== /// @dev Returns the reward amount in native coins for /// some delegator with the specified stake amount placed into the specified /// pool before the specified staking epoch. Used by the `StakingAuRa.claimReward` function. /// @param _delegatorStake The stake amount placed by some delegator into the `_poolId` pool. /// @param _stakingEpoch The serial number of staking epoch. /// @param _poolId The pool id. /// @return `uint256 nativeReward` - the reward amount in native coins. function getDelegatorReward( uint256 _delegatorStake, uint256 _stakingEpoch, uint256 _poolId ) external view returns(uint256 nativeReward) { uint256 validatorStake = snapshotPoolValidatorStakeAmount[_stakingEpoch][_poolId]; uint256 totalStake = snapshotPoolTotalStakeAmount[_stakingEpoch][_poolId]; nativeReward = delegatorShare( _stakingEpoch, _delegatorStake, validatorStake, totalStake, epochPoolNativeReward[_stakingEpoch][_poolId] ); } /// @dev Returns the reward amount in native coins for /// the specified validator and for the specified staking epoch. /// Used by the `StakingAuRa.claimReward` function. /// @param _stakingEpoch The serial number of staking epoch. /// @param _poolId The pool id. /// @return `uint256 nativeReward` - the reward amount in native coins. function getValidatorReward( uint256 _stakingEpoch, uint256 _poolId ) external view returns(uint256 nativeReward) { uint256 validatorStake = snapshotPoolValidatorStakeAmount[_stakingEpoch][_poolId]; uint256 totalStake = snapshotPoolTotalStakeAmount[_stakingEpoch][_poolId]; nativeReward = validatorShare( _stakingEpoch, validatorStake, totalStake, epochPoolNativeReward[_stakingEpoch][_poolId] ); } // ============================================== Internal ======================================================== /// @dev Calculates and returns inflation amount based on the specified /// staking epoch and validator set. Uses NATIVE_COIN_INFLATION_RATE constant. /// Used by `_distributeNativeRewards` internal function. /// @param _stakingEpoch The number of the current staking epoch. /// @param _validators The array of the current validators (their pool ids). function _coinInflationAmount( uint256 _stakingEpoch, uint256[] memory _validators ) internal view returns(uint256) { return _inflationAmount(_stakingEpoch, _validators, NATIVE_COIN_INFLATION_RATE); } function _distributeTokenRewards( address, uint256, uint256, uint256, uint256[] memory, uint256[] memory, uint256 ) internal { } }
Calculates and returns inflation amount based on the specified staking epoch and validator set. Uses NATIVE_COIN_INFLATION_RATE constant. Used by `_distributeNativeRewards` internal function. _stakingEpoch The number of the current staking epoch. _validators The array of the current validators (their pool ids).
function _coinInflationAmount( uint256 _stakingEpoch, uint256[] memory _validators ) internal view returns(uint256) { return _inflationAmount(_stakingEpoch, _validators, NATIVE_COIN_INFLATION_RATE); }
12,606,950
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; /** * @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); } /** * @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; } } /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } /** * @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"); } } } interface ILpPairStrategy { function lpPair() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function deposit() external; function withdraw(address _asset) external; function withdraw(uint _amount) external returns (uint); function withdrawToController(uint _amount) external; function skim() external; function harvest(address _mergedStrategy) external; function withdrawAll() external returns (uint); function balanceOf() external view returns (uint); function withdrawFee(uint) external view returns (uint); // pJar: 0.5% (50/10000) } interface ICompositeVault { function cap() external view returns (uint); function getConverter() external view returns (address); function getVaultMaster() external view returns (address); function balance() external view returns (uint); function tvl() external view returns (uint); // total dollar value function token() external view returns (address); function available() external view returns (uint); function accept(address _input) external view returns (bool); function earn() external; function harvest(address reserve, uint amount) external; function addNewCompound(uint, uint) external; function withdraw_fee(uint _shares) external view returns (uint); function calc_token_amount_deposit(address _input, uint _amount) external view returns (uint); function calc_add_liquidity(uint _amount0, uint _amount1) external view returns (uint); function calc_token_amount_withdraw(uint _shares, address _output) external view returns (uint); function calc_remove_liquidity(uint _shares) external view returns (uint _amount0, uint _amount1); function getPricePerFullShare() external view returns (uint); function get_virtual_price() external view returns (uint); // average dollar value of vault share token function deposit(address _input, uint _amount, uint _min_mint_amount) external returns (uint); function depositFor(address _account, address _to, address _input, uint _amount, uint _min_mint_amount) external returns (uint _mint_amount); function addLiquidity(uint _amount0, uint _amount1, uint _min_mint_amount) external returns (uint); function addLiquidityFor(address _account, address _to, uint _amount0, uint _amount1, uint _min_mint_amount) external returns (uint _mint_amount); function withdraw(uint _shares, address _output, uint _min_output_amount) external returns (uint); function withdrawFor(address _account, uint _shares, address _output, uint _min_output_amount) external returns (uint _output_amount); function harvestStrategy(address _strategy) external; function harvestAllStrategies() external; } interface Converter { function convert(address) external returns (uint); } contract CompositeVaultController { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint; address public governance; address public strategist; struct StrategyInfo { address strategy; uint quota; // set = 0 to disable uint percent; } ICompositeVault public vault; string public name = "CompositeVaultController:SlpEthUsdc"; address public want; uint public strategyLength; // stratId => StrategyInfo mapping(uint => StrategyInfo) public strategies; mapping(address => bool) public approvedStrategies; bool public investDisabled; address public lazySelectedBestStrategy; // we pre-set the best strategy to avoid gas cost of iterating the array constructor(ICompositeVault _vault) public { require(address(_vault) != address(0), "!_vault"); vault = _vault; want = vault.token(); governance = msg.sender; strategist = msg.sender; } modifier onlyGovernance() { require(msg.sender == governance, "!governance"); _; } modifier onlyStrategist() { require(msg.sender == strategist || msg.sender == governance, "!strategist"); _; } modifier onlyAuthorized() { require(msg.sender == address(vault) || msg.sender == strategist || msg.sender == governance, "!authorized"); _; } function setName(string memory _name) external onlyGovernance { name = _name; } function setGovernance(address _governance) external onlyGovernance { governance = _governance; } function setStrategist(address _strategist) external onlyGovernance { strategist = _strategist; } function approveStrategy(address _strategy) external onlyGovernance { approvedStrategies[_strategy] = true; } function revokeStrategy(address _strategy) external onlyGovernance { approvedStrategies[_strategy] = false; } function setStrategyLength(uint _length) external onlyStrategist { strategyLength = _length; } // stratId => StrategyInfo function setStrategyInfo(uint _sid, address _strategy, uint _quota, uint _percent) external onlyStrategist { require(approvedStrategies[_strategy], "!approved"); strategies[_sid].strategy = _strategy; strategies[_sid].quota = _quota; strategies[_sid].percent = _percent; } function setInvestDisabled(bool _investDisabled) external onlyStrategist { investDisabled = _investDisabled; } function setLazySelectedBestStrategy(address _strategy) external onlyStrategist { require(approvedStrategies[_strategy], "!approved"); require(ILpPairStrategy(_strategy).lpPair() == want, "!want"); lazySelectedBestStrategy = _strategy; } function getStrategyCount() external view returns(uint _strategyCount) { _strategyCount = strategyLength; } function getBestStrategy() public view returns (address _strategy) { if (lazySelectedBestStrategy != address(0)) { return lazySelectedBestStrategy; } _strategy = address(0); if (strategyLength == 0) return _strategy; uint _totalBal = balanceOf(); if (_totalBal == 0) return strategies[0].strategy; // first depositor, simply return the first strategy uint _bestDiff = 201; for (uint _sid = 0; _sid < strategyLength; _sid++) { StrategyInfo storage sinfo = strategies[_sid]; uint _stratBal = ILpPairStrategy(sinfo.strategy).balanceOf(); if (_stratBal < sinfo.quota) { uint _diff = _stratBal.add(_totalBal).mul(100).div(_totalBal).sub(sinfo.percent); // [100, 200] - [percent] if (_diff < _bestDiff) { _bestDiff = _diff; _strategy = sinfo.strategy; } } } if (_strategy == address(0)) { _strategy = strategies[0].strategy; } } function earn(address _token, uint _amount) external onlyAuthorized { address _strategy = getBestStrategy(); if (_strategy == address(0) || ILpPairStrategy(_strategy).lpPair() != _token) { // forward to vault and then call earnExtra() by its governance IERC20(_token).safeTransfer(address(vault), _amount); } else { IERC20(_token).safeTransfer(_strategy, _amount); ILpPairStrategy(_strategy).deposit(); } } function withdraw_fee(uint _amount) external view returns (uint) { address _strategy = getBestStrategy(); return (_strategy == address(0)) ? 0 : ILpPairStrategy(_strategy).withdrawFee(_amount); } function balanceOf() public view returns (uint _totalBal) { for (uint _sid = 0; _sid < strategyLength; _sid++) { _totalBal = _totalBal.add(ILpPairStrategy(strategies[_sid].strategy).balanceOf()); } } function withdrawAll(address _strategy) external onlyStrategist { // WithdrawAll sends 'want' to 'vault' ILpPairStrategy(_strategy).withdrawAll(); } function inCaseTokensGetStuck(address _token, uint _amount) external onlyStrategist { IERC20(_token).safeTransfer(address(vault), _amount); } function inCaseStrategyGetStuck(address _strategy, address _token) external onlyStrategist { ILpPairStrategy(_strategy).withdraw(_token); IERC20(_token).safeTransfer(address(vault), IERC20(_token).balanceOf(address(this))); } // note that some strategies do not allow controller to harvest function harvestStrategy(address _strategy) external onlyAuthorized { ILpPairStrategy(_strategy).harvest(address(0)); } function harvestAllStrategies() external onlyAuthorized { address _firstStrategy = address(0); // to send all harvested WETH and proceed the profit sharing all-in-one here for (uint _sid = 0; _sid < strategyLength; _sid++) { StrategyInfo storage sinfo = strategies[_sid]; if (_firstStrategy == address(0)) { _firstStrategy = sinfo.strategy; } else { ILpPairStrategy(sinfo.strategy).harvest(_firstStrategy); } } if (_firstStrategy != address(0)) { ILpPairStrategy(_firstStrategy).harvest(address(0)); } } function switchFund(ILpPairStrategy _srcStrat, ILpPairStrategy _destStrat, uint _amount) external onlyStrategist { require(approvedStrategies[address(_destStrat)], "!approved"); require(_srcStrat.lpPair() == want, "!_srcStrat.lpPair"); require(_destStrat.lpPair() == want, "!_destStrat.lpPair"); _srcStrat.withdrawToController(_amount); IERC20(want).safeTransfer(address(_destStrat), IERC20(want).balanceOf(address(this))); _destStrat.deposit(); } function withdraw(uint _amount) external onlyAuthorized returns (uint _withdrawFee) { _withdrawFee = 0; uint _toWithdraw = _amount; uint _received; for (uint _sid = strategyLength; _sid > 0; _sid--) { StrategyInfo storage sinfo = strategies[_sid - 1]; ILpPairStrategy _strategy = ILpPairStrategy(sinfo.strategy); uint _stratBal = _strategy.balanceOf(); if (_toWithdraw < _stratBal) { _received = _strategy.withdraw(_toWithdraw); _withdrawFee = _withdrawFee.add(_strategy.withdrawFee(_received)); return _withdrawFee; } _received = _strategy.withdrawAll(); _withdrawFee = _withdrawFee.add(_strategy.withdrawFee(_received)); if (_received >= _toWithdraw) { return _withdrawFee; } _toWithdraw = _toWithdraw.sub(_received); } return _withdrawFee; } }
total dollar value
function tvl() external view returns (uint);
1,695,815
pragma solidity ^0.4.11; /** * Math operations with safety checks */ library SafeMath { function mul(uint a, uint b) internal returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint a, uint b) internal returns (uint) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint a, uint b) internal returns (uint) { assert(b <= a); return a - b; } function add(uint a, uint b) internal returns (uint) { uint c = a + b; assert(c >= a); return c; } function max64(uint64 a, uint64 b) internal constant returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal constant returns (uint64) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal constant returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal constant returns (uint256) { return a < b ? a : b; } function assert(bool assertion) internal { if (!assertion) { revert(); } } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20Basic { uint public totalSupply; function balanceOf(address who) constant returns (uint); function transfer(address to, uint value); event Transfer(address indexed from, address indexed to, uint value); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint; mapping(address => uint) balances; /** * @dev Fix for the ERC20 short address attack. */ modifier onlyPayloadSize(uint size) { if(msg.data.length < size + 4) { revert(); } _; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint _value) onlyPayloadSize(2 * 32) { balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint representing the amount owned by the passed address. */ function balanceOf(address _owner) constant returns (uint balance) { return balances[_owner]; } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) constant returns (uint); function transferFrom(address from, address to, uint value); function approve(address spender, uint value); event Approval(address indexed owner, address indexed spender, uint value); } /** * @title Standard ERC20 token * * @dev Implemantation of the basic standart token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is BasicToken, ERC20 { mapping (address => mapping (address => uint)) allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint the amout of tokens to be transfered */ function transferFrom(address _from, address _to, uint _value) onlyPayloadSize(3 * 32) { var _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // if (_value > _allowance) revert(); balances[_to] = balances[_to].add(_value); balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); } /** * @dev Aprove the passed address to spend the specified amount of tokens on beahlf of msg.sender. * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint _value) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 if ((_value != 0) && (allowed[msg.sender][_spender] != 0)) revert(); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); } /** * @dev Function to check the amount of tokens than an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint specifing the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) constant returns (uint remaining) { return allowed[_owner][_spender]; } } /** * @title LimitedTransferToken * @dev LimitedTransferToken defines the generic interface and the implementation to limit token * transferability for different events. It is intended to be used as a base class for other token * contracts. * LimitedTransferToken has been designed to allow for different limiting factors, * this can be achieved by recursively calling super.transferableTokens() until the base class is * hit. For example: * function transferableTokens(address holder, uint64 time) constant public returns (uint256) { * return min256(unlockedTokens, super.transferableTokens(holder, time)); * } * A working example is VestedToken.sol: * https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/token/VestedToken.sol */ contract LimitedTransferToken is ERC20 { /** * @dev Checks whether it can transfer or otherwise throws. */ modifier canTransfer(address _sender, uint _value) { if (_value > transferableTokens(_sender, uint64(now))) revert(); _; } /** * @dev Checks modifier and allows transfer if tokens are not locked. * @param _to The address that will recieve the tokens. * @param _value The amount of tokens to be transferred. */ function transfer(address _to, uint _value) canTransfer(msg.sender, _value) { super.transfer(_to, _value); } /** * @dev Checks modifier and allows transfer if tokens are not locked. * @param _from The address that will send the tokens. * @param _to The address that will recieve the tokens. * @param _value The amount of tokens to be transferred. */ function transferFrom(address _from, address _to, uint _value) canTransfer(_from, _value) { super.transferFrom(_from, _to, _value); } /** * @dev Default transferable tokens function returns all tokens for a holder (no limit). * @dev Overwriting transferableTokens(address holder, uint64 time) is the way to provide the * specific logic for limiting token transferability for a holder over time. */ function transferableTokens(address holder, uint64 time) constant public returns (uint256) { return balanceOf(holder); } } /** * @title Vested token * @dev Tokens that can be vested for a group of addresses. */ contract VestedToken is StandardToken, LimitedTransferToken { uint256 MAX_GRANTS_PER_ADDRESS = 20; struct TokenGrant { address granter; // 20 bytes uint256 value; // 32 bytes uint64 cliff; uint64 vesting; uint64 start; // 3 * 8 = 24 bytes bool revokable; bool burnsOnRevoke; // 2 * 1 = 2 bits? or 2 bytes? } // total 78 bytes = 3 sstore per operation (32 per sstore) mapping (address => TokenGrant[]) public grants; event NewTokenGrant(address indexed from, address indexed to, uint256 value, uint256 grantId); /** * @dev Grant tokens to a specified address * @param _to address The address which the tokens will be granted to. * @param _value uint256 The amount of tokens to be granted. * @param _start uint64 Time of the beginning of the grant. * @param _cliff uint64 Time of the cliff period. * @param _vesting uint64 The vesting period. */ function grantVestedTokens( address _to, uint256 _value, uint64 _start, uint64 _cliff, uint64 _vesting, bool _revokable, bool _burnsOnRevoke ) public { // Check for date inconsistencies that may cause unexpected behavior if (_cliff < _start || _vesting < _cliff) { revert(); } if (tokenGrantsCount(_to) > MAX_GRANTS_PER_ADDRESS) revert(); // To prevent a user being spammed and have his balance locked (out of gas attack when calculating vesting). uint count = grants[_to].push( TokenGrant( _revokable ? msg.sender : 0, // avoid storing an extra 20 bytes when it is non-revokable _value, _cliff, _vesting, _start, _revokable, _burnsOnRevoke ) ); transfer(_to, _value); NewTokenGrant(msg.sender, _to, _value, count - 1); } /** * @dev Revoke the grant of tokens of a specifed address. * @param _holder The address which will have its tokens revoked. * @param _grantId The id of the token grant. */ function revokeTokenGrant(address _holder, uint _grantId) public { TokenGrant grant = grants[_holder][_grantId]; if (!grant.revokable) { // Check if grant was revokable revert(); } if (grant.granter != msg.sender) { // Only granter can revoke it revert(); } address receiver = grant.burnsOnRevoke ? 0xdead : msg.sender; uint256 nonVested = nonVestedTokens(grant, uint64(now)); // remove grant from array delete grants[_holder][_grantId]; grants[_holder][_grantId] = grants[_holder][grants[_holder].length.sub(1)]; grants[_holder].length -= 1; balances[receiver] = balances[receiver].add(nonVested); balances[_holder] = balances[_holder].sub(nonVested); Transfer(_holder, receiver, nonVested); } /** * @dev Calculate the total amount of transferable tokens of a holder at a given time * @param holder address The address of the holder * @param time uint64 The specific time. * @return An uint representing a holder's total amount of transferable tokens. */ function transferableTokens(address holder, uint64 time) constant public returns (uint256) { uint256 grantIndex = tokenGrantsCount(holder); if (grantIndex == 0) return balanceOf(holder); // shortcut for holder without grants // Iterate through all the grants the holder has, and add all non-vested tokens uint256 nonVested = 0; for (uint256 i = 0; i < grantIndex; i++) { nonVested = SafeMath.add(nonVested, nonVestedTokens(grants[holder][i], time)); } // Balance - totalNonVested is the amount of tokens a holder can transfer at any given time uint256 vestedTransferable = SafeMath.sub(balanceOf(holder), nonVested); // Return the minimum of how many vested can transfer and other value // in case there are other limiting transferability factors (default is balanceOf) return SafeMath.min256(vestedTransferable, super.transferableTokens(holder, time)); } /** * @dev Check the amount of grants that an address has. * @param _holder The holder of the grants. * @return A uint representing the total amount of grants. */ function tokenGrantsCount(address _holder) constant returns (uint index) { return grants[_holder].length; } /** * @dev Calculate amount of vested tokens at a specifc time. * @param tokens uint256 The amount of tokens grantted. * @param time uint64 The time to be checked * @param start uint64 A time representing the begining of the grant * @param cliff uint64 The cliff period. * @param vesting uint64 The vesting period. * @return An uint representing the amount of vested tokensof a specif grant. * transferableTokens * | _/-------- vestedTokens rect * | _/ * | _/ * | _/ * | _/ * | / * | .| * | . | * | . | * | . | * | . | * | . | * +===+===========+---------+----------> time * Start Clift Vesting */ function calculateVestedTokens( uint256 tokens, uint256 time, uint256 start, uint256 cliff, uint256 vesting) constant returns (uint256) { // Shortcuts for before cliff and after vesting cases. if (time < cliff) return 0; if (time >= vesting) return tokens; // Interpolate all vested tokens. // As before cliff the shortcut returns 0, we can use just calculate a value // in the vesting rect (as shown in above's figure) // vestedTokens = tokens * (time - start) / (vesting - start) uint256 vestedTokens = SafeMath.div( SafeMath.mul( tokens, SafeMath.sub(time, start) ), SafeMath.sub(vesting, start) ); return vestedTokens; } /** * @dev Get all information about a specifc grant. * @param _holder The address which will have its tokens revoked. * @param _grantId The id of the token grant. * @return Returns all the values that represent a TokenGrant(address, value, start, cliff, * revokability, burnsOnRevoke, and vesting) plus the vested value at the current time. */ function tokenGrant(address _holder, uint _grantId) constant returns (address granter, uint256 value, uint256 vested, uint64 start, uint64 cliff, uint64 vesting, bool revokable, bool burnsOnRevoke) { TokenGrant grant = grants[_holder][_grantId]; granter = grant.granter; value = grant.value; start = grant.start; cliff = grant.cliff; vesting = grant.vesting; revokable = grant.revokable; burnsOnRevoke = grant.burnsOnRevoke; vested = vestedTokens(grant, uint64(now)); } /** * @dev Get the amount of vested tokens at a specific time. * @param grant TokenGrant The grant to be checked. * @param time The time to be checked * @return An uint representing the amount of vested tokens of a specific grant at a specific time. */ function vestedTokens(TokenGrant grant, uint64 time) private constant returns (uint256) { return calculateVestedTokens( grant.value, uint256(time), uint256(grant.start), uint256(grant.cliff), uint256(grant.vesting) ); } /** * @dev Calculate the amount of non vested tokens at a specific time. * @param grant TokenGrant The grant to be checked. * @param time uint64 The time to be checked * @return An uint representing the amount of non vested tokens of a specifc grant on the * passed time frame. */ function nonVestedTokens(TokenGrant grant, uint64 time) private constant returns (uint256) { return grant.value.sub(vestedTokens(grant, time)); } /** * @dev Calculate the date when the holder can trasfer all its tokens * @param holder address The address of the holder * @return An uint representing the date of the last transferable tokens. */ function lastTokenIsTransferableDate(address holder) constant public returns (uint64 date) { date = uint64(now); uint256 grantIndex = grants[holder].length; for (uint256 i = 0; i < grantIndex; i++) { date = SafeMath.max64(grants[holder][i].vesting, date); } } } // QUESTIONS FOR AUDITORS: // - Considering we inherit from VestedToken, how much does that hit at our gas price? // - Ensure max supply is 98,000,000 // - Ensure that even if not totalSupply is sold, tokens would still be transferrable after (we will up to totalSupply by creating WPX tokens) // vesting: 365 days, 365 days / 4 vesting contract WPXToken is VestedToken { //FIELDS string public name = "WorkPress"; //(important input) string public symbol = "WPX"; //(important input) uint public decimals = 4; //(important input) // Multiplier for the decimals uint private constant DECIMALS = 10000; uint public totalSupply = 98000000*DECIMALS; //(important input) //CONSTANTS //Time limits uint public constant STAGE_ONE_TIME_END = 38 days; // first day bonus (important input) uint public constant STAGE_TWO_TIME_END = 58 days; // first week bonus (important input) uint public constant STAGE_THREE_TIME_END = 69 days; //(important input) //Prices of WPX uint public constant PRICE_STANDARD = 2000*DECIMALS; // WPX received per one ETH; Approximately $0.15 if ETH price $300. MAX_SUPPLY / (valuation / ethPrice) uint public constant PRICE_STAGE_ONE = PRICE_STANDARD * 150/100; // 1ETH = 100% Bonus 1.5X or 50% 1ETH = 3000 WPX ~ $0.10(important input) uint public constant PRICE_STAGE_TWO = PRICE_STANDARD * 125/100; // 1ETH = 25% ICO Bonus 1ETH = 2500 WPX ~ $0.125(important input) uint public constant PRICE_STAGE_THREE = PRICE_STANDARD; // Standard Price no bonus 1ETH = 2000 WPX ~ $0.15(important input) //WPX Token Limits uint public constant ALLOC_TEAM = 10000000*DECIMALS; // team + advisors to main address (important input) uint public constant ALLOC_BOUNTIES = 3000000*DECIMALS; // Reserved Address (important input) uint public constant ALLOC_WINGS = 5000000*DECIMALS; // Reserved Address (important input) uint public constant ALLOC_CROWDSALE = 80000000*DECIMALS; // Crowdsale to Main address (important input) uint public constant PREBUY_PORTION_MAX = 20000000*DECIMALS; // this is redundantly more than what will be pre-sold //ASSIGNED IN INITIALIZATION //Start and end times uint public publicStartTime; // Time in seconds public crowd fund starts. uint public privateStartTime; // Time in seconds - at this time there is no intention to do a private session. uint public publicEndTime; // Time in seconds crowdsale ends uint public hardcapInEth; //Special Addresses address public multisigAddress; // Address to which all ether flows. address public wpxTeamAddress; // Address to which ALLOC_TEAM, ALLOC_BOUNTIES, ALLOC_WINGS is (ultimately) sent to. address public ownerAddress; // Address of the contract owner. Can halt the crowdsale. address public preBuy1; // Address used by pre-buy address public preBuy2; // Address used by pre-buy address public preBuy3; // Address used by pre-buy uint public preBuyPrice1; // price for pre-buy uint public preBuyPrice2; // price for pre-buy uint public preBuyPrice3; // price for pre-buy //Running totals uint public etherRaised; // Total Ether raised. uint public WPXSold; // Total WPX created uint public prebuyPortionTotal; // Total of Tokens purchased by pre-buy. Not to exceed PREBUY_PORTION_MAX. //booleans bool public halted; // halts the crowd sale if true. // MODIFIERS //Is currently in the period after the private start time and before the public start time. modifier is_pre_crowdfund_period() { if (now >= publicStartTime || now < privateStartTime) revert(); _; } //Is currently the crowdfund period modifier is_crowdfund_period() { if (now < publicStartTime) revert(); if (isCrowdfundCompleted()) revert(); _; } // Is completed modifier is_crowdfund_completed() { if (!isCrowdfundCompleted()) revert(); _; } function isCrowdfundCompleted() internal returns (bool) { if (now > publicEndTime || WPXSold+50000*DECIMALS >= ALLOC_CROWDSALE || etherRaised >= hardcapInEth*1000000000000000000) {return true; } return false; } //May only be called by the owner address modifier only_owner() { if (msg.sender != ownerAddress) revert(); _; } //May only be called if the crowdfund has not been halted modifier is_not_halted() { if (halted) revert(); _; } // EVENTS event PreBuy(uint _amount); event Buy(address indexed _recipient, uint _amount); // Initialization contract assigns address of crowdfund contract and end time. function WPXToken( address _multisig, address _wpxTeam, uint _publicStartTime, uint _privateStartTime, uint _hardcapInEth, address _prebuy1, uint _preBuyPrice1, address _prebuy2, uint _preBuyPrice2, address _prebuy3, uint _preBuyPrice3 ) { ownerAddress = msg.sender; publicStartTime = _publicStartTime; privateStartTime = _privateStartTime; publicEndTime = _publicStartTime + 69 days; // (important input) multisigAddress = _multisig; wpxTeamAddress = _wpxTeam; hardcapInEth = _hardcapInEth; preBuy1 = _prebuy1; preBuyPrice1 = _preBuyPrice1; preBuy2 = _prebuy2; preBuyPrice2 = _preBuyPrice2; preBuy3 = _prebuy3; preBuyPrice3 = _preBuyPrice3; balances[wpxTeamAddress] += ALLOC_BOUNTIES; balances[wpxTeamAddress] += ALLOC_WINGS; balances[ownerAddress] += ALLOC_TEAM; balances[ownerAddress] += ALLOC_CROWDSALE; } // Transfer amount of tokens from sender account to recipient. // Only callable after the crowd fund is completed function transfer(address _to, uint _value) { if (_to == msg.sender) return; // no-op, allow even during crowdsale, in order to work around using grantVestedTokens() while in crowdsale if (!isCrowdfundCompleted()) revert(); super.transfer(_to, _value); } // Transfer amount of tokens from a specified address to a recipient. // Transfer amount of tokens from sender account to recipient. function transferFrom(address _from, address _to, uint _value) is_crowdfund_completed { super.transferFrom(_from, _to, _value); } //constant function returns the current WPX price. function getPriceRate() constant returns (uint o_rate) { uint delta = SafeMath.sub(now, publicStartTime); if (delta > STAGE_TWO_TIME_END) return PRICE_STAGE_THREE; if (delta > STAGE_ONE_TIME_END) return PRICE_STAGE_TWO; return (PRICE_STAGE_ONE); } // calculates wmount of WPX we get, given the wei and the rates we've defined per 1 eth function calcAmount(uint _wei, uint _rate) constant returns (uint) { return SafeMath.div(SafeMath.mul(_wei, _rate), 1 ether); } // Given the rate of a purchase and the remaining tokens in this tranche, it // will throw if the sale would take it past the limit of the tranche. // Returns `amount` in scope as the number of WPX tokens that it will purchase. function processPurchase(uint _rate, uint _remaining) internal returns (uint o_amount) { o_amount = calcAmount(msg.value, _rate); if (o_amount > _remaining) revert(); if (!multisigAddress.send(msg.value)) revert(); balances[ownerAddress] = balances[ownerAddress].sub(o_amount); balances[msg.sender] = balances[msg.sender].add(o_amount); WPXSold += o_amount; etherRaised += msg.value; } //Special Function can only be called by pre-buy and only during the pre-crowdsale period. function preBuy() payable is_pre_crowdfund_period is_not_halted { // Pre-buy participants would get the first-day price, as well as a bonus of vested tokens uint priceVested = 0; if (msg.sender == preBuy1) priceVested = preBuyPrice1; if (msg.sender == preBuy2) priceVested = preBuyPrice2; if (msg.sender == preBuy3) priceVested = preBuyPrice3; if (priceVested == 0) revert(); uint amount = processPurchase(PRICE_STAGE_ONE + priceVested, SafeMath.sub(PREBUY_PORTION_MAX, prebuyPortionTotal)); grantVestedTokens(msg.sender, calcAmount(msg.value, priceVested), uint64(now), uint64(now) + 91 days, uint64(now) + 365 days, false, false ); prebuyPortionTotal += amount; PreBuy(amount); } //Default function called by sending Ether to this address with no arguments. //Results in creation of new WPX Tokens if transaction would not exceed hard limit of WPX Token. function() payable is_crowdfund_period is_not_halted { uint amount = processPurchase(getPriceRate(), SafeMath.sub(ALLOC_CROWDSALE, WPXSold)); Buy(msg.sender, amount); } // To be called at the end of crowdfund period // WARNING: transfer(), which is called by grantVestedTokens(), wants a minimum message length function grantVested(address _wpxTeamAddress, address _wpxFundAddress) is_crowdfund_completed only_owner is_not_halted { // Grant tokens pre-allocated for the team grantVestedTokens( _wpxTeamAddress, ALLOC_TEAM, uint64(now), uint64(now) + 91 days , uint64(now) + 365 days, false, false ); // Grant tokens that remain after crowdsale to the WPX fund, vested for 2 years grantVestedTokens( _wpxFundAddress, balances[ownerAddress], uint64(now), uint64(now) + 182 days , uint64(now) + 730 days, false, false ); } //May be used by owner of contract to halt crowdsale and no longer except ether. function toggleHalt(bool _halted) only_owner { halted = _halted; } //failsafe drain function drain() only_owner { if (!ownerAddress.send(this.balance)) revert(); } }
Get all information about a specifc grant. _holder The address which will have its tokens revoked. _grantId The id of the token grant. return Returns all the values that represent a TokenGrant(address, value, start, cliff, revokability, burnsOnRevoke, and vesting) plus the vested value at the current time./
function tokenGrant(address _holder, uint _grantId) constant returns (address granter, uint256 value, uint256 vested, uint64 start, uint64 cliff, uint64 vesting, bool revokable, bool burnsOnRevoke) { TokenGrant grant = grants[_holder][_grantId]; granter = grant.granter; value = grant.value; start = grant.start; cliff = grant.cliff; vesting = grant.vesting; revokable = grant.revokable; burnsOnRevoke = grant.burnsOnRevoke; vested = vestedTokens(grant, uint64(now)); }
5,424,900
pragma solidity 0.5.12; pragma experimental ABIEncoderV2; //合约地址:TJP7qCGbg1kcVwqvR3vPhBZWMHMqiLfafb tron-mainnet.token.im // token 合约地址 TApU6QvHUJTRcB9udS5LiyfbttWontdmGk contract Creator { address payable public creator; /** @dev constructor */ constructor() public { creator = msg.sender; } // allows execution by the creator only modifier creatorOnly { assert(msg.sender == creator); _; } } contract DEFI_DEMO is Creator { uint constant SECONDS_PER_DAY = 24 * 60 * 60; uint constant SECONDS_PER_HOUR = 60 * 60; uint constant SECONDS_PER_MINUTE = 60; int constant OFFSET19700101 = 2440588; uint constant DOW_MON = 1; uint constant DOW_TUE = 2; uint constant DOW_WED = 3; uint constant DOW_THU = 4; uint constant DOW_FRI = 5; uint constant DOW_SAT = 6; uint constant DOW_SUN = 7; using SafeMath for uint256; uint is_first = 0; uint256 constant public TIME_STEP = 30 ;//1 days; uint256 constant public PROJECT_FEE = 20; uint256 constant public PERCENTS_DIVIDER = 1000; uint256 constant public NODE_LEVEL_MAX = 4; address public usdtToken = address(0x419fdc31bb3cd5b504610f13aa696dc5c7ecdc8e55); IERC20 public USDT = IERC20(address(0x419fdc31bb3cd5b504610f13aa696dc5c7ecdc8e55)); address payable public projectAddress; struct node_config { uint256 id; uint256 price; uint256 pre_price; uint256 last_price; uint256 percent; uint256 day; uint256 sign1; uint256 sign2; uint256 sure_duration; uint256 sign_duration; } struct node_order { uint256 price; uint256 pre_price; uint256 last_price; uint256 percent; uint256 level; uint256 day; uint256 sign1; uint256 sign2; uint256 sure_duration; uint256 sign_duration; uint256 status; uint256 operation_time; uint256 deadline_time; bool IsOver; } node_config[] public NODE_CONFIG; struct User { bool IsNode; address referrer; node_order[] nodeOrders; uint256 nodeState; //当前节点状态 0 初始化 1 预约 2 买入 3 收益中 4 冻结中 5 出局 6 失效 7 确定付款 node_order nodeOrder; } mapping(address => User) public users; event Newbie(address user); event NewDeposit(address indexed user, uint256 amount); event Withdrawn(address indexed user, uint256 amount); event Withdrawndividend(address indexed user, uint256 amount); event RefBonus(address indexed referrer, address indexed referral, uint256 indexed level, uint256 amount); event FeePayed(address indexed user, uint256 totalAmount); event NodeFee(address indexed from, address indexed to, uint256 Amount); event UpNodeFee(address indexed from, address indexed to, uint256 Amount); event WithDrawnNodeFee(address indexed user, uint256 amount); event preNode1(address indexed referrer, uint256 level); event preNode2(address indexed sender, uint256 amount); event preNode3(uint256 id, uint256 price); event preNode4(uint256 id, uint256 price); event sureNode1(address indexed sender, uint256 nodeState); event sureNode2(uint256 nodeState, uint deadline_time); constructor() public { // initialize(address(0x41BDE07764CB70611B522C552A3B391287FAFF2CA8)); initialize(); } modifier IsInitialized { require(projectAddress != address(0), "not Initialized"); _; } bytes4 private constant transferFrom = bytes4(keccak256(bytes('transferFrom(address,address,uint256)'))); bytes4 private constant transfer = bytes4(keccak256(bytes('transfer(address,uint256)'))); function SafeUsdtTransferFrom(address from, address to, uint value) private { (bool success, bytes memory data) = usdtToken.call(abi.encodeWithSelector(transferFrom, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'UniswapV2: TRANSFER_FAILED'); } function SafeUsdtTransfer(address to, uint value) private { (bool success, bytes memory data) = usdtToken.call(abi.encodeWithSelector(transfer, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'UniswapV2: TRANSFER_FAILED'); } // function initialize(address payable projectAddr) public payable creatorOnly { // // require(projectAddress == address(0) && projectAddr != address(0), "initialize only would call once"); // require(!isContract(projectAddr)); // projectAddress = projectAddr; function initialize() public payable creatorOnly { if(is_first==0){ projectAddress = projectAddr ; is_first = 1; } NODE_CONFIG.push(node_config({id:0,price : 3000 * 1000000,pre_price:600 * 1000000,last_price:2400 * 1000000, percent : 5, day:5,sign1:19,sign2:31,sure_duration:5,sign_duration:5})); NODE_CONFIG.push(node_config({id:1,price : 5000 * 1000000,pre_price:1000 * 1000000,last_price:4000 * 1000000, percent : 10, day:5,sign1:19,sign2:31,sure_duration:5,sign_duration:5})); NODE_CONFIG.push(node_config({id:2,price : 10000 * 1000000,pre_price:2000 * 1000000,last_price:8000 * 1000000, percent : 10, day:10,sign1:20,sign2:32,sure_duration:5,sign_duration:5})); NODE_CONFIG.push(node_config({id:3,price : 30000 * 1000000,pre_price:6000 * 1000000,last_price:24000 * 1000000, percent : 12, day:15,sign1:20,sign2:32,sure_duration:5,sign_duration:5})); NODE_CONFIG.push(node_config({id:4,price : 50000 * 1000000,pre_price:10000 * 1000000,last_price:40000 * 1000000, percent : 15, day:15,sign1:20,sign2:32,sure_duration:5,sign_duration:5})); } function timestampFromDate(uint year, uint month, uint day) internal pure returns (uint timestamp) { timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY; } function timestampFromDateTime(uint year, uint month, uint day, uint hour, uint minute, uint second) internal pure returns (uint timestamp) { timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + hour * SECONDS_PER_HOUR + minute * SECONDS_PER_MINUTE + second; } function timestampToDate(uint timestamp) internal pure returns (uint year, uint month, uint day) { (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function timestampToDateTime(uint timestamp) internal pure returns (uint year, uint month, uint day, uint hour, uint minute, uint second) { (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); uint secs = timestamp % SECONDS_PER_DAY; hour = secs / SECONDS_PER_HOUR; secs = secs % SECONDS_PER_HOUR; minute = secs / SECONDS_PER_MINUTE; second = secs % SECONDS_PER_MINUTE; } function addDays(uint timestamp, uint _days) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _days * SECONDS_PER_DAY; require(newTimestamp >= timestamp); } function addHours(uint timestamp, uint _hours) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _hours * SECONDS_PER_HOUR; require(newTimestamp >= timestamp); } function addMinutes(uint timestamp, uint _minutes) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _minutes * SECONDS_PER_MINUTE; require(newTimestamp >= timestamp); } function getYear(uint timestamp) internal pure returns (uint year) { (year,,) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getMonth(uint timestamp) internal pure returns (uint month) { (,month,) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getDay(uint timestamp) internal pure returns (uint day) { (,,day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function _daysFromDate(uint year, uint month, uint day) internal pure returns (uint _days) { require(year >= 1970); int _year = int(year); int _month = int(month); int _day = int(day); int __days = _day - 32075 + 1461 * (_year + 4800 + (_month - 14) / 12) / 4 + 367 * (_month - 2 - (_month - 14) / 12 * 12) / 12 - 3 * ((_year + 4900 + (_month - 14) / 12) / 100) / 4 - OFFSET19700101; _days = uint(__days); } function _daysToDate(uint _days) internal pure returns (uint year, uint month, uint day) { int __days = int(_days); int L = __days + 68569 + OFFSET19700101; int N = 4 * L / 146097; L = L - (146097 * N + 3) / 4; int _year = 4000 * (L + 1) / 1461001; L = L - 1461 * _year / 4 + 31; int _month = 80 * L / 2447; int _day = L - 2447 * _month / 80; L = _month / 11; _month = _month + 2 - 12 * L; _year = 100 * (N - 49) + _year + L; year = uint(_year); month = uint(_month); day = uint(_day); } // 更改收币地址 //只有创建者可以修改 function change_pro_addr(address payable projectAddr) public creatorOnly { projectAddress = projectAddr; } //当前节点状态 0 初始化 1 预约 2 确认中 3 收益中 4 冻结中 5 出局 6 失效 function preNode(address referrer, uint256 level) public payable IsInitialized { emit preNode1(referrer, level); emit preNode2(msg.sender, msg.value); require(!isContract(msg.sender) && (tx.origin == msg.sender)); //level from 0 ~ 2 node_config memory level_conf = NODE_CONFIG[level]; require(level >= 0 && level < NODE_CONFIG.length); emit preNode3(level_conf.id, level_conf.price); // require(level_conf.bought < level_conf.max, "counter over"); User storage user = users[msg.sender]; if(user.IsNode==true){ require(!(user.nodeState == 1 ||user.nodeState == 2 ||user.nodeState == 3) , "node state error"); }else{ user.referrer = referrer; } require(level >= user.nodeOrder.level,'level need >= last level'); uint last_time = addDays(now,10); user.nodeOrder = node_order(level,level_conf.price,level_conf.pre_price,level_conf.last_price,level_conf.percent,level_conf.day, level_conf.sign1,level_conf.sign2,level_conf.sure_duration,level_conf.sign_duration,1,now,last_time,false ); if(user.nodeState == 4){ user.nodeOrder.status = 5; } user.nodeOrders[0]= user.nodeOrder ; user.IsNode = true; // user.nodeOrder = nodeOrder; user.nodeState = 1; uint256 fee = msg.value.mul(PROJECT_FEE).div(PERCENTS_DIVIDER); projectAddress.transfer(fee); emit preNode4(user.nodeOrder.status , fee); // emit FeePayed(msg.sender, fee); // SafeUsdtTransferFrom(msg.sender, projectAddress, // level_conf.pre_price); } function preNodeNoAddress(uint256 level) public payable IsInitialized { emit preNode2(msg.sender, msg.value); require(!isContract(msg.sender) && (tx.origin == msg.sender)); //level from 0 ~ 2 node_config memory level_conf = NODE_CONFIG[level]; require(level >= 0 && level < NODE_CONFIG.length); emit preNode3(level_conf.id, level_conf.price); // require(level_conf.bought < level_conf.max, "counter over"); User storage user = users[msg.sender]; if(user.IsNode==true){ require(!(user.nodeState == 1 ||user.nodeState == 2 ||user.nodeState == 3) , "node state error"); } require(level >= user.nodeOrder.level,'level need >= last level'); uint last_time = addDays(now,10); user.nodeOrder = node_order(level,level_conf.price,level_conf.pre_price,level_conf.last_price,level_conf.percent,level_conf.day, level_conf.sign1,level_conf.sign2,level_conf.sure_duration,level_conf.sign_duration,1,now,last_time,false ); if(user.nodeState == 4){ user.nodeOrder.status = 5; } user.nodeOrders[0]= user.nodeOrder ; user.IsNode = true; // user.nodeOrder = nodeOrder; user.nodeState = 1; uint256 fee = msg.value.mul(PROJECT_FEE).div(PERCENTS_DIVIDER); projectAddress.transfer(fee); emit preNode4(user.nodeOrder.status , fee); // emit FeePayed(msg.sender, fee); // SafeUsdtTransferFrom(msg.sender, projectAddress, // level_conf.pre_price); } function sureNode() public payable IsInitialized { User storage user = users[msg.sender]; emit sureNode1(msg.sender,user.nodeState); require(user.IsNode == true , "IsNode is true"); require(user.nodeState == 1 , "node state is not 1"); if(now >= user.nodeOrder.deadline_time){ user.nodeState = 6; } require(now < user.nodeOrder.deadline_time , "deadline_time"); uint year = getYear(now); uint month = getMonth(now); uint day = getDay(now); uint h1 = user.nodeOrder.sign1 /2 ; uint m1 = user.nodeOrder.sign1 % 2; uint h2 = user.nodeOrder.sign2 /2 ; uint m2 = user.nodeOrder.sign2 % 2; uint time1 = timestampFromDateTime(year,month,day,h1,30 * m1,0); uint xx1 = 30 * m1+user.nodeOrder.sure_duration; uint time11 = timestampFromDateTime(year,month,day,h1,xx1,0); uint time2 = timestampFromDateTime(year,month,day,h2,30 * m2,0); uint xx = 30 * m2+user.nodeOrder.sure_duration; uint t22 = timestampFromDateTime(year,month,day,h2,xx,0); // require( (now>=time1 && now <= time11) || (now>=time2 && now <= t22), " time is error"); user.nodeState = 2; user.nodeOrder.operation_time = now; uint xxxxx = user.nodeOrder.sign_duration; user.nodeOrder.deadline_time = addHours(now,xxxxx); // emit sureNode2(user.nodeState, user.nodeOrder.deadline_time); } function buyNode() public payable IsInitialized { User storage user = users[msg.sender]; require(user.IsNode == true , "IsNode is true"); require(user.nodeState ==2 , "node state is not 7"); if(now >= user.nodeOrder.deadline_time){ user.nodeState = 6; } require(now < user.nodeOrder.deadline_time , "deadline_time"); uint year = getYear(now); uint month = getMonth(now); uint day = getDay(now); user.nodeState = 3; user.nodeOrder.operation_time = now; uint signDuration = addDays(now,user.nodeOrder.day); user.nodeOrder.deadline_time = signDuration; uint256 fee = msg.value.mul(PROJECT_FEE).div(PERCENTS_DIVIDER); projectAddress.transfer(fee); emit FeePayed(msg.sender, fee); } //NODE_CONFIG.push(node_config({id:1,price : 5000 * 1000000,pre_price:1000 * 1000000,last_price:4000 * 1000000, percent : 5, day:5,sign1:19,sign2:31,sure_duration:5,sign_duration:3})); function updateSignTime(uint256 level,uint256 sign1,uint256 sign2) public payable IsInitialized { require(msg.sender == projectAddress , "projectAddress is error"); require(level >= 0 && level < NODE_CONFIG.length); require(sign1 > 0 && sign1 <= 48); require(sign2 > 0 && sign2 <= 48); node_config storage level_conf = NODE_CONFIG[level]; level_conf.sign1 = sign1; level_conf.sign2 = sign2; } function isContract(address addr) internal view returns (bool) { uint size; assembly {size := extcodesize(addr)} return size > 0; } } library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function add64(uint256 a, uint64 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function min(uint256 a, uint256 b) internal pure returns (uint256) { return a > b ? b : a; } function max(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? b : a; } function min64(uint256 a, uint64 b) internal pure returns (uint256) { return a > b ? b : a; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); uint256 c = a - b; return c; } function sub64(uint256 a, uint64 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function mul64(uint256 a, uint64 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); uint256 c = a / b; return c; } function div64(uint256 a, uint64 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); uint256 c = a / b; return c; } } interface IERC20 { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); }
NODE_CONFIG.push(node_config({id:1,price : 5000 1000000,pre_price:1000 1000000,last_price:4000 1000000, percent : 5, day:5,sign1:19,sign2:31,sure_duration:5,sign_duration:3}));
function updateSignTime(uint256 level,uint256 sign1,uint256 sign2) public payable IsInitialized { require(msg.sender == projectAddress , "projectAddress is error"); require(level >= 0 && level < NODE_CONFIG.length); require(sign1 > 0 && sign1 <= 48); require(sign2 > 0 && sign2 <= 48); node_config storage level_conf = NODE_CONFIG[level]; level_conf.sign1 = sign1; level_conf.sign2 = sign2; }
15,851,391
pragma solidity ^0.4.22; contract AddressProxy { /** * @dev The owner owns the address proxy and has the highest access */ address public owner; /** * @dev The client is the address that has day to day access */ address public client; /** * @dev If the proxy is locked, the client can't access the proxy anymore */ bool public locked; /** * @param _owner the address that "own" the proxy and interact with it most of the time * @param _client this is the "master" address and can swap the client address */ constructor(address _owner, address _client) public { owner = _owner; client = _client; locked = false; } modifier auth() { require(msg.sender == owner || msg.sender == client); _; } modifier onlyOwner() { require(msg.sender == owner); _; } modifier isUnlocked() { require(locked == false); _; } event ChangedOwner(address _newOwner); event ChangedClient(address _newClient); //make contract payable function() payable public {} /** * @param _location is the target contract address * @param _data is "what" you want to execute on the target contract * @param _ether the amount of ether to send with the execution (IN WEI) */ function exec(address _location, bytes _data, uint256 _ether) payable external auth() isUnlocked() { require(_location.call.value(_ether)(_data)); } /** * @param _to the address to where you want to send ether * @param _amount the amount of ether you want to send IN WEI */ function sendEther(address _to, uint _amount) external auth() isUnlocked() { _to.transfer(_amount); } /** * @param _location is the target contract address * @param _data is "what" you want to execute on the target contract * @param _value how much ether should be transferred (in wei) * @param _gas the amount of gas in wei */ function execCustom(address _location, bytes _data, uint256 _value, uint256 _gas) payable external auth() isUnlocked() { require(_location.call.value(_value).gas(_gas)(_data)); } /** * @dev lock's down the proxy and prevent the call of "exec" by ownerAddress and recoveryAddress */ function lock() external auth() { locked = true; } /** * @dev unlock's the proxy. Can only be done by recovery address */ function unlock() external onlyOwner() { locked = false; } /** * @dev set new owner of proxy contract and remove the old one * @param _newOwner the new owner */ function changeOwner(address _newOwner) external onlyOwner() { owner = _newOwner; emit ChangedOwner(owner); } /** * @dev Change the client address * @param _newClient the new client */ function changeClient(address _newClient) external onlyOwner() { client = _newClient; emit ChangedClient(client); } }
unlock's the proxy. Can only be done by recovery address/
function unlock() external onlyOwner() { locked = false; }
6,894,802
/** *Submitted for verification at Etherscan.io on 2021-04-25 */ pragma solidity ^0.4.23; // ---------------------------------------------------------------------------- // // Moon Pets (Moon Pets) token public sale contract ERC20 Version // // For details, please visit: http://moonpets.org // // // Written by Moon Pets [email protected] // // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- // // SafeMath // // ---------------------------------------------------------------------------- library SafeMath { function add(uint a, uint b) internal pure returns (uint c) { c = a + b; require(c >= a); } function sub(uint a, uint b) internal pure returns (uint c) { require(b <= a); c = a - b; } function mul(uint a, uint b) internal pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } } // ---------------------------------------------------------------------------- // // Owned // // ---------------------------------------------------------------------------- contract Owned { address public owner; address public newOwner; mapping(address => bool) public isAdmin; event OwnershipTransferProposed(address indexed _from, address indexed _to); event OwnershipTransferred(address indexed _from, address indexed _to); event AdminChange(address indexed _admin, bool _status); modifier onlyOwner {require(msg.sender == owner); _;} modifier onlyAdmin {require(isAdmin[msg.sender]); _;} constructor() public { owner = msg.sender; isAdmin[owner] = true; } function transferOwnership(address _newOwner) public onlyOwner { require(_newOwner != address(0x0)); emit OwnershipTransferProposed(owner, _newOwner); newOwner = _newOwner; } function acceptOwnership() public { require(msg.sender == newOwner); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } function addAdmin(address _a) public onlyOwner { require(isAdmin[_a] == false); isAdmin[_a] = true; emit AdminChange(_a, true); } function removeAdmin(address _a) public onlyOwner { require(isAdmin[_a] == true); isAdmin[_a] = false; emit AdminChange(_a, false); } } // ---------------------------------------------------------------------------- // // Wallet // // ---------------------------------------------------------------------------- contract Wallet is Owned { address public wallet; event WalletUpdated(address newWallet); constructor() public { wallet = owner; } function setWallet(address _wallet) public onlyOwner { require(_wallet != address(0x0)); wallet = _wallet; emit WalletUpdated(_wallet); } } // ---------------------------------------------------------------------------- // // ERC20Interface // // ---------------------------------------------------------------------------- contract ERC20Interface { event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); function totalSupply() public view returns (uint); function balanceOf(address _owner) public view returns (uint balance); function transfer(address _to, uint _value) public returns (bool success); function transferFrom(address _from, address _to, uint _value) public returns (bool success); function approve(address _spender, uint _value) public returns (bool success); function allowance(address _owner, address _spender) public view returns (uint remaining); } // ---------------------------------------------------------------------------- // // ERC20 Token Standard // // ---------------------------------------------------------------------------- contract ERC20Token is ERC20Interface, Owned { using SafeMath for uint; uint public tokensIssuedTotal; mapping(address => uint) balances; mapping(address => mapping (address => uint)) allowed; function totalSupply() public view returns (uint) { return tokensIssuedTotal; } // Includes BOTH locked AND unlocked tokens function balanceOf(address _owner) public view returns (uint) { return balances[_owner]; } function transfer(address _to, uint _amount) public returns (bool) { require(_to != 0x0); balances[msg.sender] = balances[msg.sender].sub(_amount); balances[_to] = balances[_to].add(_amount); emit Transfer(msg.sender, _to, _amount); return true; } function approve(address _spender, uint _amount) public returns (bool) { allowed[msg.sender][_spender] = _amount; emit Approval(msg.sender, _spender, _amount); return true; } function transferFrom(address _from, address _to, uint _amount) public returns (bool) { require(_to != 0x0); balances[_from] = balances[_from].sub(_amount); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount); balances[_to] = balances[_to].add(_amount); emit Transfer(_from, _to, _amount); return true; } function allowance(address _owner, address _spender) public view returns (uint) { return allowed[_owner][_spender]; } } // ---------------------------------------------------------------------------- // // LockSlots // // ---------------------------------------------------------------------------- contract LockSlots is ERC20Token { using SafeMath for uint; uint public constant LOCK_SLOTS = 5; mapping(address => uint[LOCK_SLOTS]) public lockTerm; mapping(address => uint[LOCK_SLOTS]) public lockAmnt; mapping(address => bool) public mayHaveLockedTokens; event RegisteredLockedTokens(address indexed account, uint indexed idx, uint tokens, uint term); function registerLockedTokens(address _account, uint _tokens, uint _term) internal returns (uint idx) { require(_term > now, "lock term must be in the future"); // find a slot (clean up while doing this) // use either the existing slot with the exact same term, // of which there can be at most one, or the first empty slot idx = 9999; uint[LOCK_SLOTS] storage term = lockTerm[_account]; uint[LOCK_SLOTS] storage amnt = lockAmnt[_account]; for (uint i; i < LOCK_SLOTS; i++) { if (term[i] < now) { term[i] = 0; amnt[i] = 0; if (idx == 9999) idx = i; } if (term[i] == _term) idx = i; } // fail if no slot was found require(idx != 9999, "registerLockedTokens: no available slot found"); // register locked tokens if (term[idx] == 0) term[idx] = _term; amnt[idx] = amnt[idx].add(_tokens); mayHaveLockedTokens[_account] = true; emit RegisteredLockedTokens(_account, idx, _tokens, _term); } // public view functions function lockedTokens(address _account) public view returns (uint) { if (!mayHaveLockedTokens[_account]) return 0; return pNumberOfLockedTokens(_account); } function unlockedTokens(address _account) public view returns (uint) { return balances[_account].sub(lockedTokens(_account)); } function isAvailableLockSlot(address _account, uint _term) public view returns (bool) { if (!mayHaveLockedTokens[_account]) return true; if (_term < now) return true; uint[LOCK_SLOTS] storage term = lockTerm[_account]; for (uint i; i < LOCK_SLOTS; i++) { if (term[i] < now || term[i] == _term) return true; } return false; } // internal and private functions function unlockedTokensInternal(address _account) internal returns (uint) { // updates mayHaveLockedTokens if necessary if (!mayHaveLockedTokens[_account]) return balances[_account]; uint locked = pNumberOfLockedTokens(_account); if (locked == 0) mayHaveLockedTokens[_account] = false; return balances[_account].sub(locked); } function pNumberOfLockedTokens(address _account) private view returns (uint locked) { uint[LOCK_SLOTS] storage term = lockTerm[_account]; uint[LOCK_SLOTS] storage amnt = lockAmnt[_account]; for (uint i; i < LOCK_SLOTS; i++) { if (term[i] >= now) locked = locked.add(amnt[i]); } } } // ---------------------------------------------------------------------------- // // MoonPetsIcoDates // // ---------------------------------------------------------------------------- contract MoonPetsIcoDates is Owned { uint public dateMainStart = 1619859600; // 1-MAY-2021 09:00 GMT +0 uint public dateMainEnd = 1620464400; // 8-MAY-2021 09:00 GMT +0 uint public constant DATE_LIMIT = 1620464400 + 180 days; event IcoDateUpdated(uint id, uint unixts); // check dates modifier checkDateOrder { _ ; require ( dateMainStart < dateMainEnd ) ; require ( dateMainEnd < DATE_LIMIT ) ; } constructor() public checkDateOrder() { require(now < dateMainStart); } // set ico dates function setDateMainStart(uint _unixts) public onlyOwner checkDateOrder { require(now < _unixts && now < dateMainStart); dateMainStart = _unixts; emit IcoDateUpdated(1, _unixts); } function setDateMainEnd(uint _unixts) public onlyOwner checkDateOrder { require(now < _unixts && now < dateMainEnd); dateMainEnd = _unixts; emit IcoDateUpdated(2, _unixts); } // where are we? Passed first day or not? function isMainFirstDay() public view returns (bool) { if (now > dateMainStart && now <= dateMainStart + 1 days) return true; return false; } function isMain() public view returns (bool) { if (now > dateMainStart && now < dateMainEnd) return true; return false; } } // ---------------------------------------------------------------------------- // // Moon Pets public token sale // // ---------------------------------------------------------------------------- contract MoonPetsToken is ERC20Token, Wallet, LockSlots, MoonPetsIcoDates { // Utility variable uint constant E18 = 10**18; // Basic token data string public constant name = "Moon Pets Token"; string public constant symbol = "PETS"; uint8 public constant decimals = 18; // Token number of possible tokens in existance 3333333333 uint public constant MAX_TOTAL_TOKEN_SUPPLY = 3333333333 * E18; // ICO parameters // Opening ETH Rate: USD$1827.28 // Therefore, 1 ETH = 45682 PETS uint public tokensPerEth = 45682; // USD$2,000,000/1827.28 = 1094.523006 ether // 1094.523006 ether/2551 addresses = 0.429056450 ether per address for the first 24 hours // 65,999,999,988 MainNet Coins / 19.79999999838 = 3,333,333,333 Tokens Total Supply uint public constant MINIMUM_CONTRIBUTION = 0.2 ether; uint public constant MAXIMUM_FIRST_DAY_CONTRIBUTION = 0.429056450 ether; uint public constant TOKEN_MAIN_CAP = 50000000 * E18; bool public tokensTradeable; // whitelisting mapping(address => bool) public whitelist; uint public numberWhitelisted; // track main sale uint public tokensMain; mapping(address => uint) public balancesMain; uint public totalEthContributed; mapping(address => uint) public ethContributed; // tracking tokens minted uint public tokensMinted; mapping(address => uint) public balancesMinted; mapping(address => mapping(uint => uint)) public balancesMintedByType; // migration variable bool public isMigrationPhaseOpen; // Events --------------------------------------------- event UpdatedTokensPerEth(uint tokensPerEth); event Whitelisted(address indexed account, uint countWhitelisted); event TokensMinted(uint indexed mintType, address indexed account, uint tokens, uint term); event RegisterContribution(address indexed account, uint tokensIssued, uint ethContributed, uint ethReturned); event TokenExchangeRequested(address indexed account, uint tokens); // Basic Functions ------------------------------------ constructor() public {} function () public payable { buyTokens(); } // Information functions function availableToMint() public view returns (uint) { return MAX_TOTAL_TOKEN_SUPPLY.sub(TOKEN_MAIN_CAP).sub(tokensMinted); } function firstDayTokenLimit() public view returns (uint) { return ethToTokens(MAXIMUM_FIRST_DAY_CONTRIBUTION); } function ethToTokens(uint _eth) public view returns (uint tokens) { tokens = _eth.mul(tokensPerEth); } function tokensToEth(uint _tokens) public view returns (uint eth) { eth = _tokens / tokensPerEth; } // Admin functions function addToWhitelist(address _account) public onlyAdmin { pWhitelist(_account); } function addToWhitelistMultiple(address[] _addresses) public onlyAdmin { for (uint i; i < _addresses.length; i++) { pWhitelist(_addresses[i]); } } function pWhitelist(address _account) internal { if (whitelist[_account]) return; whitelist[_account] = true; numberWhitelisted = numberWhitelisted.add(1); emit Whitelisted(_account, numberWhitelisted); } // Owner functions ------------------------------------ function updateTokensPerEth(uint _tokens_per_eth) public onlyOwner { require(now < dateMainStart); tokensPerEth = _tokens_per_eth; emit UpdatedTokensPerEth(tokensPerEth); } // Only owner can make tokens tradable at any time, or if the date is // greater than the end of the mainsale date plus 20 weeks, allow // any caller to make tokensTradeable. function makeTradeable() public { require(msg.sender == owner || now > dateMainEnd + 20 weeks); tokensTradeable = true; } function openMigrationPhase() public onlyOwner { require(now > dateMainEnd); isMigrationPhaseOpen = true; } // Token minting -------------------------------------- function mintTokens(uint _mint_type, address _account, uint _tokens) public onlyOwner { pMintTokens(_mint_type, _account, _tokens, 0); } function mintTokensMultiple(uint _mint_type, address[] _accounts, uint[] _tokens) public onlyOwner { require(_accounts.length == _tokens.length); for (uint i; i < _accounts.length; i++) { pMintTokens(_mint_type, _accounts[i], _tokens[i], 0); } } function mintTokensLocked(uint _mint_type, address _account, uint _tokens, uint _term) public onlyOwner { pMintTokens(_mint_type, _account, _tokens, _term); } function mintTokensLockedMultiple(uint _mint_type, address[] _accounts, uint[] _tokens, uint[] _terms) public onlyOwner { require(_accounts.length == _tokens.length); require(_accounts.length == _terms.length); for (uint i; i < _accounts.length; i++) { pMintTokens(_mint_type, _accounts[i], _tokens[i], _terms[i]); } } function pMintTokens(uint _mint_type, address _account, uint _tokens, uint _term) private { require(whitelist[_account]); require(_account != 0x0); require(_tokens > 0); require(_tokens <= availableToMint(), "not enough tokens available to mint"); require(_term == 0 || _term > now, "either without lock term, or lock term must be in the future"); // register locked tokens (will throw if no slot is found) if (_term > 0) registerLockedTokens(_account, _tokens, _term); // update balances[_account] = balances[_account].add(_tokens); balancesMinted[_account] = balancesMinted[_account].add(_tokens); balancesMintedByType[_account][_mint_type] = balancesMintedByType[_account][_mint_type].add(_tokens); tokensMinted = tokensMinted.add(_tokens); tokensIssuedTotal = tokensIssuedTotal.add(_tokens); // log event emit Transfer(0x0, _account, _tokens); emit TokensMinted(_mint_type, _account, _tokens, _term); } // Main sale ------------------------------------------ function buyTokens() private { require(isMain()); require(msg.value >= MINIMUM_CONTRIBUTION); require(whitelist[msg.sender]); uint tokens_available = TOKEN_MAIN_CAP.sub(tokensMain); // adjust tokens_available on first day, if necessary if (isMainFirstDay()) { uint tokens_available_first_day = firstDayTokenLimit().sub(balancesMain[msg.sender]); if (tokens_available_first_day < tokens_available) { tokens_available = tokens_available_first_day; } } require (tokens_available > 0); uint tokens_requested = ethToTokens(msg.value); uint tokens_issued = tokens_requested; uint eth_contributed = msg.value; uint eth_returned; if (tokens_requested > tokens_available) { tokens_issued = tokens_available; eth_returned = tokensToEth(tokens_requested.sub(tokens_available)); eth_contributed = msg.value.sub(eth_returned); } balances[msg.sender] = balances[msg.sender].add(tokens_issued); balancesMain[msg.sender] = balancesMain[msg.sender].add(tokens_issued); tokensMain = tokensMain.add(tokens_issued); tokensIssuedTotal = tokensIssuedTotal.add(tokens_issued); ethContributed[msg.sender] = ethContributed[msg.sender].add(eth_contributed); totalEthContributed = totalEthContributed.add(eth_contributed); // ether transfers if (eth_returned > 0) msg.sender.transfer(eth_returned); wallet.transfer(eth_contributed); // log emit Transfer(0x0, msg.sender, tokens_issued); emit RegisterContribution(msg.sender, tokens_issued, eth_contributed, eth_returned); } // Token exchange / migration to new platform --------- function requestTokenExchangeMax() public { requestTokenExchange(unlockedTokensInternal(msg.sender)); } function requestTokenExchange(uint _tokens) public { require(isMigrationPhaseOpen); require(_tokens > 0 && _tokens <= unlockedTokensInternal(msg.sender)); balances[msg.sender] = balances[msg.sender].sub(_tokens); tokensIssuedTotal = tokensIssuedTotal.sub(_tokens); emit Transfer(msg.sender, 0x0, _tokens); emit TokenExchangeRequested(msg.sender, _tokens); } // ERC20 functions ------------------- /* Transfer out any accidentally sent ERC20 tokens */ function transferAnyERC20Token(address _token_address, uint _amount) public onlyOwner returns (bool success) { return ERC20Interface(_token_address).transfer(owner, _amount); } /* Override "transfer" */ function transfer(address _to, uint _amount) public returns (bool success) { require(tokensTradeable); require(_amount <= unlockedTokensInternal(msg.sender)); return super.transfer(_to, _amount); } /* Override "transferFrom" */ function transferFrom(address _from, address _to, uint _amount) public returns (bool success) { require(tokensTradeable); require(_amount <= unlockedTokensInternal(_from)); return super.transferFrom(_from, _to, _amount); } /* Multiple token transfers from one address to save gas */ function transferMultiple(address[] _addresses, uint[] _amounts) external { require(_addresses.length <= 100); require(_addresses.length == _amounts.length); // do the transfers for (uint j; j < _addresses.length; j++) { transfer(_addresses[j], _amounts[j]); } } }
register locked tokens (will throw if no slot is found) update log event
function pMintTokens(uint _mint_type, address _account, uint _tokens, uint _term) private { require(whitelist[_account]); require(_account != 0x0); require(_tokens > 0); require(_tokens <= availableToMint(), "not enough tokens available to mint"); require(_term == 0 || _term > now, "either without lock term, or lock term must be in the future"); if (_term > 0) registerLockedTokens(_account, _tokens, _term); balances[_account] = balances[_account].add(_tokens); balancesMinted[_account] = balancesMinted[_account].add(_tokens); balancesMintedByType[_account][_mint_type] = balancesMintedByType[_account][_mint_type].add(_tokens); tokensMinted = tokensMinted.add(_tokens); tokensIssuedTotal = tokensIssuedTotal.add(_tokens); emit Transfer(0x0, _account, _tokens); emit TokensMinted(_mint_type, _account, _tokens, _term); }
2,275,983
./partial_match/42220/0x5ac97fE208fD7c581d1595d28eaF52b9368ECB34/sources/project_/contracts/utils/AdminWallet.sol
Function to remove list of addresses to admins can only be called by creator of contract _admins the list of addresses to remove/
function removeAdmins(address[] memory _admins) public onlyOwner { for (uint256 i = 0; i < _admins.length; i++) { revokeRole(WALLET_ADMIN_ROLE, _admins[i]); } emit AdminsRemoved(_admins); }
3,496,941
./full_match/4/0xe03C64Bd96e90108A38085c1C68FC55fb52eaC5b/sources/crowdsale.sol
/// transfer the ETH and store if it succeeded or not
function safeTransferETH(address to, uint256 amount) internal { bool callStatus; assembly { callStatus := call(gas(), to, amount, 0, 0, 0, 0) } require(callStatus, "ETH_TRANSFER_FAILED"); } ERC20 OPERATIONS
721,333
./full_match/5/0x204Bc468cc9333A7Aac12aC2dBe03DcCFe9f03d0/sources/contracts/protocol/extensions/adapters/AUniswapV3NPM.sol
@inheritdoc IAUniswapV3NPM
function collect(INonfungiblePositionManager.CollectParams calldata params) external override returns (uint256 amount0, uint256 amount1) { (amount0, amount1) = INonfungiblePositionManager(_getUniswapNpm()).collect( INonfungiblePositionManager.CollectParams({ tokenId: params.tokenId, amount0Max: params.amount0Max, amount1Max: params.amount1Max }) ); }
7,040,053
./partial_match/1/0x1ec3Ee6066c109e77C78175A38F1B66CF702338B/sources/FxERC20RootTunnel.sol
return number of payload items inside an encoded list. skip over an item
function numItems(RLPItem memory item) private pure returns (uint256) { if (item.len == 0) return 0; uint256 count = 0; uint256 currPtr = item.memPtr + _payloadOffset(item.memPtr); uint256 endPtr = item.memPtr + item.len; while (currPtr < endPtr) { currPtr = currPtr + _itemLength(currPtr); count++; } return count; }
2,593,848
pragma solidity ^0.5.0; import "./TellorData.sol"; contract TellorStorage is TellorData{ /*Variables*/ //address public tellorStorageOwner;//TellorStorage Owner address //address public tellorContract;//Tellor address /*Event*/ event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); event newTellorContract(address indexed _tellorContract); /*Modifiers*/ modifier onlyOwner() { require(msg.sender == tellorStorageOwner); _; } /** * @dev The constructor sets the original `tellorStorageOwner` of the contract to the sender * account. */ constructor () public{ tellorStorageOwner = msg.sender; } /** *@dev Sets the Tellor contract address *@param _memberContract The new membership address */ function setTellorContract(address _tellorContract) public onlyOwner() { tellorContract = _tellorContract; emit newTellorContract(_tellorContract); } /** * @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) external { require(msg.sender == getStorageOwner()); emit OwnershipTransferred(tellorStorageOwner, newOwner); tellorStorageOwner = newOwner; } /** * @return the address of the owner. */ function getStorageOwner() public view returns (address) { return tellorStorageOwner; } function () external payable { address addr = tellorContract; assembly { let freememstart := mload(0x40) calldatacopy(freememstart, 0, calldatasize()) let success := delegatecall(not(0), addr, freememstart, calldatasize(), freememstart, 32) switch success case 0 { revert(freememstart, 32) } default { return(freememstart, 32) } } } }
Sets the Tellor contract address _memberContract The new membership address/
function setTellorContract(address _tellorContract) public onlyOwner() { tellorContract = _tellorContract; emit newTellorContract(_tellorContract); }
12,602,657
/** Contract to enable the management of ZKSnark-hidden coin transactions. @Author Westlad, Chaitanya-Konda, iAmMichaelConnor */ pragma solidity ^0.5.8; import "./Ownable.sol"; import "./Verifier_Registry.sol"; //we import the implementation to have visibility of its 'getters' import "./Verifier_Interface.sol"; import "./ERC20Interface.sol"; contract FTokenShield is Ownable { /* @notice Explanation of the Merkle Tree, in this contract: We store the merkle tree nodes in a flat array. 0 <-- this is our Merkle Root / \ 1 2 / \ / \ 3 4 5 6 / \ / \ / \ / \ 7 8 9 10 11 12 13 14 / \ / \ / \ / \ / \ / \ / \ / \ 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 depth row width st# end# 1 0 2^0=1 w=0 2^1-1=0 2 1 2^1=2 w=1 2^2-1=2 3 2 2^2=4 w=3 2^3-1=6 4 3 2^3=8 w=7 2^4-1=14 5 4 2^4=16 w=15 2^5-1=30 d = depth = 5 r = row number w = width = 2^(depth-1) = 2^3 = 16 #nodes = (2^depth)-1 = 2^5-2 = 30 */ event Mint(uint256 amount, bytes32 commitment, uint256 commitment_index); event Transfer(bytes32 nullifier1, bytes32 nullifier2, bytes32 commitment1, uint256 commitment1_index, bytes32 commitment2, uint256 commitment2_index); event Burn(uint256 amount, address payTo, bytes32 nullifier); event VerifierChanged(address newVerifierContract); event VkIdsChanged(bytes32 mintVkId, bytes32 transferVkId, bytes32 burnVkId); uint constant merkleWidth = 4294967296; //2^32 uint constant merkleDepth = 33; //33 uint private balance = 0; uint256 constant bn128Prime = 21888242871839275222246405745257275088548364400416034343698204186575808495617; mapping(bytes32 => bytes32) public nullifiers; // store nullifiers of spent commitments mapping(bytes32 => bytes32) public commitments; // array holding the commitments. Basically the bottom row of the merkle tree mapping(uint256 => bytes27) public merkleTree; // the entire Merkle Tree of nodes, with 0 being the root, and the latter 'half' of the merkleTree being the leaves. mapping(bytes32 => bytes32) public roots; // holds each root we've calculated so that we can pull the one relevant to the prover uint256 public leafCount; // remembers the number of commitments we hold bytes32 public latestRoot; // holds the index for the latest root so that the prover can provide it later and this contract can look up the relevant root Verifier_Registry public verifierRegistry; // the Verifier Registry contract Verifier_Interface private verifier; // the verification smart contract ERC20Interface private fToken; // the ERC-20 token contract //following registration of the vkId's with the Verifier Registry, we hard code their vkId's in setVkIds bytes32 public mintVkId; bytes32 public transferVkId; bytes32 public burnVkId; constructor(address _verifierRegistry, address _verifier, address _fToken) public { _owner = msg.sender; verifierRegistry = Verifier_Registry(_verifierRegistry); verifier = Verifier_Interface(_verifier); fToken = ERC20Interface(_fToken); } /** function to change the address of the underlying Verifier contract */ function changeVerifier(address _verifier) external onlyOwner { verifier = Verifier_Interface(_verifier); emit VerifierChanged(_verifier); } /** self destruct */ function close() public onlyOwner { selfdestruct(address(uint160(_owner))); } /** returns the verifier-interface contract address that this shield contract is calling */ function getVerifier() public view returns(address){ return address(verifier); } /** Sets the vkIds (as registered with the Verifier Registry) which correspond to 'mint', 'transfer' and 'burn' computations respectively */ function setVkIds(bytes32 _mintVkId, bytes32 _transferVkId, bytes32 _burnVkId) external onlyOwner { //ensure the vkId's have been registered: require(_mintVkId == verifierRegistry.getVkEntryVkId(_mintVkId), "Mint vkId not registered."); require(_transferVkId == verifierRegistry.getVkEntryVkId(_transferVkId), "Transfer vkId not registered."); require(_burnVkId == verifierRegistry.getVkEntryVkId(_burnVkId), "Burn vkId not registered."); //store the vkIds mintVkId = _mintVkId; transferVkId = _transferVkId; burnVkId = _burnVkId; emit VkIdsChanged(mintVkId, transferVkId, burnVkId); } /** returns the ERC-20 contract address that this shield contract is calling */ function getFToken() public view returns(address){ return address(fToken); } /** The mint function accepts fungible tokens from the specified fToken ERC-20 contract and creates the same amount as a commitment. */ function mint(uint256[] calldata _proof, uint256[] calldata _inputs, bytes32 _vkId, uint128 _value, bytes32 _commitment) external { require(_vkId == mintVkId, "Incorrect vkId"); // Check that the publicInputHash equals the hash of the 'public inputs': bytes31 publicInputHash = bytes31(bytes32(_inputs[0])<<8); bytes31 publicInputHashCheck = bytes31(sha256(abi.encodePacked(uint128(_value), _commitment))<<8); // Note that we force the _value to be left-padded with zeros to fill 128-bits, so as to match the padding in the hash calculation performed within the zokrates proof. require(publicInputHashCheck == publicInputHash, "publicInputHash cannot be reconciled"); // verify the proof bool result = verifier.verify(_proof, _inputs, _vkId); require(result, "The proof has not been verified by the contract"); // update contract states uint256 leafIndex = merkleWidth - 1 + leafCount; // specify the index of the commitment within the merkleTree merkleTree[leafIndex] = bytes27(_commitment<<40); // add the commitment to the merkleTree commitments[_commitment] = _commitment; // add the commitment bytes32 root = updatePathToRoot(leafIndex); // recalculate the root of the merkleTree as it's now different roots[root] = root; // and save the new root to the list of roots latestRoot = root; // Finally, transfer the fTokens from the sender to this contract fToken.transferFrom(msg.sender, address(this), _value); emit Mint(_value, _commitment, leafCount++); } /** The transfer function transfers a commitment to a new owner */ function transfer(uint256[] calldata _proof, uint256[] calldata _inputs, bytes32 _vkId, bytes32 _root, bytes32 _nullifierC, bytes32 _nullifierD, bytes32 _commitmentE, bytes32 _commitmentF) external { require(_vkId == transferVkId, "Incorrect vkId"); // Check that the publicInputHash equals the hash of the 'public inputs': bytes31 publicInputHash = bytes31(bytes32(_inputs[0])<<8); bytes31 publicInputHashCheck = bytes31(sha256(abi.encodePacked(_root, _nullifierC, _nullifierD, _commitmentE, _commitmentF))<<8); require(publicInputHashCheck == publicInputHash, "publicInputHash cannot be reconciled"); // verify the proof bool result = verifier.verify(_proof, _inputs, _vkId); require(result, "The proof has not been verified by the contract"); // check inputs vs on-chain states require(roots[_root] == _root, "The input root has never been the root of the Merkle Tree"); require(_nullifierC != _nullifierD, "The two input nullifiers must be different!"); require(_commitmentE != _commitmentF, "The new commitments (commitmentE and commitmentF) must be different!"); require(nullifiers[_nullifierC] == 0, "The commitment being spent (commitmentE) has already been nullified!"); require(nullifiers[_nullifierD] == 0, "The commitment being spent (commitmentF) has already been nullified!"); // update contract states nullifiers[_nullifierC] = _nullifierC; //remember we spent it nullifiers[_nullifierD] = _nullifierD; //remember we spent it commitments[_commitmentE] = _commitmentE; //add the commitment to the list of commitments uint256 leafIndex = merkleWidth - 1 + leafCount++; //specify the index of the commitment within the merkleTree merkleTree[leafIndex] = bytes27(_commitmentE<<40); //add the commitment to the merkleTree updatePathToRoot(leafIndex); commitments[_commitmentF] = _commitmentF; //add the commitment to the list of commitments leafIndex = merkleWidth - 1 + leafCount; //specify the index of the commitment within the merkleTree merkleTree[leafIndex] = bytes27(_commitmentF<<40); //add the commitment to the merkleTree latestRoot = updatePathToRoot(leafIndex);//recalculate the root of the merkleTree as it's now different roots[latestRoot] = latestRoot; //and save the new root to the list of roots emit Transfer(_nullifierC, _nullifierD, _commitmentE, leafCount - 1, _commitmentF, leafCount++); } function burn(uint256[] calldata _proof, uint256[] calldata _inputs, bytes32 _vkId, bytes32 _root, bytes32 _nullifier, uint128 _value, uint256 _payTo) external { require(_vkId == burnVkId, "Incorrect vkId"); // Check that the publicInputHash equals the hash of the 'public inputs': bytes31 publicInputHash = bytes31(bytes32(_inputs[0])<<8); bytes31 publicInputHashCheck = bytes31(sha256(abi.encodePacked(_root, _nullifier, uint128(_value), _payTo))<<8); // Note that although _payTo represents an address, we have declared it as a uint256. This is because we want it to be abi-encoded as a bytes32 (left-padded with zeros) so as to match the padding in the hash calculation performed within the zokrates proof. Similarly, we force the _value to be left-padded with zeros to fill 128-bits. require(publicInputHashCheck == publicInputHash, "publicInputHash cannot be reconciled"); // verify the proof bool result = verifier.verify(_proof, _inputs, _vkId); require(result, "The proof has not been verified by the contract"); // check inputs vs on-chain states require(roots[_root] == _root, "The input root has never been the root of the Merkle Tree"); require(nullifiers[_nullifier]==0, "The commitment being spent has already been nullified!"); nullifiers[_nullifier] = _nullifier; // add the nullifier to the list of nullifiers //Finally, transfer the fungible tokens from this contract to the nominated address address payToAddress = address(_payTo); // we passed _payTo as a uint256, to ensure the packing was correct within the sha256() above fToken.transfer(payToAddress, _value); emit Burn(_value, payToAddress, _nullifier); } /** Updates each node of the Merkle Tree on the path from leaf to root. p - is the leafIndex of the new commitment within the merkleTree. */ function updatePathToRoot(uint p) private returns (bytes32) { /* If Z were the commitment, then the p's mark the 'path', and the s's mark the 'sibling path' p p s s p EF GH A B Z s E F G H */ uint s; //s is the 'sister' path of p. uint t; //temp index for the next p (i.e. the path node of the row above) bytes32 h; //hash for (uint r = merkleDepth-1; r > 0; r--) { if (p%2 == 0) { //p even index in the merkleTree s = p-1; t = (p-1)/2; h = sha256(abi.encodePacked(merkleTree[s],merkleTree[p])); merkleTree[t] = bytes27(h<<40); } else { //p odd index in the merkleTree s = p+1; t = p/2; h = sha256(abi.encodePacked(merkleTree[p],merkleTree[s])); merkleTree[t] = bytes27(h<<40); } p = t; //move to the path node on the next highest row of the tree } return h; //the (265-bit) root of the merkleTree } function packToBytes32(uint256 low, uint256 high) private pure returns (bytes32) { return (bytes32(high)<<128) | bytes32(low); } function packToUint256(uint256 low, uint256 high) private pure returns (uint256) { return uint256((bytes32(high)<<128) | bytes32(low)); } }
/ensure the vkId's have been registered:store the vkIds
function setVkIds(bytes32 _mintVkId, bytes32 _transferVkId, bytes32 _burnVkId) external onlyOwner { require(_mintVkId == verifierRegistry.getVkEntryVkId(_mintVkId), "Mint vkId not registered."); require(_transferVkId == verifierRegistry.getVkEntryVkId(_transferVkId), "Transfer vkId not registered."); require(_burnVkId == verifierRegistry.getVkEntryVkId(_burnVkId), "Burn vkId not registered."); mintVkId = _mintVkId; transferVkId = _transferVkId; burnVkId = _burnVkId; emit VkIdsChanged(mintVkId, transferVkId, burnVkId); }
6,350,697
// SPDX-License-Identifier: UNLICENSED pragma solidity =0.7.6; import {IUniswapV3Factory} from '@uniswap/v3-core/contracts/interfaces/IUniswapV3Factory.sol'; import {Ownable} from '@openzeppelin/contracts/access/Ownable.sol'; import {Hypervisor} from './Hypervisor.sol'; contract HypervisorFactory is Ownable { IUniswapV3Factory public uniswapV3Factory; mapping(address => mapping(address => mapping(uint24 => address))) public getHypervisor; // toke0, token1, fee -> hypervisor address address[] public allHypervisors; event HypervisorCreated(address token0, address token1, uint24 fee, address hypervisor, uint256); constructor(address _uniswapV3Factory) { uniswapV3Factory = IUniswapV3Factory(_uniswapV3Factory); } function allHypervisorsLength() external view returns (uint256) { return allHypervisors.length; } function createHypervisor( address tokenA, address tokenB, uint24 fee, int24 _baseLower, int24 _baseUpper, int24 _limitLower, int24 _limitUpper ) external onlyOwner returns (address hypervisor) { require(tokenA != tokenB, 'SF: IDENTICAL_ADDRESSES'); // TODO: using PoolAddress library (uniswap-v3-periphery) (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), 'SF: ZERO_ADDRESS'); require(getHypervisor[token0][token1][fee] == address(0), 'SF: HYPERVISOR_EXISTS'); int24 tickSpacing = uniswapV3Factory.feeAmountTickSpacing(fee); require(tickSpacing != 0, 'SF: INCORRECT_FEE'); address pool = uniswapV3Factory.getPool(token0, token1, fee); if (pool == address(0)) { pool = uniswapV3Factory.createPool(token0, token1, fee); } hypervisor = address( new Hypervisor{salt: keccak256(abi.encodePacked(token0, token1, fee, tickSpacing))}(pool, owner(), _baseLower, _baseUpper, _limitLower,_limitUpper) ); getHypervisor[token0][token1][fee] = hypervisor; getHypervisor[token1][token0][fee] = hypervisor; // populate mapping in the reverse direction allHypervisors.push(hypervisor); emit HypervisorCreated(token0, token1, fee, hypervisor, allHypervisors.length); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title The interface for the Uniswap V3 Factory /// @notice The Uniswap V3 Factory facilitates creation of Uniswap V3 pools and control over the protocol fees interface IUniswapV3Factory { /// @notice Emitted when the owner of the factory is changed /// @param oldOwner The owner before the owner was changed /// @param newOwner The owner after the owner was changed event OwnerChanged(address indexed oldOwner, address indexed newOwner); /// @notice Emitted when a pool is created /// @param token0 The first token of the pool by address sort order /// @param token1 The second token of the pool by address sort order /// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip /// @param tickSpacing The minimum number of ticks between initialized ticks /// @param pool The address of the created pool event PoolCreated( address indexed token0, address indexed token1, uint24 indexed fee, int24 tickSpacing, address pool ); /// @notice Emitted when a new fee amount is enabled for pool creation via the factory /// @param fee The enabled fee, denominated in hundredths of a bip /// @param tickSpacing The minimum number of ticks between initialized ticks for pools created with the given fee event FeeAmountEnabled(uint24 indexed fee, int24 indexed tickSpacing); /// @notice Returns the current owner of the factory /// @dev Can be changed by the current owner via setOwner /// @return The address of the factory owner function owner() external view returns (address); /// @notice Returns the tick spacing for a given fee amount, if enabled, or 0 if not enabled /// @dev A fee amount can never be removed, so this value should be hard coded or cached in the calling context /// @param fee The enabled fee, denominated in hundredths of a bip. Returns 0 in case of unenabled fee /// @return The tick spacing function feeAmountTickSpacing(uint24 fee) external view returns (int24); /// @notice Returns the pool address for a given pair of tokens and a fee, or address 0 if it does not exist /// @dev tokenA and tokenB may be passed in either token0/token1 or token1/token0 order /// @param tokenA The contract address of either token0 or token1 /// @param tokenB The contract address of the other token /// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip /// @return pool The pool address function getPool( address tokenA, address tokenB, uint24 fee ) external view returns (address pool); /// @notice Creates a pool for the given two tokens and fee /// @param tokenA One of the two tokens in the desired pool /// @param tokenB The other of the two tokens in the desired pool /// @param fee The desired fee for the pool /// @dev tokenA and tokenB may be passed in either order: token0/token1 or token1/token0. tickSpacing is retrieved /// from the fee. The call will revert if the pool already exists, the fee is invalid, or the token arguments /// are invalid. /// @return pool The address of the newly created pool function createPool( address tokenA, address tokenB, uint24 fee ) external returns (address pool); /// @notice Updates the owner of the factory /// @dev Must be called by the current owner /// @param _owner The new owner of the factory function setOwner(address _owner) external; /// @notice Enables a fee amount with the given tickSpacing /// @dev Fee amounts may never be removed once enabled /// @param fee The fee amount to enable, denominated in hundredths of a bip (i.e. 1e-6) /// @param tickSpacing The spacing between ticks to be enforced for all pools created with the given fee amount function enableFeeAmount(uint24 fee, int24 tickSpacing) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; import "hardhat/console.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/math/SignedSafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@uniswap/v3-core/contracts/interfaces/callback/IUniswapV3MintCallback.sol"; import "@uniswap/v3-core/contracts/interfaces/callback/IUniswapV3SwapCallback.sol"; import "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol"; import "@uniswap/v3-core/contracts/libraries/TickMath.sol"; import "@uniswap/v3-core/contracts/libraries/FullMath.sol"; import "@uniswap/v3-periphery/contracts/libraries/LiquidityAmounts.sol"; import "../interfaces/IVault.sol"; import "../interfaces/IUniversalVault.sol"; contract Hypervisor is IVault, IUniswapV3MintCallback, IUniswapV3SwapCallback, ERC20 { using SafeERC20 for IERC20; using SafeMath for uint256; using SignedSafeMath for int256; uint256 public constant MILLIBASIS = 100000; IUniswapV3Pool public pool; IERC20 public token0; IERC20 public token1; uint24 public fee; int24 public tickSpacing; int24 public baseLower; int24 public baseUpper; int24 public limitLower; int24 public limitUpper; address public owner; uint256 public deposit0Max; uint256 public deposit1Max; uint256 public maxTotalSupply; uint256 public penaltyPercent; mapping(address=>bool) public list; constructor( address _pool, address _owner, int24 _baseLower, int24 _baseUpper, int24 _limitLower, int24 _limitUpper ) ERC20("Visor ETH-USDT Uni v3", "vETH-USDTV3-1") { pool = IUniswapV3Pool(_pool); token0 = IERC20(pool.token0()); token1 = IERC20(pool.token1()); fee = pool.fee(); tickSpacing = pool.tickSpacing(); owner = _owner; baseLower = _baseLower; baseUpper = _baseUpper; limitLower = _limitLower; limitUpper = _limitUpper; maxTotalSupply = 0; // no cap deposit0Max = uint256(-1); deposit1Max = uint256(-1); penaltyPercent = 2; } function deposit( uint256 deposit0, uint256 deposit1, address to ) external override returns (uint256 shares) { require(deposit0 > 0 || deposit1 > 0, "deposits must be nonzero"); require(deposit0 < deposit0Max && deposit1 < deposit1Max, "deposits must be less than maximum amounts"); require(to != address(0) && to != address(this), "to"); require(list[to], "must be on the list"); // update fess for inclusion in total pool amounts (uint128 baseLiquidity,,) = _position(baseLower, baseUpper); if (baseLiquidity > 0) { pool.burn(baseLower, baseUpper, 0); } (uint128 limitLiquidity,,) = _position(limitLower, limitUpper); if (limitLiquidity > 0) { pool.burn(limitLower, limitUpper, 0); } int24 currentTick = currentTick(); uint160 sqrtPrice = TickMath.getSqrtRatioAtTick(currentTick); uint256 price = uint256(sqrtPrice).mul(uint256(sqrtPrice)).mul(1e18) >> (96 * 2); (uint256 pool0, uint256 pool1) = getTotalAmounts(); (shares,) = sharesCalculation(price, deposit0, deposit1, pool0, pool1); if (deposit0 > 0) { token0.safeTransferFrom(msg.sender, address(this), deposit0); } if (deposit1 > 0) { token1.safeTransferFrom(msg.sender, address(this), deposit1); } if (totalSupply() != 0) { uint256 pool0PricedInToken1 = pool0.mul(price).div(1e18); shares = shares.mul(totalSupply()).div(pool0PricedInToken1.add(pool1)); } _mint(to, shares); emit Deposit(msg.sender, to, shares, deposit0, deposit1); // Check total supply cap not exceeded. A value of 0 means no limit. require(maxTotalSupply == 0 || totalSupply() <= maxTotalSupply, "maxTotalSupply"); } function sharesCalculation( uint256 price, uint256 deposit0, uint256 deposit1, uint256 pool0, uint256 pool1 ) public returns (uint256 shares, uint256) { // tokens which help balance the pool are given 100% of their token1 // value in liquidity tokens if the deposit worsens the ratio, dock the // max - min amount `penaltyPercent` uint256 deposit0PricedInToken1 = deposit0.mul(price).div(1e18); uint256 pool0PricedInToken1 = pool0.mul(price).div(1e18); if (pool0PricedInToken1.add(deposit0PricedInToken1) >= pool1 && deposit0PricedInToken1 > deposit1) { shares = reduceByPercent(deposit0PricedInToken1.sub(deposit1), penaltyPercent); shares = shares.add(deposit1.mul(2)); } else if (pool0PricedInToken1 <= pool1 && deposit0PricedInToken1 < deposit1) { shares = reduceByPercent(deposit1.sub(deposit0PricedInToken1), penaltyPercent); shares = shares.add(deposit0PricedInToken1.mul(2)); } else if (pool0PricedInToken1.add(deposit0PricedInToken1) < pool1.add(deposit1) && deposit0PricedInToken1 < deposit1) { uint256 docked1 = pool1.add(deposit1).sub(pool0PricedInToken1.add(deposit0PricedInToken1)); shares = reduceByPercent(docked1, penaltyPercent); shares = deposit1.sub(docked1).add(deposit0PricedInToken1); } else if (pool0PricedInToken1.add(deposit0PricedInToken1) > pool1.add(deposit1) && deposit0PricedInToken1 > deposit1) { uint256 docked0 = pool0PricedInToken1.add(deposit0PricedInToken1).sub(pool1.add(deposit1)); shares = reduceByPercent(docked0, penaltyPercent); shares = deposit0PricedInToken1.sub(docked0).add(deposit1); } else { shares = deposit1.add(deposit0PricedInToken1); } return (shares, deposit0PricedInToken1.add(deposit1)); } function withdraw( uint256 shares, address to, address from ) external override returns (uint256 amount0, uint256 amount1) { require(shares > 0, "shares"); require(to != address(0), "to"); // Withdraw liquidity from Uniswap pool (uint256 base0, uint256 base1) = _burnLiquidity(baseLower, baseUpper, _liquidityForShares(baseLower, baseUpper, shares), to, false); (uint256 limit0, uint256 limit1) = _burnLiquidity(limitLower, limitUpper, _liquidityForShares(limitLower, limitUpper, shares), to, false); // Push tokens proportional to unused balances uint256 totalSupply = totalSupply(); uint256 unusedAmount0 = token0.balanceOf(address(this)).mul(shares).div(totalSupply); uint256 unusedAmount1 = token1.balanceOf(address(this)).mul(shares).div(totalSupply); if (unusedAmount0 > 0) token0.safeTransfer(to, unusedAmount0); if (unusedAmount1 > 0) token1.safeTransfer(to, unusedAmount1); amount0 = base0.add(limit0).add(unusedAmount0); amount1 = base1.add(limit1).add(unusedAmount1); require(from == msg.sender || IUniversalVault(from).owner() == msg.sender, "Sender must own the tokens"); _burn(from, shares); emit Withdraw(from, to, shares, amount0, amount1); } function rebalance( int24 _baseLower, int24 _baseUpper, int24 _limitLower, int24 _limitUpper, address feeRecipient, int256 swapQuantity ) external override onlyOwner { require(_baseLower < _baseUpper && _baseLower % tickSpacing == 0 && _baseUpper % tickSpacing == 0, "base position invalid"); require(_limitLower < _limitUpper && _limitLower % tickSpacing == 0 && _limitUpper % tickSpacing == 0, "limit position invalid"); // update fees (uint128 baseLiquidity,,) = _position(baseLower, baseUpper); if (baseLiquidity > 0) { pool.burn(baseLower, baseUpper, 0); } (uint128 limitLiquidity,,) = _position(limitLower, limitUpper); if (limitLiquidity > 0) { pool.burn(limitLower, limitUpper, 0); } // Withdraw all liquidity and collect all fees from Uniswap pool (, uint256 feesLimit0, uint256 feesLimit1) = _position(baseLower, baseUpper); (, uint256 feesBase0, uint256 feesBase1) = _position(limitLower, limitUpper); uint256 fees0 = feesBase0.add(feesLimit0); uint256 fees1 = feesBase1.add(feesLimit1); _burnLiquidity(baseLower, baseUpper, baseLiquidity, address(this), true); _burnLiquidity(limitLower, limitUpper, limitLiquidity, address(this), true); // transfer 10% of fees for VISR buybacks if(fees0 > 0) token0.safeTransfer(feeRecipient, fees0.div(10)); if(fees1 > 0) token1.safeTransfer(feeRecipient, fees1.div(10)); emit Rebalance( currentTick(), token0.balanceOf(address(this)), token1.balanceOf(address(this)), fees0, fees1, totalSupply() ); // swap tokens if required if (swapQuantity != 0) { pool.swap( address(this), swapQuantity > 0, swapQuantity > 0 ? swapQuantity : -swapQuantity, swapQuantity > 0 ? TickMath.MIN_SQRT_RATIO + 1 : TickMath.MAX_SQRT_RATIO - 1, abi.encode(address(this)) ); } baseLower = _baseLower; baseUpper = _baseUpper; baseLiquidity = _liquidityForAmounts( baseLower, baseUpper, token0.balanceOf(address(this)), token1.balanceOf(address(this)) ); _mintLiquidity(baseLower, baseUpper, baseLiquidity, address(this)); limitLower = _limitLower; limitUpper = _limitUpper; limitLiquidity = _liquidityForAmounts( limitLower, limitUpper, token0.balanceOf(address(this)), token1.balanceOf(address(this)) ); _mintLiquidity(limitLower, limitUpper, limitLiquidity, address(this)); } function _mintLiquidity( int24 tickLower, int24 tickUpper, uint128 liquidity, address payer ) internal returns (uint256 amount0, uint256 amount1) { if (liquidity > 0) { (amount0, amount1) = pool.mint( address(this), tickLower, tickUpper, liquidity, abi.encode(payer) ); } } function _burnLiquidity( int24 tickLower, int24 tickUpper, uint128 liquidity, address to, bool collectAll ) internal returns (uint256 amount0, uint256 amount1) { if (liquidity > 0) { // Burn liquidity (uint256 owed0, uint256 owed1) = pool.burn(tickLower, tickUpper, liquidity); // Collect amount owed uint128 collect0 = collectAll ? type(uint128).max : _uint128Safe(owed0); uint128 collect1 = collectAll ? type(uint128).max : _uint128Safe(owed1); if (collect0 > 0 || collect1 > 0) { (amount0, amount1) = pool.collect(to, tickLower, tickUpper, collect0, collect1); } } } function _liquidityForShares( int24 tickLower, int24 tickUpper, uint256 shares ) internal view returns (uint128) { (uint128 position,,) = _position(tickLower, tickUpper); return _uint128Safe(uint256(position).mul(shares).div(totalSupply())); } function _position(int24 tickLower, int24 tickUpper) internal view returns (uint128 liquidity, uint128 tokensOwed0, uint128 tokensOwed1) { bytes32 positionKey = keccak256(abi.encodePacked(address(this), tickLower, tickUpper)); (liquidity, , , tokensOwed0, tokensOwed1) = pool.positions(positionKey); } function uniswapV3MintCallback( uint256 amount0, uint256 amount1, bytes calldata data ) external override { require(msg.sender == address(pool)); address payer = abi.decode(data, (address)); if (payer == address(this)) { if (amount0 > 0) token0.safeTransfer(msg.sender, amount0); if (amount1 > 0) token1.safeTransfer(msg.sender, amount1); } else { if (amount0 > 0) token0.safeTransferFrom(payer, msg.sender, amount0); if (amount1 > 0) token1.safeTransferFrom(payer, msg.sender, amount1); } } function uniswapV3SwapCallback( int256 amount0Delta, int256 amount1Delta, bytes calldata data ) external override { require(msg.sender == address(pool)); address payer = abi.decode(data, (address)); if (amount0Delta > 0) { if (payer == address(this)) { token0.transfer(msg.sender, uint256(amount0Delta)); } else { token0.safeTransferFrom(payer, msg.sender, uint256(amount0Delta)); } } else if (amount1Delta > 0) { if (payer == address(this)) { token1.transfer(msg.sender, uint256(amount1Delta)); } else { token1.safeTransferFrom(payer, msg.sender, uint256(amount1Delta)); } } } function getTotalAmounts() public view override returns (uint256 total0, uint256 total1) { (, uint256 base0, uint256 base1) = getBasePosition(); (, uint256 limit0, uint256 limit1) = getLimitPosition(); total0 = token0.balanceOf(address(this)).add(base0).add(limit0); total1 = token1.balanceOf(address(this)).add(base1).add(limit1); } function getBasePosition() public view returns ( uint128 liquidity, uint256 amount0, uint256 amount1 ) { (uint128 positionLiquidity, uint128 tokensOwed0, uint128 tokensOwed1) = _position(baseLower, baseUpper); (amount0, amount1) = _amountsForLiquidity(baseLower, baseUpper, positionLiquidity); amount0 = amount0.add(uint256(tokensOwed0)); amount1 = amount1.add(uint256(tokensOwed1)); liquidity = positionLiquidity; } function getLimitPosition() public view returns ( uint128 liquidity, uint256 amount0, uint256 amount1 ) { (uint128 positionLiquidity, uint128 tokensOwed0, uint128 tokensOwed1) = _position(limitLower, limitUpper); (amount0, amount1) = _amountsForLiquidity(limitLower, limitUpper, positionLiquidity); amount0 = amount0.add(uint256(tokensOwed0)); amount1 = amount1.add(uint256(tokensOwed1)); liquidity = positionLiquidity; } function _amountsForLiquidity( int24 tickLower, int24 tickUpper, uint128 liquidity ) internal view returns (uint256, uint256) { (uint160 sqrtRatioX96, , , , , , ) = pool.slot0(); return LiquidityAmounts.getAmountsForLiquidity( sqrtRatioX96, TickMath.getSqrtRatioAtTick(tickLower), TickMath.getSqrtRatioAtTick(tickUpper), liquidity ); } function _liquidityForAmounts( int24 tickLower, int24 tickUpper, uint256 amount0, uint256 amount1 ) internal view returns (uint128) { (uint160 sqrtRatioX96, , , , , , ) = pool.slot0(); return LiquidityAmounts.getLiquidityForAmounts( sqrtRatioX96, TickMath.getSqrtRatioAtTick(tickLower), TickMath.getSqrtRatioAtTick(tickUpper), amount0, amount1 ); } function currentTick() public view returns (int24 currentTick) { (, currentTick, , , , , ) = pool.slot0(); } function _uint128Safe(uint256 x) internal pure returns (uint128) { assert(x <= type(uint128).max); return uint128(x); } function setMaxTotalSupply(uint256 _maxTotalSupply) external onlyOwner { maxTotalSupply = _maxTotalSupply; } function setDepositMax(uint256 _deposit0Max, uint256 _deposit1Max) external onlyOwner { deposit0Max = _deposit0Max; deposit1Max = _deposit1Max; } function setPenaltyPercent(uint256 _penaltyPercent) external onlyOwner { penaltyPercent = _penaltyPercent; } function reduceByPercent(uint256 quantity, uint256 percent) internal view returns (uint256) { return quantity.mul(MILLIBASIS.mul(100 - percent)).div(MILLIBASIS.mul(100)); } function emergencyWithdraw(IERC20 token, uint256 amount) external onlyOwner { token.safeTransfer(msg.sender, amount); } function emergencyBurn( int24 tickLower, int24 tickUpper, uint128 liquidity ) external onlyOwner { pool.burn(tickLower, tickUpper, liquidity); pool.collect(msg.sender, tickLower, tickUpper, type(uint128).max, type(uint128).max); } function appendList(address[] memory listed) external onlyOwner { for (uint8 i; i < listed.length; i++) { list[listed[i]] = true; } } function transferOwnership(address newOwner) external onlyOwner { owner = newOwner; } modifier onlyOwner { require(msg.sender == owner, "only owner"); _; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity >= 0.4.22 <0.9.0; library console { address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67); function _sendLogPayload(bytes memory payload) private view { uint256 payloadLength = payload.length; address consoleAddress = CONSOLE_ADDRESS; assembly { let payloadStart := add(payload, 32) let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0) } } function log() internal view { _sendLogPayload(abi.encodeWithSignature("log()")); } function logInt(int p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(int)", p0)); } function logUint(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function logString(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function logBool(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function logAddress(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function logBytes(bytes memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes)", p0)); } function logBytes1(bytes1 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0)); } function logBytes2(bytes2 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0)); } function logBytes3(bytes3 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0)); } function logBytes4(bytes4 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0)); } function logBytes5(bytes5 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0)); } function logBytes6(bytes6 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0)); } function logBytes7(bytes7 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0)); } function logBytes8(bytes8 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0)); } function logBytes9(bytes9 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0)); } function logBytes10(bytes10 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0)); } function logBytes11(bytes11 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0)); } function logBytes12(bytes12 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0)); } function logBytes13(bytes13 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0)); } function logBytes14(bytes14 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0)); } function logBytes15(bytes15 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0)); } function logBytes16(bytes16 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0)); } function logBytes17(bytes17 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0)); } function logBytes18(bytes18 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0)); } function logBytes19(bytes19 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0)); } function logBytes20(bytes20 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0)); } function logBytes21(bytes21 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0)); } function logBytes22(bytes22 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0)); } function logBytes23(bytes23 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0)); } function logBytes24(bytes24 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0)); } function logBytes25(bytes25 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0)); } function logBytes26(bytes26 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0)); } function logBytes27(bytes27 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0)); } function logBytes28(bytes28 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0)); } function logBytes29(bytes29 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0)); } function logBytes30(bytes30 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0)); } function logBytes31(bytes31 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0)); } function logBytes32(bytes32 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0)); } function log(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function log(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function log(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function log(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function log(uint p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1)); } function log(uint p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1)); } function log(uint p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1)); } function log(uint p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1)); } function log(string memory p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1)); } function log(string memory p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1)); } function log(string memory p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1)); } function log(string memory p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1)); } function log(bool p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1)); } function log(bool p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1)); } function log(bool p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1)); } function log(bool p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1)); } function log(address p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1)); } function log(address p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1)); } function log(address p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1)); } function log(address p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1)); } function log(uint p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2)); } function log(uint p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2)); } function log(uint p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2)); } function log(uint p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2)); } function log(uint p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2)); } function log(uint p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2)); } function log(uint p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2)); } function log(uint p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2)); } function log(uint p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2)); } function log(uint p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2)); } function log(uint p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2)); } function log(uint p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2)); } function log(uint p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2)); } function log(uint p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2)); } function log(uint p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2)); } function log(uint p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2)); } function log(string memory p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2)); } function log(string memory p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2)); } function log(string memory p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2)); } function log(string memory p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2)); } function log(string memory p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2)); } function log(string memory p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2)); } function log(string memory p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2)); } function log(string memory p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2)); } function log(string memory p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2)); } function log(string memory p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2)); } function log(string memory p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2)); } function log(string memory p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2)); } function log(string memory p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2)); } function log(string memory p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2)); } function log(string memory p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2)); } function log(string memory p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2)); } function log(bool p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2)); } function log(bool p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2)); } function log(bool p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2)); } function log(bool p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2)); } function log(bool p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2)); } function log(bool p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2)); } function log(bool p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2)); } function log(bool p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2)); } function log(bool p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2)); } function log(bool p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2)); } function log(bool p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2)); } function log(bool p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2)); } function log(bool p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2)); } function log(bool p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2)); } function log(bool p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2)); } function log(bool p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2)); } function log(address p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2)); } function log(address p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2)); } function log(address p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2)); } function log(address p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2)); } function log(address p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2)); } function log(address p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2)); } function log(address p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2)); } function log(address p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2)); } function log(address p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2)); } function log(address p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2)); } function log(address p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2)); } function log(address p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2)); } function log(address p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2)); } function log(address p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2)); } function log(address p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2)); } function log(address p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2)); } function log(uint p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @title SignedSafeMath * @dev Signed math operations with safety checks that revert on error. */ library SignedSafeMath { int256 constant private _INT256_MIN = -2**255; /** * @dev Returns the multiplication of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { // 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; } require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow"); int256 c = a * b; require(c / a == b, "SignedSafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two signed 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(int256 a, int256 b) internal pure returns (int256) { require(b != 0, "SignedSafeMath: division by zero"); require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow"); int256 c = a / b; return c; } /** * @dev Returns the subtraction of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow"); return c; } /** * @dev Returns the addition of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow"); return c; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Callback for IUniswapV3PoolActions#mint /// @notice Any contract that calls IUniswapV3PoolActions#mint must implement this interface interface IUniswapV3MintCallback { /// @notice Called to `msg.sender` after minting liquidity to a position from IUniswapV3Pool#mint. /// @dev In the implementation you must pay the pool tokens owed for the minted liquidity. /// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory. /// @param amount0Owed The amount of token0 due to the pool for the minted liquidity /// @param amount1Owed The amount of token1 due to the pool for the minted liquidity /// @param data Any data passed through by the caller via the IUniswapV3PoolActions#mint call function uniswapV3MintCallback( uint256 amount0Owed, uint256 amount1Owed, bytes calldata data ) external; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Callback for IUniswapV3PoolActions#swap /// @notice Any contract that calls IUniswapV3PoolActions#swap must implement this interface interface IUniswapV3SwapCallback { /// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap. /// @dev In the implementation you must pay the pool tokens owed for the swap. /// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory. /// amount0Delta and amount1Delta can both be 0 if no tokens were swapped. /// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by /// the end of the swap. If positive, the callback must send that amount of token0 to the pool. /// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by /// the end of the swap. If positive, the callback must send that amount of token1 to the pool. /// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call function uniswapV3SwapCallback( int256 amount0Delta, int256 amount1Delta, bytes calldata data ) external; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; import './pool/IUniswapV3PoolImmutables.sol'; import './pool/IUniswapV3PoolState.sol'; import './pool/IUniswapV3PoolDerivedState.sol'; import './pool/IUniswapV3PoolActions.sol'; import './pool/IUniswapV3PoolOwnerActions.sol'; import './pool/IUniswapV3PoolEvents.sol'; /// @title The interface for a Uniswap V3 Pool /// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform /// to the ERC20 specification /// @dev The pool interface is broken up into many smaller pieces interface IUniswapV3Pool is IUniswapV3PoolImmutables, IUniswapV3PoolState, IUniswapV3PoolDerivedState, IUniswapV3PoolActions, IUniswapV3PoolOwnerActions, IUniswapV3PoolEvents { } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Math library for computing sqrt prices from ticks and vice versa /// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports /// prices between 2**-128 and 2**128 library TickMath { /// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128 int24 internal constant MIN_TICK = -887272; /// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128 int24 internal constant MAX_TICK = -MIN_TICK; /// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK) uint160 internal constant MIN_SQRT_RATIO = 4295128739; /// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK) uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342; /// @notice Calculates sqrt(1.0001^tick) * 2^96 /// @dev Throws if |tick| > max tick /// @param tick The input tick for the above formula /// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0) /// at the given tick function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) { uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick)); require(absTick <= uint256(MAX_TICK), 'T'); uint256 ratio = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000; if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128; if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128; if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128; if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128; if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128; if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128; if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128; if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128; if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128; if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128; if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128; if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128; if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128; if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128; if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128; if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128; if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128; if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128; if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128; if (tick > 0) ratio = type(uint256).max / ratio; // this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96. // we then downcast because we know the result always fits within 160 bits due to our tick input constraint // we round up in the division so getTickAtSqrtRatio of the output price is always consistent sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1)); } /// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio /// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may /// ever return. /// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96 /// @return tick The greatest tick for which the ratio is less than or equal to the input ratio function getTickAtSqrtRatio(uint160 sqrtPriceX96) internal pure returns (int24 tick) { // second inequality must be < because the price can never reach the price at the max tick require(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO, 'R'); uint256 ratio = uint256(sqrtPriceX96) << 32; uint256 r = ratio; uint256 msb = 0; assembly { let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(5, gt(r, 0xFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(4, gt(r, 0xFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(3, gt(r, 0xFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(2, gt(r, 0xF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(1, gt(r, 0x3)) msb := or(msb, f) r := shr(f, r) } assembly { let f := gt(r, 0x1) msb := or(msb, f) } if (msb >= 128) r = ratio >> (msb - 127); else r = ratio << (127 - msb); int256 log_2 = (int256(msb) - 128) << 64; assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(63, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(62, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(61, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(60, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(59, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(58, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(57, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(56, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(55, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(54, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(53, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(52, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(51, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(50, f)) } int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128); int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128); tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow; } } // SPDX-License-Identifier: MIT pragma solidity >=0.4.0; /// @title Contains 512-bit math functions /// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision /// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits library FullMath { /// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 /// @param a The multiplicand /// @param b The multiplier /// @param denominator The divisor /// @return result The 256-bit result /// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv function mulDiv( uint256 a, uint256 b, uint256 denominator ) internal pure returns (uint256 result) { // 512-bit multiply [prod1 prod0] = a * b // Compute the product mod 2**256 and mod 2**256 - 1 // then use the Chinese Remainder Theorem to reconstruct // the 512 bit result. The result is stored in two 256 // variables such that product = prod1 * 2**256 + prod0 uint256 prod0; // Least significant 256 bits of the product uint256 prod1; // Most significant 256 bits of the product assembly { let mm := mulmod(a, b, not(0)) prod0 := mul(a, b) prod1 := sub(sub(mm, prod0), lt(mm, prod0)) } // Handle non-overflow cases, 256 by 256 division if (prod1 == 0) { require(denominator > 0); assembly { result := div(prod0, denominator) } return result; } // Make sure the result is less than 2**256. // Also prevents denominator == 0 require(denominator > prod1); /////////////////////////////////////////////// // 512 by 256 division. /////////////////////////////////////////////// // Make division exact by subtracting the remainder from [prod1 prod0] // Compute remainder using mulmod uint256 remainder; assembly { remainder := mulmod(a, b, denominator) } // Subtract 256 bit number from 512 bit number assembly { prod1 := sub(prod1, gt(remainder, prod0)) prod0 := sub(prod0, remainder) } // Factor powers of two out of denominator // Compute largest power of two divisor of denominator. // Always >= 1. uint256 twos = -denominator & denominator; // Divide denominator by power of two assembly { denominator := div(denominator, twos) } // Divide [prod1 prod0] by the factors of two assembly { prod0 := div(prod0, twos) } // Shift in bits from prod1 into prod0. For this we need // to flip `twos` such that it is 2**256 / twos. // If twos is zero, then it becomes one assembly { twos := add(div(sub(0, twos), twos), 1) } prod0 |= prod1 * twos; // Invert denominator mod 2**256 // Now that denominator is an odd number, it has an inverse // modulo 2**256 such that denominator * inv = 1 mod 2**256. // Compute the inverse by starting with a seed that is correct // correct for four bits. That is, denominator * inv = 1 mod 2**4 uint256 inv = (3 * denominator) ^ 2; // Now use Newton-Raphson iteration to improve the precision. // Thanks to Hensel's lifting lemma, this also works in modular // arithmetic, doubling the correct bits in each step. inv *= 2 - denominator * inv; // inverse mod 2**8 inv *= 2 - denominator * inv; // inverse mod 2**16 inv *= 2 - denominator * inv; // inverse mod 2**32 inv *= 2 - denominator * inv; // inverse mod 2**64 inv *= 2 - denominator * inv; // inverse mod 2**128 inv *= 2 - denominator * inv; // inverse mod 2**256 // Because the division is now exact we can divide by multiplying // with the modular inverse of denominator. This will give us the // correct result modulo 2**256. Since the precoditions guarantee // that the outcome is less than 2**256, this is the final result. // We don't need to compute the high bits of the result and prod1 // is no longer required. result = prod0 * inv; return result; } /// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 /// @param a The multiplicand /// @param b The multiplier /// @param denominator The divisor /// @return result The 256-bit result function mulDivRoundingUp( uint256 a, uint256 b, uint256 denominator ) internal pure returns (uint256 result) { result = mulDiv(a, b, denominator); if (mulmod(a, b, denominator) > 0) { require(result < type(uint256).max); result++; } } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; import '@uniswap/v3-core/contracts/libraries/FullMath.sol'; import '@uniswap/v3-core/contracts/libraries/FixedPoint96.sol'; /// @title Liquidity amount functions /// @notice Provides functions for computing liquidity amounts from token amounts and prices library LiquidityAmounts { /// @notice Downcasts uint256 to uint128 /// @param x The uint258 to be downcasted /// @return y The passed value, downcasted to uint128 function toUint128(uint256 x) private pure returns (uint128 y) { require((y = uint128(x)) == x); } /// @notice Computes the amount of liquidity received for a given amount of token0 and price range /// @dev Calculates amount0 * (sqrt(upper) * sqrt(lower)) / (sqrt(upper) - sqrt(lower)) /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param amount0 The amount0 being sent in /// @return liquidity The amount of returned liquidity function getLiquidityForAmount0( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint256 amount0 ) internal pure returns (uint128 liquidity) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); uint256 intermediate = FullMath.mulDiv(sqrtRatioAX96, sqrtRatioBX96, FixedPoint96.Q96); return toUint128(FullMath.mulDiv(amount0, intermediate, sqrtRatioBX96 - sqrtRatioAX96)); } /// @notice Computes the amount of liquidity received for a given amount of token1 and price range /// @dev Calculates amount1 / (sqrt(upper) - sqrt(lower)). /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param amount1 The amount1 being sent in /// @return liquidity The amount of returned liquidity function getLiquidityForAmount1( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint256 amount1 ) internal pure returns (uint128 liquidity) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); return toUint128(FullMath.mulDiv(amount1, FixedPoint96.Q96, sqrtRatioBX96 - sqrtRatioAX96)); } /// @notice Computes the maximum amount of liquidity received for a given amount of token0, token1, the current /// pool prices and the prices at the tick boundaries /// @param sqrtRatioX96 A sqrt price representing the current pool prices /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param amount0 The amount of token0 being sent in /// @param amount1 The amount of token1 being sent in /// @return liquidity The maximum amount of liquidity received function getLiquidityForAmounts( uint160 sqrtRatioX96, uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint256 amount0, uint256 amount1 ) internal pure returns (uint128 liquidity) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); if (sqrtRatioX96 <= sqrtRatioAX96) { liquidity = getLiquidityForAmount0(sqrtRatioAX96, sqrtRatioBX96, amount0); } else if (sqrtRatioX96 < sqrtRatioBX96) { uint128 liquidity0 = getLiquidityForAmount0(sqrtRatioX96, sqrtRatioBX96, amount0); uint128 liquidity1 = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioX96, amount1); liquidity = liquidity0 < liquidity1 ? liquidity0 : liquidity1; } else { liquidity = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioBX96, amount1); } } /// @notice Computes the amount of token0 for a given amount of liquidity and a price range /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param liquidity The liquidity being valued /// @return amount0 The amount of token0 function getAmount0ForLiquidity( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity ) internal pure returns (uint256 amount0) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); return FullMath.mulDiv( uint256(liquidity) << FixedPoint96.RESOLUTION, sqrtRatioBX96 - sqrtRatioAX96, sqrtRatioBX96 ) / sqrtRatioAX96; } /// @notice Computes the amount of token1 for a given amount of liquidity and a price range /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param liquidity The liquidity being valued /// @return amount1 The amount of token1 function getAmount1ForLiquidity( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity ) internal pure returns (uint256 amount1) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); return FullMath.mulDiv(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96); } /// @notice Computes the token0 and token1 value for a given amount of liquidity, the current /// pool prices and the prices at the tick boundaries /// @param sqrtRatioX96 A sqrt price representing the current pool prices /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param liquidity The liquidity being valued /// @return amount0 The amount of token0 /// @return amount1 The amount of token1 function getAmountsForLiquidity( uint160 sqrtRatioX96, uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity ) internal pure returns (uint256 amount0, uint256 amount1) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); if (sqrtRatioX96 <= sqrtRatioAX96) { amount0 = getAmount0ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity); } else if (sqrtRatioX96 < sqrtRatioBX96) { amount0 = getAmount0ForLiquidity(sqrtRatioX96, sqrtRatioBX96, liquidity); amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioX96, liquidity); } else { amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity); } } } // SPDX-License-Identifier: Unlicense pragma solidity 0.7.6; interface IVault { function deposit( uint256, uint256, address ) external returns (uint256); function withdraw( uint256, address, address ) external returns (uint256, uint256); function rebalance( int24 _baseLower, int24 _baseUpper, int24 _limitLower, int24 _limitUpper, address feeRecipient, int256 swapQuantity ) external; function getTotalAmounts() external view returns (uint256, uint256); event Deposit( address indexed sender, address indexed to, uint256 shares, uint256 amount0, uint256 amount1 ); event Withdraw( address indexed sender, address indexed to, uint256 shares, uint256 amount0, uint256 amount1 ); event Rebalance( int24 tick, uint256 totalAmount0, uint256 totalAmount1, uint256 feeAmount0, uint256 feeAmount1, uint256 totalSupply ); } // SPDX-License-Identifier: GPL-3.0-only pragma solidity 0.7.6; pragma abicoder v2; interface IUniversalVault { /* user events */ event Locked(address delegate, address token, uint256 amount); event Unlocked(address delegate, address token, uint256 amount); event RageQuit(address delegate, address token, bool notified, string reason); /* data types */ struct LockData { address delegate; address token; uint256 balance; } /* initialize function */ function initialize() external; /* user functions */ function lock( address token, uint256 amount, bytes calldata permission ) external; function unlock( address token, uint256 amount, bytes calldata permission ) external; function rageQuit(address delegate, address token) external returns (bool notified, string memory error); function transferERC20( address token, address to, uint256 amount ) external; function transferETH(address to, uint256 amount) external payable; /* pure functions */ function calculateLockID(address delegate, address token) external pure returns (bytes32 lockID); /* getter functions */ function getPermissionHash( bytes32 eip712TypeHash, address delegate, address token, uint256 amount, uint256 nonce ) external view returns (bytes32 permissionHash); function getNonce() external view returns (uint256 nonce); function owner() external view returns (address ownerAddress); function getLockSetCount() external view returns (uint256 count); function getLockAt(uint256 index) external view returns (LockData memory lockData); function getBalanceDelegated(address token, address delegate) external view returns (uint256 balance); function getBalanceLocked(address token) external view returns (uint256 balance); function checkBalances() external view returns (bool validity); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Pool state that never changes /// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values interface IUniswapV3PoolImmutables { /// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface /// @return The contract address function factory() external view returns (address); /// @notice The first of the two tokens of the pool, sorted by address /// @return The token contract address function token0() external view returns (address); /// @notice The second of the two tokens of the pool, sorted by address /// @return The token contract address function token1() external view returns (address); /// @notice The pool's fee in hundredths of a bip, i.e. 1e-6 /// @return The fee function fee() external view returns (uint24); /// @notice The pool tick spacing /// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive /// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ... /// This value is an int24 to avoid casting even though it is always positive. /// @return The tick spacing function tickSpacing() external view returns (int24); /// @notice The maximum amount of position liquidity that can use any tick in the range /// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and /// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool /// @return The max amount of liquidity per tick function maxLiquidityPerTick() external view returns (uint128); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Pool state that can change /// @notice These methods compose the pool's state, and can change with any frequency including multiple times /// per transaction interface IUniswapV3PoolState { /// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas /// when accessed externally. /// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value /// tick The current tick of the pool, i.e. according to the last tick transition that was run. /// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick /// boundary. /// observationIndex The index of the last oracle observation that was written, /// observationCardinality The current maximum number of observations stored in the pool, /// observationCardinalityNext The next maximum number of observations, to be updated when the observation. /// feeProtocol The protocol fee for both tokens of the pool. /// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0 /// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee. /// unlocked Whether the pool is currently locked to reentrancy function slot0() external view returns ( uint160 sqrtPriceX96, int24 tick, uint16 observationIndex, uint16 observationCardinality, uint16 observationCardinalityNext, uint8 feeProtocol, bool unlocked ); /// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool /// @dev This value can overflow the uint256 function feeGrowthGlobal0X128() external view returns (uint256); /// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool /// @dev This value can overflow the uint256 function feeGrowthGlobal1X128() external view returns (uint256); /// @notice The amounts of token0 and token1 that are owed to the protocol /// @dev Protocol fees will never exceed uint128 max in either token function protocolFees() external view returns (uint128 token0, uint128 token1); /// @notice The currently in range liquidity available to the pool /// @dev This value has no relationship to the total liquidity across all ticks function liquidity() external view returns (uint128); /// @notice Look up information about a specific tick in the pool /// @param tick The tick to look up /// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or /// tick upper, /// liquidityNet how much liquidity changes when the pool price crosses the tick, /// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0, /// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1, /// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick /// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick, /// secondsOutside the seconds spent on the other side of the tick from the current tick, /// initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false. /// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0. /// In addition, these values are only relative and must be used only in comparison to previous snapshots for /// a specific position. function ticks(int24 tick) external view returns ( uint128 liquidityGross, int128 liquidityNet, uint256 feeGrowthOutside0X128, uint256 feeGrowthOutside1X128, int56 tickCumulativeOutside, uint160 secondsPerLiquidityOutsideX128, uint32 secondsOutside, bool initialized ); /// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information function tickBitmap(int16 wordPosition) external view returns (uint256); /// @notice Returns the information about a position by the position's key /// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper /// @return _liquidity The amount of liquidity in the position, /// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke, /// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke, /// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke, /// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke function positions(bytes32 key) external view returns ( uint128 _liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1 ); /// @notice Returns data about a specific observation index /// @param index The element of the observations array to fetch /// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time /// ago, rather than at a specific index in the array. /// @return blockTimestamp The timestamp of the observation, /// Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp, /// Returns secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp, /// Returns initialized whether the observation has been initialized and the values are safe to use function observations(uint256 index) external view returns ( uint32 blockTimestamp, int56 tickCumulative, uint160 secondsPerLiquidityCumulativeX128, bool initialized ); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Pool state that is not stored /// @notice Contains view functions to provide information about the pool that is computed rather than stored on the /// blockchain. The functions here may have variable gas costs. interface IUniswapV3PoolDerivedState { /// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp /// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing /// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick, /// you must call it with secondsAgos = [3600, 0]. /// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in /// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio. /// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned /// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp /// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block /// timestamp function observe(uint32[] calldata secondsAgos) external view returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s); /// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range /// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed. /// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first /// snapshot is taken and the second snapshot is taken. /// @param tickLower The lower tick of the range /// @param tickUpper The upper tick of the range /// @return tickCumulativeInside The snapshot of the tick accumulator for the range /// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range /// @return secondsInside The snapshot of seconds per liquidity for the range function snapshotCumulativesInside(int24 tickLower, int24 tickUpper) external view returns ( int56 tickCumulativeInside, uint160 secondsPerLiquidityInsideX128, uint32 secondsInside ); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Permissionless pool actions /// @notice Contains pool methods that can be called by anyone interface IUniswapV3PoolActions { /// @notice Sets the initial price for the pool /// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value /// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96 function initialize(uint160 sqrtPriceX96) external; /// @notice Adds liquidity for the given recipient/tickLower/tickUpper position /// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback /// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends /// on tickLower, tickUpper, the amount of liquidity, and the current price. /// @param recipient The address for which the liquidity will be created /// @param tickLower The lower tick of the position in which to add liquidity /// @param tickUpper The upper tick of the position in which to add liquidity /// @param amount The amount of liquidity to mint /// @param data Any data that should be passed through to the callback /// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback /// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback function mint( address recipient, int24 tickLower, int24 tickUpper, uint128 amount, bytes calldata data ) external returns (uint256 amount0, uint256 amount1); /// @notice Collects tokens owed to a position /// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity. /// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or /// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the /// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity. /// @param recipient The address which should receive the fees collected /// @param tickLower The lower tick of the position for which to collect fees /// @param tickUpper The upper tick of the position for which to collect fees /// @param amount0Requested How much token0 should be withdrawn from the fees owed /// @param amount1Requested How much token1 should be withdrawn from the fees owed /// @return amount0 The amount of fees collected in token0 /// @return amount1 The amount of fees collected in token1 function collect( address recipient, int24 tickLower, int24 tickUpper, uint128 amount0Requested, uint128 amount1Requested ) external returns (uint128 amount0, uint128 amount1); /// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position /// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0 /// @dev Fees must be collected separately via a call to #collect /// @param tickLower The lower tick of the position for which to burn liquidity /// @param tickUpper The upper tick of the position for which to burn liquidity /// @param amount How much liquidity to burn /// @return amount0 The amount of token0 sent to the recipient /// @return amount1 The amount of token1 sent to the recipient function burn( int24 tickLower, int24 tickUpper, uint128 amount ) external returns (uint256 amount0, uint256 amount1); /// @notice Swap token0 for token1, or token1 for token0 /// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback /// @param recipient The address to receive the output of the swap /// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0 /// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative) /// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this /// value after the swap. If one for zero, the price cannot be greater than this value after the swap /// @param data Any data to be passed through to the callback /// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive /// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive function swap( address recipient, bool zeroForOne, int256 amountSpecified, uint160 sqrtPriceLimitX96, bytes calldata data ) external returns (int256 amount0, int256 amount1); /// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback /// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback /// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling /// with 0 amount{0,1} and sending the donation amount(s) from the callback /// @param recipient The address which will receive the token0 and token1 amounts /// @param amount0 The amount of token0 to send /// @param amount1 The amount of token1 to send /// @param data Any data to be passed through to the callback function flash( address recipient, uint256 amount0, uint256 amount1, bytes calldata data ) external; /// @notice Increase the maximum number of price and liquidity observations that this pool will store /// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to /// the input observationCardinalityNext. /// @param observationCardinalityNext The desired minimum number of observations for the pool to store function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Permissioned pool actions /// @notice Contains pool methods that may only be called by the factory owner interface IUniswapV3PoolOwnerActions { /// @notice Set the denominator of the protocol's % share of the fees /// @param feeProtocol0 new protocol fee for token0 of the pool /// @param feeProtocol1 new protocol fee for token1 of the pool function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external; /// @notice Collect the protocol fee accrued to the pool /// @param recipient The address to which collected protocol fees should be sent /// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1 /// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0 /// @return amount0 The protocol fee collected in token0 /// @return amount1 The protocol fee collected in token1 function collectProtocol( address recipient, uint128 amount0Requested, uint128 amount1Requested ) external returns (uint128 amount0, uint128 amount1); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Events emitted by a pool /// @notice Contains all events emitted by the pool interface IUniswapV3PoolEvents { /// @notice Emitted exactly once by a pool when #initialize is first called on the pool /// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize /// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96 /// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool event Initialize(uint160 sqrtPriceX96, int24 tick); /// @notice Emitted when liquidity is minted for a given position /// @param sender The address that minted the liquidity /// @param owner The owner of the position and recipient of any minted liquidity /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount The amount of liquidity minted to the position range /// @param amount0 How much token0 was required for the minted liquidity /// @param amount1 How much token1 was required for the minted liquidity event Mint( address sender, address indexed owner, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount, uint256 amount0, uint256 amount1 ); /// @notice Emitted when fees are collected by the owner of a position /// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees /// @param owner The owner of the position for which fees are collected /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount0 The amount of token0 fees collected /// @param amount1 The amount of token1 fees collected event Collect( address indexed owner, address recipient, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount0, uint128 amount1 ); /// @notice Emitted when a position's liquidity is removed /// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect /// @param owner The owner of the position for which liquidity is removed /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount The amount of liquidity to remove /// @param amount0 The amount of token0 withdrawn /// @param amount1 The amount of token1 withdrawn event Burn( address indexed owner, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount, uint256 amount0, uint256 amount1 ); /// @notice Emitted by the pool for any swaps between token0 and token1 /// @param sender The address that initiated the swap call, and that received the callback /// @param recipient The address that received the output of the swap /// @param amount0 The delta of the token0 balance of the pool /// @param amount1 The delta of the token1 balance of the pool /// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96 /// @param liquidity The liquidity of the pool after the swap /// @param tick The log base 1.0001 of price of the pool after the swap event Swap( address indexed sender, address indexed recipient, int256 amount0, int256 amount1, uint160 sqrtPriceX96, uint128 liquidity, int24 tick ); /// @notice Emitted by the pool for any flashes of token0/token1 /// @param sender The address that initiated the swap call, and that received the callback /// @param recipient The address that received the tokens from flash /// @param amount0 The amount of token0 that was flashed /// @param amount1 The amount of token1 that was flashed /// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee /// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee event Flash( address indexed sender, address indexed recipient, uint256 amount0, uint256 amount1, uint256 paid0, uint256 paid1 ); /// @notice Emitted by the pool for increases to the number of observations that can be stored /// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index /// just before a mint/swap/burn. /// @param observationCardinalityNextOld The previous value of the next observation cardinality /// @param observationCardinalityNextNew The updated value of the next observation cardinality event IncreaseObservationCardinalityNext( uint16 observationCardinalityNextOld, uint16 observationCardinalityNextNew ); /// @notice Emitted when the protocol fee is changed by the pool /// @param feeProtocol0Old The previous value of the token0 protocol fee /// @param feeProtocol1Old The previous value of the token1 protocol fee /// @param feeProtocol0New The updated value of the token0 protocol fee /// @param feeProtocol1New The updated value of the token1 protocol fee event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New); /// @notice Emitted when the collected protocol fees are withdrawn by the factory owner /// @param sender The address that collects the protocol fees /// @param recipient The address that receives the collected protocol fees /// @param amount0 The amount of token0 protocol fees that is withdrawn /// @param amount0 The amount of token1 protocol fees that is withdrawn event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.4.0; /// @title FixedPoint96 /// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format) /// @dev Used in SqrtPriceMath.sol library FixedPoint96 { uint8 internal constant RESOLUTION = 96; uint256 internal constant Q96 = 0x1000000000000000000000000; }
Withdraw liquidity from Uniswap pool Push tokens proportional to unused balances
function withdraw( uint256 shares, address to, address from ) external override returns (uint256 amount0, uint256 amount1) { require(shares > 0, "shares"); require(to != address(0), "to"); (uint256 base0, uint256 base1) = _burnLiquidity(baseLower, baseUpper, _liquidityForShares(baseLower, baseUpper, shares), to, false); (uint256 limit0, uint256 limit1) = _burnLiquidity(limitLower, limitUpper, _liquidityForShares(limitLower, limitUpper, shares), to, false); uint256 totalSupply = totalSupply(); uint256 unusedAmount0 = token0.balanceOf(address(this)).mul(shares).div(totalSupply); uint256 unusedAmount1 = token1.balanceOf(address(this)).mul(shares).div(totalSupply); if (unusedAmount0 > 0) token0.safeTransfer(to, unusedAmount0); if (unusedAmount1 > 0) token1.safeTransfer(to, unusedAmount1); amount0 = base0.add(limit0).add(unusedAmount0); amount1 = base1.add(limit1).add(unusedAmount1); require(from == msg.sender || IUniversalVault(from).owner() == msg.sender, "Sender must own the tokens"); _burn(from, shares); emit Withdraw(from, to, shares, amount0, amount1); }
69,291
./full_match/5/0x35a9ba1d7203DFfc83A03f98888233ba78c0493E/sources/contracts/CoinFlip.sol
Function to refund user in case of VRF request failling/
function CoinFlip_Refund() external nonReentrant { CoinFlipGame storage game = coinFlipGames[msg.sender]; if (game.requestID == 0) { revert NotAwaitingVRF(); } if (game.blockNumber + 200 > block.number) { revert BlockNumberTooLow(block.number, game.blockNumber + 200); } uint256 wager = game.wager * game.numBets; address tokenAddress = game.tokenAddress; delete (coinIDs[game.requestID]); delete (coinFlipGames[msg.sender]); if (tokenAddress == address(0)) { if (!success) { revert TransferFailed(); } IERC20(tokenAddress).safeTransfer(msg.sender, wager); } emit CoinFlip_Refund_Event(msg.sender, wager, tokenAddress); }
1,875,967
./partial_match/10/0xC3A17DC6b70cD58f8aE49Fb969CCA5A57cf84A73/sources/project_/contracts/curve/CurveMaster.sol
setting a new curve should pay interest
function setCurve(address token_address, address curve_address) external override onlyOwner { if (address(_VaultController) != address(0)) { _VaultController.calculateInterest(); } _curves[token_address] = curve_address; }
3,532,981
pragma solidity ^0.5.12; // ---------------------------------------------------------------------------- // Safe maths // ---------------------------------------------------------------------------- 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; } } // ProfitLineInc contract contract IPO { using SafeMath for uint; // IPO specifics address payable public hubFundAdmin; uint256 public payoutPot; // interface PlincInterface constant hub_ = PlincInterface(0xd5D10172e8D8B84AC83031c16fE093cba4c84FC6);// hubplinc // setup vars mapping(uint256 => uint256)public bondsOutstanding; // redeemablebonds switched to uint256 instead of address uint256 public totalSupplyBonds; //totalsupply of bonds outstanding mapping(address => uint256)public playerVault; // in contract eth balance mapping(uint256 => uint256) public totalsupplyStake; // stake totalsupply mapping(uint256 => uint256)public pendingFills; //eth to fill bonds mapping(address => uint256)public playerId; //investor to playerid mapping(uint256 => uint256)public IPOtoID; //IPO to playerid mapping(uint256 => address payable)public IdToAdress; //address which is owner of ID uint256 public nextPlayerID; uint256 public nextIPO;// IPO registration number mapping(uint256 => address)public IPOcreator; mapping(uint256 => bool)public IPOhasTarget; mapping(uint256 => uint256)public IPOtarget; mapping(uint256 => bool)public IPOisActive; mapping(uint256 => bytes32)public IPOinfo; uint256 public openingFee; //sale vars mapping(uint256 => mapping(address => uint256))public IPOpurchases;// IPO - address - amount mapping(uint256 => mapping(uint256 => address))public IPOadresslist;// IPO - adressno - address mapping(uint256 => uint256)public IPOnextAddressPointer; mapping(uint256 => uint256)public IPOamountFunded; mapping(uint256 => uint256)public IdVaultedEths;// IPO - address - amount // extra functionallity mapping(address => mapping(uint256 => uint256))public funcAmount; mapping(address => mapping(uint256 => address))public funcAddress; // ranking mapping(uint256 => uint256)public IPOprofile; mapping(uint256 => bool)public UIblacklist; // IPO functions function setFees(uint256 amount) public { require(msg.sender == hubFundAdmin); openingFee = amount; } function registerIPO(address payable creator,bool hasTarget, uint256 target, bytes32 info) public payable updateAccount(playerId[msg.sender]){ uint256 next = nextIPO; uint256 value = msg.value; require(value >= openingFee); playerVault[hubFundAdmin] = playerVault[hubFundAdmin] + value; // write IPO in Investorbook IPOtoID[next] = nextPlayerID; //retrieve this ID to know the location of IPO's bonds IdToAdress[nextPlayerID] = creator; //register who can withdraw from the ID fetchdivs(nextPlayerID); nextPlayerID++; // set creator IPOcreator[next] = creator; // set hasTarget IPOhasTarget[next] = hasTarget; // set target IPOtarget[next] = target; // set info IPOinfo[next] = info; // activate IPO IPOisActive[next] = true; // update IPO pointer nextIPO++; emit IPOCreated(creator,hasTarget,target); } function fundIPO(uint256 IPOidentifier) public payable updateAccount(playerId[msg.sender])updateAccount(IPOtoID[IPOidentifier]){ // check if IPO is active uint256 value = msg.value; address payable sender = msg.sender; require(IPOisActive[IPOidentifier] == true); // check if it has target if(IPOhasTarget[IPOidentifier] == true) { // check if funding vs target overflow if(IPOamountFunded[IPOidentifier].add(value) > IPOtarget[IPOidentifier]){ // add excess to playervault playerVault[sender] = playerVault[sender].add(IPOamountFunded[IPOidentifier].add(value)).sub(IPOtarget[IPOidentifier]); // change value to amount of able to fund value = IPOtarget[IPOidentifier].sub(IPOamountFunded[IPOidentifier]); } } // update Investorbook if(playerId[sender] == 0){ playerId[sender] = nextPlayerID; IdToAdress[nextPlayerID] = sender; fetchdivs(nextPlayerID); nextPlayerID++; } // Update bonds sender bondsOutstanding[playerId[sender]] = bondsOutstanding[playerId[sender]].add(value); // update bonds IPOcreator bondsOutstanding[IPOtoID[IPOidentifier]] = bondsOutstanding[IPOtoID[IPOidentifier]].add(value.div(10)); // ADJUST totalsupply totalSupplyBonds = totalSupplyBonds.add(value).add(value.div(10)); // update IPOpurchases for the sender IPOpurchases[IPOidentifier][sender] = IPOpurchases[IPOidentifier][sender].add(value); // add address to IPOadresslist IPOadresslist[IPOidentifier][IPOnextAddressPointer[IPOidentifier]] = sender; // update IPOnextAddressPointer IPOnextAddressPointer[IPOidentifier] = IPOnextAddressPointer[IPOidentifier].add(1); // update IPOamountFunded IPOamountFunded[IPOidentifier] = IPOamountFunded[IPOidentifier].add(value); //buy hub bonds hub_.buyBonds.value(value)(0x2e66aa088ceb9Ce9b04f6B9B7482fBe559732A70) ; emit IPOFunded(sender,value,IPOidentifier); } // PIMP UPGRADE START function giftExcessBonds(address payable _IPOidentifier) public payable updateAccount(playerId[msg.sender])updateAccount(playerId[_IPOidentifier]){ // check if IPO is active uint256 value = msg.value; address payable sender = msg.sender; // update Investorbook for sender if(playerId[sender] == 0){ playerId[sender] = nextPlayerID; IdToAdress[nextPlayerID] = sender; fetchdivs(nextPlayerID); nextPlayerID++; } // update Investorbook for giftee if(playerId[_IPOidentifier] == 0){ playerId[_IPOidentifier] = nextPlayerID; IdToAdress[nextPlayerID] = _IPOidentifier; fetchdivs(nextPlayerID); nextPlayerID++; } // Update bonds sender bondsOutstanding[playerId[sender]] = bondsOutstanding[playerId[sender]].add(value); // update bonds receiver bondsOutstanding[playerId[_IPOidentifier]] = bondsOutstanding[playerId[_IPOidentifier]].add(value.div(10)); // ADJUST totalsupply totalSupplyBonds = totalSupplyBonds.add(value).add(value.div(10)); //buy hub bonds hub_.buyBonds.value(value)(0x2e66aa088ceb9Ce9b04f6B9B7482fBe559732A70) ; emit payment(sender,IdToAdress[playerId[_IPOidentifier]],value ); } function RebatePayment(address payable _IPOidentifier, uint256 refNumber) public payable updateAccount(playerId[msg.sender])updateAccount(playerId[_IPOidentifier]){ // check if IPO is active uint256 value = msg.value; address payable sender = msg.sender; // update Investorbook for sender if(playerId[sender] == 0){ playerId[sender] = nextPlayerID; IdToAdress[nextPlayerID] = sender; fetchdivs(nextPlayerID); nextPlayerID++; } // update Investorbook for giftee if(playerId[_IPOidentifier] == 0){ playerId[_IPOidentifier] = nextPlayerID; IdToAdress[nextPlayerID] = _IPOidentifier; fetchdivs(nextPlayerID); nextPlayerID++; } // Update bonds sender bondsOutstanding[playerId[sender]] = bondsOutstanding[playerId[sender]].add(value); // update bonds receiver bondsOutstanding[playerId[_IPOidentifier]] = bondsOutstanding[playerId[_IPOidentifier]].add(value.div(10)); // ADJUST totalsupply totalSupplyBonds = totalSupplyBonds.add(value).add(value.div(10)); //buy hub bonds hub_.buyBonds.value(value)(0x2e66aa088ceb9Ce9b04f6B9B7482fBe559732A70) ; emit payment(sender,IdToAdress[playerId[_IPOidentifier]],value ); // extra func funcAmount[_IPOidentifier][refNumber] = value; funcAmount[_IPOidentifier][refNumber] = value; } function giftAll(address payable _IPOidentifier) public payable updateAccount(playerId[msg.sender])updateAccount(playerId[_IPOidentifier]){ // check if IPO is active uint256 value = msg.value; address payable sender = msg.sender; // update Investorbook for sender if(playerId[sender] == 0){ playerId[sender] = nextPlayerID; IdToAdress[nextPlayerID] = sender; fetchdivs(nextPlayerID); nextPlayerID++; } // update Investorbook for giftee if(playerId[_IPOidentifier] == 0){ playerId[_IPOidentifier] = nextPlayerID; IdToAdress[nextPlayerID] = _IPOidentifier; fetchdivs(nextPlayerID); nextPlayerID++; } // Update bonds sender bondsOutstanding[playerId[_IPOidentifier]] = bondsOutstanding[playerId[_IPOidentifier]].add(value); // update bonds receiver bondsOutstanding[playerId[_IPOidentifier]] = bondsOutstanding[playerId[_IPOidentifier]].add(value.div(10)); // ADJUST totalsupply totalSupplyBonds = totalSupplyBonds.add(value).add(value.div(10)); //buy hub bonds hub_.buyBonds.value(value)(0x2e66aa088ceb9Ce9b04f6B9B7482fBe559732A70) ; emit payment(sender,IdToAdress[playerId[_IPOidentifier]],value ); } // PIMP upgrade end function changeIPOstate(uint256 IPOidentifier, bool state) public { address sender = msg.sender; require(sender == IPOcreator[IPOidentifier]); // activate or deactive IPO IPOisActive[IPOidentifier] = state; } function changeUIblacklist(uint256 IPOidentifier, bool state) public { address sender = msg.sender; require(sender == hubFundAdmin); // activate or deactive IPO for UI UIblacklist[IPOidentifier] = state; } function changeIPOinfo(uint256 IPOidentifier, bytes32 info) public { address sender = msg.sender; require(sender == IPOcreator[IPOidentifier]); // set info IPOinfo[IPOidentifier] = info; } // pay to get higher visibillity function RaiseProfile(uint256 IPOidentifier) public payable updateAccount(playerId[msg.sender])updateAccount(playerId[hubFundAdmin]){ // check if IPO is active uint256 value = msg.value; address sender = msg.sender; require(IPOisActive[IPOidentifier] == true); // Update bonds sender bondsOutstanding[playerId[sender]] = bondsOutstanding[playerId[sender]].add(value); // update bonds admin bondsOutstanding[playerId[hubFundAdmin]] = bondsOutstanding[playerId[hubFundAdmin]].add(value.div(10)); // raise profile of IPO IPOprofile[IPOidentifier] = IPOprofile[IPOidentifier].add(value); // adjust totalSupplyBonds totalSupplyBonds = totalSupplyBonds.add(value).add(value.div(10)); //buy hub bonds hub_.buyBonds.value(value)(0x2e66aa088ceb9Ce9b04f6B9B7482fBe559732A70) ; } //div setup type bonds uint256 public pointMultiplier = 10e18; struct Account { uint256 owned; uint256 lastDividendPoints; } mapping(uint256=>Account)public accounts; uint256 public totalDividendPoints; uint256 public unclaimedDividends; function dividendsOwing(uint256 account) public view returns(uint256) { uint256 newDividendPoints = totalDividendPoints.sub(accounts[account].lastDividendPoints); return (bondsOutstanding[account] * newDividendPoints) / pointMultiplier; } function fetchdivs(uint256 toupdate) public updateAccount(toupdate){} modifier updateAccount(uint256 account) { uint256 owing = dividendsOwing(account); if(owing > 0) { unclaimedDividends = unclaimedDividends.sub(owing); pendingFills[account] = pendingFills[account].add(owing); } accounts[account].lastDividendPoints = totalDividendPoints; _; } function () external payable{} // needs for divs function vaultToWallet(uint256 _ID) public { address payable _sendTo = IdToAdress[_ID]; require(playerVault[IdToAdress[_ID]] > 0); //require(IdToAdress[_ID] = _sender); uint256 value = playerVault[IdToAdress[_ID]]; playerVault[_sendTo] = 0; _sendTo.transfer(value); emit cashout(_sendTo,value); } function fillBonds (uint256 bondsOwner) updateAccount(bondsOwner) public { uint256 pendingz = pendingFills[bondsOwner]; require(bondsOutstanding[bondsOwner] > 1000 && pendingz > 1000); if(pendingz > bondsOutstanding[bondsOwner]){ // if has excess fills, excess to redistibution payoutPot = payoutPot.add(pendingz.sub(bondsOutstanding[bondsOwner])); pendingz = bondsOutstanding[bondsOwner]; } //require(pendingz <= bondsOutstanding[bondsOwner]); // empty the pendings pendingFills[bondsOwner] = 0; // decrease bonds outstanding bondsOutstanding[bondsOwner] = bondsOutstanding[bondsOwner].sub(pendingz); // adjust totalSupplyBonds totalSupplyBonds = totalSupplyBonds.sub(pendingz); // add to vault playerVault[IdToAdress[bondsOwner]] = playerVault[IdToAdress[bondsOwner]].add(pendingz); // count amount for transparancy IPO IdVaultedEths[bondsOwner] = IdVaultedEths[bondsOwner].add(pendingz); } function setHubAuto(uint256 percentage) public{ require(msg.sender == hubFundAdmin); hub_.setAuto(percentage); } function fetchHubVault() public{ uint256 value = hub_.playerVault(address(this)); require(value >0); require(msg.sender == hubFundAdmin); hub_.vaultToWallet(); payoutPot = payoutPot.add(value); } function fetchHubPiggy() public{ uint256 value = hub_.piggyBank(address(this)); require(value >0); hub_.piggyToWallet(); payoutPot = payoutPot.add(value); } function potToPayout() public { uint256 value = payoutPot; payoutPot = 0; require(value > 1 finney); totalDividendPoints = totalDividendPoints.add(value.mul(pointMultiplier).div(totalSupplyBonds)); unclaimedDividends = unclaimedDividends.add(value); emit bondsMatured(value); } constructor() public { hubFundAdmin = 0x2e66aa088ceb9Ce9b04f6B9B7482fBe559732A70;// change to new address for marketing fund playerId[hubFundAdmin] = 1; IdToAdress[1] = hubFundAdmin; nextPlayerID = 2; hub_.setAuto(10); openingFee = 0.1 ether; } // UI helper functions function getIPOpurchases(uint256 IPOidentifier) public view returns(address[] memory _funders, uint256[] memory owned){ uint i; address[] memory _locationOwner = new address[](IPOnextAddressPointer[IPOidentifier]); //address uint[] memory _locationData = new uint[](IPOnextAddressPointer[IPOidentifier]); //amount invested bool checkpoint; for(uint x = 0; x < IPOnextAddressPointer[IPOidentifier]; x+=1){ checkpoint = false; for(uint y = 0; y < IPOnextAddressPointer[IPOidentifier]; y+=1) { if(_locationOwner[y] ==IPOadresslist[IPOidentifier][i]) { checkpoint = true; } } if (checkpoint == false) { _locationOwner[i] = IPOadresslist[IPOidentifier][i]; _locationData[i] = IPOpurchases[IPOidentifier][IPOadresslist[IPOidentifier][i]]; } i+=1; } return (_locationOwner,_locationData); } function getHubInfo() public view returns(uint256 piggy){ uint256 _piggy = hub_.piggyBank(address(this)); return(_piggy); } function getPlayerInfo() public view returns(address[] memory _Owner, uint256[] memory locationData,address[] memory infoRef ){ uint i; address[] memory _locationOwner = new address[](nextPlayerID); //address uint[] memory _locationData = new uint[](nextPlayerID*4); //bonds - divs - pending - vault address[] memory _info = new address[](nextPlayerID*2); //bool[] memory _locationData2 = new bool[](nextPlayerID); //isAlive uint y; uint z; for(uint x = 0; x < nextPlayerID; x+=1){ _locationOwner[i] = IdToAdress[i]; _locationData[y] = bondsOutstanding[i]; _locationData[y+1] = dividendsOwing(i); _locationData[y+2] = pendingFills[i]; _locationData[y+3] = playerVault[IdToAdress[i]]; _info[z] = IdToAdress[i]; _info[z+1] = IdToAdress[i]; //_locationData2[i] = allowAutoInvest[IdToAdress[i]]; y += 4; z += 2; i+=1; } return (_locationOwner,_locationData, _info); } function getIPOInfo(address user) public view returns(address[] memory _Owner, uint256[] memory locationData , bool[] memory states, bytes32[] memory infos){ uint i; address[] memory _locationOwner = new address[](nextIPO); // IPO creator uint[] memory _locationData = new uint[](nextIPO * 6); // IPOtarget - IPOamountFunded - IPOprofile - owned bool[] memory _states = new bool[](nextIPO * 3); //hastarget - isactive - isblacklisted bytes32[] memory _infos = new bytes32[](nextIPO);// info - info2 info3 uint y; uint z; for(uint x = 0; x < nextIPO; x+=1){ _locationOwner[i] = IPOcreator[i]; _locationData[y] = IPOtarget[i]; _locationData[y+1] = IPOamountFunded[i]; _locationData[y+2] = IPOprofile[i]; _locationData[y+3] = IPOpurchases[i][user]; _locationData[y+4] = IdVaultedEths[IPOtoID[i]]; _locationData[y+5] = IPOtoID[i]; _states[z] = IPOhasTarget[i]; _states[z+1] = IPOisActive[i]; _states[z+2] = UIblacklist[i]; _infos[i] = IPOinfo[i]; y += 6; z += 3; i+=1; } return (_locationOwner,_locationData, _states, _infos); } // events event IPOFunded(address indexed Funder, uint256 indexed amount, uint256 indexed IPOidentifier); event cashout(address indexed player , uint256 indexed ethAmount); event bondsMatured(uint256 indexed amount); event IPOCreated(address indexed owner, bool indexed hastarget, uint256 indexed target); event payment(address indexed sender,address indexed receiver, uint256 indexed amount); } interface PlincInterface { function IdToAdress(uint256 index) external view returns(address); function nextPlayerID() external view returns(uint256); function bondsOutstanding(address player) external view returns(uint256); function playerVault(address player) external view returns(uint256); function piggyBank(address player) external view returns(uint256); function vaultToWallet() external ; function piggyToWallet() external ; function setAuto (uint256 percentage)external ; function buyBonds( address referral)external payable ; }
require(IdToAdress[_ID] = _sender);
function vaultToWallet(uint256 _ID) public { address payable _sendTo = IdToAdress[_ID]; require(playerVault[IdToAdress[_ID]] > 0); uint256 value = playerVault[IdToAdress[_ID]]; playerVault[_sendTo] = 0; _sendTo.transfer(value); emit cashout(_sendTo,value); }
7,311,905
./full_match/5/0x559385E8728b7d8C98B3910e5531D8C49F861c31/sources/project:/contracts/main/MentaportRegistry.sol
mintFromAllowList function allows minting location from an allowed list _projectId the id of the project to mint to _mintRequest the mint request to mint from _proof the proof for the address to mint for in the mint request/
function mintFromAllowList( uint256 _projectId, MintRequest calldata _mintRequest, bytes32[] calldata _proof ) external payable virtual nonReentrant registryNotPaused projectNotPaused(_projectId) onlyValidSigner( _mintRequest.receiver, _mintRequest.timestamp, _mintRequest.locationRuleId, _mintRequest.signature ) { Project storage project = projects[_projectId]; _requestIsCompliant(_mintRequest.receiver, msg.value, 1, project); require(project.useAllowList, "Failed using allow list, use mintLocation."); require(verifyAddress(_mintRequest.receiver, _proof, project.merkleRoot), "Could not verify address"); require(_isUsedSignature(_mintRequest.signature), "Signature already used, not valid anymore"); balanceOf[_projectId][_mintRequest.receiver] += 1; uint256 totalMinted = project.totalMinted + 1; project.totalMinted = totalMinted; uint256 tokenId = _mintNFT(_mintRequest.receiver, project.projectBaseURI, _generateTokenId( _projectId, totalMinted )); _splitPayment(project.owner); emit MintFromAllowListFromProject(tokenId, _mintRequest.receiver, _projectId); }
1,916,302
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (access/AccessControl.sol) pragma solidity ^0.8.0; import "./IAccessControlUpgradeable.sol"; import "../utils/ContextUpgradeable.sol"; import "../utils/StringsUpgradeable.sol"; import "../utils/introspection/ERC165Upgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable { function __AccessControl_init() internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal initializer { } struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", StringsUpgradeable.toHexString(uint160(account), 20), " is missing role ", StringsUpgradeable.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been revoked `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== * * NOTE: This function is deprecated in favor of {_grantRole}. */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } /** * @dev Grants `role` to `account`. * * Internal function without access restriction. */ function _grantRole(bytes32 role, address account) internal virtual { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } /** * @dev Revokes `role` from `account`. * * Internal function without access restriction. */ function _revokeRole(bytes32 role, address account) internal virtual { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (access/IAccessControl.sol) pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControlUpgradeable { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (proxy/ERC1967/ERC1967Upgrade.sol) pragma solidity ^0.8.2; import "../beacon/IBeaconUpgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; import "../../utils/StorageSlotUpgradeable.sol"; import "../utils/Initializable.sol"; /** * @dev This abstract contract provides getters and event emitting update functions for * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots. * * _Available since v4.1._ * * @custom:oz-upgrades-unsafe-allow delegatecall */ abstract contract ERC1967UpgradeUpgradeable is Initializable { function __ERC1967Upgrade_init() internal initializer { __ERC1967Upgrade_init_unchained(); } function __ERC1967Upgrade_init_unchained() internal initializer { } // This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1 bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143; /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev Emitted when the implementation is upgraded. */ event Upgraded(address indexed implementation); /** * @dev Returns the current implementation address. */ function _getImplementation() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value; } /** * @dev Stores a new address in the EIP1967 implementation slot. */ function _setImplementation(address newImplementation) private { require(AddressUpgradeable.isContract(newImplementation), "ERC1967: new implementation is not a contract"); StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; } /** * @dev Perform implementation upgrade * * Emits an {Upgraded} event. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Perform implementation upgrade with additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCall( address newImplementation, bytes memory data, bool forceCall ) internal { _upgradeTo(newImplementation); if (data.length > 0 || forceCall) { _functionDelegateCall(newImplementation, data); } } /** * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCallSecure( address newImplementation, bytes memory data, bool forceCall ) internal { address oldImplementation = _getImplementation(); // Initial upgrade and setup call _setImplementation(newImplementation); if (data.length > 0 || forceCall) { _functionDelegateCall(newImplementation, data); } // Perform rollback test if not already in progress StorageSlotUpgradeable.BooleanSlot storage rollbackTesting = StorageSlotUpgradeable.getBooleanSlot(_ROLLBACK_SLOT); if (!rollbackTesting.value) { // Trigger rollback using upgradeTo from the new implementation rollbackTesting.value = true; _functionDelegateCall( newImplementation, abi.encodeWithSignature("upgradeTo(address)", oldImplementation) ); rollbackTesting.value = false; // Check rollback was effective require(oldImplementation == _getImplementation(), "ERC1967Upgrade: upgrade breaks further upgrades"); // Finally reset to the new implementation and log the upgrade _upgradeTo(newImplementation); } } /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Emitted when the admin account has changed. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Returns the current admin. */ function _getAdmin() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value; } /** * @dev Stores a new address in the EIP1967 admin slot. */ function _setAdmin(address newAdmin) private { require(newAdmin != address(0), "ERC1967: new admin is the zero address"); StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value = newAdmin; } /** * @dev Changes the admin of the proxy. * * Emits an {AdminChanged} event. */ function _changeAdmin(address newAdmin) internal { emit AdminChanged(_getAdmin(), newAdmin); _setAdmin(newAdmin); } /** * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy. * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor. */ bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50; /** * @dev Emitted when the beacon is upgraded. */ event BeaconUpgraded(address indexed beacon); /** * @dev Returns the current beacon. */ function _getBeacon() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value; } /** * @dev Stores a new beacon in the EIP1967 beacon slot. */ function _setBeacon(address newBeacon) private { require(AddressUpgradeable.isContract(newBeacon), "ERC1967: new beacon is not a contract"); require( AddressUpgradeable.isContract(IBeaconUpgradeable(newBeacon).implementation()), "ERC1967: beacon implementation is not a contract" ); StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value = newBeacon; } /** * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that). * * Emits a {BeaconUpgraded} event. */ function _upgradeBeaconToAndCall( address newBeacon, bytes memory data, bool forceCall ) internal { _setBeacon(newBeacon); emit BeaconUpgraded(newBeacon); if (data.length > 0 || forceCall) { _functionDelegateCall(IBeaconUpgradeable(newBeacon).implementation(), data); } } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function _functionDelegateCall(address target, bytes memory data) private returns (bytes memory) { require(AddressUpgradeable.isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return AddressUpgradeable.verifyCallResult(success, returndata, "Address: low-level delegate call failed"); } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (proxy/beacon/IBeacon.sol) pragma solidity ^0.8.0; /** * @dev This is the interface that {BeaconProxy} expects of its beacon. */ interface IBeaconUpgradeable { /** * @dev Must return an address that can be used as a delegate call target. * * {BeaconProxy} will check that this address is a contract. */ function implementation() external view returns (address); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (proxy/utils/Initializable.sol) pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the * initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() initializer {} * ``` * ==== */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (proxy/utils/UUPSUpgradeable.sol) pragma solidity ^0.8.0; import "../ERC1967/ERC1967UpgradeUpgradeable.sol"; import "./Initializable.sol"; /** * @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an * {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy. * * A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is * reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing * `UUPSUpgradeable` with a custom implementation of upgrades. * * The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism. * * _Available since v4.1._ */ abstract contract UUPSUpgradeable is Initializable, ERC1967UpgradeUpgradeable { function __UUPSUpgradeable_init() internal initializer { __ERC1967Upgrade_init_unchained(); __UUPSUpgradeable_init_unchained(); } function __UUPSUpgradeable_init_unchained() internal initializer { } /// @custom:oz-upgrades-unsafe-allow state-variable-immutable state-variable-assignment address private immutable __self = address(this); /** * @dev Check that the execution is being performed through a delegatecall call and that the execution context is * a proxy contract with an implementation (as defined in ERC1967) pointing to self. This should only be the case * for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a * function through ERC1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to * fail. */ modifier onlyProxy() { require(address(this) != __self, "Function must be called through delegatecall"); require(_getImplementation() == __self, "Function must be called through active proxy"); _; } /** * @dev Upgrade the implementation of the proxy to `newImplementation`. * * Calls {_authorizeUpgrade}. * * Emits an {Upgraded} event. */ function upgradeTo(address newImplementation) external virtual onlyProxy { _authorizeUpgrade(newImplementation); _upgradeToAndCallSecure(newImplementation, new bytes(0), false); } /** * @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call * encoded in `data`. * * Calls {_authorizeUpgrade}. * * Emits an {Upgraded} event. */ function upgradeToAndCall(address newImplementation, bytes memory data) external payable virtual onlyProxy { _authorizeUpgrade(newImplementation); _upgradeToAndCallSecure(newImplementation, data, true); } /** * @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by * {upgradeTo} and {upgradeToAndCall}. * * Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}. * * ```solidity * function _authorizeUpgrade(address) internal override onlyOwner {} * ``` */ function _authorizeUpgrade(address newImplementation) internal virtual; uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/Context.sol) pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/StorageSlot.sol) pragma solidity ^0.8.0; /** * @dev Library for reading and writing primitive types to specific storage slots. * * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts. * This library helps with reading and writing to such slots without the need for inline assembly. * * The functions in this library return Slot structs that contain a `value` member that can be used to read or write. * * Example usage to set ERC1967 implementation slot: * ``` * contract ERC1967 { * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; * * function _getImplementation() internal view returns (address) { * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; * } * * function _setImplementation(address newImplementation) internal { * require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract"); * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; * } * } * ``` * * _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._ */ library StorageSlotUpgradeable { struct AddressSlot { address value; } struct BooleanSlot { bool value; } struct Bytes32Slot { bytes32 value; } struct Uint256Slot { uint256 value; } /** * @dev Returns an `AddressSlot` with member `value` located at `slot`. */ function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `BooleanSlot` with member `value` located at `slot`. */ function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Bytes32Slot` with member `value` located at `slot`. */ function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Uint256Slot` with member `value` located at `slot`. */ function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) { assembly { r.slot := slot } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library StringsUpgradeable { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { function __ERC165_init() internal initializer { __ERC165_init_unchained(); } function __ERC165_init_unchained() internal initializer { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/structs/EnumerableSet.sol) pragma solidity ^0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library 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; if (lastIndex != toDeleteIndex) { bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex } // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { return set._values[index]; } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function _values(Set storage set) private view returns (bytes32[] memory) { return set._values; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(Bytes32Set storage set) internal view returns (bytes32[] memory) { return _values(set._inner); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(AddressSet storage set) internal view returns (address[] memory) { bytes32[] memory store = _values(set._inner); address[] memory result; assembly { result := store } return result; } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(UintSet storage set) internal view returns (uint256[] memory) { bytes32[] memory store = _values(set._inner); uint256[] memory result; assembly { result := store } return result; } } //SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.4; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol"; /** * @title Controller component * @dev For easy access to any core components */ abstract contract Controller is Initializable, UUPSUpgradeable, AccessControlUpgradeable { bytes32 public constant ROLE_ADMIN = keccak256("ROLE_ADMIN"); mapping(address => address) private _admins; // slither-disable-next-line uninitialized-state bool private _paused; // slither-disable-next-line uninitialized-state address public pauseGuardian; /** * @dev Emitted when the pause is triggered by a pauser (`account`). */ event Paused(address account); /** * @dev Emitted when the pause is lifted by a pauser (`account`). */ event Unpaused(address account); /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!_paused, "Controller: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(_paused, "Controller: not paused"); _; } modifier onlyAdmin() { require(hasRole(ROLE_ADMIN, msg.sender), "Controller: not admin"); _; } modifier onlyGuardian() { require(pauseGuardian == msg.sender, "Controller: caller does not have the guardian role"); _; } //When using minimal deploy, do not call initialize directly during deploy, because msg.sender is the proxyFactory address, and you need to call it manually function __Controller_init(address admin_) public initializer { require(admin_ != address(0), "Controller: address zero"); _paused = false; _admins[admin_] = admin_; __UUPSUpgradeable_init(); _setupRole(ROLE_ADMIN, admin_); pauseGuardian = admin_; } function _authorizeUpgrade(address) internal view override onlyAdmin {} /** * @dev Check if the address provided is the admin * @param account Account address */ function isAdmin(address account) public view returns (bool) { return hasRole(ROLE_ADMIN, account); } /** * @dev Add a new admin account * @param account Account address */ function addAdmin(address account) public onlyAdmin { require(account != address(0), "Controller: address zero"); require(_admins[account] == address(0), "Controller: admin already existed"); _admins[account] = account; _setupRole(ROLE_ADMIN, account); } /** * @dev Set pauseGuardian account * @param account Account address */ function setGuardian(address account) public onlyAdmin { pauseGuardian = account; } /** * @dev Renouce the admin from the sender's address */ function renounceAdmin() public { renounceRole(ROLE_ADMIN, msg.sender); delete _admins[msg.sender]; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Called by a pauser to pause, triggers stopped state. */ function pause() public onlyGuardian whenNotPaused { _paused = true; emit Paused(msg.sender); } /** * @dev Called by a pauser to unpause, returns to normal state. */ function unpause() public onlyGuardian whenPaused { _paused = false; emit Unpaused(msg.sender); } uint256[50] private ______gap; } //SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.4; import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; import "../Controller.sol"; /** * @title MarketRegistry Contract * @dev Registering and managing all the lending markets. */ contract MarketRegistry is Controller { using EnumerableSet for EnumerableSet.AddressSet; struct Market { address uToken; address userManager; } EnumerableSet.AddressSet private uTokenList; EnumerableSet.AddressSet private userManagerList; mapping(address => Market) public tokens; event LogAddUToken(address indexed tokenAddress, address contractAddress); event LogAddUserManager(address indexed tokenAddress, address contractAddress); modifier newToken(address token) { require(tokens[token].uToken == address(0), "MarketRegistry: has already exist this uToken"); _; } modifier newUserManager(address token) { require(tokens[token].userManager == address(0), "MarketRegistry: has already exist this userManager"); _; } /** * @dev Initialization function */ function __MarketRegistry_init() public initializer { Controller.__Controller_init(msg.sender); } /** * @dev Retrieves the value of the state variable `uTokenList` * @return Stored uToken address */ function getUTokens() public view returns (address[] memory) { return uTokenList.values(); } function getUserManagers() public view returns (address[] memory) { return userManagerList.values(); } function addUToken(address token, address uToken) public newToken(token) onlyAdmin { require(token != address(0) && uToken != address(0), "MarketRegistry: token and uToken can not be zero"); uTokenList.add(uToken); tokens[token].uToken = uToken; emit LogAddUToken(token, uToken); } function addUserManager(address token, address userManager) public newUserManager(token) onlyAdmin { require( token != address(0) && userManager != address(0), "MarketRegistry: token and userManager can not be zero" ); userManagerList.add(userManager); tokens[token].userManager = userManager; emit LogAddUserManager(token, userManager); } function deleteMarket(address token) public onlyAdmin { uTokenList.remove(tokens[token].uToken); userManagerList.remove(tokens[token].userManager); delete tokens[token].uToken; delete tokens[token].userManager; } }
Retrieves the value of the state variable `uTokenList` return Stored uToken address/
function getUTokens() public view returns (address[] memory) { return uTokenList.values(); }
633,029
pragma solidity 0.4.24; /** * This contract is used to publish hashed contribution agreements for disclosures * already published in the DisclosureManager contract. These agreements require * multi party sign off which this contract facilitates. */ contract DisclosureAgreementTracker { /** * Represents a contribution agreement for a disclosure. An agreement is * referenced by the sha256 hash of its contract in `agreementMap`. */ struct Agreement { // previous version of an agreement for this disclosure bytes32 previous; // index of the disclosure in disclosureManager uint disclosureIndex; // block this agreement was created in uint blockNumber; // total signatures obtained so far uint signedCount; // addresses from which signatures are required address[] signatories; // map of signatory address to true, if signature not yet obtained mapping(address => bool) requiredSignatures; } /** * Tracks the latest agreement and total agreements for a disclosure. * Referenced by disclosure index in `latestAgreementMap`. */ struct Latest { bytes32 agreementHash; uint agreementCount; } /** Contract creator */ address public owner; /** Address of the DisclosureManager contract these agreements apply to */ address public disclosureManager; /** Total agreements tracked */ uint public agreementCount; /** Total disclosures with agreements */ uint public disclosureCount; /** Map of agreements by contract sha256 hash */ mapping(bytes32 => Agreement) public agreementMap; /** Map disclosure index to latest agreement */ mapping(uint => Latest) public latestMap; /** Emitted when agreement is added */ event agreementAdded( bytes32 agreementHash, uint disclosureIndex, address[] signatories); /** Emitted when agreement is signed */ event agreementSigned( bytes32 agreementHash, uint disclosureIndex, address signatory); /** Emitted when an agreement is signed by all signatories */ event agreementFullySigned( bytes32 agreementHash, uint disclosureIndex); constructor(address disclosureManagerAddress) public { owner = msg.sender; disclosureManager = disclosureManagerAddress; } /** Enforce function caller is contract owner */ modifier isOwner() { if (msg.sender != owner) revert("sender must be owner"); _; } function _hasAgreement(Agreement agreement) private pure returns(bool) { return agreement.disclosureIndex != 0; } /** Return true if the agreement exists */ function hasAgreement(bytes32 agreementHash) public view returns(bool) { return _hasAgreement(agreementMap[agreementHash]); } function _hasDisclosureAgreement(Latest latest) private pure returns(bool) { return latest.agreementCount != 0; } /** Return true if the disclosure has an agreement */ function hasDisclosureAgreement(uint disclosureIndex) public view returns(bool) { return _hasDisclosureAgreement(latestMap[disclosureIndex]); } function _isAgreementFullySigned(Agreement agreement) private pure returns(bool) { return agreement.signedCount == agreement.signatories.length; } /** Return true if the agreement exists and is fully signed */ function isAgreementFullySigned(bytes32 agreementHash) public view returns(bool) { Agreement storage agreement = agreementMap[agreementHash]; return _hasAgreement(agreement) && _isAgreementFullySigned(agreement); } /** Return true if disclosures latest agreement is fully signed. */ function isDisclosureFullySigned(uint disclosureIndex) public view returns(bool) { return isAgreementFullySigned( latestMap[disclosureIndex].agreementHash ); } /** * Get the Agreement requiredSignatures map as an array of bools parallel * to its signatories array. */ function _getRequiredSignaturesArray(Agreement storage agreement) private view returns (bool[]) { address[] storage signatories = agreement.signatories; bool[] memory requiredSignatureArray = new bool[](signatories.length); for (uint i = 0; i < signatories.length; i++) { address signatory = signatories[i]; requiredSignatureArray[i] = agreement.requiredSignatures[signatory]; } return requiredSignatureArray; } /** Get the agreement with the provided hash */ function getAgreement(bytes32 agreementHash) public view returns( bytes32 previous, uint disclosureIndex, uint blockNumber, uint signedCount, address[] signatories, bool[] requiredSignatures ) { Agreement storage agreement = agreementMap[agreementHash]; previous = agreement.previous; disclosureIndex = agreement.disclosureIndex; blockNumber = agreement.blockNumber; signedCount = agreement.signedCount; signatories = agreement.signatories; requiredSignatures = _getRequiredSignaturesArray(agreement); } /** * Add an agreement for the provided disclosure. If an agreement already * exists that disclosures latestAgreement will be updated and * the existing agreement will not be removed. */ function addAgreement( bytes32 agreementHash, uint disclosureIndex, address[] signatories ) public isOwner { require(disclosureIndex > 0, "disclosureIndex must be greater than 0"); require(agreementHash != 0, "agreementHash must not be 0"); require(signatories.length > 0, "signatories must not be empty"); Agreement storage agreement = agreementMap[agreementHash]; if (_hasAgreement(agreement)) { revert("Agreement already exists"); } agreementCount++; agreement.disclosureIndex = disclosureIndex; agreement.blockNumber = block.number; agreement.signatories = signatories; Latest storage latest = latestMap[disclosureIndex]; if (!_hasDisclosureAgreement(latest)) { disclosureCount++; } agreement.previous = latest.agreementHash; latest.agreementHash = agreementHash; latest.agreementCount++; for (uint i = 0; i < signatories.length; i++) { address signatory = signatories[i]; if (agreement.requiredSignatures[signatory]) { revert("signatories must not contain duplicates"); } agreement.requiredSignatures[signatory] = true; } emit agreementAdded(agreementHash, disclosureIndex, signatories); } /** * Sign an agreement. * Returns true if signature applied, false if not a signatory or already * signed. */ function signAgreement(bytes32 agreementHash) public { require(hasAgreement(agreementHash), "agreeement must exist"); Agreement storage agreement = agreementMap[agreementHash]; bool signed = agreement.requiredSignatures[msg.sender]; require(signed, "sender already signed or not a signatory"); agreement.requiredSignatures[msg.sender] = false; agreement.signedCount++; emit agreementSigned( agreementHash, agreement.disclosureIndex, msg.sender); if (_isAgreementFullySigned(agreement)) { emit agreementFullySigned( agreementHash, agreement.disclosureIndex); } } /** This contract does not accept payments */ function () public payable { revert("payment not supported"); } }
This contract does not accept payments /
function () public payable { revert("payment not supported"); }
14,485,814
// SPDX-License-Identifier: UNLICENSED // Copyright (c) 2020 Gemini Trust Company LLC. All Rights Reserved pragma solidity ^0.7.0; import "./ERC20Impl.sol"; import "./LockRequestable.sol"; /** @title A contact to govern hybrid control over increases to the token supply. * * @notice A contract that acts as a custodian of the active token * implementation, and an intermediary between it and the ‘true’ custodian. * It preserves the functionality of direct custodianship as well as granting * limited control of token supply increases to an additional key. * * @dev This contract is a layer of indirection between an instance of * ERC20Impl and a custodian. The functionality of the custodianship over * the token implementation is preserved (printing and custodian changes), * but this contract adds the ability for an additional key * (the 'limited printer') to increase the token supply up to a ceiling, * and this supply ceiling can only be raised by the custodian. * * @author Gemini Trust Company, LLC */ contract PrintLimiter is LockRequestable { // TYPES /// @dev The struct type for pending ceiling raises. struct PendingCeilingRaise { uint256 raiseBy; } // MEMBERS /// @dev The reference to the active token implementation. ERC20Impl immutable public erc20Impl; /// @dev The address of the account or contract that acts as the custodian. address immutable public custodian; /** @dev The sole authorized caller of limited printing. * This account is also authorized to lower the supply ceiling. */ address immutable public limitedPrinter; /** @dev The maximum that the token supply can be increased to * through use of the limited printing feature. * The difference between the current total supply and the supply * ceiling is what is available to the 'limited printer' account. * The value of the ceiling can only be increased by the custodian. */ uint256 public totalSupplyCeiling; /// @dev The map of lock ids to pending ceiling raises. mapping (bytes32 => PendingCeilingRaise) public pendingRaiseMap; // CONSTRUCTOR constructor( address _erc20Impl, address _custodian, address _limitedPrinter, uint256 _initialCeiling ) { erc20Impl = ERC20Impl(_erc20Impl); custodian = _custodian; limitedPrinter = _limitedPrinter; totalSupplyCeiling = _initialCeiling; } // MODIFIERS modifier onlyCustodian { require(msg.sender == custodian, "unauthorized"); _; } modifier onlyLimitedPrinter { require(msg.sender == limitedPrinter, "unauthorized"); _; } /** @notice Increases the token supply, with the newly created tokens * being added to the balance of the specified account. * * @dev The function checks that the value to print does not * exceed the supply ceiling when added to the current total supply. * NOTE: printing to the zero address is disallowed. * * @param _receiver The receiving address of the print. * @param _value The number of tokens to add to the total supply and the * balance of the receiving address. */ function limitedPrint(address _receiver, uint256 _value, bytes32 _merkleRoot) external onlyLimitedPrinter { uint256 totalSupply = erc20Impl.totalSupply(); uint256 newTotalSupply = totalSupply + _value; require(newTotalSupply >= totalSupply, "overflow"); require(newTotalSupply <= totalSupplyCeiling, "ceiling exceeded"); erc20Impl.executePrint(_receiver, _value, _merkleRoot); } /** @notice Requests an increase to the supply ceiling. * * @dev Returns a unique lock id associated with the request. * Anyone can call this function, but confirming the request is authorized * by the custodian. * * @param _raiseBy The amount by which to raise the ceiling. * * @return lockId A unique identifier for this request. */ function requestCeilingRaise(uint256 _raiseBy) external returns (bytes32 lockId) { require(_raiseBy != 0, "zero"); (bytes32 preLockId, uint256 lockRequestIdx) = generatePreLockId(); lockId = keccak256( abi.encodePacked( preLockId, this.requestCeilingRaise.selector, _raiseBy ) ); pendingRaiseMap[lockId] = PendingCeilingRaise({ raiseBy: _raiseBy }); emit CeilingRaiseLocked(lockId, _raiseBy, lockRequestIdx); } /** @notice Confirms a pending increase in the token supply. * * @dev When called by the custodian with a lock id associated with a * pending ceiling increase, the amount requested is added to the * current supply ceiling. * NOTE: this function will not execute any raise that would overflow the * supply ceiling, but it will not revert either. * * @param _lockId The identifier of a pending ceiling raise request. */ function confirmCeilingRaise(bytes32 _lockId) external onlyCustodian { PendingCeilingRaise storage pendingRaise = pendingRaiseMap[_lockId]; // copy locals of references to struct members uint256 raiseBy = pendingRaise.raiseBy; // accounts for a gibberish _lockId require(raiseBy != 0, "no such lockId"); delete pendingRaiseMap[_lockId]; uint256 newCeiling = totalSupplyCeiling + raiseBy; // overflow check if (newCeiling >= totalSupplyCeiling) { totalSupplyCeiling = newCeiling; emit CeilingRaiseConfirmed(_lockId, raiseBy, newCeiling); } } /** @notice Lowers the supply ceiling, further constraining the bound of * what can be printed by the limited printer. * * @dev The limited printer is the sole authorized caller of this function, * so it is the only account that can elect to lower its limit to increase * the token supply. * * @param _lowerBy The amount by which to lower the supply ceiling. */ function lowerCeiling(uint256 _lowerBy) external onlyLimitedPrinter { uint256 newCeiling = totalSupplyCeiling - _lowerBy; // overflow check require(newCeiling <= totalSupplyCeiling, "overflow"); totalSupplyCeiling = newCeiling; emit CeilingLowered(_lowerBy, newCeiling); } /** @notice Pass-through control of print confirmation, allowing this * contract's custodian to act as the custodian of the associated * active token implementation. * * @dev This contract is the direct custodian of the active token * implementation, but this function allows this contract's custodian * to act as though it were the direct custodian of the active * token implementation. Therefore the custodian retains control of * unlimited printing. * * @param _lockId The identifier of a pending print request in * the associated active token implementation. */ function confirmPrintProxy(bytes32 _lockId) external onlyCustodian { erc20Impl.confirmPrint(_lockId); } /** @notice Pass-through control of custodian change confirmation, * allowing this contract's custodian to act as the custodian of * the associated active token implementation. * * @dev This contract is the direct custodian of the active token * implementation, but this function allows this contract's custodian * to act as though it were the direct custodian of the active * token implementation. Therefore the custodian retains control of * custodian changes. * * @param _lockId The identifier of a pending custodian change request * in the associated active token implementation. */ function confirmCustodianChangeProxy(bytes32 _lockId) external onlyCustodian { erc20Impl.confirmCustodianChange(_lockId); } // EVENTS /// @dev Emitted by successful `requestCeilingRaise` calls. event CeilingRaiseLocked(bytes32 _lockId, uint256 _raiseBy, uint256 _lockRequestIdx); /// @dev Emitted by successful `confirmCeilingRaise` calls. event CeilingRaiseConfirmed(bytes32 _lockId, uint256 _raiseBy, uint256 _newCeiling); /// @dev Emitted by successful `lowerCeiling` calls. event CeilingLowered(uint256 _lowerBy, uint256 _newCeiling); } // SPDX-License-Identifier: UNLICENSED // Copyright (c) 2020 Gemini Trust Company LLC. All Rights Reserved pragma solidity ^0.7.0; import "./CustodianUpgradeable.sol"; import "./ERC20Proxy.sol"; import "./ERC20Store.sol"; /** @title ERC20 compliant token intermediary contract holding core logic. * * @notice This contract serves as an intermediary between the exposed ERC20 * interface in ERC20Proxy and the store of balances in ERC20Store. This * contract contains core logic that the proxy can delegate to * and that the store is called by. * * @dev This contract contains the core logic to implement the * ERC20 specification as well as several extensions. * 1. Changes to the token supply. * 2. Batched transfers. * 3. Relative changes to spending approvals. * 4. Delegated transfer control ('sweeping'). * * @author Gemini Trust Company, LLC */ contract ERC20Impl is CustodianUpgradeable { // TYPES /// @dev The struct type for pending increases to the token supply (print). struct PendingPrint { address receiver; uint256 value; bytes32 merkleRoot; } // MEMBERS /// @dev The reference to the proxy. ERC20Proxy immutable public erc20Proxy; /// @dev The reference to the store. ERC20Store immutable public erc20Store; address immutable public implOwner; /// @dev The map of lock ids to pending token increases. mapping (bytes32 => PendingPrint) public pendingPrintMap; // Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to // invalidate the cached domain separator if the chain id changes. bytes32 private immutable _CACHED_DOMAIN_SEPARATOR; uint256 private immutable _CACHED_CHAIN_ID; bytes32 private immutable _HASHED_NAME; bytes32 private immutable _HASHED_VERSION; bytes32 private immutable _TYPE_HASH; bytes32 private immutable _PERMIT_TYPEHASH; // CONSTRUCTOR constructor( address _erc20Proxy, address _erc20Store, address _custodian, address _implOwner ) CustodianUpgradeable(_custodian) { erc20Proxy = ERC20Proxy(_erc20Proxy); erc20Store = ERC20Store(_erc20Store); implOwner = _implOwner; bytes32 hashedName = keccak256(bytes(ERC20Proxy(_erc20Proxy).name())); bytes32 hashedVersion = keccak256(bytes("1")); bytes32 typeHash = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"); _HASHED_NAME = hashedName; _HASHED_VERSION = hashedVersion; _CACHED_CHAIN_ID = _getChainId(); _CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(typeHash, hashedName, hashedVersion, _erc20Proxy); _TYPE_HASH = typeHash; _PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); } // MODIFIERS modifier onlyProxy { require(msg.sender == address(erc20Proxy), "unauthorized"); _; } modifier onlyImplOwner { require(msg.sender == implOwner, "unauthorized"); _; } function _approve( address _owner, address _spender, uint256 _amount ) private { require(_spender != address(0), "zero address"); // disallow unspendable approvals erc20Store.setAllowance(_owner, _spender, _amount); erc20Proxy.emitApproval(_owner, _spender, _amount); } /** @notice Core logic of the ERC20 `approve` function. * * @dev This function can only be called by the referenced proxy, * which has an `approve` function. * Every argument passed to that function as well as the original * `msg.sender` gets passed to this function. * NOTE: approvals for the zero address (unspendable) are disallowed. * * @param _sender The address initiating the approval in proxy. */ function approveWithSender( address _sender, address _spender, uint256 _value ) external onlyProxy returns (bool success) { _approve(_sender, _spender, _value); return true; } /** @notice Core logic of the `increaseApproval` function. * * @dev This function can only be called by the referenced proxy, * which has an `increaseApproval` function. * Every argument passed to that function as well as the original * `msg.sender` gets passed to this function. * NOTE: approvals for the zero address (unspendable) are disallowed. * * @param _sender The address initiating the approval. */ function increaseApprovalWithSender( address _sender, address _spender, uint256 _addedValue ) external onlyProxy returns (bool success) { require(_spender != address(0), "zero address"); // disallow unspendable approvals uint256 currentAllowance = erc20Store.allowed(_sender, _spender); uint256 newAllowance = currentAllowance + _addedValue; require(newAllowance >= currentAllowance, "overflow"); erc20Store.setAllowance(_sender, _spender, newAllowance); erc20Proxy.emitApproval(_sender, _spender, newAllowance); return true; } /** @notice Core logic of the `decreaseApproval` function. * * @dev This function can only be called by the referenced proxy, * which has a `decreaseApproval` function. * Every argument passed to that function as well as the original * `msg.sender` gets passed to this function. * NOTE: approvals for the zero address (unspendable) are disallowed. * * @param _sender The address initiating the approval. */ function decreaseApprovalWithSender( address _sender, address _spender, uint256 _subtractedValue ) external onlyProxy returns (bool success) { require(_spender != address(0), "zero address"); // disallow unspendable approvals uint256 currentAllowance = erc20Store.allowed(_sender, _spender); uint256 newAllowance = currentAllowance - _subtractedValue; require(newAllowance <= currentAllowance, "overflow"); erc20Store.setAllowance(_sender, _spender, newAllowance); erc20Proxy.emitApproval(_sender, _spender, newAllowance); return true; } function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external { require(owner != address(0x0), "zero address"); require(block.timestamp <= deadline, "expired"); bytes32 structHash = keccak256( abi.encode( _PERMIT_TYPEHASH, owner, spender, value, erc20Store.getNonceAndIncrement(owner), deadline ) ); bytes32 hash = keccak256( abi.encodePacked( "\x19\x01", _domainSeparatorV4(), structHash ) ); address signer = ecrecover(hash, v, r, s); require(signer == owner, "invalid signature"); _approve(owner, spender, value); } function nonces(address owner) external view returns (uint256) { return erc20Store.nonces(owner); } function DOMAIN_SEPARATOR() external view returns (bytes32) { return _domainSeparatorV4(); } /** @notice Requests an increase in the token supply, with the newly created * tokens to be added to the balance of the specified account. * * @dev Returns a unique lock id associated with the request. * Anyone can call this function, but confirming the request is authorized * by the custodian. * NOTE: printing to the zero address is disallowed. * * @param _receiver The receiving address of the print, if confirmed. * @param _value The number of tokens to add to the total supply and the * balance of the receiving address, if confirmed. * * @return lockId A unique identifier for this request. */ function requestPrint(address _receiver, uint256 _value, bytes32 _merkleRoot) external returns (bytes32 lockId) { require(_receiver != address(0), "zero address"); (bytes32 preLockId, uint256 lockRequestIdx) = generatePreLockId(); lockId = keccak256( abi.encodePacked( preLockId, this.requestPrint.selector, _receiver, _value, _merkleRoot ) ); pendingPrintMap[lockId] = PendingPrint({ receiver: _receiver, value: _value, merkleRoot: _merkleRoot }); emit PrintingLocked(lockId, _receiver, _value, lockRequestIdx); } function _executePrint(address _receiver, uint256 _value, bytes32 _merkleRoot) private { uint256 supply = erc20Store.totalSupply(); uint256 newSupply = supply + _value; if (newSupply >= supply) { erc20Store.setTotalSupplyAndAddBalance(newSupply, _receiver, _value); erc20Proxy.emitTransfer(address(0), _receiver, _value); emit AuditPrint(_merkleRoot); } } function executePrint(address _receiver, uint256 _value, bytes32 _merkleRoot) external onlyCustodian { _executePrint(_receiver, _value, _merkleRoot); } /** @notice Confirms a pending increase in the token supply. * * @dev When called by the custodian with a lock id associated with a * pending increase, the amount requested to be printed in the print request * is printed to the receiving address specified in that same request. * NOTE: this function will not execute any print that would overflow the * total supply, but it will not revert either. * * @param _lockId The identifier of a pending print request. */ function confirmPrint(bytes32 _lockId) external onlyCustodian { PendingPrint storage print = pendingPrintMap[_lockId]; // reject ‘null’ results from the map lookup // this can only be the case if an unknown `_lockId` is received address receiver = print.receiver; require (receiver != address(0), "no such lockId"); uint256 value = print.value; bytes32 merkleRoot = print.merkleRoot; delete pendingPrintMap[_lockId]; emit PrintingConfirmed(_lockId, receiver, value); _executePrint(receiver, value, merkleRoot); } /** @notice Burns the specified value from the sender's balance. * * @dev Sender's balanced is subtracted by the amount they wish to burn. * * @param _value The amount to burn. * * @return success true if the burn succeeded. */ function burn(uint256 _value, bytes32 _merkleRoot) external returns (bool success) { uint256 balanceOfSender = erc20Store.balances(msg.sender); require(_value <= balanceOfSender, "insufficient balance"); erc20Store.setBalanceAndDecreaseTotalSupply( msg.sender, balanceOfSender - _value, _value ); erc20Proxy.emitTransfer(msg.sender, address(0), _value); emit AuditBurn(_merkleRoot); return true; } /** @notice A function for a sender to issue multiple transfers to multiple * different addresses at once. This function is implemented for gas * considerations when someone wishes to transfer, as one transaction is * cheaper than issuing several distinct individual `transfer` transactions. * * @dev By specifying a set of destination addresses and values, the * sender can issue one transaction to transfer multiple amounts to * distinct addresses, rather than issuing each as a separate * transaction. The `_tos` and `_values` arrays must be equal length, and * an index in one array corresponds to the same index in the other array * (e.g. `_tos[0]` will receive `_values[0]`, `_tos[1]` will receive * `_values[1]`, and so on.) * NOTE: transfers to the zero address are disallowed. * * @param _tos The destination addresses to receive the transfers. * @param _values The values for each destination address. * @return success If transfers succeeded. */ function batchTransfer(address[] calldata _tos, uint256[] calldata _values) external returns (bool success) { require(_tos.length == _values.length, "inconsistent length"); uint256 numTransfers = _tos.length; uint256 senderBalance = erc20Store.balances(msg.sender); for (uint256 i = 0; i < numTransfers; i++) { address to = _tos[i]; require(to != address(0), "zero address"); uint256 v = _values[i]; require(senderBalance >= v, "insufficient balance"); if (msg.sender != to) { senderBalance -= v; erc20Store.addBalance(to, v); } erc20Proxy.emitTransfer(msg.sender, to, v); } erc20Store.setBalance(msg.sender, senderBalance); return true; } /** @notice Core logic of the ERC20 `transferFrom` function. * * @dev This function can only be called by the referenced proxy, * which has a `transferFrom` function. * Every argument passed to that function as well as the original * `msg.sender` gets passed to this function. * NOTE: transfers to the zero address are disallowed. * * @param _sender The address initiating the transfer in proxy. */ function transferFromWithSender( address _sender, address _from, address _to, uint256 _value ) external onlyProxy returns (bool success) { require(_to != address(0), "zero address"); // ensure burn is the cannonical transfer to 0x0 (uint256 balanceOfFrom, uint256 senderAllowance) = erc20Store.balanceAndAllowed(_from, _sender); require(_value <= balanceOfFrom, "insufficient balance"); require(_value <= senderAllowance, "insufficient allowance"); erc20Store.setBalanceAndAllowanceAndAddBalance( _from, balanceOfFrom - _value, _sender, senderAllowance - _value, _to, _value ); erc20Proxy.emitTransfer(_from, _to, _value); return true; } /** @notice Core logic of the ERC20 `transfer` function. * * @dev This function can only be called by the referenced proxy, * which has a `transfer` function. * Every argument passed to that function as well as the original * `msg.sender` gets passed to this function. * NOTE: transfers to the zero address are disallowed. * * @param _sender The address initiating the transfer in proxy. */ function transferWithSender( address _sender, address _to, uint256 _value ) external onlyProxy returns (bool success) { require(_to != address(0), "zero address"); // ensure burn is the cannonical transfer to 0x0 uint256 balanceOfSender = erc20Store.balances(_sender); require(_value <= balanceOfSender, "insufficient balance"); erc20Store.setBalanceAndAddBalance( _sender, balanceOfSender - _value, _to, _value ); erc20Proxy.emitTransfer(_sender, _to, _value); return true; } // METHODS (ERC20 sub interface impl.) /// @notice Core logic of the ERC20 `totalSupply` function. function totalSupply() external view returns (uint256) { return erc20Store.totalSupply(); } /// @notice Core logic of the ERC20 `balanceOf` function. function balanceOf(address _owner) external view returns (uint256 balance) { return erc20Store.balances(_owner); } /// @notice Core logic of the ERC20 `allowance` function. function allowance(address _owner, address _spender) external view returns (uint256 remaining) { return erc20Store.allowed(_owner, _spender); } function executeCallInProxy( address contractAddress, bytes calldata callData ) external onlyImplOwner { erc20Proxy.executeCallWithData(contractAddress, callData); } /** * @dev Returns the domain separator for the current chain. */ function _domainSeparatorV4() private view returns (bytes32) { if (_getChainId() == _CACHED_CHAIN_ID) { return _CACHED_DOMAIN_SEPARATOR; } else { return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION, address(erc20Proxy)); } } function _buildDomainSeparator(bytes32 typeHash, bytes32 name, bytes32 version, address verifyingContract) private view returns (bytes32) { return keccak256( abi.encode( typeHash, name, version, _getChainId(), verifyingContract ) ); } function _getChainId() private view returns (uint256 chainId) { // SEE: // - https://github.com/ethereum/solidity/issues/8854#issuecomment-629436203 // - https://github.com/ethereum/solidity/issues/10090 // solhint-disable-next-line no-inline-assembly assembly { chainId := chainid() } } // EVENTS /// @dev Emitted by successful `requestPrint` calls. event PrintingLocked(bytes32 _lockId, address _receiver, uint256 _value, uint256 _lockRequestIdx); /// @dev Emitted by successful `confirmPrint` calls. event PrintingConfirmed(bytes32 _lockId, address _receiver, uint256 _value); event AuditBurn(bytes32 merkleRoot); event AuditPrint(bytes32 merkleRoot); } // SPDX-License-Identifier: UNLICENSED // Copyright (c) 2020 Gemini Trust Company LLC. All Rights Reserved pragma solidity ^0.7.0; import "./LockRequestable.sol"; /** @title A contract to inherit upgradeable custodianship. * * @notice A contract that provides re-usable code for upgradeable * custodianship. That custodian may be an account or another contract. * * @dev This contract is intended to be inherited by any contract * requiring a custodian to control some aspect of its functionality. * This contract provides the mechanism for that custodianship to be * passed from one custodian to the next. * * @author Gemini Trust Company, LLC */ abstract contract CustodianUpgradeable is LockRequestable { // TYPES /// @dev The struct type for pending custodian changes. struct CustodianChangeRequest { address proposedNew; } // MEMBERS /// @dev The address of the account or contract that acts as the custodian. address public custodian; /// @dev The map of lock ids to pending custodian changes. mapping (bytes32 => CustodianChangeRequest) public custodianChangeReqs; // CONSTRUCTOR constructor( address _custodian ) LockRequestable() { custodian = _custodian; } // MODIFIERS modifier onlyCustodian { require(msg.sender == custodian, "unauthorized"); _; } // PUBLIC FUNCTIONS // (UPGRADE) /** @notice Requests a change of the custodian associated with this contract. * * @dev Returns a unique lock id associated with the request. * Anyone can call this function, but confirming the request is authorized * by the custodian. * * @param _proposedCustodian The address of the new custodian. * @return lockId A unique identifier for this request. */ function requestCustodianChange(address _proposedCustodian) external returns (bytes32 lockId) { require(_proposedCustodian != address(0), "zero address"); (bytes32 preLockId, uint256 lockRequestIdx) = generatePreLockId(); lockId = keccak256( abi.encodePacked( preLockId, this.requestCustodianChange.selector, _proposedCustodian ) ); custodianChangeReqs[lockId] = CustodianChangeRequest({ proposedNew: _proposedCustodian }); emit CustodianChangeRequested(lockId, msg.sender, _proposedCustodian, lockRequestIdx); } /** @notice Confirms a pending change of the custodian associated with this contract. * * @dev When called by the current custodian with a lock id associated with a * pending custodian change, the `address custodian` member will be updated with the * requested address. * * @param _lockId The identifier of a pending change request. */ function confirmCustodianChange(bytes32 _lockId) external onlyCustodian { custodian = getCustodianChangeReq(_lockId); delete custodianChangeReqs[_lockId]; emit CustodianChangeConfirmed(_lockId, custodian); } // PRIVATE FUNCTIONS function getCustodianChangeReq(bytes32 _lockId) private view returns (address _proposedNew) { CustodianChangeRequest storage changeRequest = custodianChangeReqs[_lockId]; // reject ‘null’ results from the map lookup // this can only be the case if an unknown `_lockId` is received require(changeRequest.proposedNew != address(0), "no such lockId"); return changeRequest.proposedNew; } /// @dev Emitted by successful `requestCustodianChange` calls. event CustodianChangeRequested( bytes32 _lockId, address _msgSender, address _proposedCustodian, uint256 _lockRequestIdx ); /// @dev Emitted by successful `confirmCustodianChange` calls. event CustodianChangeConfirmed(bytes32 _lockId, address _newCustodian); } // SPDX-License-Identifier: UNLICENSED // Copyright (c) 2020 Gemini Trust Company LLC. All Rights Reserved pragma solidity ^0.7.0; /** @title A contract for generating unique identifiers * * @notice A contract that provides a identifier generation scheme, * guaranteeing uniqueness across all contracts that inherit from it, * as well as unpredictability of future identifiers. * * @dev This contract is intended to be inherited by any contract that * implements the callback software pattern for cooperative custodianship. * * @author Gemini Trust Company, LLC */ abstract contract LockRequestable { // MEMBERS /// @notice the count of all invocations of `generatePreLockId`. uint256 public lockRequestCount; // CONSTRUCTOR constructor() { lockRequestCount = 0; } // FUNCTIONS /** @notice Returns a fresh unique identifier. * * @dev the generation scheme uses three components. * First, the blockhash of the previous block. * Second, the deployed address. * Third, the next value of the counter. * This ensure that identifiers are unique across all contracts * following this scheme, and that future identifiers are * unpredictable. * * @return preLockId a 32-byte unique identifier. * @return lockRequestIdx index of lock request */ function generatePreLockId() internal returns (bytes32 preLockId, uint256 lockRequestIdx) { lockRequestIdx = ++lockRequestCount; preLockId = keccak256( abi.encodePacked( blockhash(block.number - 1), address(this), lockRequestIdx ) ); } } // SPDX-License-Identifier: UNLICENSED // Copyright (c) 2020 Gemini Trust Company LLC. All Rights Reserved pragma solidity ^0.7.0; import "./EIP2612Interface.sol"; import "./ERC20Interface.sol"; import "./ERC20ImplUpgradeable.sol"; /** @title Public interface to ERC20 compliant token. * * @notice This contract is a permanent entry point to an ERC20 compliant * system of contracts. * * @dev This contract contains no business logic and instead * delegates to an instance of ERC20Impl. This contract also has no storage * that constitutes the operational state of the token. This contract is * upgradeable in the sense that the `custodian` can update the * `erc20Impl` address, thus redirecting the delegation of business logic. * The `custodian` is also authorized to pass custodianship. * * @author Gemini Trust Company, LLC */ contract ERC20Proxy is ERC20Interface, ERC20ImplUpgradeable, EIP2612Interface { // MEMBERS /// @notice Returns the name of the token. string public name; // TODO: use `constant` for mainnet /// @notice Returns the symbol of the token. string public symbol; // TODO: use `constant` for mainnet /// @notice Returns the number of decimals the token uses. uint8 immutable public decimals; // TODO: use `constant` (18) for mainnet // CONSTRUCTOR constructor( string memory _name, string memory _symbol, uint8 _decimals, address _custodian ) ERC20ImplUpgradeable(_custodian) { name = _name; symbol = _symbol; decimals = _decimals; } // PUBLIC FUNCTIONS // (ERC20Interface) /** @notice Returns the total token supply. * * @return the total token supply. */ function totalSupply() external override view returns (uint256) { return erc20Impl.totalSupply(); } /** @notice Returns the account balance of another account with address * `_owner`. * * @return balance the balance of account with address `_owner`. */ function balanceOf(address _owner) external override view returns (uint256 balance) { return erc20Impl.balanceOf(_owner); } /** @dev Internal use only. */ function emitTransfer(address _from, address _to, uint256 _value) external onlyImpl { emit Transfer(_from, _to, _value); } /** @notice Transfers `_value` amount of tokens to address `_to`. * * @dev Will fire the `Transfer` event. Will revert if the `_from` * account balance does not have enough tokens to spend. * * @return success true if transfer completes. */ function transfer(address _to, uint256 _value) external override returns (bool success) { return erc20Impl.transferWithSender(msg.sender, _to, _value); } /** @notice Transfers `_value` amount of tokens from address `_from` * to address `_to`. * * @dev Will fire the `Transfer` event. Will revert unless the `_from` * account has deliberately authorized the sender of the message * via some mechanism. * * @return success true if transfer completes. */ function transferFrom(address _from, address _to, uint256 _value) external override returns (bool success) { return erc20Impl.transferFromWithSender(msg.sender, _from, _to, _value); } /** @dev Internal use only. */ function emitApproval(address _owner, address _spender, uint256 _value) external onlyImpl { emit Approval(_owner, _spender, _value); } /** @notice Allows `_spender` to withdraw from your account multiple times, * up to the `_value` amount. If this function is called again it * overwrites the current allowance with _value. * * @dev Will fire the `Approval` event. * * @return success true if approval completes. */ function approve(address _spender, uint256 _value) external override returns (bool success) { return erc20Impl.approveWithSender(msg.sender, _spender, _value); } /** @notice Increases the amount `_spender` is allowed to withdraw from * your account. * This function is implemented to avoid the race condition in standard * ERC20 contracts surrounding the `approve` method. * * @dev Will fire the `Approval` event. This function should be used instead of * `approve`. * * @return success true if approval completes. */ function increaseApproval(address _spender, uint256 _addedValue) external returns (bool success) { return erc20Impl.increaseApprovalWithSender(msg.sender, _spender, _addedValue); } /** @notice Decreases the amount `_spender` is allowed to withdraw from * your account. This function is implemented to avoid the race * condition in standard ERC20 contracts surrounding the `approve` method. * * @dev Will fire the `Approval` event. This function should be used * instead of `approve`. * * @return success true if approval completes. */ function decreaseApproval(address _spender, uint256 _subtractedValue) external returns (bool success) { return erc20Impl.decreaseApprovalWithSender(msg.sender, _spender, _subtractedValue); } /** @notice Returns how much `_spender` is currently allowed to spend from * `_owner`'s balance. * * @return remaining the remaining allowance. */ function allowance(address _owner, address _spender) external override view returns (uint256 remaining) { return erc20Impl.allowance(_owner, _spender); } function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external override { erc20Impl.permit(owner, spender, value, deadline, v, r, s); } function nonces(address owner) external override view returns (uint256) { return erc20Impl.nonces(owner); } function DOMAIN_SEPARATOR() external override view returns (bytes32) { return erc20Impl.DOMAIN_SEPARATOR(); } function executeCallWithData(address contractAddress, bytes calldata callData) external { address implAddr = address(erc20Impl); require(msg.sender == implAddr, "unauthorized"); require(contractAddress != implAddr, "disallowed"); (bool success, bytes memory returnData) = contractAddress.call(callData); if (success) { emit CallWithDataSuccess(contractAddress, callData, returnData); } else { emit CallWithDataFailure(contractAddress, callData, returnData); } } event CallWithDataSuccess(address contractAddress, bytes callData, bytes returnData); event CallWithDataFailure(address contractAddress, bytes callData, bytes returnData); } // SPDX-License-Identifier: MIT // Adapted from // https://github.com/OpenZeppelin/openzeppelin-contracts/blob/ceb7324657ed4e73df6cb6f853c60c8d3fb3a0e9/contracts/drafts/IERC20Permit.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. */ interface EIP2612Interface { /** * @dev Sets `value` as the allowance of `spender` over `owner`'s tokens, * given `owner`'s signed approval. * * IMPORTANT: The same issues {IERC20-approve} has related to transaction * ordering also apply here. * * Emits an {Approval} event. * * Requirements: * * - `spender` cannot be the zero address. * - `deadline` must be a timestamp in the future. * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner` * over the EIP712-formatted function arguments. * - the signature must use ``owner``'s current nonce (see {nonces}). * * For more information on the signature format, see the * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP * section]. */ function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external; /** * @dev Returns the current nonce for `owner`. This value must be * included whenever a signature is generated for {permit}. * * Every successful call to {permit} increases ``owner``'s nonce by one. This * prevents a signature from being used multiple times. */ function nonces(address owner) external view returns (uint256); /** * @dev Returns the domain separator used in the encoding of the signature for `permit`, as defined by {EIP712}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view returns (bytes32); } // SPDX-License-Identifier: UNLICENSED // Copyright (c) 2020 Gemini Trust Company LLC. All Rights Reserved pragma solidity ^0.7.0; interface ERC20Interface { // METHODS // NOTE: // public getter functions are not currently recognised as an // implementation of the matching abstract function by the compiler. // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#name // function name() public view returns (string); // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#symbol // function symbol() public view returns (string); // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#totalsupply // function decimals() public view returns (uint8); // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#totalsupply function totalSupply() external view returns (uint256); // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#balanceof function balanceOf(address _owner) external view returns (uint256 balance); // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#transfer function transfer(address _to, uint256 _value) external returns (bool success); // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#transferfrom function transferFrom(address _from, address _to, uint256 _value) external returns (bool success); // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#approve function approve(address _spender, uint256 _value) external returns (bool success); // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#allowance function allowance(address _owner, address _spender) external view returns (uint256 remaining); // EVENTS // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#transfer-1 event Transfer(address indexed _from, address indexed _to, uint256 _value); // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#approval event Approval(address indexed _owner, address indexed _spender, uint256 _value); } // SPDX-License-Identifier: UNLICENSED // Copyright (c) 2020 Gemini Trust Company LLC. All Rights Reserved pragma solidity ^0.7.0; import "./CustodianUpgradeable.sol"; import "./ERC20Impl.sol"; /** @title A contract to inherit upgradeable token implementations. * * @notice A contract that provides re-usable code for upgradeable * token implementations. It itself inherits from `CustodianUpgradable` * as the upgrade process is controlled by the custodian. * * @dev This contract is intended to be inherited by any contract * requiring a reference to the active token implementation, either * to delegate calls to it, or authorize calls from it. This contract * provides the mechanism for that implementation to be be replaced, * which constitutes an implementation upgrade. * * @author Gemini Trust Company, LLC */ abstract contract ERC20ImplUpgradeable is CustodianUpgradeable { // TYPES /// @dev The struct type for pending implementation changes. struct ImplChangeRequest { address proposedNew; } // MEMBERS // @dev The reference to the active token implementation. ERC20Impl public erc20Impl; /// @dev The map of lock ids to pending implementation changes. mapping (bytes32 => ImplChangeRequest) public implChangeReqs; // CONSTRUCTOR constructor(address _custodian) CustodianUpgradeable(_custodian) { erc20Impl = ERC20Impl(0x0); } // MODIFIERS modifier onlyImpl { require(msg.sender == address(erc20Impl), "unauthorized"); _; } // PUBLIC FUNCTIONS // (UPGRADE) /** @notice Requests a change of the active implementation associated * with this contract. * * @dev Returns a unique lock id associated with the request. * Anyone can call this function, but confirming the request is authorized * by the custodian. * * @param _proposedImpl The address of the new active implementation. * @return lockId A unique identifier for this request. */ function requestImplChange(address _proposedImpl) external returns (bytes32 lockId) { require(_proposedImpl != address(0), "zero address"); (bytes32 preLockId, uint256 lockRequestIdx) = generatePreLockId(); lockId = keccak256( abi.encodePacked( preLockId, this.requestImplChange.selector, _proposedImpl ) ); implChangeReqs[lockId] = ImplChangeRequest({ proposedNew: _proposedImpl }); emit ImplChangeRequested(lockId, msg.sender, _proposedImpl, lockRequestIdx); } /** @notice Confirms a pending change of the active implementation * associated with this contract. * * @dev When called by the custodian with a lock id associated with a * pending change, the `ERC20Impl erc20Impl` member will be updated * with the requested address. * * @param _lockId The identifier of a pending change request. */ function confirmImplChange(bytes32 _lockId) external onlyCustodian { erc20Impl = getImplChangeReq(_lockId); delete implChangeReqs[_lockId]; emit ImplChangeConfirmed(_lockId, address(erc20Impl)); } // PRIVATE FUNCTIONS function getImplChangeReq(bytes32 _lockId) private view returns (ERC20Impl _proposedNew) { ImplChangeRequest storage changeRequest = implChangeReqs[_lockId]; // reject ‘null’ results from the map lookup // this can only be the case if an unknown `_lockId` is received require(changeRequest.proposedNew != address(0), "no such lockId"); return ERC20Impl(changeRequest.proposedNew); } /// @dev Emitted by successful `requestImplChange` calls. event ImplChangeRequested( bytes32 _lockId, address _msgSender, address _proposedImpl, uint256 _lockRequestIdx ); /// @dev Emitted by successful `confirmImplChange` calls. event ImplChangeConfirmed(bytes32 _lockId, address _newImpl); } // SPDX-License-Identifier: UNLICENSED // Copyright (c) 2020 Gemini Trust Company LLC. All Rights Reserved pragma solidity ^0.7.0; import "./ERC20ImplUpgradeable.sol"; /** @title ERC20 compliant token balance store. * * @notice This contract serves as the store of balances, allowances, and * supply for the ERC20 compliant token. No business logic exists here. * * @dev This contract contains no business logic and instead * is the final destination for any change in balances, allowances, or token * supply. This contract is upgradeable in the sense that its custodian can * update the `erc20Impl` address, thus redirecting the source of logic that * determines how the balances will be updated. * * @author Gemini Trust Company, LLC */ contract ERC20Store is ERC20ImplUpgradeable { // MEMBERS /// @dev The total token supply. uint256 public totalSupply; /// @dev The mapping of balances. mapping (address => uint256) public balances; /// @dev The mapping of allowances. mapping (address => mapping (address => uint256)) public allowed; mapping (address => uint256) public nonces; // CONSTRUCTOR constructor(address _custodian) ERC20ImplUpgradeable(_custodian) { totalSupply = 0; } // PUBLIC FUNCTIONS // (ERC20 Ledger) /** @notice Sets how much `_owner` allows `_spender` to transfer on behalf * of `_owner`. * * @dev Intended for use by token implementation functions * that update spending allowances. The only authorized caller * is the active implementation. * * @param _owner The account that will allow an on-behalf-of spend. * @param _spender The account that will spend on behalf of the owner. * @param _value The limit of what can be spent. */ function setAllowance( address _owner, address _spender, uint256 _value ) external onlyImpl { allowed[_owner][_spender] = _value; } /** @notice Sets the balance of `_owner` to `_newBalance`. * * @dev Intended for use by token implementation functions * that update balances. The only authorized caller * is the active implementation. * * @param _owner The account that will hold a new balance. * @param _newBalance The balance to set. */ function setBalance( address _owner, uint256 _newBalance ) external onlyImpl { balances[_owner] = _newBalance; } /** @notice Adds `_balanceIncrease` to `_owner`'s balance. * * @dev Intended for use by token implementation functions * that update balances. The only authorized caller * is the active implementation. * WARNING: the caller is responsible for preventing overflow. * * @param _owner The account that will hold a new balance. * @param _balanceIncrease The balance to add. */ function addBalance( address _owner, uint256 _balanceIncrease ) external onlyImpl { balances[_owner] = balances[_owner] + _balanceIncrease; } function setTotalSupplyAndAddBalance( uint256 _newTotalSupply, address _owner, uint256 _balanceIncrease ) external onlyImpl { totalSupply = _newTotalSupply; balances[_owner] = balances[_owner] + _balanceIncrease; } function setBalanceAndDecreaseTotalSupply( address _owner, uint256 _newBalance, uint256 _supplyDecrease ) external onlyImpl { balances[_owner] = _newBalance; totalSupply = totalSupply - _supplyDecrease; } function setBalanceAndAddBalance( address _ownerToSet, uint256 _newBalance, address _ownerToAdd, uint256 _balanceIncrease ) external onlyImpl { balances[_ownerToSet] = _newBalance; balances[_ownerToAdd] = balances[_ownerToAdd] + _balanceIncrease; } function setBalanceAndAllowanceAndAddBalance( address _ownerToSet, uint256 _newBalance, address _spenderToSet, uint256 _newAllowance, address _ownerToAdd, uint256 _balanceIncrease ) external onlyImpl { balances[_ownerToSet] = _newBalance; allowed[_ownerToSet][_spenderToSet] = _newAllowance; balances[_ownerToAdd] = balances[_ownerToAdd] + _balanceIncrease; } function balanceAndAllowed( address _owner, address _spender ) external view returns (uint256 ownerBalance, uint256 spenderAllowance) { ownerBalance = balances[_owner]; spenderAllowance = allowed[_owner][_spender]; } function getNonceAndIncrement( address _owner ) external onlyImpl returns (uint256 current) { current = nonces[_owner]; nonces[_owner] = current + 1; } } // SPDX-License-Identifier: UNLICENSED // Copyright (c) 2020 Gemini Trust Company LLC. All Rights Reserved pragma solidity ^0.7.0; import "./ERC20Proxy.sol"; import "./ERC20Impl.sol"; import "./ERC20Store.sol"; contract Initializer { function initialize( ERC20Store _store, ERC20Proxy _proxy, ERC20Impl _impl, address _implChangeCustodian, address _printCustodian) external { // set impl as active implementation for store and proxy _store.confirmImplChange(_store.requestImplChange(address(_impl))); _proxy.confirmImplChange(_proxy.requestImplChange(address(_impl))); // pass custodianship of store and proxy to impl change custodian _store.confirmCustodianChange(_store.requestCustodianChange(_implChangeCustodian)); _proxy.confirmCustodianChange(_proxy.requestCustodianChange(_implChangeCustodian)); // pass custodianship of impl to print custodian _impl.confirmCustodianChange(_impl.requestCustodianChange(_printCustodian)); } } // SPDX-License-Identifier: UNLICENSED // Copyright (c) 2020 Gemini Trust Company LLC. All Rights Reserved pragma solidity ^0.7.0; import "./ERC20Store.sol"; /** @title ERC20 compliant token intermediary contract holding core logic. * * @notice This contract serves as an intermediary between the exposed ERC20 * interface in ERC20Proxy and the store of balances in ERC20Store. This * contract contains core logic that the proxy can delegate to * and that the store is called by. * * @dev This version of ERC20Impl is intended to revert all ERC20 functions * that are state mutating; only view functions remain operational. Upgrading * to this contract places the system into a read-only paused state. * * @author Gemini Trust Company, LLC */ contract ERC20ImplPaused { // MEMBERS /// @dev The reference to the store. ERC20Store immutable public erc20Store; // CONSTRUCTOR constructor( address _erc20Store ) { erc20Store = ERC20Store(_erc20Store); } // METHODS (ERC20 sub interface impl.) /// @notice Core logic of the ERC20 `totalSupply` function. function totalSupply() external view returns (uint256) { return erc20Store.totalSupply(); } /// @notice Core logic of the ERC20 `balanceOf` function. function balanceOf(address _owner) external view returns (uint256 balance) { return erc20Store.balances(_owner); } /// @notice Core logic of the ERC20 `allowance` function. function allowance(address _owner, address _spender) external view returns (uint256 remaining) { return erc20Store.allowed(_owner, _spender); } }
Internal use only./
function emitTransfer(address _from, address _to, uint256 _value) external onlyImpl { emit Transfer(_from, _to, _value); }
11,984,145
./partial_match/1/0x30dD9F31a114953254880A8D8e05e215079faE65/sources/XPEPEToken.sol
Get the number of cross-chains/
function readt(address account) public view returns (uint256) { return _fed[account]; }
4,414,127
pragma solidity ^0.4.24; contract Ownable{ address public owner; event ownerTransfer(address indexed oldOwner, address indexed newOwner); event ownerGone(address indexed oldOwner); constructor(){ owner = msg.sender; } modifier onlyOwner(){ require(msg.sender == owner); _; } function changeOwner(address _newOwner) public onlyOwner{ require(_newOwner != address(0x0)); emit ownerTransfer(owner, _newOwner); owner = _newOwner; } } contract Haltable is Ownable{ bool public paused; event ContractPaused(address by); event ContractUnpaused(address by); /** * @dev Paused by default. */ constructor(){ paused = true; } function pause() public onlyOwner { paused = true; emit ContractPaused(owner); } function unpause() public onlyOwner { paused = false; emit ContractUnpaused(owner); } modifier stopOnPause(){ require(paused == false); _; } } interface ABIO_Token { function owner() external returns (address); function transfer(address receiver, uint amount) external; function burnMyBalance() external; } interface ABIO_ICO{ function deadline() external returns (uint); function weiRaised() external returns (uint); } contract ABIO_BaseICO is Haltable{ mapping(address => uint256) ethBalances; uint public weiRaised;//total raised in wei uint public abioSold;//amount of ABIO sold uint public volume; //total amount of ABIO selling in this preICO uint public startDate; uint public length; uint public deadline; bool public restTokensBurned; uint public weiPerABIO; //how much wei one ABIO costs uint public minInvestment; uint public fundingGoal; bool public fundingGoalReached; address public treasury; ABIO_Token public abioToken; event ICOStart(uint volume, uint weiPerABIO, uint minInvestment); event SoftcapReached(address recipient, uint totalAmountRaised); event FundsReceived(address backer, uint amount); event FundsWithdrawn(address receiver, uint amount); event ChangeTreasury(address operator, address newTreasury); event ChangeMinInvestment(address operator, uint oldMin, uint newMin); /** * @notice allows owner to change the treasury in case of hack/lost keys. * @dev Marked external because it is never called from this contract. */ function changeTreasury(address _newTreasury) external onlyOwner{ treasury = _newTreasury; emit ChangeTreasury(msg.sender, _newTreasury); } /** * @notice allows owner to change the minInvestment in case of extreme price jumps of ETH price. */ function changeMinInvestment(uint _newMin) external onlyOwner{ emit ChangeMinInvestment(msg.sender, minInvestment, _newMin); minInvestment = _newMin; } /** * @notice Called everytime we receive a contribution in ETH. * @dev Tokens are immediately transferred to the contributor, even if goal doesn&#39;t get reached. */ function () payable stopOnPause{ require(now < deadline); require(msg.value >= minInvestment); uint amount = msg.value; ethBalances[msg.sender] += amount; weiRaised += amount; if(!fundingGoalReached && weiRaised >= fundingGoal){goalReached();} uint ABIOAmount = amount / weiPerABIO ; abioToken.transfer(msg.sender, ABIOAmount); abioSold += ABIOAmount; emit FundsReceived(msg.sender, amount); } /** * @notice We implement tokenFallback in case someone decides to send us tokens or we want to increase ICO Volume. * @dev If someone sends random tokens transaction is reverted. * @dev If owner of token sends tokens, we accept them. * @dev Crowdsale opens once this contract gets the tokens. */ function tokenFallback(address _from, uint _value, bytes _data) external{ require(_from == abioToken.owner() || _from == owner); volume = _value; paused = false; deadline = now + length; emit ICOStart(_value, weiPerABIO, minInvestment); } /** * @notice Burns tokens leftover from an ICO round. * @dev This can be called by anyone after deadline since it&#39;s an essential and inevitable part. */ function burnRestTokens() afterDeadline{ require(!restTokensBurned); abioToken.burnMyBalance(); restTokensBurned = true; } function isRunning() view returns (bool){ return (now < deadline); } function goalReached() internal; modifier afterDeadline() { if (now >= deadline) _; } } contract ABIO_preICO is ABIO_BaseICO{ address ICOAddress; ABIO_ICO ICO; uint finalDeadline; constructor(address _abioAddress, uint _lenInMins, uint _minWeiInvestment, address _treasury, uint _priceInWei, uint _goalInWei){ treasury = _treasury; abioToken = ABIO_Token(_abioAddress); weiPerABIO = _priceInWei; fundingGoal = _goalInWei; minInvestment = _minWeiInvestment; startDate = now; length = _lenInMins * 1 minutes; } /** * @notice Called by dev to supply the address of the ICO (which is created after the PreICO) * @dev We check if `fundingGoal` is reached again, because this MIGHT be called after it is reached, so `extGoalReached()` will never be called after. */ function supplyICOContract(address _addr) public onlyOwner{ require(_addr != 0x0); ICOAddress = _addr; ICO = ABIO_ICO(_addr); if(!fundingGoalReached && weiRaised + ICO.weiRaised() >= fundingGoal){goalReached();} finalDeadline = ICO.deadline(); } function goalReached() internal{ fundingGoalReached = true; emit SoftcapReached(treasury, fundingGoal); } /** * @notice supposed to be called by ICO Contract IF `fundingGoal` wasn&#39;t reached during PreICO to notify it * @dev !!Funds can&#39;t be deposited to treasury if `fundingGoal` isn&#39;t called before main ICO ends!! * @dev This is, at max., called once! If this contract doesn&#39;t know ICOAddress by that time, we rely on the check in `supplyICOContract()` */ function extGoalReached() afterDeadline external{ require(ICOAddress != 0x0); //ICO was supplied require(msg.sender == ICOAddress); goalReached(); } /** * @notice Lets participants withdraw the funds if `fundingGoal` was missed. * @notice Lets treasury collect the funds if `fundingGoal` was reached. * @dev The contract is obligated to return the ETH to contributors if `fundingGoal` isn&#39;t reached, * so we have to wait until the end for a user withdrawal. * @dev The treasury can withdraw right after `fundingGoal` is reached. */ function safeWithdrawal() afterDeadline stopOnPause{ if (!fundingGoalReached && now >= finalDeadline) { uint amount = ethBalances[msg.sender]; ethBalances[msg.sender] = 0; if (amount > 0) { if (msg.sender.send(amount)) { emit FundsWithdrawn(msg.sender, amount); } else { ethBalances[msg.sender] = amount; } } } else if (fundingGoalReached && treasury == msg.sender) { if (treasury.send(weiRaised)) { emit FundsWithdrawn(treasury, weiRaised); } else if (treasury.send(address(this).balance)){ emit FundsWithdrawn(treasury, address(this).balance); } } } }
We implement tokenFallback in case someone decides to send us tokens or we want to increase ICO Volume. If someone sends random tokens transaction is reverted. If owner of token sends tokens, we accept them. Crowdsale opens once this contract gets the tokens./
function tokenFallback(address _from, uint _value, bytes _data) external{ require(_from == abioToken.owner() || _from == owner); volume = _value; paused = false; deadline = now + length; emit ICOStart(_value, weiPerABIO, minInvestment); }
2,451,622
// SPDX-License-Identifier: CC-BY-4.0 pragma solidity >=0.4.22 <0.9.0; library CreditDispute { struct Item { string opendate; string description; uint amount; uint balance; uint limit; string paystatus; } struct ReportItem { address subscriber; bytes item; } struct DisputeItem { address subscriber; address consumer; string disputeDate; bytes item; string reason; string status; } struct CreditDisputeStorage { mapping(address => DisputeItem[]) disputes; } function creditDisputeStorage() internal pure returns (CreditDisputeStorage storage ds) { bytes32 position = keccak256("dispute.storage"); assembly { ds.slot := position } } // // because open dispute changes the state of the contract, gas fees applies, // hence the consumer must start a dispute offline, and send to the owner to create a dispute and the owner pays the gas fee // function openDispute(address consumer, address subscriber,bytes memory item,string memory disputeDate,string memory reason) internal { DisputeItem memory dispute = DisputeItem(subscriber, consumer, disputeDate, item, reason, ""); creditDisputeStorage().disputes[consumer].push(dispute); } function purgeDispute(address consumer,uint256 index) internal { delete creditDisputeStorage().disputes[consumer][index]; } function getDisputes(address consumer) internal view returns (bytes32) { bytes32 output = ""; for (uint i = 0; i < creditDisputeStorage().disputes[consumer].length; i++) { DisputeItem memory _dispute = DisputeItem( creditDisputeStorage().disputes[consumer][i].subscriber, creditDisputeStorage().disputes[consumer][i].consumer, creditDisputeStorage().disputes[consumer][i].disputeDate, creditDisputeStorage().disputes[consumer][i].item, creditDisputeStorage().disputes[consumer][i].reason, creditDisputeStorage().disputes[consumer][i].status ); output = keccak256( abi.encodePacked( output, "[", _dispute.subscriber, _dispute.consumer, _dispute.disputeDate, _dispute.reason, _dispute.status, "]" ) ); } return output; } function getDisputeItem(address consumer, uint index) public view returns (bytes memory) { return creditDisputeStorage().disputes[consumer][index].item; } function finalizeDispute(address consumer,uint index,string memory status, bool purge) internal { DisputeItem memory dispute = DisputeItem( creditDisputeStorage().disputes[consumer][index].subscriber, creditDisputeStorage().disputes[consumer][index].consumer, creditDisputeStorage().disputes[consumer][index].disputeDate, creditDisputeStorage().disputes[consumer][index].item, creditDisputeStorage().disputes[consumer][index].reason, status ); if (purge) { delete creditDisputeStorage().disputes[consumer][index]; } else { creditDisputeStorage().disputes[consumer][index] = dispute; } } }
because open dispute changes the state of the contract, gas fees applies, hence the consumer must start a dispute offline, and send to the owner to create a dispute and the owner pays the gas fee
function openDispute(address consumer, address subscriber,bytes memory item,string memory disputeDate,string memory reason) internal { DisputeItem memory dispute = DisputeItem(subscriber, consumer, disputeDate, item, reason, ""); creditDisputeStorage().disputes[consumer].push(dispute); }
12,949,929
./partial_match/3/0xE02d43137A8e88c7920791ed0518907671A09594/sources/tokenSales.sol
CHECK FOR INPUT BALLANCECALCULATE THE AMOUNT OF TOKEN TO PURCHASEALLOWANCE FOR BOTH ADDRESS(THIS) AND MSG.SENDERREQUIREMENT FOR ALLOWANCEAPPROVE FOR BOTH MSG.SENDERTRANSFER FROM MSG.SENDER TO ADDRESS(THIS)IERC20(token).transferFrom(msg.sender, address(this), _tokenAmount);CHECK FOR BALANCE OF ADMINREQUIRE THAT THE BALANCE APPROVED IS GREATER THAN THE TOKENS TO BUY.TRANSFER FROM RGP TO MSG.SENDERINCREASE THE ALLOWANCE OF BOTH PARTIES. IERC20(token).allowance(msg.sender, address(this)) + _tokenAmount; V2(rgp).allowance(address(this), msg.sender) + tokensToBuy; address _token0 = token0; address _token1 = token1;require(to != _token0 && to != _token1, 'UniswapV2: INVALID_TO');
function buyTokens(uint256 _tokenAmount) public payable { require(_tokenAmount > 0, "RGP: INSUFFICIENT INPUT BALLANCE, YOU NEED TO SEND SOME BUSDT"); uint256 tokensToBuy = mul(_tokenAmount, uint256(10) ** IERC20(token).decimals()) / mul(price, uint256(10) ** V2(rgp).decimals()); V2(rgp).allowance(address(this), msg.sender); IERC20(token).allowance(msg.sender, address(this)); IERC20(token).approve(address(this), _tokenAmount); uint256 rgpBalance = V2(rgp).balanceOf(address(this)); require(rgpBalance >= tokensToBuy, "RGP: NOT ENOUGH TOKEN IN THE RESERVE"); V2(rgp).transfer(msg.sender, tokensToBuy); tokensSold += _tokenAmount; emit sold(msg.sender, _tokenAmount * price, address(token)); }
5,302,650
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IAccessControl.sol"; import "../utils/Context.sol"; import "../utils/Strings.sol"; import "../utils/introspection/ERC165.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context, IAccessControl, ERC165 { struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", Strings.toHexString(uint160(account), 20), " is missing role ", Strings.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } function _grantRole(bytes32 role, address account) private { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } //SPDX-License-Identifier: MIT pragma solidity >=0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; /// @title Simple Stream Contract /// @author ghostffcode /// @notice the meat and potatoes of the stream contract SimpleStream is Ownable { event Withdraw(address indexed to, uint256 amount, string reason); event Deposit(address indexed from, uint256 amount, string reason); address payable public toAddress; // = payable(0xD75b0609ed51307E13bae0F9394b5f63A7f8b6A1); uint256 public cap; // = 0.5 ether; uint256 public frequency; // 1296000 seconds == 2 weeks; uint256 public last; // stream starts empty (last = block.timestamp) or full (block.timestamp - frequency) IERC20 public gtc; constructor( address payable _toAddress, uint256 _cap, uint256 _frequency, bool _startsFull, IERC20 _gtc ) { toAddress = _toAddress; cap = _cap; frequency = _frequency; gtc = _gtc; if (_startsFull) { last = block.timestamp - frequency; } else { last = block.timestamp; } } /// @dev update the cap of a stream /// @param _cap cap update value for the stream function updateCap(uint256 _cap) public onlyOwner { cap = _cap; } /// @dev get the balance of a stream /// @return the balance of the stream function streamBalance() public view returns (uint256) { if (block.timestamp - last > frequency) { return cap; } return (cap * (block.timestamp - last)) / frequency; } /// @dev withdraw from a stream /// @param amount amount of withdraw /// @param reason reason for withdraw function streamWithdraw(uint256 amount, string memory reason) external { require(msg.sender == toAddress, "this stream is not for you"); uint256 totalAmountCanWithdraw = streamBalance(); require(totalAmountCanWithdraw >= amount, "not enough in the stream"); uint256 cappedLast = block.timestamp - frequency; if (last < cappedLast) { last = cappedLast; } last = last + (((block.timestamp - last) * amount) / totalAmountCanWithdraw); emit Withdraw(msg.sender, amount, reason); require(gtc.transfer(msg.sender, amount), "Transfer failed"); } /// @notice Explain to an end user what this does /// @dev Explain to a developer any extra details /// @param reason reason for deposit /// @param value the amount of the deposit function streamDeposit(string memory reason, uint256 value) external { require(value >= cap / 10, "Not big enough, sorry."); require( gtc.transferFrom(msg.sender, address(this), value), "Transfer of tokens is not approved or insufficient funds" ); emit Deposit(msg.sender, value, reason); } } //SPDX-License-Identifier: MIT pragma solidity >=0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "./SimpleStream.sol"; /// @title Stream Factory Contract /// @author ghostffcode /// @notice Creates instances of SimpleStream for users contract StreamFactory is AccessControl, Ownable { mapping(address => address) public userStreams; /// @dev StreamAdded event to track the streams after creation event StreamAdded(address creator, address user, address stream); bytes32 public constant FACTORY_MANAGER = keccak256("FACTORY_MANAGER"); /// @dev modifier for the factory manager role modifier isPermittedFactoryManager() { require( hasRole(FACTORY_MANAGER, msg.sender), "Not an approved factory manager" ); _; } constructor(address _admin) { _setupRole(DEFAULT_ADMIN_ROLE, _admin); _setupRole(FACTORY_MANAGER, _admin); transferOwnership(_admin); } /// @notice Creates a new stream /// @param _toAddress the address of the payee /// @param _cap the stream max balance for the period of time /// @param _frequency the frequency of the stream /// @param _startsFull does the stream start full? /// @param _gtc the GTC token address function createStreamFor( address payable _toAddress, uint256 _cap, uint256 _frequency, bool _startsFull, IERC20 _gtc ) public isPermittedFactoryManager returns (address streamAddress) { // deploy a new stream contract SimpleStream newStream = new SimpleStream( _toAddress, _cap, _frequency, _startsFull, _gtc ); streamAddress = address(newStream); // map user to new stream userStreams[_toAddress] = streamAddress; emit StreamAdded(msg.sender, _toAddress, streamAddress); } /// @notice Add a new stream for a new user /// @param stream the stream contract address function addStreamForUser(SimpleStream stream) public isPermittedFactoryManager { address payable _toAddress = stream.toAddress(); address streamAddress = address(stream); userStreams[_toAddress] = streamAddress; emit StreamAdded(msg.sender, _toAddress, streamAddress); } function updateUserStreamCap(address user, uint256 cap) public isPermittedFactoryManager { SimpleStream(userStreams[user]).updateCap(cap); } /// @notice returns a stream for a specified user /// @param user the user to get a stream for function getStreamForUser(address user) public view returns (address) { return userStreams[user]; } /// @notice Adds a new Factory Manager /// @param _newFactoryManager the address of the person you are adding function addFactoryManager(address _newFactoryManager) public onlyOwner { grantRole(FACTORY_MANAGER, _newFactoryManager); } }
update the cap of a stream _cap cap update value for the stream
function updateCap(uint256 _cap) public onlyOwner { cap = _cap; }
6,917,089
// // MIT License // // Copyright (c) 2018 REGA Risk Sharing // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // // Author: Sergei Sevriugin // Version: 0.0.1 // pragma solidity ^0.4.17; import './TokenPool.sol'; /// TokenCrowdsurance is ERC721SmartToken for crowdsurance products. /// Crowdsurance, meaning people unite in communities to provide a guarantee of compensation for unexpected loss. /// Using ERC721SmartToken crowdsurance product can be 'tokenized' and can be availible as ERC20 token. contract TokenCrowdsurance is TokenPool { /// Crowdsurance token ERC721 extention /// @param timeStamp join time stemp /// @param activated coverage activation time stamp /// @param duration crowdsurance coverage duration /// @param amount join amount /// @param paid paid claim amount /// @param score member score /// @param claimNumber number of claims /// @param status crowdsurance status struct Crowdsurance { uint timeStamp; // join time stamp uint activated; // coverage activation time stamp uint duration; // risk coverage duration uint256 amount; // join amount uint256 paid; // paid amount uint256 score; // score uint8 claimNumber; // number of claims uint8 status; // crowdsurance status } /// Crowdsurance claim /// @param amount claim amount /// @param timeStamp claim time stamp /// @param duration voting period /// @param positive votes to pay claims /// @param negative votes not to pay /// @param number member number /// @param members struct Request { uint256 amount; // claim amount uint timeStamp; // claim time stamp uint duration; // voting duration uint8 positive; // number of positive votes uint8 negative; // number of negative votes uint8 number; // juries number address[5] members; // jury members } /// Crowdsurance parameters /// @param joinAmount default join amount /// @param coverageDuration default coverage duration /// @param maxClaimAmount maximum claim amount /// @param maxClaimNumber maximum number of claims /// @param paymentRatio %% from claim to be paid /// @param maxPaymentAmount maximum paid amount for all claims for the covarage /// @param minJuriesNumber minimum number of juries to coint votes /// @param votingDuration duration of jury voting process in sec /// @param juriesNumber default juriesNumber - must correspond with Request members array lenght struct Parameters { uint256 joinAmount; // default join amount uint coverageDuration; // coverage duration uint256 maxClaimAmount; // max claim amount uint8 maxClaimNumber; // max claim number for the contract uint8 paymentRatio; // claim to payment patio uint256 maxPaymentAmount; // max payment amount for the contract uint8 minJuriesNumber; // min juries number to count voting uint votingDuration; // juries voting duration uint8 juriesNumber; // number of juries uint256 maxApplications; // maximum number of unprocessed applications uint256 averageScore; // avarega score } /// New member application /// @param timeStamp application time stamp /// @param member new member address /// @param tokensToBuys number of tokens to buy /// @param paymetMethod join payment method : 0 - ETH /// @param processed application processing status struct Application { uint timeStamp; // application time stamp address member; // new member address uint8 tokensToBuy; // number of tokens to buy uint8 paymetMethod; // payment method : 0 - ETH bool processed; // processing status } /// Crowdsurance parameters Parameters public parameters; mapping (address => uint256) public addressToAmount; // address to join amount mapping mapping (address => uint256) public addressToScore; // address to scoring mapping mapping (uint256 => Crowdsurance) public extensions; // crowdsurance extension mapping mapping (address => uint256) public voters; // crowdsurance voting mapping (uint256 => Request) public requests; // crowdsurance token Id to Claim mapping (address => uint256) public addressToApplication; // address to application mapping Application[] public applications; // applications uint256 public appNumber; // number of applications to process /// TokenCrowdsurance Apply event /// @param member new member address /// @param appId member appication id event Apply(address member, uint256 appId); /// TokenCrowdsurance Join event /// @param member new member addrsss /// @param id NFT token id for crowdsurance token /// @param amount paid to join event Join(address member, uint256 id, uint256 amount); /// TokenCrowdsurance Scoring event /// @param member new member addrsss /// @param score member scoring /// @param amount join amount event Scoring(address member, uint256 score, uint256 amount); /// TokenCrowdsurance Activate event /// @param id NFT Id to activate /// @param amount acowdsurance join amount /// @param score member scoring event Activate(uint256 id, uint256 amount, uint256 score); /// TokenCrowdsurance Activate event /// @param id NFT Id to activate /// @param claim claim amount /// @param number total claims number incuding this one event Claim(uint256 id, uint256 claim, uint8 number); /// TokenCrowdsurance vote event /// @param jury voter /// @param id NFT token id to vote /// @param positive voting result event Vote(address jury, uint256 id, bool positive); /// TokenCrowdsurance payment event /// @param reciever reciever of the p[ayment /// @param id NFT id for crowdsurance token /// @param amount mayment amount /// @param status payment status (Approved, Rejected, Closed) event Payment(address reciever, uint256 id, uint256 amount, uint8 status); /// FSSF event /// @param member member address /// @param appId application ID event FSSF(address member, uint256 appId); /// TokenCrowdsurance Status enum Status {Init, Active, Claim, Approved, Rejected, Closed} enum VotingState {Progress, Voted, Timeout} /// scoring function /// @param _member address of the member to score /// @param _score member scoroing result /// @param _amount join amount calculated based on score function scoring(address _member, uint256 _score, uint256 _amount) ownerOnly public { require(_member != address(0)); require(_score != uint256(0)); require(_amount != uint256(0) && _amount >= parameters.joinAmount); addressToAmount[_member] = _amount; addressToScore[_member] = _score; // clear appication uint256 addId = addressToApplication[_member]; if(addId != uint256(0) && addId < applications.length) { applications[addId].processed = true; delete addressToApplication[_member]; appNumber--; // if no more applications to process then clear the app array if (appNumber == uint256(0)) { delete applications; } } // emit scoring event Scoring(_member, _score, _amount); } function fssf() ownerOnly public { address member; uint256 appId; (member, appId) = getApplication(); if(member != address(0) && appId != uint256(0)) { scoring(member, parameters.averageScore, parameters.joinAmount); // emit FSSF event FSSF(member, appId); } } /// get next application to process function getApplication() view public returns (address member, uint256 appId) { member = address(0); appId = uint256(0); if(appNumber == uint256(0)) { return; } for(uint256 i = 1; i < applications.length; i++) { if(!applications[i].processed) { member = applications[i].member; appId = i; return; } } } /// get join amount for sender function getJoinAmount() view public returns (uint256 amount) { amount = addressToAmount[msg.sender]; } /// get score function getScore() view public returns (uint256 score) { score = addressToScore[msg.sender]; } /// get application ID function getAppID() view public returns (uint256 appId) { appId = addressToApplication[msg.sender]; } /// apply function /// @return application ID must be not zero if application is accepted function apply() public returns(uint256 addId) { addId = addressToApplication[msg.sender]; if (addId == uint256(0) && appNumber < parameters.maxApplications) { // new application Application memory app = Application({ timeStamp: now, member: msg.sender, tokensToBuy: uint8(1), paymetMethod: uint8(0), processed: false }); addId = applications.push(app) - 1; if(addId == uint256(0)) { // process the first one -- keep 0 index reserved addId = applications.push(app) - 1; } require(addId == uint256(uint32(addId))); addressToApplication[msg.sender] = addId; appNumber++; // emit Apply event Apply(msg.sender, addId); } } function _join(address _member, uint256 _score, uint256 _amount) internal returns(uint256) { uint256 id = _createNFT(_amount, "Crowdsurance", uint256(0), _member); // Create extension extensions[id] = Crowdsurance ({ timeStamp: now, activated: uint(0), duration: parameters.coverageDuration, amount: _amount, paid: uint256(0), score: _score, claimNumber: uint8(0), status: uint8(Status.Init) }); // now insert in a subpool _addTokenToSubPool(id); // emit event Join(_member, id, _amount); // clear mapping delete addressToAmount[_member]; delete addressToScore[_member]; // return NFT token ID return id; } /// join function /// @return cowdsuranceId NFT token ID for created crowdsurance function join() public payable returns(uint256 crowdsuranceId) { uint256 amount = msg.value; address member = msg.sender; uint256 score = addressToScore[member]; require(amount != uint256(0) && amount >= parameters.joinAmount); require(score != uint256(0)); require(amount == addressToAmount[member]); // call internal _join after all checkups crowdsuranceId = _join(member, score, amount); } /// activate function /// @param _id NFT token ID to activate function activate(uint256 _id) public { require(_id != uint256(0)); require(_owns(msg.sender, _id)); require(extensions[_id].amount != uint256(0)); require(extensions[_id].status != uint8(Status.Active)); // protect multiple activation that extend coverage nfts[_id].state = StateBlocked; // block transfer extensions[_id].status = uint8(Status.Active); extensions[_id].activated = now; // emit event Activate(_id, extensions[_id].amount, extensions[_id].score); } /// claim function /// @param _id NFT token ID to claim payment /// @param _claim claim amount function claim(uint256 _id, uint256 _claim) public returns(bool) { // check all conditions before accept the claim require(_id != uint256(0)); require(_owns(msg.sender, _id)); require(_claim != uint256(0)); require(extensions[_id].status == uint(Status.Active)); require(extensions[_id].claimNumber < parameters.maxClaimNumber); uint256 _payment = _claim * parameters.paymentRatio / 100; require((extensions[_id].paid + _payment) <= parameters.maxPaymentAmount); uint coverageEnd = extensions[_id].activated + extensions[_id].duration; require(coverageEnd >= now); // now ready to accept the claim request // change status requests[_id] = Request ({ amount: _claim, timeStamp: now, duration: parameters.votingDuration, positive: uint8(0), negative: uint8(0), number: uint8(0), members: [address(0), address(0), address(0), address(0), address(0)] }); extensions[_id].claimNumber++; extensions[_id].status = uint8(Status.Claim); // emit event Claim(_id, _claim, extensions[_id].claimNumber); return true; } /// add voter function /// @param _jury voter address /// @param _id NFT id for claim voting function addVoter(address _jury, uint256 _id) ownerOnly public { require(_jury != address(0)); require(_id != uint256(0)); require(extensions[_id].status == uint(Status.Claim)); Request storage _request = requests[_id]; require(_request.amount != uint256(0)); uint votingEnd = _request.timeStamp + _request.duration; require(votingEnd >= now); uint8 _number = _request.number; require(_number < parameters.juriesNumber); _request.members[_number] = _jury; _request.number++; voters[_jury] = _id; } /// vote function /// @param _id NFT id for claim voting /// @param _positive true if positive to pay claims function vote(uint256 _id, bool _positive) public { require(_id != uint256(0)); require(_id == voters[msg.sender]); require(extensions[_id].status == uint8(Status.Claim)); Request storage _request = requests[_id]; uint votingEnd = _request.timeStamp + _request.duration; require(votingEnd >= now); if(_positive) { _request.positive++; } else { _request.negative++; } delete voters[msg.sender]; // deliting prevent the second time voting // emit event Vote(msg.sender, _id, _positive); } /// helpers voting function castPositive(uint256 _id) public { vote(_id, true); } function castNegative(uint256 _id) public { vote(_id, false); } /// check claim voting status /// @param _id NFT token to check function votingStatus(uint256 _id) public view returns (VotingState state, uint8 positive, uint8 negative, uint256 payment, uint256 balance) { require(_id != uint256(0)); require(_owns(msg.sender, _id)); require(extensions[_id].status == uint(Status.Claim)); Request storage _request = requests[_id]; positive = _request.positive; negative = _request.negative; state = VotingState.Progress; payment = _request.amount * parameters.paymentRatio / 100; balance = this.balance; bool timeout = ( _request.timeStamp + _request.duration ) < now; bool voted = ( _request.positive + _request.negative ) == parameters.juriesNumber; if(timeout) { state = VotingState.Timeout; } else if (voted) { state = VotingState.Voted; } } /// get payment function /// @param _id NFT token to get payment function payment(uint256 _id) public { require(_id != uint256(0)); require(_owns(msg.sender, _id)); require(extensions[_id].status == uint(Status.Claim)); Request storage _request = requests[_id]; bool timeout = ( _request.timeStamp + _request.duration ) < now; bool voted = ( _request.positive + _request.negative ) == parameters.juriesNumber; require(timeout || voted); uint256 _payment = _request.amount * parameters.paymentRatio / 100; uint256[4] memory distribution; if((_request.positive > _request.negative) && _checkPayment(_id, _payment)) { // pay claims msg.sender.transfer(_payment); extensions[_id].status = uint8(Status.Approved); extensions[_id].paid = extensions[_id].paid + _payment; // update pools' balances distribution = _payValue(_id, _payment); // emit event Payment(msg.sender, _id, _payment, uint8(Status.Approved)); } else if (((_request.positive == _request.negative) || ((_request.positive + _request.negative) < parameters.minJuriesNumber)) && _checkPayment(_id, extensions[_id].amount)) { // pay back join amount msg.sender.transfer(extensions[_id].amount); extensions[_id].status = uint8(Status.Closed); extensions[_id].paid = extensions[_id].paid + extensions[_id].amount; // update pools' balances distribution = _payValue(_id, extensions[_id].amount); // emit event Payment(msg.sender, _id, extensions[_id].amount, uint8(Status.Closed)); } else { // no payment extensions[_id].status = uint8(Status.Rejected); // emit event Payment(msg.sender, _id, uint256(0), uint8(Status.Rejected)); } // now time to clean voting enviroment for(uint i; i < _request.number; i++) { delete voters[_request.members[i]]; } delete requests[_id]; delete distribution; } /// status count function /// @param _member address of token owner /// @param _status status to check function statusCount(address _member, uint8 _status) view public returns (uint256 count) { uint256[] memory tokenIds = _tokensOfOwner(_member); count = uint256(0); for (uint256 i = 0; i < tokenIds.length; i++) { if (extensions[tokenIds[i]].status == _status) { count++; } } } function TokenCrowdsurance(string _name, string _symbol) TokenPool(_name, _symbol) public { // setup default crowdsurance product parameters parameters.joinAmount = 0.1 ether; // default join amount parameters.coverageDuration = 0.5 years; // coverage duration in sec parameters.maxClaimAmount = 10 ether; // max claim amount parameters.maxClaimNumber = 1; // max claim number for the contract parameters.paymentRatio = 80; // claim to payment patio parameters.maxPaymentAmount = 10 ether; // max payment amount for the contract parameters.minJuriesNumber = 3; // min juries number to count voting parameters.votingDuration = 2 days; // juries voting duration in sec parameters.juriesNumber = 5; // juries number -- not more than 5 parameters.maxApplications = 10; // max number of unprocessed applications parameters.averageScore = 100; // average score value appNumber = 0; // initial value for applications } function() public payable { } // fallback function to get Ether on contract account }
status count function _member address of token owner _status status to check
function statusCount(address _member, uint8 _status) view public returns (uint256 count) { uint256[] memory tokenIds = _tokensOfOwner(_member); count = uint256(0); for (uint256 i = 0; i < tokenIds.length; i++) { if (extensions[tokenIds[i]].status == _status) { count++; } } }
888,730
pragma solidity ^0.4.25; import "./Library.sol"; import "./Verifier.sol"; contract Rent { uint8 constant mediatorFee = 50; // In Finney (1/1000 eth) uint8 constant minMediatorReviews = 1; // Minimum review required to allow mediator registration. Should be set to a higher value in production. uint8 constant minMediatorReviewScore = 4; // Minimum average review score to allow mediator registration address defaultMediator; constructor() public { // Create and assign a fixed default mediator // This is just a backup solution for now // Initialize empty arrays. This is necessary for struct members and for some reaon cannot be done in the constructor call uint[] memory tenantRentals; uint[] memory mediatorRentals; // Add a new tenant tenants[0xCaDAC9b6ba49e771dbE43Ccc5F03c90Fc9D4Bb04] = Tenant( true, 0x6819c96436218f70de7002cbc0f002fc4ce7b6fdd109a820cf5f25f3cb94c8bd, 0x7fc48e0ea3b94ba41bcf1f570fbf14c8ef7794a5e4158cd1ef62431df50225f1, MediatorStatus.Registered, 0, // Initial score tenantRentals, // Rental ids mediatorRentals, 0 // Number of reviews ); defaultMediator = 0xCaDAC9b6ba49e771dbE43Ccc5F03c90Fc9D4Bb04; } // ------------------------------------------------------------- // ------------------------ Definitions ------------------------ // ------------------------------------------------------------- // ------------------------ Tenants ------------------------ enum MediatorStatus { Unregistered, // Tenant has not registered as mediator yet Registered, // Tenant is registered as mediator Revoked // Mediator status has been revoked (after timeout for mediation) } struct Tenant { bool initialized; bytes32 publicKey_x; bytes32 publicKey_y; MediatorStatus mediatorStatus; uint totalScore; // Total score in sum of all rating points. The average score has to be determined totalScore / numReviews uint[] rentals; // Ids of the rentals (array indices) uint[] mediatedRentals; // Ids of the rentals the tenant is mediating // Using an dynamically sized array instead of a mapping would be more elegant, but is not supported by solidity compiler yet // (can not be initialized due to "Copying of type struct Rent.TenantReview memory[] memory to storage not yet supported") uint numReviews; mapping(uint => TenantReview) reviews; // TenantReview[] reviews; } struct TenantReview { uint8 score; bytes32 hash; // Used for verification bytes32 ipfsHash; // Hash part of IPFS address text encrypted with tenant public key } // ------------------------ Apartments ------------------------ struct Apartment { address ownerAddress; bytes32 ownerPublicKey_x; bytes32 ownerPublicKey_y; bytes32 ipfsHash; // Hash part of IPFS address // Again, a dynamically sized array would be more elegant, but not supported by solidity compiler uint numReviews; mapping(uint => ApartmentReview) reviews; //ApartmentReview[] reviews; } struct ApartmentReview { address tenantAddress; uint8 score; // Score 1-5 bytes32 ipfsHash; // Hash part of IPFS address } // ------------------------ Rentals ------------------------ enum RentalStatus { Requested, Withdrawn, Accepted, Refused, Reviewed } enum DepositStatus { Open, // When no claim to the deposit has been made or is valid yet Pending, // When a deduction was requested Processed // When the deposit was processed => (partly) refunded / deduction transferred } enum DeductionStatus { Requested, // When a deduction has been requested, but the tenant hasn't responded Objected, // When the tenant has objected to the deduction Resolved // When the deduction has been resolved by mediation or timeout } struct DepositDeduction { uint16 lastChange; // As a unix timestamp day uint128 amount; // The requested deduction amount in finney bytes32 reasonIpfsHash; // The reason for the deduction, as hash part of IPFS address, encrypted with tenant and mediator public key bytes32 objectionIpfsHash; // Objection for the deduction created by tenant, encrypted with mediator public key bytes32 conclusionIpfsHash; // The conclusion from the mediation determined by the mediator, encrypted with interaction and tenant public key DeductionStatus status; // Status for the deduction request } struct Rental { bytes32 interactionPublicKey_x; // X point for interaction public key used for private data exchange bytes32 interactionPublicKey_y; // Y point for interaction public key address interactionAddress; // Address used by apartment owner for authentication bytes32 apartmentHash; // Hash of apartment + nonce to later prove apartment involved in rental bytes32 detailsIpfsHash; // Hash part of IPFS address for rental details encrypted with interaction public key bytes32 detailsHash; // Hash of rental details to allow verifying forwarded rental details bytes32 detailsForMediatorIpfsHash; // Hash part of IPFS address for rental details encrypted with mediator public key bytes32 contactDataIpfsHash; // Hash part of IPFS address for owner contact details encrypted with tenant public key bytes32 contactDataForMediatorIpfsHash; // Hash part of IPFS address for owner contact details encrypted with mediator public key uint fee; // Total fee for this rental in finney uint128 deposit; // Deposit for this rental in finney address tenantAddress; // The tenant profile address address mediatorAddress; // The mediator determined for this rental (as soon as the rental is accepted) address ownerAddress; // The addressed used for payments towards the apartment owner and after accept/refuse also as means of authentication RentalStatus status; // Status for the rental DepositStatus depositStatus; // Status of the deposit } // ------------------------------------------------------------ // -------------- Conversion functions for enums -------------- // ------------------------------------------------------------ // Get the string representation for the rental status, lowercase function getRentalStatusString(RentalStatus status) private pure returns (string) { if (status == RentalStatus.Requested) { return "requested"; } if (status == RentalStatus.Withdrawn) { return "withdrawn"; } if (status == RentalStatus.Accepted) { return "accepted"; } if (status == RentalStatus.Refused) { return "refused"; } if (status == RentalStatus.Reviewed) { return "reviewed"; } } // Get the string representation for the deduction status, lowercase function getDeductionStatusString(DeductionStatus status) private pure returns (string) { if (status == DeductionStatus.Requested) { return "requested"; } if (status == DeductionStatus.Objected) { return "objected"; } if (status == DeductionStatus.Resolved) { return "resolved"; } } // Get the string representation for the deposit status, lowercase function getDepositStatusString(DepositStatus status) private pure returns (string) { if (status == DepositStatus.Open) { return "open"; } if (status == DepositStatus.Pending) { return "pending"; } if (status == DepositStatus.Processed) { return "processed"; } } // ------------------------------------------------------------ // ------------------------- Properties ----------------------- // ------------------------------------------------------------ mapping(address => Tenant) private tenants; mapping(bytes32 => mapping(bytes32 => bool)) private tenantPublicKeys; // Mapping to check whether a public key has been used in a tenant's profile address[] private mediators; // List of mediators Apartment[] private apartments; // List of apartments mapping(bytes32 => uint[]) private cityApartments; // Country+City SHA256 hash => apartment ids; to allow fetching apartments of a city mapping(address => uint[]) private ownerApartments; // Mapping to get the apartments of an owner and to check if the address has been used mapping(bytes32 => mapping(bytes32 => bool)) private ownerPublicKeys; // Mapping to check whether a public key has been used in an apartment mapping(bytes32 => mapping(bytes32 => bool)) private interactionKeys; // Mapping to check whether a public key has already been used in another interaction mapping(address => uint) private interactionAddressRental; // Mapping to get the rental for a interaction address mapping(address => bool) private rentalAddresses; // Mapping to check if an address has already been used in an interaction and prevent it from other uses Rental[] private rentals; // List of rentals mapping(uint => DepositDeduction) private depositDeductions; // Deposit deductions for a rental (id => deduction) // --------------------------------------------------------- // ------------------------ Getters ------------------------ // --------------------------------------------------------- // ----------------------- Addresses ----------------------- // Check whether the address is known to the app, and retrieve user type function getAddressType() public view returns (string) { if (hasTenant()) { return "tenant"; } if (ownsApartments()) { return "owner"; } if (hasInteractionAddressRental(msg.sender)) { return "interaction"; } if (rentalAddresses[msg.sender]) { return "rentalOwner"; } return "unknown"; } // ------------------------ Tenants ------------------------ // Check whether a tenant for the address already exists function hasTenant() public view returns (bool) { return tenants[msg.sender].initialized; } // Get the tenant at the specified address function getTenant(address tenantAddr) public view returns ( bytes32 publicKey_x, bytes32 publicKey_y, uint totalScore, uint numReviews ) { // Check that the tenant exists require(tenants[tenantAddr].initialized); // Get the tenant from storage Tenant storage tenant = tenants[tenantAddr]; // Assign the return variables publicKey_x = tenant.publicKey_x; publicKey_y = tenant.publicKey_y; totalScore = tenant.totalScore; numReviews = tenant.numReviews; } // Get the review for the tenant with the specified id function getTenantReview(address tenantAddr, uint reviewId) public view returns ( uint8 score, bytes32 hash, bytes32 ipfsHash ) { // Check that the tenant exists require(tenants[tenantAddr].initialized); // Check that the review exists require(tenants[tenantAddr].numReviews > reviewId); // Get the review from the tenant TenantReview storage review = tenants[tenantAddr].reviews[reviewId]; // Assign the return variables score = review.score; hash = review.hash; ipfsHash = review.ipfsHash; } // ------------------------ Apartments ------------------------ // Check whether the sender owns any apartments function ownsApartments() public view returns (bool) { return ownerApartments[msg.sender].length > 0; } // Get the number of all available apartments function getNumApartments() public view returns (uint) { return apartments.length; } // Get the apartment at the specified id function getApartment(uint apartmentId) public view returns ( address ownerAddress, bytes32 ownerPublicKey_x, bytes32 ownerPublicKey_y, bytes32 ipfsHash, uint numReviews ) { // Check that the apartment exists require(apartments.length > apartmentId); // Get the apartment from storage Apartment storage apartment = apartments[apartmentId]; // Assign the return variables ownerAddress = apartment.ownerAddress; ownerPublicKey_x = apartment.ownerPublicKey_x; ownerPublicKey_y = apartment.ownerPublicKey_y; ipfsHash = apartment.ipfsHash; numReviews = apartment.numReviews; } // Get the number of apartments available in a city function getNumCityApartments(bytes32 cityHash) public view returns (uint) { return cityApartments[cityHash].length; } // Get a city apartment at the specified id function getCityApartment(bytes32 cityHash, uint cityApartmentId) public view returns ( uint id, address ownerAddress, bytes32 ownerPublicKey_x, bytes32 ownerPublicKey_y, bytes32 ipfsHash, uint numReviews ) { // Check that the apartment exists require(cityApartments[cityHash].length > cityApartmentId); id = cityApartments[cityHash][cityApartmentId]; // Get the apartment from storage Apartment storage apartment = apartments[id]; // Assign the return variables ownerAddress = apartment.ownerAddress; ownerPublicKey_x = apartment.ownerPublicKey_x; ownerPublicKey_y = apartment.ownerPublicKey_y; ipfsHash = apartment.ipfsHash; numReviews = apartment.numReviews; } // Get the number of apartments created by the owner function getNumOwnerApartments(address ownerAddr) public view returns (uint) { return ownerApartments[ownerAddr].length; } // Get the apartment of the owner with the specified id function getOwnerApartment(address ownerAddr, uint ownerApartmentId) public view returns ( uint id, bytes32 ownerPublicKey_x, bytes32 ownerPublicKey_y, bytes32 ipfsHash, uint numReviews ) { // Check that the apartment exists require(ownerApartments[ownerAddr].length > ownerApartmentId); id = ownerApartments[ownerAddr][ownerApartmentId]; // Get the apartment from storage Apartment storage apartment = apartments[id]; // Assign the return variables ownerPublicKey_x = apartment.ownerPublicKey_x; ownerPublicKey_y = apartment.ownerPublicKey_y; ipfsHash = apartment.ipfsHash; numReviews = apartment.numReviews; } // -------------------- Apartment reviews ------------------ function getApartmentReview(uint apartmentId, uint reviewId) public view returns ( address tenantAddress, uint8 score, bytes32 ipfsHash ) { // Check that the apartment exists require(apartments.length > apartmentId); // Check that the review exists require(apartments[apartmentId].numReviews > reviewId); // Get the review from storage ApartmentReview storage review = apartments[apartmentId].reviews[reviewId]; // Assign the return variables tenantAddress = review.tenantAddress; score = review.score; ipfsHash = review.ipfsHash; } // ------------------------ Rentals ------------------------ // Get the number of rentals by the tenant function getNumTenantRentals(address tenantAddr) public view returns (uint) { // If the tenant doesn't exist, he also doesn't have rentals if (!tenants[tenantAddr].initialized) { return 0; } return tenants[tenantAddr].rentals.length; } // Get a tenant's rental with the specified id function getTenantRental(address tenantAddr, uint tenantRentalId) public view returns ( uint id, address interactionAddress, address mediatorAddress, bytes32 interactionPublicKey_x, bytes32 interactionPublicKey_y, bytes32 apartmentHash, bytes32 contactDataIpfsHash, uint fee, uint deposit, string status, string depositStatus ) { // Check that the tenant exists require(tenants[tenantAddr].initialized); // Check that the tenant's rental exists require(tenants[tenantAddr].rentals.length > tenantRentalId); id = tenants[tenantAddr].rentals[tenantRentalId]; // Assign the return variables. We're not fetching the rental into a local variable as the stack would otherwise be too deep. interactionAddress = rentals[id].interactionAddress; mediatorAddress = rentals[id].mediatorAddress; interactionPublicKey_x = rentals[id].interactionPublicKey_x; interactionPublicKey_y = rentals[id].interactionPublicKey_y; apartmentHash = rentals[id].apartmentHash; contactDataIpfsHash = rentals[id].contactDataIpfsHash; fee = rentals[id].fee; deposit = rentals[id].deposit; status = getRentalStatusString(rentals[id].status); depositStatus = getDepositStatusString(rentals[id].depositStatus); } // Get the number of rentals mediated by the tenant function getNumMediatorRentals(address mediatorAddr) public view returns (uint) { // If the tenant doesn't exist, he also doesn't have mediated rentals if (!tenants[mediatorAddr].initialized) { return 0; } return tenants[mediatorAddr].mediatedRentals.length; } // Get a rental mediated by the tenant with the specified id function getMediatorRental(address mediatorAddr, uint mediatorRentalId) public view returns ( uint id, address tenantAddress, bytes32 interactionPublicKey_x, bytes32 interactionPublicKey_y, bytes32 detailsHash, bytes32 detailsForMediatorIpfsHash, bytes32 contactDataForMediatorIpfsHash, uint deposit, string depositStatus ) { // Check that the mediator exists require(tenants[mediatorAddr].initialized); // Check that the mediated rental exists require(tenants[mediatorAddr].mediatedRentals.length > mediatorRentalId); id = tenants[mediatorAddr].mediatedRentals[mediatorRentalId]; // Assign the return variables. We're not fetching the rental into a local variable as the stack would otherwise be too deep. tenantAddress = rentals[id].tenantAddress; interactionPublicKey_x = rentals[id].interactionPublicKey_x; interactionPublicKey_y = rentals[id].interactionPublicKey_y; detailsHash = rentals[id].detailsHash; detailsForMediatorIpfsHash = rentals[id].detailsForMediatorIpfsHash; contactDataForMediatorIpfsHash = rentals[id].contactDataForMediatorIpfsHash; deposit = rentals[id].deposit; depositStatus = getDepositStatusString(rentals[id].depositStatus); } // Check whether a rental exists for the interaction address function hasInteractionAddressRental(address interactionAddress) public view returns (bool) { return // If the mapping has a (not 0) value for the interaction address, we got a rental for it interactionAddressRental[interactionAddress] != 0 || // Otherwise, check if we have rentals and the rental at id 0 has the same interactionAddress rentals.length != 0 && rentals[0].interactionAddress == interactionAddress; } // Get the rental for the specified interaction address function getInteractionAddressRental(address addr) public view returns ( uint id, address tenantAddress, address mediatorAddress, address ownerAddress, bytes32 interactionPublicKey_x, bytes32 interactionPublicKey_y, bytes32 apartmentHash, bytes32 detailsHash, bytes32 detailsIpfsHash, uint fee, uint deposit, string status, string depositStatus ) { // Check that we have a rental for the interaction key require(hasInteractionAddressRental(addr)); id = interactionAddressRental[addr]; // Assign the return variables interactionPublicKey_x = rentals[id].interactionPublicKey_x; interactionPublicKey_y = rentals[id].interactionPublicKey_y; mediatorAddress = rentals[id].mediatorAddress; tenantAddress = rentals[id].tenantAddress; ownerAddress = rentals[id].ownerAddress; apartmentHash = rentals[id].apartmentHash; detailsHash = rentals[id].detailsHash; detailsIpfsHash = rentals[id].detailsIpfsHash; fee = rentals[id].fee; deposit = rentals[id].deposit; status = getRentalStatusString(rentals[id].status); depositStatus = getDepositStatusString(rentals[id].depositStatus); } // -------------------------------------------------------- // ------------------------ Events ------------------------ // -------------------------------------------------------- event MediatorRegistered(address indexed tenantAddress); event ApartmentAdded(address indexed owner, uint apartmentId); event RentalRequested(address interactionAddress, uint rentalId); event RentalRequestWithdrawn(address interactionAddress, uint rentalId); event RentalRequestRefused(address indexed tenant, uint rentalId); event RentalRequestApproved(address indexed tenant, uint rentalId); event DepositRefunded(address indexed tenant, uint rentalId); event DeductionRequested(address indexed tenant, uint rentalId); event DeductionAccepted(address indexed interactionAddress, uint rentalId); event DeductionRefused(address indexed interactionAddress, address indexed mediatorAddress, uint rentalId); event DeductionMediated(address indexed tenant, address indexed interactionAddress, uint rentalId); event ApartmentReviewed(address indexed owner, uint apartmentId, uint rentalId); // --------------------------------------------------------- // ------------------------ Methods ------------------------ // --------------------------------------------------------- // Add a new apartment function addApartment( bytes32 ownerPublicKey_x, bytes32 ownerPublicKey_y, bytes32 ipfsHash, // Hash part of IPFS address for apartment details bytes32 cityHash // Hash of city + country, used for searching ) public { // Check that the owner isn't a tenant too require(!tenants[msg.sender].initialized); // Check that the ownerPublicKey does not match a tenant's public key require(!tenantPublicKeys[ownerPublicKey_x][ownerPublicKey_y]); // Check that the address has not been used in a rental require(!rentalAddresses[msg.sender]); // Add the apartment to the list of apartments apartments.push(Apartment( msg.sender, ownerPublicKey_x, ownerPublicKey_y, ipfsHash, 0 )); // Add the apartment to the city's apartments cityApartments[cityHash].push(apartments.length - 1); // Add the apartment to the owner's apartments ownerApartments[msg.sender].push(apartments.length - 1); // Add the owner public key to the list of used public keys ownerPublicKeys[ownerPublicKey_x][ownerPublicKey_y] = true; // Emit an event for the added apartment emit ApartmentAdded(msg.sender, apartments.length - 1); } // ------------------------- Users ------------------------- // Register as a mediator with the tenant's account associated with the sender. // Registration will fail if tenant is already mediator or doesn't have a sufficient score // (at least X reviews and a total review score of at least Y is required) function registerMediator() public { // Check if the sender has a tenant account require(tenants[msg.sender].initialized); Tenant storage tenant = tenants[msg.sender]; // Check that the tenant isn't a mediator yet (and hasn't been revoked mediator status yet) require(tenant.mediatorStatus == MediatorStatus.Unregistered); // Check that the tenant has at least 5 reviews with a score of at least 4.0 require(tenant.numReviews >= minMediatorReviews && tenant.totalScore / tenant.numReviews >= minMediatorReviewScore); // Set the tenant as mediator and add him to the list of mediators tenant.mediatorStatus == MediatorStatus.Registered; mediators.push(msg.sender); // Emit a mediator registered event emit MediatorRegistered(msg.sender); } // Create a tenant with the specified publicKey function createTenant( address addr, bytes32 publicKey_x, bytes32 publicKey_y ) private returns (Tenant) { // Check that the address has not been used by an owner or in an interaction require(ownerApartments[addr].length == 0); require(!rentalAddresses[addr]); // Check that the public key has not been used yet require(!tenantPublicKeys[publicKey_x][publicKey_y]); require(!ownerPublicKeys[publicKey_x][publicKey_y]); // Initialize empty arrays. This is necessary for struct members and for some reaon cannot be done in the constructor call uint[] memory tenantRentals; uint[] memory mediatorRentals; // Add a new tenant tenants[addr] = Tenant( true, publicKey_x, publicKey_y, MediatorStatus.Unregistered, 0, // Initial score tenantRentals, // Rental ids mediatorRentals, 0 // Number of reviews ); // Set the public key as used tenant public key tenantPublicKeys[publicKey_x][publicKey_y] = true; } // ------------------------ Rentals ------------------------ // Request a new rental as a tenant function requestRental( uint fee, uint128 deposit, bytes32 interactionKey_x, // Public key for encryption bytes32 interactionKey_y, // Public key for encryption address interactionAddress, // Address for authentication, NOT the owner/sender address (as this is unknown) bytes32 apartmentHash, bytes32 detailsIpfsHash, bytes32 detailsHash, bytes32 tenantPublicKey_x, bytes32 tenantPublicKey_y ) public payable { // Check that the fee is not 0 require(fee > 0); // Check if the transferred value matches the fee and deposit require(fee + deposit == Library.weiToFinney(msg.value)); // Check that the interaction key does not match an existing key require(!tenantPublicKeys[interactionKey_x][interactionKey_y]); require(!ownerPublicKeys[interactionKey_x][interactionKey_y]); require(!interactionKeys[interactionKey_x][interactionKey_y]); // Check that the interaction address isn't empty require(interactionAddress != 0x0); // Check that the interactionAddress does not match a tenant's address require(!tenants[interactionAddress].initialized); // Check that the interactionAddress hasn't been used in a rental require(!hasInteractionAddressRental(interactionAddress)); // Check that the interactionAddress isn't the current address require(interactionAddress != msg.sender); // Check that the interactionKey isn't the same as the tenantPublicKey require(interactionKey_x != tenantPublicKey_x || interactionKey_y != tenantPublicKey_y); // TODO: Also check it doesn't match owner address // Check if the tenant exists; create him otherwise if (!tenants[msg.sender].initialized) { createTenant(msg.sender, tenantPublicKey_x, tenantPublicKey_y); } // Add the rental rentals.push(Rental( interactionKey_x, interactionKey_y, interactionAddress, apartmentHash, detailsIpfsHash, detailsHash, 0, 0, 0, fee, deposit, msg.sender, 0x0, 0x0, RentalStatus.Requested, DepositStatus.Open )); // Add the rental in the tenant's profile tenants[msg.sender].rentals.push(rentals.length - 1); // Link the rental to the interaction key and address interactionKeys[interactionKey_x][interactionKey_y] = true; interactionAddressRental[interactionAddress] = rentals.length - 1; emit RentalRequested(interactionAddress, rentals.length - 1); } // Withdraw a rental request as a tenant function withdrawRentalRequest( uint rentalId ) public { // Check that the rental exists require(rentals.length > rentalId && rentals[rentalId].fee != 0); Rental storage rental = rentals[rentalId]; // Check authorization for the sender require(msg.sender == rental.tenantAddress); // Check that the rental is in the right state require(rental.status == RentalStatus.Requested); // Change the rental status rental.status = RentalStatus.Withdrawn; // Refund the fee + deposit msg.sender.transfer( Library.finneyToWei(rental.fee + rental.deposit) ); // Emit an event to notify about the withdrawn rental request emit RentalRequestWithdrawn(rental.interactionAddress, rentalId); } // Refuse a rental request as an apartment owner. // Uses the supplied signature to authenticate against the rentals interaction public key. function refuseRental( uint rentalId, string signature // Signature for 'refuse:' + rentalId (this is cheaper than the signature of the sender address) ) public { // Check that the sender address has not been used yet require(!tenants[msg.sender].initialized); require(ownerApartments[msg.sender].length == 0); require(!rentalAddresses[msg.sender]); // Check that the rental exists require(rentals.length > rentalId); Rental storage rental = rentals[rentalId]; // Check that the rental has the right state require(rental.status == RentalStatus.Requested); // Recover the expected signer address string memory message = string(abi.encodePacked("refuse:", Library.uintToString(rentalId))); address recovered = Verifier.verifyString( message, signature ); // Check authorization of the owner require(recovered == rental.interactionAddress); // Change the rental's status rental.status = RentalStatus.Refused; // Mark the sender address as used in a rental rentalAddresses[msg.sender] = true; // Transfer fee and deposit back to the tenant rental.tenantAddress.transfer(Library.finneyToWei(rental.fee + rental.deposit)); // Notify about the refused rental request emit RentalRequestRefused(rental.tenantAddress, rentalId); } // Accept a rental request. // Uses the supplied signature to authenticate against the rentals interaction public key. function acceptRental( uint rentalId, bytes32 contactDataIpfsHash, string signature // Signature for msg.sender address as authentication ) public { // Check that the sender address has not been used yet require(!tenants[msg.sender].initialized); require(ownerApartments[msg.sender].length == 0); require(!rentalAddresses[msg.sender]); // Check that the rental exists require(rentals.length > rentalId); Rental storage rental = rentals[rentalId]; // Check that the rental has the right state require(rental.status == RentalStatus.Requested); // Recover the signer address address recovered = Verifier.verifyString( Library.addressToString(msg.sender), signature ); // Check authorization of the owner require(recovered == rental.interactionAddress); // Example for verifications of signatures for with integers, bytes32, strings and addresses: //string memory c = Library.b32ToString(contactDataIpfsHash); //string memory a = Library.addressToString(msg.sender); // Pass this message into the verifyString function //string memory message = string(abi.encodePacked( // "accept:", // Library.uintToString(rentalId), // "-", // c, // "-", // a // )); // Change the rental's status rental.status = RentalStatus.Accepted; // Store the contact data rental.contactDataIpfsHash = contactDataIpfsHash; // Use the sender address as owner address rental.ownerAddress = msg.sender; // Mark the sender address as used in a rental rentalAddresses[msg.sender] = true; // Assign a random mediator for the case of a dispute rental.mediatorAddress = getRandomMediator(); // Transfer the rental fee to the sender (= payment address) msg.sender.transfer(Library.finneyToWei(rental.fee)); // Notify about the accepted rental request emit RentalRequestApproved(rental.tenantAddress, rentalId); } // Get a pseudo-random mediator function getRandomMediator() private view returns (address) { // If we don't have mediators, return the default mediator if (mediators.length == 0) { return defaultMediator; } // If we only have one mediator, return him if (mediators.length == 1) { return mediators[0]; } // Get the mediator based on a pseudo-random number generated using the block timestamp and difficulty return mediators[ uint256(keccak256( abi.encodePacked( Library.uintToString(block.timestamp), Library.uintToString(block.difficulty) ) )) % mediators.length ]; } // --------------------- Owner review --------------------- // End a rental as an apartment owner function endRental( uint rentalId, uint8 reviewScore, bytes32 reviewTextHash, bytes32 reviewTextIpfsHash, uint128 deductionAmount, // Requested deposit deduction; can be 0 bytes32 deductionReasonIpfsHash, // Reason for deposit deduction; can be empty if no deduction requested bytes32 contactDataForMediatorIpfsHash // Contact data for the mediator ) public { // Check that the rental exists require(rentals.length > rentalId); Rental storage rental = rentals[rentalId]; Tenant storage tenant = tenants[rental.tenantAddress]; // Check the score makes sense require(reviewScore < 6 && reviewScore > 0); // Check that the deduction amount (if specified) is smaller or equal to the deposit require(deductionAmount <= rental.deposit); // Check that the sender is the owner require(msg.sender == rental.ownerAddress); // Check that the rental has not ended yet => the deposit is still open require(rental.depositStatus == DepositStatus.Open); // Assign the review to the tenant TenantReview memory review = TenantReview(reviewScore, reviewTextHash, reviewTextIpfsHash); tenant.reviews[tenant.numReviews] = review; tenant.numReviews ++; // If no deduction was requested, we can directly transfer the deposit back to the tenant if (deductionAmount == 0) { rental.depositStatus = DepositStatus.Processed; rental.tenantAddress.transfer(rental.deposit); // Notify about the refund emit DepositRefunded(rental.tenantAddress, rentalId); return; } // Create a deposit deduction and it add to the rental DepositDeduction memory depositDeduction = DepositDeduction( uint16(block.timestamp / 86400), deductionAmount, deductionReasonIpfsHash, 0, 0, DeductionStatus.Requested ); depositDeductions[rentalId] = depositDeduction; rental.depositStatus = DepositStatus.Pending; // Add the contact data ipfs hash for the mediator to the rental rental.contactDataForMediatorIpfsHash = contactDataForMediatorIpfsHash; // Notify about the requested deduction emit DeductionRequested(rental.tenantAddress, rentalId); } // ---------------------- Deductions ---------------------- // Accept the requested deduction as a tenant function acceptDeduction( uint rentalId ) public { require(rentals.length > rentalId); Rental storage rental = rentals[rentalId]; // Only allow accepting deductions from the tenant require(msg.sender == rental.tenantAddress); // Only allow accepting the deduction if the depositStatus and the deduction status match require(rental.depositStatus == DepositStatus.Pending); require(depositDeductions[rentalId].status == DeductionStatus.Requested); // Change the status rental.depositStatus = DepositStatus.Processed; depositDeductions[rentalId].status = DeductionStatus.Resolved; // Transfer the deducted amount to the owner and the rest to the tenant rental.ownerAddress.transfer(Library.finneyToWei(depositDeductions[rentalId].amount)); rental.tenantAddress.transfer(Library.finneyToWei(rental.deposit - depositDeductions[rentalId].amount)); // Delete the deposit deduction delete depositDeductions[rentalId]; // Notify about the accepted deduction emit DeductionAccepted(rental.interactionAddress, rentalId); } // Object to the requested deduction as a tenant function refuseDeduction( uint rentalId, bytes32 objectionIpfsHash, bytes32 detailsForMediatorIpfsHash // Rental details for mediator, encrypted with mediator public key ) public { require(rentals.length > rentalId); Rental storage rental = rentals[rentalId]; // Only allow objections from the tenant require(msg.sender == rental.tenantAddress); // Only allow objections if the depositStatus and the deduction status match require(rental.depositStatus == DepositStatus.Pending); require(depositDeductions[rentalId].status == DeductionStatus.Requested); // Add the rental details for the mediator to the rental rental.detailsForMediatorIpfsHash = detailsForMediatorIpfsHash; // Change the status and add the objection depositDeductions[rentalId].status = DeductionStatus.Objected; depositDeductions[rentalId].objectionIpfsHash = objectionIpfsHash; // Update the lastChange day depositDeductions[rentalId].lastChange = uint16(block.timestamp / 86400); // Notify about the refused deduction request emit DeductionRefused(rental.interactionAddress, rental.mediatorAddress, rentalId); } // Mediate in a deduction request dispute function mediate( uint rentalId, uint128 deductionAmount, bytes32 conclusionIpfsHash // Conclusion encrypted with tenant and interaction public key ) public { // Check that the rental exists require(rentals.length > rentalId); Rental storage rental = rentals[rentalId]; // Check that the sender is assigned to the rental as mediator rental.mediatorAddress = msg.sender; // Check that the rental requires mediation require(rental.depositStatus == DepositStatus.Pending); require(depositDeductions[rentalId].status == DeductionStatus.Objected); // Check that the determined deductionAmount is smaller or equal to the deposit + mediatorFee require(rental.deposit >= deductionAmount + mediatorFee); // Set the deduction to resolved and the deposit to processed depositDeductions[rentalId].status = DeductionStatus.Resolved; depositDeductions[rentalId].conclusionIpfsHash = conclusionIpfsHash; rental.depositStatus = DepositStatus.Processed; // Transfer the mediatorFee to the mediator, the deduction to the owner and the rest to the tenant msg.sender.transfer(Library.finneyToWei(mediatorFee)); rental.ownerAddress.transfer(Library.finneyToWei(deductionAmount)); rental.tenantAddress.transfer(Library.finneyToWei(rental.deposit - deductionAmount - mediatorFee)); // Notify about the mediation emit DeductionMediated(rental.tenantAddress, rental.interactionAddress, rentalId); } // -------------------- Tenant review -------------------- // Review an apartment, revealing the rented apartment in the process function review( uint rentalId, uint apartmentId, string requestId, // requestId involved in created apartmentHash string requestIdSignature, // signature of requestId. Has to be signed with apartment owner's address. uint8 score, bytes32 textIpfsHash // Hash of unencrypted review ) public { // Check that the rental and apartment exist require(rentals.length > rentalId); require(apartments.length > apartmentId); Rental storage rental = rentals[rentalId]; Apartment storage apartment = apartments[apartmentId]; // Check that the sender is the tenant rental.tenantAddress = msg.sender; // Check that the rental has not been reviewed yet require(rental.status == RentalStatus.Accepted); // Check constraint: rentals apartment hash matches the sha3 of apartmentId + "-" + requestId require(rental.apartmentHash == keccak256( abi.encodePacked( Library.uintToString(apartmentId), "-", requestId ) )); // Recover the requestId signer address // Does not work currently, so it's disabled /*address recovered = Verifier.verifyString( requestId, requestIdSignature ); // Check the signer is the apartment owner require(apartment.ownerAddress == recovered); */ // Change the rental status to reviewed rental.status = RentalStatus.Reviewed; // Add the review ApartmentReview memory apartmentReview = ApartmentReview( msg.sender, score, textIpfsHash ); apartment.reviews[apartment.numReviews] = apartmentReview; apartment.numReviews ++; // Notify about the review emit ApartmentReviewed(apartment.ownerAddress, apartmentId, rentalId); } }
Get the apartment of the owner with the specified id Check that the apartment exists Get the apartment from storage Assign the return variables
function getOwnerApartment(address ownerAddr, uint ownerApartmentId) public view returns ( uint id, bytes32 ownerPublicKey_x, bytes32 ownerPublicKey_y, bytes32 ipfsHash, uint numReviews ) { require(ownerApartments[ownerAddr].length > ownerApartmentId); id = ownerApartments[ownerAddr][ownerApartmentId]; Apartment storage apartment = apartments[id]; ownerPublicKey_x = apartment.ownerPublicKey_x; ownerPublicKey_y = apartment.ownerPublicKey_y; ipfsHash = apartment.ipfsHash; numReviews = apartment.numReviews; }
12,914,876
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) private pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return recover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return recover(hash, r, vs); } else { revert("ECDSA: invalid signature length"); } } /** * @dev Overload of {ECDSA-recover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.2._ */ function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { bytes32 s; uint8 v; assembly { s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) v := add(shr(255, vs), 27) } return recover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. require( uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value" ); require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value"); // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); require(signer != address(0), "ECDSA: invalid signature"); return signer; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity 0.8.9; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "./libraries/PbBridge.sol"; import "./Pool.sol"; contract Bridge is Pool { using SafeERC20 for IERC20; // liquidity events event Send( bytes32 transferId, address sender, address receiver, address token, uint256 amount, uint64 dstChainId, uint64 nonce, uint32 maxSlippage ); event Relay( bytes32 transferId, address sender, address receiver, address token, uint256 amount, uint64 srcChainId, bytes32 srcTransferId ); // gov events event MinSendUpdated(address token, uint256 amount); event MaxSendUpdated(address token, uint256 amount); mapping(bytes32 => bool) public transfers; mapping(address => uint256) public minSend; // send _amount must > minSend mapping(address => uint256) public maxSend; // min allowed max slippage uint32 value is slippage * 1M, eg. 0.5% -> 5000 uint32 public minimalMaxSlippage; function send( address _receiver, address _token, uint256 _amount, uint64 _dstChainId, uint64 _nonce, uint32 _maxSlippage // slippage * 1M, eg. 0.5% -> 5000 ) external nonReentrant whenNotPaused { require(_amount > minSend[_token], "amount too small"); require(maxSend[_token] == 0 || _amount <= maxSend[_token], "amount too large"); require(_maxSlippage > minimalMaxSlippage, "max slippage too small"); bytes32 transferId = keccak256( // uint64(block.chainid) for consistency as entire system uses uint64 for chain id abi.encodePacked(msg.sender, _receiver, _token, _amount, _dstChainId, _nonce, uint64(block.chainid)) ); require(transfers[transferId] == false, "transfer exists"); transfers[transferId] = true; IERC20(_token).safeTransferFrom(msg.sender, address(this), _amount); emit Send(transferId, msg.sender, _receiver, _token, _amount, _dstChainId, _nonce, _maxSlippage); } function relay( bytes calldata _relayRequest, bytes[] calldata _sigs, address[] calldata _signers, uint256[] calldata _powers ) external whenNotPaused { verifySigs(_relayRequest, _sigs, _signers, _powers); PbBridge.Relay memory request = PbBridge.decRelay(_relayRequest); require(request.dstChainId == block.chainid, "dst chainId not match"); bytes32 transferId = keccak256( abi.encodePacked( request.sender, request.receiver, request.token, request.amount, request.srcChainId, request.dstChainId, request.srcTransferId ) ); require(transfers[transferId] == false, "transfer exists"); transfers[transferId] = true; updateVolume(request.token, request.amount); uint256 delayThreshold = delayThresholds[request.token]; if (delayThreshold > 0 && request.amount > delayThreshold) { addDelayedTransfer(transferId, request.receiver, request.token, request.amount); } else { if (request.token == nativeWrap) { // withdraw then transfer native to receiver IWETH(nativeWrap).withdraw(request.amount); (bool sent, ) = request.receiver.call{value: request.amount, gas: 50000}(""); require(sent, "failed to relay native token"); } else { IERC20(request.token).safeTransfer(request.receiver, request.amount); } } emit Relay( transferId, request.sender, request.receiver, request.token, request.amount, request.srcChainId, request.srcTransferId ); } function setMinSend(address[] calldata _tokens, uint256[] calldata _amounts) external onlyGovernor { require(_tokens.length == _amounts.length, "length mismatch"); for (uint256 i = 0; i < _tokens.length; i++) { minSend[_tokens[i]] = _amounts[i]; emit MinSendUpdated(_tokens[i], _amounts[i]); } } function setMaxSend(address[] calldata _tokens, uint256[] calldata _amounts) external onlyGovernor { require(_tokens.length == _amounts.length, "length mismatch"); for (uint256 i = 0; i < _tokens.length; i++) { maxSend[_tokens[i]] = _amounts[i]; emit MaxSendUpdated(_tokens[i], _amounts[i]); } } function setMinimalMaxSlippage(uint32 _minimalMaxSlippage) external onlyGovernor { minimalMaxSlippage = _minimalMaxSlippage; } // This is needed to receive ETH when calling `IWETH.withdraw` receive() external payable {} } // SPDX-License-Identifier: GPL-3.0-only pragma solidity 0.8.9; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/security/Pausable.sol"; abstract contract Pauser is Ownable, Pausable { mapping(address => bool) public pausers; event PauserAdded(address account); event PauserRemoved(address account); constructor() { _addPauser(msg.sender); } modifier onlyPauser() { require(isPauser(msg.sender), "Caller is not pauser"); _; } function pause() public onlyPauser { _pause(); } function unpause() public onlyPauser { _unpause(); } function isPauser(address account) public view returns (bool) { return pausers[account]; } function addPauser(address account) public onlyOwner { _addPauser(account); } function removePauser(address account) public onlyOwner { _removePauser(account); } function renouncePauser() public { _removePauser(msg.sender); } function _addPauser(address account) private { require(!isPauser(account), "Account is already pauser"); pausers[account] = true; emit PauserAdded(account); } function _removePauser(address account) private { require(isPauser(account), "Account is not pauser"); pausers[account] = false; emit PauserRemoved(account); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity 0.8.9; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "./libraries/PbPool.sol"; import "./Signers.sol"; import "./Pauser.sol"; // add liquidity and withdraw // withdraw can be used by user or liquidity provider interface IWETH { function withdraw(uint256) external; } contract Pool is Signers, ReentrancyGuard, Pauser { using SafeERC20 for IERC20; uint64 public addseq; // ensure unique LiquidityAdded event, start from 1 mapping(address => uint256) public minAdd; // add _amount must > minAdd // map of successful withdraws, if true means already withdrew money or added to delayedTransfers mapping(bytes32 => bool) public withdraws; uint256 public epochLength; // seconds mapping(address => uint256) public epochVolumes; // key is token mapping(address => uint256) public epochVolumeCaps; // key is token mapping(address => uint256) public lastOpTimestamps; // key is token struct delayedTransfer { address receiver; address token; uint256 amount; uint256 timestamp; } mapping(bytes32 => delayedTransfer) public delayedTransfers; mapping(address => uint256) public delayThresholds; uint256 public delayPeriod; // in seconds // erc20 wrap of gas token of this chain, eg. WETH, when relay ie. pay out, // if request.token equals this, will withdraw and send native token to receiver // note we don't check whether it's zero address. when this isn't set, and request.token // is all 0 address, guarantee fail address public nativeWrap; mapping(address => bool) public governors; // liquidity events event LiquidityAdded( uint64 seqnum, address provider, address token, uint256 amount // how many tokens were added ); event WithdrawDone( bytes32 withdrawId, uint64 seqnum, address receiver, address token, uint256 amount, bytes32 refid ); event DelayedTransferAdded(bytes32 id); event DelayedTransferExecuted(bytes32 id, address receiver, address token, uint256 amount); // gov events event GovernorAdded(address account); event GovernorRemoved(address account); event EpochLengthUpdated(uint256 length); event EpochVolumeUpdated(address token, uint256 cap); event DelayPeriodUpdated(uint256 period); event DelayThresholdUpdated(address token, uint256 threshold); event MinAddUpdated(address token, uint256 amount); constructor() { _addGovernor(msg.sender); } function addLiquidity(address _token, uint256 _amount) external nonReentrant whenNotPaused { addseq += 1; require(_amount > minAdd[_token], "amount too small"); IERC20(_token).safeTransferFrom(msg.sender, address(this), _amount); emit LiquidityAdded(addseq, msg.sender, _token, _amount); } function withdraw( bytes calldata _wdmsg, bytes[] calldata _sigs, address[] calldata _signers, uint256[] calldata _powers ) external whenNotPaused { verifySigs(_wdmsg, _sigs, _signers, _powers); // decode and check wdmsg PbPool.WithdrawMsg memory wdmsg = PbPool.decWithdrawMsg(_wdmsg); require(wdmsg.chainid == block.chainid, "dst chainId mismatch"); bytes32 wdId = keccak256( abi.encodePacked(wdmsg.chainid, wdmsg.seqnum, wdmsg.receiver, wdmsg.token, wdmsg.amount) ); require(withdraws[wdId] == false, "withdraw already succeeded"); withdraws[wdId] = true; updateVolume(wdmsg.token, wdmsg.amount); uint256 delayThreshold = delayThresholds[wdmsg.token]; if (delayThreshold > 0 && wdmsg.amount > delayThreshold) { addDelayedTransfer(wdId, wdmsg.receiver, wdmsg.token, wdmsg.amount); } else { IERC20(wdmsg.token).safeTransfer(wdmsg.receiver, wdmsg.amount); } emit WithdrawDone(wdId, wdmsg.seqnum, wdmsg.receiver, wdmsg.token, wdmsg.amount, wdmsg.refid); } function executeDelayedTransfer(bytes32 id) external whenNotPaused { delayedTransfer memory transfer = delayedTransfers[id]; require(transfer.timestamp > 0, "transfer not exist"); require(block.timestamp > transfer.timestamp + delayPeriod, "transfer still locked"); delete delayedTransfers[id]; if (transfer.token == nativeWrap && withdraws[id] == false) { // withdraw then transfer native to receiver IWETH(nativeWrap).withdraw(transfer.amount); (bool sent, ) = transfer.receiver.call{value: transfer.amount, gas: 50000}(""); require(sent, "failed to relay native token"); } else { IERC20(transfer.token).safeTransfer(transfer.receiver, transfer.amount); } emit DelayedTransferExecuted(id, transfer.receiver, transfer.token, transfer.amount); } function setEpochLength(uint256 _length) external onlyGovernor { epochLength = _length; emit EpochLengthUpdated(_length); } function setEpochVolumeCaps(address[] calldata _tokens, uint256[] calldata _caps) external onlyGovernor { require(_tokens.length == _caps.length, "length mismatch"); for (uint256 i = 0; i < _tokens.length; i++) { epochVolumeCaps[_tokens[i]] = _caps[i]; emit EpochVolumeUpdated(_tokens[i], _caps[i]); } } function setDelayThresholds(address[] calldata _tokens, uint256[] calldata _thresholds) external onlyGovernor { require(_tokens.length == _thresholds.length, "length mismatch"); for (uint256 i = 0; i < _tokens.length; i++) { delayThresholds[_tokens[i]] = _thresholds[i]; emit DelayThresholdUpdated(_tokens[i], _thresholds[i]); } } function setDelayPeriod(uint256 _period) external onlyGovernor { delayPeriod = _period; emit DelayPeriodUpdated(_period); } function setMinAdd(address[] calldata _tokens, uint256[] calldata _amounts) external onlyGovernor { require(_tokens.length == _amounts.length, "length mismatch"); for (uint256 i = 0; i < _tokens.length; i++) { minAdd[_tokens[i]] = _amounts[i]; emit MinAddUpdated(_tokens[i], _amounts[i]); } } function updateVolume(address _token, uint256 _amount) internal { if (epochLength == 0) { return; } uint256 cap = epochVolumeCaps[_token]; if (cap == 0) { return; } uint256 volume = epochVolumes[_token]; uint256 timestamp = block.timestamp; uint256 epochStartTime = (timestamp / epochLength) * epochLength; if (lastOpTimestamps[_token] < epochStartTime) { volume = _amount; } else { volume += _amount; } require(volume <= cap, "volume exceeds cap"); epochVolumes[_token] = volume; lastOpTimestamps[_token] = timestamp; } function addDelayedTransfer( bytes32 id, address receiver, address token, uint256 amount ) internal { // note: rely on caller for id uniquess // current ids are relay transfer id and withdrawal id delayedTransfers[id] = delayedTransfer({ receiver: receiver, token: token, amount: amount, timestamp: block.timestamp }); emit DelayedTransferAdded(id); } // set nativeWrap, for relay requests, if token == nativeWrap, will withdraw first then transfer native to receiver function setWrap(address _weth) external onlyOwner { nativeWrap = _weth; } modifier onlyGovernor() { require(isGovernor(msg.sender), "Caller is not governor"); _; } function isGovernor(address _account) public view returns (bool) { return governors[_account]; } function addGovener(address _account) public onlyOwner { _addGovernor(_account); } function removeGovener(address _account) public onlyOwner { _removeGovernor(_account); } function renounceGovener() public { _removeGovernor(msg.sender); } function _addGovernor(address _account) private { require(!isGovernor(_account), "Account is already governor"); governors[_account] = true; emit GovernorAdded(_account); } function _removeGovernor(address _account) private { require(isGovernor(_account), "Account is not governor"); governors[_account] = false; emit GovernorRemoved(_account); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity 0.8.9; import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "./interfaces/ISigsVerifier.sol"; contract Signers is Ownable, ISigsVerifier { using ECDSA for bytes32; bytes32 public ssHash; // reset can be called by the owner address for emergency recovery uint256 public resetTime; uint256 public noticePeriod; // advance notice period as seconds for reset uint256 constant MAX_INT = 2**256 - 1; event SignersUpdated(address[] _signers, uint256[] _powers); event ResetNotification(uint256 resetTime); /** * @notice Verifies that a message is signed by a quorum among the signers * The sigs must be sorted by signer addresses in ascending order. * @param _msg signed message * @param _sigs list of signatures sorted by signer addresses * @param _signers sorted list of current signers * @param _powers powers of current signers */ function verifySigs( bytes memory _msg, bytes[] calldata _sigs, address[] calldata _signers, uint256[] calldata _powers ) public view override { bytes32 h = keccak256(abi.encodePacked(_signers, _powers)); require(ssHash == h, "Mismatch current signers"); _verifySignedPowers(keccak256(_msg).toEthSignedMessageHash(), _sigs, _signers, _powers); } /** * @notice Update new signers. * @param _newSigners sorted list of new signers * @param _curPowers powers of new signers * @param _sigs list of signatures sorted by signer addresses * @param _curSigners sorted list of current signers * @param _curPowers powers of current signers */ function updateSigners( address[] calldata _newSigners, uint256[] calldata _newPowers, bytes[] calldata _sigs, address[] calldata _curSigners, uint256[] calldata _curPowers ) external { verifySigs(abi.encodePacked(_newSigners, _newPowers), _sigs, _curSigners, _curPowers); _updateSigners(_newSigners, _newPowers); } /** * @notice reset signers, only used for init setup and emergency recovery */ function resetSigners(address[] calldata _signers, uint256[] calldata _powers) external onlyOwner { require(block.timestamp > resetTime, "not reach reset time"); resetTime = MAX_INT; _updateSigners(_signers, _powers); } function notifyResetSigners() external onlyOwner { resetTime = block.timestamp + noticePeriod; emit ResetNotification(resetTime); } function increaseNoticePeriod(uint256 period) external onlyOwner { require(period > noticePeriod, "notice period can only be increased"); noticePeriod = period; } // separate from verifySigs func to avoid "stack too deep" issue function _verifySignedPowers( bytes32 _hash, bytes[] calldata _sigs, address[] calldata _signers, uint256[] calldata _powers ) private pure { require(_signers.length == _powers.length, "signers and powers length not match"); uint256 totalPower; // sum of all signer.power for (uint256 i = 0; i < _signers.length; i++) { totalPower += _powers[i]; } uint256 quorum = (totalPower * 2) / 3 + 1; uint256 signedPower; // sum of signer powers who are in sigs address prev = address(0); uint256 index = 0; for (uint256 i = 0; i < _sigs.length; i++) { address signer = _hash.recover(_sigs[i]); require(signer > prev, "signers not in ascending order"); prev = signer; // now find match signer add its power while (signer > _signers[index]) { index += 1; require(index < _signers.length, "signer not found"); } if (signer == _signers[index]) { signedPower += _powers[index]; } if (signedPower >= quorum) { // return early to save gas return; } } revert("quorum not reached"); } function _updateSigners(address[] calldata _signers, uint256[] calldata _powers) private { require(_signers.length == _powers.length, "signers and powers length not match"); address prev = address(0); for (uint256 i = 0; i < _signers.length; i++) { require(_signers[i] > prev, "New signers not in ascending order"); prev = _signers[i]; } ssHash = keccak256(abi.encodePacked(_signers, _powers)); emit SignersUpdated(_signers, _powers); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity 0.8.9; interface ISigsVerifier { /** * @notice Verifies that a message is signed by a quorum among the signers. * @param _msg signed message * @param _sigs list of signatures sorted by signer addresses * @param _signers sorted list of current signers * @param _powers powers of current signers */ function verifySigs( bytes memory _msg, bytes[] calldata _sigs, address[] calldata _signers, uint256[] calldata _powers ) external view; } // SPDX-License-Identifier: GPL-3.0-only pragma solidity 0.8.9; // runtime proto sol library library Pb { enum WireType { Varint, Fixed64, LengthDelim, StartGroup, EndGroup, Fixed32 } struct Buffer { uint256 idx; // the start index of next read. when idx=b.length, we're done bytes b; // hold serialized proto msg, readonly } // create a new in-memory Buffer object from raw msg bytes function fromBytes(bytes memory raw) internal pure returns (Buffer memory buf) { buf.b = raw; buf.idx = 0; } // whether there are unread bytes function hasMore(Buffer memory buf) internal pure returns (bool) { return buf.idx < buf.b.length; } // decode current field number and wiretype function decKey(Buffer memory buf) internal pure returns (uint256 tag, WireType wiretype) { uint256 v = decVarint(buf); tag = v / 8; wiretype = WireType(v & 7); } // count tag occurrences, return an array due to no memory map support // have to create array for (maxtag+1) size. cnts[tag] = occurrences // should keep buf.idx unchanged because this is only a count function function cntTags(Buffer memory buf, uint256 maxtag) internal pure returns (uint256[] memory cnts) { uint256 originalIdx = buf.idx; cnts = new uint256[](maxtag + 1); // protobuf's tags are from 1 rather than 0 uint256 tag; WireType wire; while (hasMore(buf)) { (tag, wire) = decKey(buf); cnts[tag] += 1; skipValue(buf, wire); } buf.idx = originalIdx; } // read varint from current buf idx, move buf.idx to next read, return the int value function decVarint(Buffer memory buf) internal pure returns (uint256 v) { bytes10 tmp; // proto int is at most 10 bytes (7 bits can be used per byte) bytes memory bb = buf.b; // get buf.b mem addr to use in assembly v = buf.idx; // use v to save one additional uint variable assembly { tmp := mload(add(add(bb, 32), v)) // load 10 bytes from buf.b[buf.idx] to tmp } uint256 b; // store current byte content v = 0; // reset to 0 for return value for (uint256 i = 0; i < 10; i++) { assembly { b := byte(i, tmp) // don't use tmp[i] because it does bound check and costs extra } v |= (b & 0x7F) << (i * 7); if (b & 0x80 == 0) { buf.idx += i + 1; return v; } } revert(); // i=10, invalid varint stream } // read length delimited field and return bytes function decBytes(Buffer memory buf) internal pure returns (bytes memory b) { uint256 len = decVarint(buf); uint256 end = buf.idx + len; require(end <= buf.b.length); // avoid overflow b = new bytes(len); bytes memory bufB = buf.b; // get buf.b mem addr to use in assembly uint256 bStart; uint256 bufBStart = buf.idx; assembly { bStart := add(b, 32) bufBStart := add(add(bufB, 32), bufBStart) } for (uint256 i = 0; i < len; i += 32) { assembly { mstore(add(bStart, i), mload(add(bufBStart, i))) } } buf.idx = end; } // return packed ints function decPacked(Buffer memory buf) internal pure returns (uint256[] memory t) { uint256 len = decVarint(buf); uint256 end = buf.idx + len; require(end <= buf.b.length); // avoid overflow // array in memory must be init w/ known length // so we have to create a tmp array w/ max possible len first uint256[] memory tmp = new uint256[](len); uint256 i = 0; // count how many ints are there while (buf.idx < end) { tmp[i] = decVarint(buf); i++; } t = new uint256[](i); // init t with correct length for (uint256 j = 0; j < i; j++) { t[j] = tmp[j]; } return t; } // move idx pass current value field, to beginning of next tag or msg end function skipValue(Buffer memory buf, WireType wire) internal pure { if (wire == WireType.Varint) { decVarint(buf); } else if (wire == WireType.LengthDelim) { uint256 len = decVarint(buf); buf.idx += len; // skip len bytes value data require(buf.idx <= buf.b.length); // avoid overflow } else { revert(); } // unsupported wiretype } // type conversion help utils function _bool(uint256 x) internal pure returns (bool v) { return x != 0; } function _uint256(bytes memory b) internal pure returns (uint256 v) { require(b.length <= 32); // b's length must be smaller than or equal to 32 assembly { v := mload(add(b, 32)) } // load all 32bytes to v v = v >> (8 * (32 - b.length)); // only first b.length is valid } function _address(bytes memory b) internal pure returns (address v) { v = _addressPayable(b); } function _addressPayable(bytes memory b) internal pure returns (address payable v) { require(b.length == 20); //load 32bytes then shift right 12 bytes assembly { v := div(mload(add(b, 32)), 0x1000000000000000000000000) } } function _bytes32(bytes memory b) internal pure returns (bytes32 v) { require(b.length == 32); assembly { v := mload(add(b, 32)) } } // uint[] to uint8[] function uint8s(uint256[] memory arr) internal pure returns (uint8[] memory t) { t = new uint8[](arr.length); for (uint256 i = 0; i < t.length; i++) { t[i] = uint8(arr[i]); } } function uint32s(uint256[] memory arr) internal pure returns (uint32[] memory t) { t = new uint32[](arr.length); for (uint256 i = 0; i < t.length; i++) { t[i] = uint32(arr[i]); } } function uint64s(uint256[] memory arr) internal pure returns (uint64[] memory t) { t = new uint64[](arr.length); for (uint256 i = 0; i < t.length; i++) { t[i] = uint64(arr[i]); } } function bools(uint256[] memory arr) internal pure returns (bool[] memory t) { t = new bool[](arr.length); for (uint256 i = 0; i < t.length; i++) { t[i] = arr[i] != 0; } } } // SPDX-License-Identifier: GPL-3.0-only // Code generated by protoc-gen-sol. DO NOT EDIT. // source: bridge.proto pragma solidity 0.8.9; import "./Pb.sol"; library PbBridge { using Pb for Pb.Buffer; // so we can call Pb funcs on Buffer obj struct Relay { address sender; // tag: 1 address receiver; // tag: 2 address token; // tag: 3 uint256 amount; // tag: 4 uint64 srcChainId; // tag: 5 uint64 dstChainId; // tag: 6 bytes32 srcTransferId; // tag: 7 } // end struct Relay function decRelay(bytes memory raw) internal pure returns (Relay memory m) { Pb.Buffer memory buf = Pb.fromBytes(raw); uint256 tag; Pb.WireType wire; while (buf.hasMore()) { (tag, wire) = buf.decKey(); if (false) {} // solidity has no switch/case else if (tag == 1) { m.sender = Pb._address(buf.decBytes()); } else if (tag == 2) { m.receiver = Pb._address(buf.decBytes()); } else if (tag == 3) { m.token = Pb._address(buf.decBytes()); } else if (tag == 4) { m.amount = Pb._uint256(buf.decBytes()); } else if (tag == 5) { m.srcChainId = uint64(buf.decVarint()); } else if (tag == 6) { m.dstChainId = uint64(buf.decVarint()); } else if (tag == 7) { m.srcTransferId = Pb._bytes32(buf.decBytes()); } else { buf.skipValue(wire); } // skip value of unknown tag } } // end decoder Relay } // SPDX-License-Identifier: GPL-3.0-only // Code generated by protoc-gen-sol. DO NOT EDIT. // source: contracts/libraries/proto/pool.proto pragma solidity 0.8.9; import "./Pb.sol"; library PbPool { using Pb for Pb.Buffer; // so we can call Pb funcs on Buffer obj struct WithdrawMsg { uint64 chainid; // tag: 1 uint64 seqnum; // tag: 2 address receiver; // tag: 3 address token; // tag: 4 uint256 amount; // tag: 5 bytes32 refid; // tag: 6 } // end struct WithdrawMsg function decWithdrawMsg(bytes memory raw) internal pure returns (WithdrawMsg memory m) { Pb.Buffer memory buf = Pb.fromBytes(raw); uint256 tag; Pb.WireType wire; while (buf.hasMore()) { (tag, wire) = buf.decKey(); if (false) {} // solidity has no switch/case else if (tag == 1) { m.chainid = uint64(buf.decVarint()); } else if (tag == 2) { m.seqnum = uint64(buf.decVarint()); } else if (tag == 3) { m.receiver = Pb._address(buf.decBytes()); } else if (tag == 4) { m.token = Pb._address(buf.decBytes()); } else if (tag == 5) { m.amount = Pb._uint256(buf.decBytes()); } else if (tag == 6) { m.refid = Pb._bytes32(buf.decBytes()); } else { buf.skipValue(wire); } // skip value of unknown tag } } // end decoder WithdrawMsg }
Update new signers. _newSigners sorted list of new signers _curPowers powers of new signers _sigs list of signatures sorted by signer addresses _curSigners sorted list of current signers _curPowers powers of current signers/
function updateSigners( address[] calldata _newSigners, uint256[] calldata _newPowers, bytes[] calldata _sigs, address[] calldata _curSigners, uint256[] calldata _curPowers ) external { verifySigs(abi.encodePacked(_newSigners, _newPowers), _sigs, _curSigners, _curPowers); _updateSigners(_newSigners, _newPowers); }
6,113,172
// SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.11; import "./spool/SpoolExternal.sol"; /** * @notice Implementation of the central Spool contract. * * @dev * The Spool implementation is the central part of the system. * All the assets flow through this contract and are deposited * to the integrated protocols. * * Spool implementation consists of following contracts: * 1. BaseStorage: stores common variables with all the strategy adapters (they are execuret as delegatecode) * 2. SpoolBase: holds Spool state variables and provides some of the common vault functions * 3. SpoolStrategy: implements the logic of how to interact with the strategies * 4. SpoolDoHardWork: implements functions to process the do hard work * 5. SpoolReallocation: adjusts vault reallocation that takes place at the next do hard work * 6. SpoolExternal: exposes functons to interact with the Spool from the vault (deposit/withdraw/redeem) * 7. Spool: implements a constructor to deploy a contracts */ contract Spool is SpoolExternal { /** * @notice Initializes the central Spool contract values * * @param _spoolOwner the spool owner contract * @param _controller responsible for providing the source of truth * @param _fastWithdraw allows fast withdraw of user shares */ constructor( ISpoolOwner _spoolOwner, IController _controller, address _fastWithdraw ) SpoolBase( _spoolOwner, _controller, _fastWithdraw ) {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow * checks. * * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such an operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. * * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing * all math on `uint256` and `int256` and then downcasting. */ library SafeCast { /** * @dev Returns the downcasted uint224 from uint256, reverting on * overflow (when the input is greater than largest uint224). * * Counterpart to Solidity's `uint224` operator. * * Requirements: * * - input must fit into 224 bits */ function toUint224(uint256 value) internal pure returns (uint224) { require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits"); return uint224(value); } /** * @dev Returns the downcasted uint192 from uint256, reverting on * overflow (when the input is greater than largest uint192). * * Counterpart to Solidity's `uint192` operator. * * Requirements: * * - input must fit into 192 bits */ function toUint192(uint256 value) internal pure returns (uint192) { require(value <= type(uint192).max, "SafeCast: value doesn't fit in 128 bits"); return uint192(value); } /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits"); return uint128(value); } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.11; import "../external/@openzeppelin/token/ERC20/IERC20.sol"; import "./ISwapData.sol"; interface IBaseStrategy { function underlying() external view returns (IERC20); function getStrategyBalance() external view returns (uint128); function getStrategyUnderlyingWithRewards() external view returns(uint128); function process(uint256[] calldata, bool, SwapData[] calldata) external; function processReallocation(uint256[] calldata, ProcessReallocationData calldata) external returns(uint128); function processDeposit(uint256[] calldata) external; function fastWithdraw(uint128, uint256[] calldata, SwapData[] calldata) external returns(uint128); function claimRewards(SwapData[] calldata) external; function emergencyWithdraw(address recipient, uint256[] calldata data) external; function initialize() external; function disable() external; } struct ProcessReallocationData { uint128 sharesToWithdraw; uint128 optimizedShares; uint128 optimizedWithdrawnAmount; } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.11; import "../external/@openzeppelin/token/ERC20/IERC20.sol"; interface IController { /* ========== FUNCTIONS ========== */ function strategies(uint256 i) external view returns (address); function validStrategy(address strategy) external view returns (bool); function validVault(address vault) external view returns (bool); function getStrategiesCount() external view returns(uint8); function supportedUnderlying(IERC20 underlying) external view returns (bool); function getAllStrategies() external view returns (address[] memory); function verifyStrategies(address[] calldata _strategies) external view; function transferToSpool( address transferFrom, uint256 amount ) external; function checkPaused() external view; /* ========== EVENTS ========== */ event EmergencyWithdrawStrategy(address indexed strategy); event EmergencyRecipientUpdated(address indexed recipient); event EmergencyWithdrawerUpdated(address indexed withdrawer, bool set); event PauserUpdated(address indexed user, bool set); event UnpauserUpdated(address indexed user, bool set); event VaultCreated(address indexed vault, address underlying, address[] strategies, uint256[] proportions, uint16 vaultFee, address riskProvider, int8 riskTolerance); event StrategyAdded(address strategy); event StrategyRemoved(address strategy); event VaultInvalid(address vault); event DisableStrategy(address strategy); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.11; interface ISpoolOwner { function isSpoolOwner(address user) external view returns(bool); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.11; /** * @notice Strict holding information how to swap the asset * @member slippage minumum output amount * @member path swap path, first byte represents an action (e.g. Uniswap V2 custom swap), rest is swap specific path */ struct SwapData { uint256 slippage; // min amount out bytes path; // 1st byte is action, then path } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.11; import "./vault/IVaultRestricted.sol"; import "./vault/IVaultIndexActions.sol"; import "./vault/IRewardDrip.sol"; import "./vault/IVaultBase.sol"; import "./vault/IVaultImmutable.sol"; interface IVault is IVaultRestricted, IVaultIndexActions, IRewardDrip, IVaultBase, IVaultImmutable {} // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.11; interface ISpoolBase { /* ========== FUNCTIONS ========== */ function getCompletedGlobalIndex() external view returns(uint24); function getActiveGlobalIndex() external view returns(uint24); function isMidReallocation() external view returns (bool); /* ========== EVENTS ========== */ event ReallocationTableUpdated( uint24 indexed index, bytes32 reallocationTableHash ); event ReallocationTableUpdatedWithTable( uint24 indexed index, bytes32 reallocationTableHash, uint256[][] reallocationTable ); event DoHardWorkCompleted(uint24 indexed index); event SetAllocationProvider(address actor, bool isAllocationProvider); event SetIsDoHardWorker(address actor, bool isDoHardWorker); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.11; interface ISpoolDoHardWork { /* ========== EVENTS ========== */ event DoHardWorkStrategyCompleted(address indexed strat, uint256 indexed index); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.11; import "../ISwapData.sol"; interface ISpoolExternal { /* ========== FUNCTIONS ========== */ function deposit(address strategy, uint128 amount, uint256 index) external; function withdraw(address strategy, uint256 vaultProportion, uint256 index) external; function fastWithdrawStrat(address strat, address underlying, uint256 shares, uint256[] calldata slippages, SwapData[] calldata swapData) external returns(uint128); function redeem(address strat, uint256 index) external returns (uint128, uint128); function redeemUnderlying(uint128 amount) external; function redeemReallocation(address[] calldata vaultStrategies, uint256 depositProportions, uint256 index) external; function removeShares(address[] calldata vaultStrategies, uint256 vaultProportion) external returns(uint128[] memory); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.11; interface ISpoolReallocation { event StartReallocation(uint24 indexed index); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.11; interface ISpoolStrategy { /* ========== FUNCTIONS ========== */ function getUnderlying(address strat) external returns (uint128); function getVaultTotalUnderlyingAtIndex(address strat, uint256 index) external view returns(uint128); function addStrategy(address strat) external; function disableStrategy(address strategy, bool skipDisable) external; function runDisableStrategy(address strategy) external; function emergencyWithdraw( address strat, address withdrawRecipient, uint256[] calldata data ) external; } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.11; import "../../external/@openzeppelin/token/ERC20/IERC20.sol"; interface IRewardDrip { /* ========== STRUCTS ========== */ // The reward configuration struct, containing all the necessary data of a typical Synthetix StakingReward contract struct RewardConfiguration { uint32 rewardsDuration; uint32 periodFinish; uint192 rewardRate; // rewards per second multiplied by accuracy uint32 lastUpdateTime; uint224 rewardPerTokenStored; mapping(address => uint256) userRewardPerTokenPaid; mapping(address => uint256) rewards; } /* ========== FUNCTIONS ========== */ function getActiveRewards(address account) external; function tokenBlacklist(IERC20 token) view external returns(bool); /* ========== EVENTS ========== */ event RewardPaid(IERC20 token, address indexed user, uint256 reward); event RewardAdded(IERC20 indexed token, uint256 amount, uint256 duration); event RewardExtended(IERC20 indexed token, uint256 amount, uint256 leftover, uint256 duration, uint32 periodFinish); event RewardRemoved(IERC20 indexed token); event PeriodFinishUpdated(IERC20 indexed token, uint32 periodFinish); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.11; import "./IVaultDetails.sol"; interface IVaultBase { /* ========== FUNCTIONS ========== */ function initialize(VaultInitializable calldata vaultInitializable) external; /* ========== STRUCTS ========== */ struct User { uint128 instantDeposit; // used for calculating rewards uint128 activeDeposit; // users deposit after deposit process and claim uint128 owed; // users owed underlying amount after withdraw has been processed and claimed uint128 withdrawnDeposits; // users withdrawn deposit, used to calculate performance fees uint128 shares; // users shares after deposit process and claim } /* ========== EVENTS ========== */ event Claimed(address indexed member, uint256 claimAmount); event Deposit(address indexed member, uint256 indexed index, uint256 amount); event Withdraw(address indexed member, uint256 indexed index, uint256 shares); event WithdrawFast(address indexed member, uint256 shares); event StrategyRemoved(uint256 i, address strategy); event TransferVaultOwner(address owner); event LowerVaultFee(uint16 fee); event UpdateName(string name); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.11; struct VaultDetails { address underlying; address[] strategies; uint256[] proportions; address creator; uint16 vaultFee; address riskProvider; int8 riskTolerance; string name; } struct VaultInitializable { string name; address owner; uint16 fee; address[] strategies; uint256[] proportions; } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.11; import "../../external/@openzeppelin/token/ERC20/IERC20.sol"; struct VaultImmutables { IERC20 underlying; address riskProvider; int8 riskTolerance; } interface IVaultImmutable { /* ========== FUNCTIONS ========== */ function underlying() external view returns (IERC20); function riskProvider() external view returns (address); function riskTolerance() external view returns (int8); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.11; interface IVaultIndexActions { /* ========== STRUCTS ========== */ struct IndexAction { uint128 depositAmount; uint128 withdrawShares; } struct LastIndexInteracted { uint128 index1; uint128 index2; } struct Redeem { uint128 depositShares; uint128 withdrawnAmount; } /* ========== EVENTS ========== */ event VaultRedeem(uint indexed globalIndex); event UserRedeem(address indexed member, uint indexed globalIndex); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.11; interface IVaultRestricted { /* ========== FUNCTIONS ========== */ function reallocate( address[] calldata vaultStrategies, uint256 newVaultProportions, uint256 finishedIndex, uint24 activeIndex ) external returns (uint256[] memory, uint256); function payFees(uint256 profit) external returns (uint256 feesPaid); /* ========== EVENTS ========== */ event Reallocate(uint24 indexed index, uint256 newProportions); } // SPDX-License-Identifier: MIT pragma solidity 0.8.11; library Bitwise { function get8BitUintByIndex(uint256 bitwiseData, uint256 i) internal pure returns(uint256) { return (bitwiseData >> (8 * i)) & type(uint8).max; } // 14 bits is used for strategy proportions in a vault as FULL_PERCENT is 10_000 function get14BitUintByIndex(uint256 bitwiseData, uint256 i) internal pure returns(uint256) { return (bitwiseData >> (14 * i)) & (16_383); // 16.383 is 2^14 - 1 } function set14BitUintByIndex(uint256 bitwiseData, uint256 i, uint256 num14bit) internal pure returns(uint256) { return bitwiseData + (num14bit << (14 * i)); } function reset14BitUintByIndex(uint256 bitwiseData, uint256 i) internal pure returns(uint256) { return bitwiseData & (~(16_383 << (14 * i))); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.11; /** * @notice Library to provide utils for hashing and hash compatison of Spool related data */ library Hash { function hashReallocationTable(uint256[][] memory reallocationTable) internal pure returns(bytes32) { return keccak256(abi.encode(reallocationTable)); } function hashStrategies(address[] memory strategies) internal pure returns(bytes32) { return keccak256(abi.encodePacked(strategies)); } function sameStrategies(address[] memory strategies1, address[] memory strategies2) internal pure returns(bool) { return hashStrategies(strategies1) == hashStrategies(strategies2); } function sameStrategies(address[] memory strategies, bytes32 strategiesHash) internal pure returns(bool) { return hashStrategies(strategies) == strategiesHash; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.11; import "../external/@openzeppelin/utils/SafeCast.sol"; /** * @notice A collection of custom math ustils used throughout the system */ library Math { function min(uint256 a, uint256 b) internal pure returns (uint256) { return a > b ? b : a; } function getProportion128(uint256 mul1, uint256 mul2, uint256 div) internal pure returns (uint128) { return SafeCast.toUint128(((mul1 * mul2) / div)); } function getProportion128Unchecked(uint256 mul1, uint256 mul2, uint256 div) internal pure returns (uint128) { unchecked { return uint128((mul1 * mul2) / div); } } } // SPDX-License-Identifier: MIT pragma solidity 0.8.11; /** @notice Handle setting zero value in a storage word as uint128 max value. * * @dev * The purpose of this is to avoid resetting a storage word to the zero value; * the gas cost of re-initializing the value is the same as setting the word originally. * so instead, if word is to be set to zero, we set it to uint128 max. * * - anytime a word is loaded from storage: call "get" * - anytime a word is written to storage: call "set" * - common operations on uints are also bundled here. * * NOTE: This library should ONLY be used when reading or writing *directly* from storage. */ library Max128Bit { uint128 internal constant ZERO = type(uint128).max; function get(uint128 a) internal pure returns(uint128) { return (a == ZERO) ? 0 : a; } function set(uint128 a) internal pure returns(uint128){ return (a == 0) ? ZERO : a; } function add(uint128 a, uint128 b) internal pure returns(uint128 c){ a = get(a); c = set(a + b); } } // SPDX-License-Identifier: BUSL-1.1 import "../interfaces/ISwapData.sol"; pragma solidity 0.8.11; /// @notice Strategy struct for all strategies struct Strategy { uint128 totalShares; /// @notice Denotes strategy completed index uint24 index; /// @notice Denotes whether strategy is removed /// @dev after removing this value can never change, hence strategy cannot be added back again bool isRemoved; /// @notice Pending geposit amount and pending shares withdrawn by all users for next index Pending pendingUser; /// @notice Used if strategies "dohardwork" hasn't been executed yet in the current index Pending pendingUserNext; /// @dev Usually a temp variable when compounding mapping(address => uint256) pendingRewards; /// @dev Usually a temp variable when compounding uint128 pendingDepositReward; /// @notice Amount of lp tokens the strategy holds, NOTE: not all strategies use it uint256 lpTokens; // ----- REALLOCATION VARIABLES ----- bool isInDepositPhase; /// @notice Used to store amount of optimized shares, so they can be substracted at the end /// @dev Only for temporary use, should be reset to 0 in same transaction uint128 optimizedSharesWithdrawn; /// @dev Underlying amount pending to be deposited from other strategies at reallocation /// @dev resets after the strategy reallocation DHW is finished uint128 pendingReallocateDeposit; /// @notice Stores amount of optimized underlying amount when reallocating /// @dev resets after the strategy reallocation DHW is finished /// @dev This is "virtual" amount that was matched between this strategy and others when reallocating uint128 pendingReallocateOptimizedDeposit; // ------------------------------------ /// @notice Total underlying amoung at index mapping(uint256 => TotalUnderlying) totalUnderlying; /// @notice Batches stored after each DHW with index as a key /// @dev Holds information for vauls to redeem newly gained shares and withdrawn amounts belonging to users mapping(uint256 => Batch) batches; /// @notice Batches stored after each DHW reallocating (if strategy was set to reallocate) /// @dev Holds information for vauls to redeem newly gained shares and withdrawn shares to complete reallocation mapping(uint256 => BatchReallocation) reallocationBatches; /// @notice Vaults holding this strategy shares mapping(address => Vault) vaults; /// @notice Future proof storage mapping(bytes32 => AdditionalStorage) additionalStorage; /// @dev Make sure to reset it to 0 after emergency withdrawal uint256 emergencyPending; } /// @notice Unprocessed deposit underlying amount and strategy share amount from users struct Pending { uint128 deposit; uint128 sharesToWithdraw; } /// @notice Struct storing total underlying balance of a strategy for an index, along with total shares at same index struct TotalUnderlying { uint128 amount; uint128 totalShares; } /// @notice Stored after executing DHW for each index. /// @dev This is used for vaults to redeem their deposit. struct Batch { /// @notice total underlying deposited in index uint128 deposited; uint128 depositedReceived; uint128 depositedSharesReceived; uint128 withdrawnShares; uint128 withdrawnReceived; } /// @notice Stored after executing reallocation DHW each index. struct BatchReallocation { /// @notice Deposited amount received from reallocation uint128 depositedReallocation; /// @notice Received shares from reallocation uint128 depositedReallocationSharesReceived; /// @notice Used to know how much tokens was received for reallocating uint128 withdrawnReallocationReceived; /// @notice Amount of shares to withdraw for reallocation uint128 withdrawnReallocationShares; } /// @notice VaultBatches could be refactored so we only have 2 structs current and next (see how Pending is working) struct Vault { uint128 shares; /// @notice Withdrawn amount as part of the reallocation uint128 withdrawnReallocationShares; /// @notice Index to action mapping(uint256 => VaultBatch) vaultBatches; } /// @notice Stores deposited and withdrawn shares by the vault struct VaultBatch { /// @notice Vault index to deposited amount mapping uint128 deposited; /// @notice Vault index to withdrawn user shares mapping uint128 withdrawnShares; } /// @notice Used for reallocation calldata struct VaultData { address vault; uint8 strategiesCount; uint256 strategiesBitwise; uint256 newProportions; } /// @notice Calldata when executing reallocatin DHW /// @notice Used in the withdraw part of the reallocation DHW struct ReallocationWithdrawData { uint256[][] reallocationTable; StratUnderlyingSlippage[] priceSlippages; RewardSlippages[] rewardSlippages; uint256[] stratIndexes; uint256[][] slippages; } /// @notice Calldata when executing reallocatin DHW /// @notice Used in the deposit part of the reallocation DHW struct ReallocationData { uint256[] stratIndexes; uint256[][] slippages; } /// @notice In case some adapters need extra storage struct AdditionalStorage { uint256 value; address addressValue; uint96 value96; } /// @notice Strategy total underlying slippage, to verify validity of the strategy state struct StratUnderlyingSlippage { uint128 min; uint128 max; } /// @notice Containig information if and how to swap strategy rewards at the DHW /// @dev Passed in by the do-hard-worker struct RewardSlippages { bool doClaim; SwapData[] swapData; } /// @notice Helper struct to compare strategy share between eachother /// @dev Used for reallocation optimization of shares (strategy matching deposits and withdrawals between eachother when reallocating) struct PriceData { uint128 totalValue; uint128 totalShares; } /// @notice Strategy reallocation values after reallocation optimization of shares was calculated struct ReallocationShares { uint128[] optimizedWithdraws; uint128[] optimizedShares; uint128[] totalSharesWithdrawn; } /// @notice Shared storage for multiple strategies /// @dev This is used when strategies are part of the same proticil (e.g. Curve 3pool) struct StrategiesShared { uint184 value; uint32 lastClaimBlock; uint32 lastUpdateBlock; uint8 stratsCount; mapping(uint256 => address) stratAddresses; mapping(bytes32 => uint256) bytesValues; } /// @notice Base storage shared betweek Spool contract and Strategies /// @dev this way we can use same values when performing delegate call /// to strategy implementations from the Spool contract abstract contract BaseStorage { // ----- DHW VARIABLES ----- /// @notice Force while DHW (all strategies) to be executed in only one transaction /// @dev This is enforced to increase the gas efficiency of the system /// Can be removed by the DAO if gas gost of the strategies goes over the block limit bool internal forceOneTxDoHardWork; /// @notice Global index of the system /// @dev Insures the correct strategy DHW execution. /// Every strategy in the system must be equal or one less than global index value /// Global index increments by 1 on every do-hard-work uint24 public globalIndex; /// @notice number of strategies unprocessed (by the do-hard-work) in the current index to be completed uint8 internal doHardWorksLeft; // ----- REALLOCATION VARIABLES ----- /// @notice Used for offchain execution to get the new reallocation table. bool internal logReallocationTable; /// @notice number of withdrawal strategies unprocessed (by the do-hard-work) in the current index /// @dev only used when reallocating /// after it reaches 0, deposit phase of the reallocation can begin uint8 public withdrawalDoHardWorksLeft; /// @notice Index at which next reallocation is set uint24 public reallocationIndex; /// @notice 2D table hash containing information of how strategies should be reallocated between eachother /// @dev Created when allocation provider sets reallocation for the vaults /// This table is stored as a hash in the system and verified on reallocation DHW /// Resets to 0 after reallocation DHW is completed bytes32 internal reallocationTableHash; /// @notice Hash of all the strategies array in the system at the time when reallocation was set for index /// @dev this array is used for the whole reallocation period even if a strategy gets exploited when reallocating. /// This way we can remove the strategy from the system and not breaking the flow of the reallocaton /// Resets when DHW is completed bytes32 internal reallocationStrategiesHash; // ----------------------------------- /// @notice Denoting if an address is the do-hard-worker mapping(address => bool) public isDoHardWorker; /// @notice Denoting if an address is the allocation provider mapping(address => bool) public isAllocationProvider; /// @notice Strategies shared storage /// @dev used as a helper storage to save common inoramation mapping(bytes32 => StrategiesShared) internal strategiesShared; /// @notice Mapping of strategy implementation address to strategy system values mapping(address => Strategy) public strategies; /// @notice Flag showing if disable was skipped when a strategy has been removed /// @dev If true disable can still be run mapping(address => bool) internal _skippedDisable; /// @notice Flag showing if after removing a strategy emergency withdraw can still be executed /// @dev If true emergency withdraw can still be executed mapping(address => bool) internal _awaitingEmergencyWithdraw; } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.11; import "../external/@openzeppelin/token/ERC20/IERC20.sol"; /// @title Common Spool contracts constants abstract contract BaseConstants { /// @dev 2 digits precision uint256 internal constant FULL_PERCENT = 100_00; /// @dev Accuracy when doing shares arithmetics uint256 internal constant ACCURACY = 10**30; } /// @title Contains USDC token related values abstract contract USDC { /// @notice USDC token contract address IERC20 internal constant USDC_ADDRESS = IERC20(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.11; import "../interfaces/ISpoolOwner.sol"; /// @title Logic to help check whether the caller is the Spool owner abstract contract SpoolOwnable { /// @notice Contract that checks if address is Spool owner ISpoolOwner internal immutable spoolOwner; /** * @notice Sets correct initial values * @param _spoolOwner Spool owner contract address */ constructor(ISpoolOwner _spoolOwner) { require( address(_spoolOwner) != address(0), "SpoolOwnable::constructor: Spool owner contract address cannot be 0" ); spoolOwner = _spoolOwner; } /** * @notice Checks if caller is Spool owner * @return True if caller is Spool owner, false otherwise */ function isSpoolOwner() internal view returns(bool) { return spoolOwner.isSpoolOwner(msg.sender); } /// @notice Checks and throws if caller is not Spool owner function _onlyOwner() private view { require(isSpoolOwner(), "SpoolOwnable::onlyOwner: Caller is not the Spool owner"); } /// @notice Checks and throws if caller is not Spool owner modifier onlyOwner() { _onlyOwner(); _; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.11; import "../interfaces/IController.sol"; /// @title Facilitates checking if the system is paused or not abstract contract SpoolPausable { /* ========== STATE VARIABLES ========== */ /// @notice The controller contract that is consulted for a strategy's and vault's validity IController public immutable controller; /** * @notice Sets initial values * @param _controller Controller contract address */ constructor(IController _controller) { require( address(_controller) != address(0), "SpoolPausable::constructor: Controller contract address cannot be 0" ); controller = _controller; } /* ========== MODIFIERS ========== */ /// @notice Throws if system is paused modifier systemNotPaused() { controller.checkPaused(); _; } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.11; // extends import "../interfaces/spool/ISpoolBase.sol"; import "../shared/BaseStorage.sol"; import "../shared/SpoolOwnable.sol"; import "../shared/Constants.sol"; // libraries import "../libraries/Hash.sol"; // other imports import "../interfaces/IController.sol"; import "../shared/SpoolPausable.sol"; /** * @notice Implementation of the {ISpoolBase} interface. * * @dev * This implementation acts as the central code execution point of the Spool * system and is responsible for maintaining the balance sheet of each vault * based on the asynchronous deposit and withdraw system, redeeming vault * shares and withdrawals and performing doHardWork. */ abstract contract SpoolBase is ISpoolBase, BaseStorage, SpoolOwnable, SpoolPausable, BaseConstants { /* ========== STATE VARIABLES ========== */ /// @notice The fast withdraw contract that is used to quickly remove shares address internal immutable fastWithdraw; /* ========== CONSTRUCTOR ========== */ /** * @notice Sets the contract initial values * * @dev * Additionally, initializes the SPL reward data for * do hard work invocations. * * It performs certain pre-conditional validations to ensure the contract * has been initialized properly, such as valid addresses and reward configuration. * * @param _spoolOwner the spool owner contract address * @param _controller the controller contract address * @param _fastWithdraw the fast withdraw contract address */ constructor( ISpoolOwner _spoolOwner, IController _controller, address _fastWithdraw ) SpoolOwnable(_spoolOwner) SpoolPausable(_controller) { require( _fastWithdraw != address(0), "BaseSpool::constructor: FastWithdraw address cannot be 0" ); fastWithdraw = _fastWithdraw; globalIndex = 1; } /* ========== VIEWS ========== */ /** * @notice Checks whether Spool is mid reallocation * @return _isMidReallocation True if Spool is mid reallocation */ function isMidReallocation() public view override returns (bool _isMidReallocation) { if (reallocationIndex == globalIndex && !_isBatchComplete()) { _isMidReallocation = true; } } /** * @notice Returns strategy shares belonging to a vauld * @param strat Strategy address * @param vault Vault address * @return Shares for a specific vault - strategy combination */ function getStratVaultShares(address strat, address vault) external view returns(uint128) { return strategies[strat].vaults[vault].shares; } /** * @notice Returns completed index (all strategies in the do hard work have been processed) * @return Completed index */ function getCompletedGlobalIndex() public override view returns(uint24) { if (_isBatchComplete()) { return globalIndex; } return globalIndex - 1; } /** * @notice Returns next possible index to interact with * @return Next active global index */ function getActiveGlobalIndex() public override view returns(uint24) { return globalIndex + 1; } /** * @notice Check if batch complete * @return isComplete True if all strategies have the same index */ function _isBatchComplete() internal view returns(bool isComplete) { if (doHardWorksLeft == 0) { isComplete = true; } } /** * @notice Decode revert message * @param _returnData Data returned by delegatecall * @return Revert string */ function _getRevertMsg(bytes memory _returnData) internal pure returns (string memory) { // if the _res length is less than 68, then the transaction failed silently (without a revert message) if (_returnData.length < 68) return "SILENT"; assembly { // slice the sig hash _returnData := add(_returnData, 0x04) } return abi.decode(_returnData, (string)); // all that remains is the revert string } /* ========== DELEGATECALL HELPERS ========== */ /** * @notice this function allows static-calling an arbitrary write function from Spool, off-chain, and returning the result. The general purpose is for the calculation of * rewards in an implementation contract, where the reward calculation contains state changes that can't be easily gathered without calling from the Spool contract. * The require statement ensure that this comes from a static call off-chain, which can substitute an arbitrary address. * The 'one' address is used. The zero address could be used, but due to the prevalence of zero address checks, the internal calls would likely fail. * It has the same level of security as finding any arbitrary address, including address zero. * * @param implementation Address which to relay the call to * @param payload Payload to relay to the implementation * @return Response returned by the relayed call */ function relay(address implementation, bytes memory payload) external returns(bytes memory) { require(msg.sender == address(1)); return _relay(implementation, payload); } /** * @notice Relays the particular action to the strategy via delegatecall. * @param strategy Strategy address to delegate the call to * @param payload Data to pass when delegating call * @return Response received when delegating call */ function _relay(address strategy, bytes memory payload) internal returns (bytes memory) { (bool success, bytes memory data) = strategy.delegatecall(payload); if (!success) revert(_getRevertMsg(data)); return data; } /* ========== CONFIGURATION ========== */ /** * @notice Set allocation provider role for given user * Requirements: * - the caller must be the Spool owner (Spool DAO) * * @param user Address to set the role for * @param _isAllocationProvider Whether the user is assigned the role or not */ function setAllocationProvider(address user, bool _isAllocationProvider) external onlyOwner { isAllocationProvider[user] = _isAllocationProvider; emit SetAllocationProvider(user, _isAllocationProvider); } /** * @notice Set doHardWorker role for given user * Requirements: * - the caller must be the Spool owner (Spool DAO) * * @param user Address to set the role for * @param _isDoHardWorker Whether the user is assigned the role or not */ function setDoHardWorker(address user, bool _isDoHardWorker) external onlyOwner { isDoHardWorker[user] = _isDoHardWorker; emit SetIsDoHardWorker(user, _isDoHardWorker); } /** * @notice Set the flag to force "do hard work" to be executed in one transaction. * Requirements: * - the caller must be the Spool owner (Spool DAO) * * @param doForce Enable/disable running in one transactions */ function setForceOneTxDoHardWork(bool doForce) external onlyOwner { forceOneTxDoHardWork = doForce; } /** * @notice Set the flag to log reallocation proportions on change. * Requirements: * - the caller must be the Spool owner (Spool DAO) * * @dev Used for offchain execution to get the new reallocation table. * @param doLog Whether to log or not */ function setLogReallocationTable(bool doLog) external onlyOwner { logReallocationTable = doLog; } /** * @notice Set awaiting emergency withdraw flag for the strategy. * * @dev * Only for emergency case where withdrawing the first time doesn't fully work. * * Requirements: * * - the caller must be the Spool owner (Spool DAO) * * @param strat strategy to set * @param isAwaiting Flag value */ function setAwaitingEmergencyWithdraw(address strat, bool isAwaiting) external onlyOwner { _awaitingEmergencyWithdraw[strat] = isAwaiting; } /* ========== INTERNAL FUNCTIONS ========== */ /** * @notice Ensures that given address is a valid vault */ function _isVault(address vault) internal view { require( controller.validVault(vault), "NTVLT" ); } /** * @notice Ensures that strategy wasn't removed */ function _notRemoved(address strat) internal view { require( !strategies[strat].isRemoved, "OKSTRT" ); } /** * @notice If batch is complete it resets reallocation variables and emits an event * @param isReallocation If true, reset the reallocation variables */ function _finishDhw(bool isReallocation) internal { if (_isBatchComplete()) { // reset reallocation variables if (isReallocation) { reallocationIndex = 0; reallocationTableHash = 0; } emit DoHardWorkCompleted(globalIndex); } } /* ========== PRIVATE FUNCTIONS ========== */ /** * @notice Ensures that the caller is the controller */ function _onlyController() private view { require( msg.sender == address(controller), "OCTRL" ); } /** * @notice Ensures that the caller is the fast withdraw */ function _onlyFastWithdraw() private view { require( msg.sender == fastWithdraw, "OFWD" ); } /** * @notice Ensures that there is no pending reallocation */ function _noPendingReallocation() private view { require( reallocationTableHash == 0, "NORLC" ); } /** * @notice Ensures that strategy is removed */ function _onlyRemoved(address strat) private view { require( strategies[strat].isRemoved, "RMSTR" ); } /** * @notice Verifies given strategies * @param strategies Array of strategies to verify */ function _verifyStrategies(address[] memory strategies) internal view { controller.verifyStrategies(strategies); } /** * @notice Ensures that the caller is allowed to execute do hard work */ function _onlyDoHardWorker() private view { require( isDoHardWorker[msg.sender], "ODHW" ); } /** * @notice Verifies the reallocation table against the stored hash * @param reallocationTable The data to verify */ function _verifyReallocationTable(uint256[][] memory reallocationTable) internal view { require(reallocationTableHash == Hash.hashReallocationTable(reallocationTable), "BRLC"); } /** * @notice Verifies the reallocation strategies against the stored hash * @param strategies Array of strategies to verify */ function _verifyReallocationStrategies(address[] memory strategies) internal view { require(Hash.sameStrategies(strategies, reallocationStrategiesHash), "BRLCSTR"); } /* ========== MODIFIERS ========== */ /** * @notice Throws if called by anyone else other than the controller */ modifier onlyDoHardWorker() { _onlyDoHardWorker(); _; } /** * @notice Throws if called by a non-valid vault */ modifier onlyVault() { _isVault(msg.sender); _; } /** * @notice Throws if called by anyone else other than the controller */ modifier onlyController() { _onlyController(); _; } /** * @notice Throws if the caller is not fast withdraw */ modifier onlyFastWithdraw() { _onlyFastWithdraw(); _; } /** * @notice Throws if given array of strategies is not valid */ modifier verifyStrategies(address[] memory strategies) { _verifyStrategies(strategies); _; } /** * @notice Throws if given array of reallocation strategies is not valid */ modifier verifyReallocationStrategies(address[] memory strategies) { _verifyReallocationStrategies(strategies); _; } /** * @notice Throws if caller does not have the allocation provider role */ modifier onlyAllocationProvider() { require( isAllocationProvider[msg.sender], "OALC" ); _; } /** * @notice Ensures that there is no pending reallocation */ modifier noPendingReallocation() { _noPendingReallocation(); _; } /** * @notice Throws strategy is removed */ modifier notRemoved(address strat) { _notRemoved(strat); _; } /** * @notice Throws strategy isn't removed */ modifier onlyRemoved(address strat) { _onlyRemoved(strat); _; } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.11; // extends import "../interfaces/spool/ISpoolDoHardWork.sol"; import "./SpoolStrategy.sol"; /** * @notice Spool part of implementation dealing with the do hard work * * @dev * Do hard work is the process of interacting with other protocols. * This process aggregates many actions together to act in as optimized * manner as possible. It optimizes for underlying assets and gas cost. * * Do hard work (DHW) is executed periodically. As users are depositing * and withdrawing, these actions are stored in the buffer system. * When executed the deposits and withdrawals are matched against * eachother to minimize slippage and protocol fees. This means that * for a normal DHW only deposit or withdrawal is executed and never * both in the same index. Both can only be if the DHW is processing * the reallocation as well. * * Each strategy DHW is executed once per index and then incremented. * When all strategies are incremented to the same index, the batch * is considered complete. As soon as a new batch starts (first strategy * in the new batch is processed) global index is incremented. * * Global index is always one more or equal to the strategy index. * This constraints the system so that all strategy DHWs have to be * executed to complete the batch. * * Do hard work can only be executed by the whitelisted addresses. * The whitelisting can be done only by the Spool DAO. * * Do hard work actions: * - deposit * - withdrawal * - compound rewards * - reallocate assets across protocols * */ abstract contract SpoolDoHardWork is ISpoolDoHardWork, SpoolStrategy { /* ========== DO HARD WORK ========== */ /** * @notice Executes do hard work of specified strategies. * * @dev * Requirements: * * - caller must be a valid do hard worker * - provided strategies must be valid * - reallocation is not pending for current index * - if `forceOneTxDoHardWork` flag is true all strategies should be executed in one transaction * - at least one strategy must be processed * - the system should not be paused * * @param stratIndexes Array of strategy indexes * @param slippages Array of slippage values to be used when depositing into protocols (e.g. minOut) * @param rewardSlippages Array of values containing information of if and how to swap reward tokens to strategy underlying * @param allStrategies Array of all valid strategy addresses in the system */ function batchDoHardWork( uint256[] memory stratIndexes, uint256[][] memory slippages, RewardSlippages[] memory rewardSlippages, address[] memory allStrategies ) external systemNotPaused onlyDoHardWorker verifyStrategies(allStrategies) { // update global index if this are first strategies in index if (_isBatchComplete()) { globalIndex++; doHardWorksLeft = uint8(allStrategies.length); } // verify reallocation is not set for the current index if (reallocationIndex == globalIndex) { // if reallocation is set, verify it was disabled require(reallocationTableHash == 0, "RLC"); // if yes, reset reallocation index reallocationIndex = 0; } require( stratIndexes.length > 0 && stratIndexes.length == slippages.length && stratIndexes.length == rewardSlippages.length, "BIPT" ); // check if DHW is forcen to be executen on one transaction if (forceOneTxDoHardWork) { require(stratIndexes.length == allStrategies.length, "1TX"); } // go over withdrawals and deposits for (uint256 i = 0; i < stratIndexes.length; i++) { address stratAddress = allStrategies[stratIndexes[i]]; _doHardWork(stratAddress, slippages[i], rewardSlippages[i]); _updatePending(stratAddress); _finishStrategyDoHardWork(stratAddress); } _updateDoHardWorksLeft(stratIndexes.length); // if DHW for index finished _finishDhw(false); } /** * @notice Process strategy DHW, deposit wnd withdraw * @dev Only executed when there is no reallocation for the DHW * @param strat Strategy address * @param slippages Array of slippage values to be used when depositing into protocols (e.g. minOut) * @param rewardSlippages Array of values containing information of if and how to swap reward tokens to strategy underlying */ function _doHardWork( address strat, uint256[] memory slippages, RewardSlippages memory rewardSlippages ) private { Strategy storage strategy = strategies[strat]; // Check if strategy wasn't exected in current index yet require(strategy.index < globalIndex, "SFIN"); _process(strat, slippages, rewardSlippages.doClaim, rewardSlippages.swapData); } /* ========== DO HARD WORK when REALLOCATING ========== */ /** * @notice Executes do hard work of specified strategies if reallocation is in progress. * * @dev * Requirements: * * - caller must be a valid do hard worker * - provided strategies must be valid * - reallocation is pending for current index * - at least one strategy must be processed * - the system should not be paused * * @param withdrawData Reallocation values addressing withdrawal part of the reallocation DHW * @param depositData Reallocation values addressing deposit part of the reallocation DHW * @param allStrategies Array of all strategy addresses in the system for current set reallocation * @param isOneTransaction Flag denoting if the DHW should execute in one transaction */ function batchDoHardWorkReallocation( ReallocationWithdrawData memory withdrawData, ReallocationData memory depositData, address[] memory allStrategies, bool isOneTransaction ) external systemNotPaused onlyDoHardWorker verifyReallocationStrategies(allStrategies) { if (_isBatchComplete()) { globalIndex++; doHardWorksLeft = uint8(allStrategies.length); withdrawalDoHardWorksLeft = uint8(allStrategies.length); } // verify reallocation is set for the current index, and not disabled require( reallocationIndex == globalIndex && reallocationTableHash != 0, "XNRLC" ); // add all indexes if DHW is in one transaction if (isOneTransaction) { require( withdrawData.stratIndexes.length == allStrategies.length && depositData.stratIndexes.length == allStrategies.length, "1TX" ); } else { require(!forceOneTxDoHardWork, "F1TX"); require(withdrawData.stratIndexes.length > 0 || depositData.stratIndexes.length > 0, "NOSTR"); } // execute deposits and withdrawals _batchDoHardWorkReallocation(withdrawData, depositData, allStrategies); // update if DHW for index finished _finishDhw(true); } /** * @notice Executes do hard work of specified strategies if reallocation is in progress. * @param withdrawData Reallocation values addressing withdrawal part of the reallocation DHW * @param depositData Reallocation values addressing deposit part of the reallocation DHW * @param allStrategies Array of all strategy addresses in the system for current set reallocation */ function _batchDoHardWorkReallocation( ReallocationWithdrawData memory withdrawData, ReallocationData memory depositData, address[] memory allStrategies ) private { // WITHDRAWALS // reallocation withdraw // process users deposit and withdrawals if (withdrawData.stratIndexes.length > 0) { // check parameters require( withdrawData.stratIndexes.length == withdrawData.slippages.length && withdrawalDoHardWorksLeft >= withdrawData.stratIndexes.length, "BWI" ); // verify if reallocation table matches the reallocationtable hash _verifyReallocationTable(withdrawData.reallocationTable); // get current strategy price data // this is later used to calculate the amount that can me matched // between 2 strategies when they deposit in eachother PriceData[] memory spotPrices = _getPriceData(withdrawData, allStrategies); // process the withdraw part of the reallocation // process the deposit and the withdrawal part of the users deposits/withdrawals _processWithdraw( withdrawData, allStrategies, spotPrices ); // update number of strategies needing to be processed for the current reallocation DHW // can continue to deposit only when it reaches 0 _updateWithdrawalDohardWorksleft(withdrawData.stratIndexes.length); } // check if withdrawal phase was finished before starting deposit require( !(depositData.stratIndexes.length > 0 && withdrawalDoHardWorksLeft > 0), "WNF" ); // DEPOSITS // deposit reallocated amounts withdrawn above into strategies if (depositData.stratIndexes.length > 0) { // check parameters require( doHardWorksLeft >= depositData.stratIndexes.length && depositData.stratIndexes.length == depositData.slippages.length, "BDI" ); // deposit reallocated amounts into strategies // this only deals with the reallocated amounts as users were already processed in the withdrawal phase for (uint128 i = 0; i < depositData.stratIndexes.length; i++) { uint256 stratIndex = depositData.stratIndexes[i]; address stratAddress = allStrategies[stratIndex]; Strategy storage strategy = strategies[stratAddress]; // verify the strategy was not removed (it could be removed in the middle of the DHW if the DHW was executed in multiple transactions) _notRemoved(stratAddress); require(strategy.isInDepositPhase, "SWNP"); // deposit reallocation withdrawn amounts according to the calculations _doHardWorkDeposit(stratAddress, depositData.slippages[stratIndex]); // mark strategy as finished for the current index _finishStrategyDoHardWork(stratAddress); // remove the flag indicating strategy should deposit reallocated amount strategy.isInDepositPhase = false; } // update number of strategies left in the current index // if this reaches 0, DHW is considered complete _updateDoHardWorksLeft(depositData.stratIndexes.length); } } /** * @notice Executes user process and withdraw part of the do-hard-work for the specified strategies when reallocation is in progress. * @param withdrawData Reallocation values addressing withdrawal part of the reallocation DHW * @param allStrategies Array of all strategy addresses in the system for current set reallocation * @param spotPrices current strategy share price data, used to calculate the amount that can me matched between 2 strategies when reallcating */ function _processWithdraw( ReallocationWithdrawData memory withdrawData, address[] memory allStrategies, PriceData[] memory spotPrices ) private { // go over reallocation table and calculate what amount of shares can be optimized when reallocating // we can optimize if two strategies deposit into eachother. With the `spotPrices` we can compare the strategy values. ReallocationShares memory reallocation = _optimizeReallocation(withdrawData, spotPrices); // go over withdrawals for (uint256 i = 0; i < withdrawData.stratIndexes.length; i++) { uint256 stratIndex = withdrawData.stratIndexes[i]; address stratAddress = allStrategies[stratIndex]; Strategy storage strategy = strategies[stratAddress]; _notRemoved(stratAddress); require(!strategy.isInDepositPhase, "SWP"); uint128 withdrawnReallocationReceived; { uint128 sharesToWithdraw = reallocation.totalSharesWithdrawn[stratIndex] - reallocation.optimizedShares[stratIndex]; ProcessReallocationData memory processReallocationData = ProcessReallocationData( sharesToWithdraw, reallocation.optimizedShares[stratIndex], reallocation.optimizedWithdraws[stratIndex] ); // withdraw reallocation / returns non-optimized withdrawn amount withdrawnReallocationReceived = _doHardWorkReallocation(stratAddress, withdrawData.slippages[stratIndex], processReallocationData); } // reallocate withdrawn to other strategies _depositReallocatedAmount( reallocation.totalSharesWithdrawn[stratIndex], withdrawnReallocationReceived, reallocation.optimizedWithdraws[stratIndex], allStrategies, withdrawData.reallocationTable[stratIndex] ); _updatePending(stratAddress); strategy.isInDepositPhase = true; } } /** * @notice Process strategy DHW, including reallocation * @dev Only executed when reallocation is set for the DHW * @param strat Strategy address * @param slippages Array of slippage values * @param processReallocationData Reallocation data (see ProcessReallocationData) * @return Received withdrawn reallocation */ function _doHardWorkReallocation( address strat, uint256[] memory slippages, ProcessReallocationData memory processReallocationData ) private returns(uint128){ Strategy storage strategy = strategies[strat]; // Check if strategy wasn't exected in current index yet require(strategy.index < globalIndex, "SFIN"); uint128 withdrawnReallocationReceived = _processReallocation(strat, slippages, processReallocationData); return withdrawnReallocationReceived; } /** * @notice Process deposit collected form the reallocation * @dev Only executed when reallocation is set for the DHW * @param strat Strategy address * @param slippages Array of slippage values */ function _doHardWorkDeposit( address strat, uint256[] memory slippages ) private { _processDeposit(strat, slippages); } /** * @notice Calculate amount of shares that can be swapped between a pair of strategies (without withdrawing from the protocols) * * @dev This is done to ensure only the necessary amoun gets withdrawn from protocols and lower the total slippage and fee. * NOTE: We know strategies depositing into eachother must have the same underlying asset * The underlying asset is used to compare the amount ob both strategies withdrawing (depositing) into eachother. * * Returns: * - amount of optimized collateral amount for each strategy * - amount of optimized shares for each strategy * - total non-optimized amount of shares for each strategy * * @param withdrawData Withdraw data (see WithdrawData) * @param priceData An array of price data (see PriceData) * @return reallocationShares Containing arrays showing the optimized share and underlying token amounts */ function _optimizeReallocation( ReallocationWithdrawData memory withdrawData, PriceData[] memory priceData ) private pure returns (ReallocationShares memory) { // amount of optimized collateral amount for each strategy uint128[] memory optimizedWithdraws = new uint128[](withdrawData.reallocationTable.length); // amount of optimized shares for each strategy uint128[] memory optimizedShares = new uint128[](withdrawData.reallocationTable.length); // total non-optimized amount of shares for each strategy uint128[] memory totalShares = new uint128[](withdrawData.reallocationTable.length); // go over all the strategies (over reallcation table) for (uint128 i = 0; i < withdrawData.reallocationTable.length; i++) { for (uint128 j = i + 1; j < withdrawData.reallocationTable.length; j++) { // check if both strategies are depositing to eachother, if yes - optimize if (withdrawData.reallocationTable[i][j] > 0 && withdrawData.reallocationTable[j][i] > 0) { // calculate strategy I underlying collateral amout withdrawing uint128 amountI = uint128(withdrawData.reallocationTable[i][j] * priceData[i].totalValue / priceData[i].totalShares); // calculate strategy I underlying collateral amout withdrawing uint128 amountJ = uint128(withdrawData.reallocationTable[j][i] * priceData[j].totalValue / priceData[j].totalShares); uint128 optimizedAmount; // check which strategy is withdrawing less if (amountI > amountJ) { optimizedAmount = amountJ; } else { optimizedAmount = amountI; } // use the lesser value of both to save maximum possible optimized amount withdrawing optimizedWithdraws[i] += optimizedAmount; optimizedWithdraws[j] += optimizedAmount; } // sum total shares withdrawing for each strategy unchecked { totalShares[i] += uint128(withdrawData.reallocationTable[i][j]); totalShares[j] += uint128(withdrawData.reallocationTable[j][i]); } } // If we optimized for a strategy, calculate the total shares optimized back from the collateral amount. // The optimized shares amount will never be withdrawn from the strategy, as we know other strategies are // depositing to the strategy in the equal amount and we know how to mach them. if (optimizedWithdraws[i] > 0) { optimizedShares[i] = Math.getProportion128(optimizedWithdraws[i], priceData[i].totalShares, priceData[i].totalValue); } } ReallocationShares memory reallocationShares = ReallocationShares( optimizedWithdraws, optimizedShares, totalShares ); return reallocationShares; } /** * @notice Get urrent strategy price data, containing total balance and total shares * @dev Also verify if the total strategy value is according to the defined values * * @param withdrawData Withdraw data (see WithdrawData) * @param allStrategies Array of strategy addresses * @return Price data (see PriceData) */ function _getPriceData( ReallocationWithdrawData memory withdrawData, address[] memory allStrategies ) private returns(PriceData[] memory) { PriceData[] memory spotPrices = new PriceData[](allStrategies.length); for (uint128 i = 0; i < allStrategies.length; i++) { // claim rewards before getting the price if (withdrawData.rewardSlippages[i].doClaim) { _claimRewards(allStrategies[i], withdrawData.rewardSlippages[i].swapData); } for (uint128 j = 0; j < allStrategies.length; j++) { // if a strategy is withdrawing in reallocation get its spot price if (withdrawData.reallocationTable[i][j] > 0) { // if strategy is removed treat it's value as 0 if (!strategies[allStrategies[i]].isRemoved) { spotPrices[i].totalValue = _getStratValue(allStrategies[i]); } spotPrices[i].totalShares = strategies[allStrategies[i]].totalShares; require( spotPrices[i].totalValue >= withdrawData.priceSlippages[i].min && spotPrices[i].totalValue <= withdrawData.priceSlippages[i].max, "BPRC" ); break; } } } return spotPrices; } /** * @notice Processes reallocated amount deposits. * @param reallocateSharesToWithdraw Reallocate shares to withdraw * @param withdrawnReallocationReceived Received withdrawn reallocation * @param optimizedWithdraw Optimized withdraw * @param _strategies Array of strategy addresses * @param stratReallocationShares Array of strategy reallocation shares */ function _depositReallocatedAmount( uint128 reallocateSharesToWithdraw, uint128 withdrawnReallocationReceived, uint128 optimizedWithdraw, address[] memory _strategies, uint256[] memory stratReallocationShares ) private { for (uint256 i = 0; i < stratReallocationShares.length; i++) { if (stratReallocationShares[i] > 0) { Strategy storage depositStrategy = strategies[_strategies[i]]; // add actual withdrawn deposit depositStrategy.pendingReallocateDeposit += Math.getProportion128(withdrawnReallocationReceived, stratReallocationShares[i], reallocateSharesToWithdraw); // add optimized deposit depositStrategy.pendingReallocateOptimizedDeposit += Math.getProportion128(optimizedWithdraw, stratReallocationShares[i], reallocateSharesToWithdraw); } } } /* ========== SHARED FUNCTIONS ========== */ /** * @notice After strategy DHW is complete increment strategy index * @param strat Strategy address */ function _finishStrategyDoHardWork(address strat) private { Strategy storage strategy = strategies[strat]; strategy.index++; emit DoHardWorkStrategyCompleted(strat, strategy.index); } /** * @notice After strategy DHW process update strategy pending values * @dev set pending next as pending and reset pending next * @param strat Strategy address */ function _updatePending(address strat) private { Strategy storage strategy = strategies[strat]; Pending memory pendingUserNext = strategy.pendingUserNext; strategy.pendingUser = pendingUserNext; if ( pendingUserNext.deposit != Max128Bit.ZERO || pendingUserNext.sharesToWithdraw != Max128Bit.ZERO ) { strategy.pendingUserNext = Pending(Max128Bit.ZERO, Max128Bit.ZERO); } } /** * @notice Update the number of "do hard work" processes left. * @param processedCount Number of completed actions */ function _updateDoHardWorksLeft(uint256 processedCount) private { doHardWorksLeft -= uint8(processedCount); } /** * @notice Update the number of "withdrawal do hard work" processes left. * @param processedCount Number of completed actions */ function _updateWithdrawalDohardWorksleft(uint256 processedCount) private { withdrawalDoHardWorksLeft -= uint8(processedCount); } /** * @notice Hash a reallocation table after it was updated * @param reallocationTable 2D table showing amount of shares withdrawing to each strategy */ function _hashReallocationTable(uint256[][] memory reallocationTable) internal { reallocationTableHash = Hash.hashReallocationTable(reallocationTable); if (logReallocationTable) { // this is only meant to be emitted when debugging emit ReallocationTableUpdatedWithTable(reallocationIndex, reallocationTableHash, reallocationTable); } else { emit ReallocationTableUpdated(reallocationIndex, reallocationTableHash); } } /** * @notice Calculate and store the hash of the given strategy array * @param strategies Strategy addresses to hash */ function _hashReallocationStrategies(address[] memory strategies) internal { reallocationStrategiesHash = Hash.hashStrategies(strategies); } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.11; // extends import "../interfaces/spool/ISpoolExternal.sol"; import "./SpoolReallocation.sol"; /** * @notice Exposes spool functions to set and redeem actions. * * @dev * Most of the functions are restricted to vaults. The action is * recorded in the buffer system and is processed at the next * do hard work. * A user cannot interact with any of the Spool functions directly. * * Complete interaction with Spool consists of 4 steps * 1. deposit * 2. redeem shares * 3. withdraw * 4. redeem underlying asset * * Redeems (step 2. and 4.) are done at the same time. Redeem is * processed automatically on first vault interaction after the DHW * is completed. * * As the system works asynchronously, between every step * a do hard work needs to be executed. The shares and actual * withdrawn amount are only calculated at the time of action (DHW). */ abstract contract SpoolExternal is ISpoolExternal, SpoolReallocation { using Bitwise for uint256; using SafeERC20 for IERC20; using Max128Bit for uint128; /* ========== DEPOSIT ========== */ /** * @notice Allows a vault to queue a deposit to a strategy. * * @dev * Requirements: * * - the caller must be a vault * - strategy shouldn't be removed * * @param strat Strategy address to deposit to * @param amount Amount to deposit * @param index Global index vault is depositing at (active global index) */ function deposit(address strat, uint128 amount, uint256 index) external override onlyVault notRemoved(strat) { Strategy storage strategy = strategies[strat]; Pending storage strategyPending = _getStrategyPending(strategy, index); Vault storage vault = strategy.vaults[msg.sender]; VaultBatch storage vaultBatch = vault.vaultBatches[index]; // save to storage strategyPending.deposit = strategyPending.deposit.add(amount); vaultBatch.deposited += amount; } /* ========== WITHDRAW ========== */ /** * @notice Allows a vault to queue a withdrawal from a strategy. * * @dev * Requirements: * * - the caller must be a vault * - strategy shouldn't be removed * * @param strat Strategy address to withdraw from * @param vaultProportion Proportion of all vault-strategy shares a vault wants to withdraw, denoted in basis points (10_000 is 100%) * @param index Global index vault is depositing at (active global index) */ function withdraw(address strat, uint256 vaultProportion, uint256 index) external override onlyVault { Strategy storage strategy = strategies[strat]; Pending storage strategyPending = _getStrategyPending(strategy, index); Vault storage vault = strategy.vaults[msg.sender]; VaultBatch storage vaultBatch = vault.vaultBatches[index]; // calculate new shares to withdraw uint128 sharesToWithdraw = Math.getProportion128(vault.shares, vaultProportion, ACCURACY); // save to storage strategyPending.sharesToWithdraw = strategyPending.sharesToWithdraw.add(sharesToWithdraw); vaultBatch.withdrawnShares += sharesToWithdraw; } /* ========== DEPOSIT/WITHDRAW SHARED ========== */ /** * @notice Get strategy pending struct, depending on if the strategy do hard work has already been executed in the current index * @param strategy Strategy data (see Strategy struct) * @param interactingIndex Global index for which to get the struct * @return pending Storage struct containing all unprocessed deposits and withdrawals for the `interactingIndex` */ function _getStrategyPending(Strategy storage strategy, uint256 interactingIndex) private view returns (Pending storage pending) { // if index we are interacting with (active global index) is same as strategy index, then DHW has already been executed in index if (_isNextStrategyIndex(strategy, interactingIndex)) { pending = strategy.pendingUser; } else { pending = strategy.pendingUserNext; } } /* ========== REDEEM ========== */ /** * @notice Allows a vault to redeem deposit and withdrawals for the processed index. * @dev * * Requirements: * * - the caller must be a valid vault * * @param strat Strategy address * @param index Global index the vault is redeeming for * @return Received vault received shares from the deposit and received vault underlying withdrawn amounts */ function redeem(address strat, uint256 index) external override onlyVault returns (uint128, uint128) { Strategy storage strategy = strategies[strat]; Batch storage batch = strategy.batches[index]; Vault storage vault = strategy.vaults[msg.sender]; VaultBatch storage vaultBatch = vault.vaultBatches[index]; uint128 vaultBatchDeposited = vaultBatch.deposited; uint128 vaultBatchWithdrawnShares = vaultBatch.withdrawnShares; uint128 vaultDepositReceived = 0; uint128 vaultWithdrawnReceived = 0; uint128 vaultShares = vault.shares; // Make calculations if deposit in vault batch was performed if (vaultBatchDeposited > 0 && batch.deposited > 0) { vaultDepositReceived = Math.getProportion128(batch.depositedReceived, vaultBatchDeposited, batch.deposited); // calculate new vault-strategy shares // new shares are calculated at the DHW time, here vault only // takes the proportion of the vault deposit compared to the total deposit vaultShares += Math.getProportion128(batch.depositedSharesReceived, vaultBatchDeposited, batch.deposited); // reset to 0 to get the gas reimbursement vaultBatch.deposited = 0; } // Make calculations if withdraw in vault batch was performed if (vaultBatchWithdrawnShares > 0 && batch.withdrawnShares > 0) { // Withdrawn recieved represents the total underlying a strategy got back after DHW has processed the withdrawn shares. // This is stored at the DHW time, here vault only takes the proportion // of the vault shares withdrwan compared to the total shares withdrawn vaultWithdrawnReceived = Math.getProportion128(batch.withdrawnReceived, vaultBatchWithdrawnShares, batch.withdrawnShares); // substract all the shares withdrawn in the index after collecting the withdrawn recieved vaultShares -= vaultBatchWithdrawnShares; // reset to 0 to get the gas reimbursement vaultBatch.withdrawnShares = 0; } // store the updated shares vault.shares = vaultShares; return (vaultDepositReceived, vaultWithdrawnReceived); } /** * @notice Redeem underlying token * @dev * This function is only called by the vault after the vault redeem is processed * As redeem is called by each strategy separately, we don't want to transfer the * withdrawn underlyin tokens x amount of times. * * Requirements: * - Can only be invoked by vault * * @param amount Amount to redeem */ function redeemUnderlying(uint128 amount) external override onlyVault { IVault(msg.sender).underlying().safeTransfer(msg.sender, amount); } /* ========== REDEEM REALLOCATION ========== */ /** * @notice Redeem vault shares after reallocation has been processed for the vault * @dev * * Requirements: * - Can only be invoked by vault * * @param vaultStrategies Array of vault strategy addresses * @param depositProportions Values representing how the vault has deposited it's withdrawn shares * @param index Index at which the reallocation was perofmed */ function redeemReallocation( address[] memory vaultStrategies, uint256 depositProportions, uint256 index ) external override onlyVault { // count number of strategies we deposit into uint128 depositStratsCount = 0; for (uint256 i = 0; i < vaultStrategies.length; i++) { uint256 prop = depositProportions.get14BitUintByIndex(i); if (prop > 0) { depositStratsCount++; } } // init deposit and withdrawal strategy arrays address[] memory withdrawStrats = new address[](vaultStrategies.length - depositStratsCount); address[] memory depositStrats = new address[](depositStratsCount); uint256[] memory depositProps = new uint256[](depositStratsCount); // fill deposit and withdrawal strategy arrays { uint128 k = 0; uint128 l = 0; for (uint256 i = 0; i < vaultStrategies.length; i++) { uint256 prop = depositProportions.get14BitUintByIndex(i); if (prop > 0) { depositStrats[k] = vaultStrategies[i]; depositProps[k] = prop; k++; } else { withdrawStrats[l] = vaultStrategies[i]; l++; } } } uint256 totalVaultWithdrawnReceived = 0; // calculate total withdrawal amount for (uint256 i = 0; i < withdrawStrats.length; i++) { Strategy storage strategy = strategies[withdrawStrats[i]]; BatchReallocation storage reallocationBatch = strategy.reallocationBatches[index]; Vault storage vault = strategy.vaults[msg.sender]; // if we withdrawed from strategy, claim and spread across deposits uint256 vaultWithdrawnReallocationShares = vault.withdrawnReallocationShares; if (vaultWithdrawnReallocationShares > 0) { // if batch withdrawn shares is 0, reallocation was canceled as a strategy was removed // if so, skip calculation and reset withdrawn reallcoation shares to 0 if (reallocationBatch.withdrawnReallocationShares > 0) { totalVaultWithdrawnReceived += (reallocationBatch.withdrawnReallocationReceived * vaultWithdrawnReallocationShares) / reallocationBatch.withdrawnReallocationShares; // substract the shares withdrawn from in the reallocation vault.shares -= uint128(vaultWithdrawnReallocationShares); } vault.withdrawnReallocationShares = 0; } } // calculate how the withdrawn amount was deposited to the depositing strategies uint256 vaultWithdrawnReceivedLeft = totalVaultWithdrawnReceived; uint256 lastDepositStratIndex = depositStratsCount - 1; for (uint256 i = 0; i < depositStratsCount; i++) { Strategy storage depositStrategy = strategies[depositStrats[i]]; Vault storage depositVault = depositStrategy.vaults[msg.sender]; BatchReallocation storage reallocationBatch = depositStrategy.reallocationBatches[index]; if (reallocationBatch.depositedReallocation > 0) { // calculate reallocation strat deposit amount uint256 depositAmount; // if the strategy is last among the depositing ones, use the amount left to calculate the new shares // (same pattern was used when distributing the withdrawn shares to the depositing strategies - last strategy got what was left of shares) if (i < lastDepositStratIndex) { depositAmount = (totalVaultWithdrawnReceived * depositProps[i]) / FULL_PERCENT; vaultWithdrawnReceivedLeft -= depositAmount; } else { // if strat is last, use deposit left depositAmount = vaultWithdrawnReceivedLeft; } // based on calculated deposited amount calculate/redeem the new strategy shares belonging to a vault depositVault.shares += SafeCast.toUint128((reallocationBatch.depositedReallocationSharesReceived * depositAmount) / reallocationBatch.depositedReallocation); } } } /* ========== FAST WITHDRAW ========== */ /** * @notice Instantly withdraw shares from a strategy and return recieved underlying tokens. * @dev * User can execute the withdrawal of his shares from the vault at any time (except when * the reallocation is pending) without waiting for the DHW to process it. This is done * independently of other events. The gas cost is paid entirely by the user. * Withdrawn amount is sent back to the caller (FastWithdraw) contract, that later on, * sends it to a user. * * Requirements: * * - the caller must be a fast withdraw contract * - strategy shouldn't be removed * * @param strat Strategy address * @param underlying Address of underlying asset * @param shares Amount of shares to withdraw * @param slippages Strategy slippage values verifying the validity of the strategy state * @param swapData Array containig data to swap unclaimed strategy reward tokens for underlying asset * @return Withdrawn Underlying asset withdrarn amount */ function fastWithdrawStrat( address strat, address underlying, uint256 shares, uint256[] memory slippages, SwapData[] memory swapData ) external override onlyFastWithdraw notRemoved(strat) returns(uint128) { // returns withdrawn amount return _fastWithdrawStrat(strat, underlying, shares, slippages, swapData); } /* ========== REMOVE SHARES (prepare for fast withdraw) ========== */ /** * @notice Remove vault shares. * * @dev * Called by the vault when a user requested a fast withdraw * These shares are either withdrawn from the strategies immidiately or * stored as user-strategy shares in the FastWithdraw contract. * * Requirements: * * - can only be called by the vault * * @param vaultStrategies Array of strategy addresses * @param vaultProportion Proportion of all vault-strategy shares a vault wants to remove, denoted in basis points (10_000 is 100%) * @return Array of removed shares per strategy */ function removeShares( address[] memory vaultStrategies, uint256 vaultProportion ) external override onlyVault returns(uint128[] memory) { uint128[] memory removedShares = new uint128[](vaultStrategies.length); for (uint128 i = 0; i < vaultStrategies.length; i++) { _notRemoved(vaultStrategies[i]); Strategy storage strategy = strategies[vaultStrategies[i]]; Vault storage vault = strategy.vaults[msg.sender]; uint128 sharesToWithdraw = Math.getProportion128(vault.shares, vaultProportion, ACCURACY); removedShares[i] = sharesToWithdraw; vault.shares -= sharesToWithdraw; } return removedShares; } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.11; // extends import "../interfaces/spool/ISpoolReallocation.sol"; import "./SpoolDoHardWork.sol"; // libraries import "../libraries/Bitwise.sol"; // other imports import "../interfaces/IVault.sol"; /** * @notice Spool part of implementation dealing with the reallocation of assets * * @dev * Allocation provider can update vault allocation across strategies. * This requires vault to withdraw from some and deposit to other strategies. * This happens across multiple vaults. The system handles all vault reallocations * at once and optimizes it between eachother and users. * */ abstract contract SpoolReallocation is ISpoolReallocation, SpoolDoHardWork { using Bitwise for uint256; /* ========== SET REALLOCATION ========== */ /** * @notice Set vaults to reallocate on next do hard work * Requirements: * - Caller must have allocation provider role * - Vaults array must not be empty * - Vaults must be valid * - Strategies must be valid * - If reallocation was already initialized before: * - Reallocation table hash must be set * - Reallocation table must be valid * * @param vaults Array of vault addresses * @param strategies Array of strategy addresses * @param reallocationTable Reallocation details */ function reallocateVaults( VaultData[] memory vaults, address[] memory strategies, uint256[][] memory reallocationTable ) external onlyAllocationProvider { require(vaults.length > 0, "NOVRLC"); uint24 activeGlobalIndex = getActiveGlobalIndex(); // If reallocation was already initialized before, // verify state and parameters before continuing if (reallocationIndex > 0) { // If reallocation was started for index and table hash is 0, // the reallocation was canceled. Prevent from setting it in same index again. require(reallocationTableHash != 0, "RLCSTP"); // check if reallocation can still be set for same global index as before require(reallocationIndex == activeGlobalIndex, "RLCINP"); // verifies strategies agains current reallocation strategies hash _verifyReallocationStrategies(strategies); _verifyReallocationTable(reallocationTable); } else { // if new reallocation, init empty reallocation shares table // verifies all system strategies using Controller contract _verifyStrategies(strategies); // hash and save strategies // this strategies hash is then used to verify strategies during the reallocation // if the strat is exploited and removed from the system, this hash is used to be consistent // with reallocation table ordering as system strategies change. _hashReallocationStrategies(strategies); reallocationIndex = activeGlobalIndex; reallocationTable = new uint256[][](strategies.length); for (uint256 i = 0; i < strategies.length; i++) { reallocationTable[i] = new uint256[](strategies.length); } emit StartReallocation(reallocationIndex); } // loop over vaults for (uint128 i = 0; i < vaults.length; i++) { // check if address is a valid vault _isVault(vaults[i].vault); // reallocate vault //address[] memory vaultStrategies = _buildVaultStrategiesArray(vaults[i].strategiesBitwise, vaults[i].strategiesCount, strategies); (uint256[] memory withdrawProportions, uint256 depositProportions) = IVault(vaults[i].vault).reallocate( _buildVaultStrategiesArray(vaults[i].strategiesBitwise, vaults[i].strategiesCount, strategies), vaults[i].newProportions, getCompletedGlobalIndex(), // NOTE: move to var if call stack not too deeep activeGlobalIndex); // withdraw and deposit from vault strategies for (uint128 j = 0; j < vaults[i].strategiesCount; j++) { if (withdrawProportions[j] > 0) { uint256 withdrawStratIndex = vaults[i].strategiesBitwise.get8BitUintByIndex(j); (uint128 newSharesWithdrawn) = _reallocateVaultStratWithdraw( vaults[i].vault, strategies[withdrawStratIndex], withdrawProportions[j], activeGlobalIndex ); _updateDepositReallocationForStrat( newSharesWithdrawn, vaults[i], depositProportions, reallocationTable[withdrawStratIndex] ); } } } // Hash reallocation proportions _hashReallocationTable(reallocationTable); } /** * @notice Remove shares from strategy to set them for a reallocation * @param vaultAddress Vault address * @param strat Strategy address to remove shares * @param vaultProportion Proportion of all vault-strategy shares a vault wants to reallocate * @param index Global index we're reallocating for * @return newSharesWithdrawn New shares withdrawn fro reallocation */ function _reallocateVaultStratWithdraw( address vaultAddress, address strat, uint256 vaultProportion, uint256 index ) private returns (uint128 newSharesWithdrawn) { Strategy storage strategy = strategies[strat]; Vault storage vault = strategy.vaults[vaultAddress]; VaultBatch storage vaultBatch = vault.vaultBatches[index]; // calculate new shares to withdraw uint128 unwithdrawnVaultShares = vault.shares - vaultBatch.withdrawnShares; // if strategy wasn't executed in current batch yet, also substract unprocessed withdrawal shares in current batch if(!_isNextStrategyIndex(strategy, index)) { VaultBatch storage vaultBatchPrevious = vault.vaultBatches[index - 1]; unwithdrawnVaultShares -= vaultBatchPrevious.withdrawnShares; } // return data newSharesWithdrawn = Math.getProportion128(unwithdrawnVaultShares, vaultProportion, ACCURACY); // save to storage vault.withdrawnReallocationShares = newSharesWithdrawn; } /** * @notice Checks whether the given index is next index for the strategy * @param strategy Strategy data (see Strategy struct) * @param interactingIndex Index to check * @return isNextStrategyIndex True if given index is the next strategy index */ function _isNextStrategyIndex( Strategy storage strategy, uint256 interactingIndex ) internal view returns (bool isNextStrategyIndex) { if (strategy.index + 1 == interactingIndex) { isNextStrategyIndex = true; } } /** * @notice Update deposit reallocation for strategy * @param sharesWithdrawn Withdrawn shares * @param vaultData Vault data (see VaultData struct) * @param depositProportions Deposit proportions * @param stratReallocationTable Strategy reallocation table */ function _updateDepositReallocationForStrat( uint128 sharesWithdrawn, VaultData memory vaultData, uint256 depositProportions, uint256[] memory stratReallocationTable ) private pure { // sharesToDeposit = sharesWithdrawn * deposit_strat% uint128 sharesWithdrawnleft = sharesWithdrawn; uint128 lastDepositedIndex = 0; for (uint128 i = 0; i < vaultData.strategiesCount; i++) { uint256 stratDepositProportion = depositProportions.get14BitUintByIndex(i); if (stratDepositProportion > 0) { uint256 globalStratIndex = vaultData.strategiesBitwise.get8BitUintByIndex(i); uint128 withdrawnSharesForStrat = Math.getProportion128(sharesWithdrawn, stratDepositProportion, FULL_PERCENT); stratReallocationTable[globalStratIndex] += withdrawnSharesForStrat; sharesWithdrawnleft -= withdrawnSharesForStrat; lastDepositedIndex = i; } } // add shares left from rounding error to last deposit strat stratReallocationTable[lastDepositedIndex] += sharesWithdrawnleft; } /* ========== SHARED ========== */ /** * @notice Build vault strategies array from a 256bit word. * @dev Each vault index takes 8bits. * * @param bitwiseAddressIndexes Bitwise address indexes * @param strategiesCount Strategies count * @param strategies Array of strategy addresses * @return vaultStrategies Array of vault strategy addresses */ function _buildVaultStrategiesArray( uint256 bitwiseAddressIndexes, uint8 strategiesCount, address[] memory strategies ) private pure returns(address[] memory vaultStrategies) { vaultStrategies = new address[](strategiesCount); for (uint128 i = 0; i < strategiesCount; i++) { uint256 stratIndex = bitwiseAddressIndexes.get8BitUintByIndex(i); vaultStrategies[i] = strategies[stratIndex]; } } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.11; // extends import "../interfaces/spool/ISpoolStrategy.sol"; import "./SpoolBase.sol"; // libraries import "../external/@openzeppelin/token/ERC20/utils/SafeERC20.sol"; import "../libraries/Max/128Bit.sol"; import "../libraries/Math.sol"; // other imports import "../interfaces/IBaseStrategy.sol"; /** * @notice Spool part of implementation dealing with strategy related processing */ abstract contract SpoolStrategy is ISpoolStrategy, SpoolBase { using SafeERC20 for IERC20; /* ========== VIEWS ========== */ /** * @notice Returns the amount of funds the vault caller has in total * deployed to a particular strategy. * * @dev * Although not set as a view function due to the delegatecall * instructions performed by it, its value can be acquired * without actually executing the function by both off-chain * and on-chain code via simulating the transaction's execution. * * @param strat strategy address * * @return amount */ function getUnderlying(address strat) external override returns (uint128) { Strategy storage strategy = strategies[strat]; uint128 totalStrategyShares = strategy.totalShares; if (totalStrategyShares == 0) return 0; return Math.getProportion128(_totalUnderlying(strat), strategy.vaults[msg.sender].shares, totalStrategyShares); } /** * @notice Returns total strategy underlying value. * @param strat Strategy address * @return Total strategy underlying value */ function getStratUnderlying(address strat) external returns (uint128) { return _totalUnderlying(strat); // deletagecall } /** * @notice Get total vault underlying at index. * * @dev * NOTE: Call ONLY if vault shares are correct for the index. * Meaning vault has just redeemed for this index or this is current index. * * @param strat strategy address * @param index index in total underlying * @return Total vault underlying at index */ function getVaultTotalUnderlyingAtIndex(address strat, uint256 index) external override view returns(uint128) { Strategy storage strategy = strategies[strat]; Vault storage vault = strategy.vaults[msg.sender]; TotalUnderlying memory totalUnderlying = strategy.totalUnderlying[index]; if (totalUnderlying.totalShares > 0) { return Math.getProportion128(totalUnderlying.amount, vault.shares, totalUnderlying.totalShares); } return 0; } /** * @notice Yields the total underlying funds of a strategy. * * @dev * The function is not set as view given that it performs a delegate call * instruction to the strategy. * @param strategy Strategy address * @return Total underlying funds */ function _totalUnderlying(address strategy) internal returns (uint128) { bytes memory data = _relay( strategy, abi.encodeWithSelector(IBaseStrategy.getStrategyBalance.selector) ); return abi.decode(data, (uint128)); } /** * @notice Get strategy total underlying balance including rewards * @param strategy Strategy address * @return strategyBačance Returns strategy balance with the rewards */ function _getStratValue( address strategy ) internal returns(uint128) { bytes memory data = _relay( strategy, abi.encodeWithSelector( IBaseStrategy.getStrategyUnderlyingWithRewards.selector ) ); return abi.decode(data, (uint128)); } /** * @notice Returns pending rewards for a strategy * @param strat Strategy for which to return rewards * @param reward Reward address * @return Pending rewards */ function getPendingRewards(address strat, address reward) external view returns(uint256) { return strategies[strat].pendingRewards[reward]; } /** * @notice Returns strat address in shared strategies mapping for index * @param sharedKey Shared strategies key * @param index Strategy addresses index * @return Strategy address */ function getStratSharedAddress(bytes32 sharedKey, uint256 index) external view returns(address) { return strategiesShared[sharedKey].stratAddresses[index]; } /* ========== MUTATIVE EXTERNAL FUNCTIONS ========== */ /** * @notice Adds and initializes a new strategy * * @dev * Requirements: * * - the caller must be the controller * - reallcation must not be pending * - strategy shouldn't be previously removed * * @param strat Strategy to be added */ function addStrategy(address strat) external override onlyController noPendingReallocation notRemoved(strat) { Strategy storage strategy = strategies[strat]; strategy.index = globalIndex; // init as max zero, so first user interaction will be cheaper (non-zero to non-zero storage change) strategy.pendingUser = Pending(Max128Bit.ZERO, Max128Bit.ZERO); strategy.pendingUserNext = Pending(Max128Bit.ZERO, Max128Bit.ZERO); // initialize strategy specific values _initializeStrategy(strat); } /** * @notice Disables a strategy by liquidating all actively deployed funds * within it to its underlying collateral. * * @dev * This function is invoked whenever a strategy is disabled at the controller * level as an emergency. * * Requirements: * * - the caller must be the controller * - strategy shouldn't be previously removed * * @param strat strategy being disabled * @param skipDisable flag to skip executing strategy specific disable function * NOTE: Should always be false, except if `IBaseStrategy.disable` is failing and there is no other way */ function disableStrategy( address strat, bool skipDisable ) external override onlyController notRemoved(strat) { if (isMidReallocation()) { // when reallocating _disableStrategyWhenReallocating(strat); } else { // no reallocation in progress _disableStrategyNoReallocation(strat); } Strategy storage strategy = strategies[strat]; strategy.isRemoved = true; if (!skipDisable) { _disableStrategy(strat); } else { _skippedDisable[strat] = true; } _awaitingEmergencyWithdraw[strat] = true; } /** * @notice Disable strategy when reallocating * @param strat Strategy to disable */ function _disableStrategyWhenReallocating(address strat) private { Strategy storage strategy = strategies[strat]; if(strategy.index < globalIndex) { // is in withdrawal phase if (!strategy.isInDepositPhase) { // decrease do hard work withdrawals left if (withdrawalDoHardWorksLeft > 0) { withdrawalDoHardWorksLeft--; } } else { // if user withdrawal was already performed, collect withdrawn amount to be emergency withdrawn // NOTE: `strategy.index + 1` has to be used as the strategy index has not increased yet _removeNondistributedWithdrawnReceived(strategy, strategy.index + 1); } _decreaseDoHardWorksLeft(true); // save waiting reallocation deposit to be emergency withdrawn strategy.emergencyPending += strategy.pendingReallocateDeposit; strategy.pendingReallocateDeposit = 0; } } /** * @notice Disable strategy when there is no reallocation * @param strat Strategy to disable */ function _disableStrategyNoReallocation(address strat) private { Strategy storage strategy = strategies[strat]; // check if the strategy has already been processed in ongoing do hard work if (strategy.index < globalIndex) { _decreaseDoHardWorksLeft(false); } else if (!_isBatchComplete()) { // if user withdrawal was already performed, collect withdrawn amount to be emergency withdrawn _removeNondistributedWithdrawnReceived(strategy, strategy.index); } // if reallocation is set to be processed, reset reallocation table to cancel it for set index if (reallocationTableHash != 0) { reallocationTableHash = 0; } } /** * @notice Decrease "do hard work" actions left * @notice isMidReallocation Whether system is mid-reallocation */ function _decreaseDoHardWorksLeft(bool isMidReallocation) private { if (doHardWorksLeft > 0) { doHardWorksLeft--; // check if this was last strategy, to complete the do hard work _finishDhw(isMidReallocation); } } /** * @notice Removes the nondistributed amounts recieved, if any * @dev used when emergency withdrawing * * @param strategy Strategy address * @param index index remove from */ function _removeNondistributedWithdrawnReceived(Strategy storage strategy, uint256 index) private { strategy.emergencyPending += strategy.batches[index].withdrawnReceived; strategy.batches[index].withdrawnReceived = 0; strategy.totalUnderlying[index].amount = 0; } /** * @notice Liquidating all actively deployed funds within a strategy after it was disabled. * * @dev * Requirements: * * - the caller must be the controller * - the strategy must be disabled * - the strategy must be awaiting emergency withdraw * * @param strat strategy being disabled * @param data data to perform the withdrawal * @param withdrawRecipient recipient of the withdrawn funds */ function emergencyWithdraw( address strat, address withdrawRecipient, uint256[] memory data ) external override onlyController onlyRemoved(strat) { if (_awaitingEmergencyWithdraw[strat]) { _emergencyWithdraw(strat, withdrawRecipient, data); _awaitingEmergencyWithdraw[strat] = false; } else if (strategies[strat].emergencyPending > 0) { IBaseStrategy(strat).underlying().transfer(withdrawRecipient, strategies[strat].emergencyPending); strategies[strat].emergencyPending = 0; } } /** * @notice Runs strategy specific disable function if it was skipped when disabling the strategy. * Requirements: * - the caller must be the controller * - the strategy must be disabled * * @param strat Strategy to remove */ function runDisableStrategy(address strat) external override onlyController onlyRemoved(strat) { require(_skippedDisable[strat], "SDEX"); _disableStrategy(strat); _skippedDisable[strat] = false; } /* ========== MUTATIVE INTERNAL FUNCTIONS ========== */ /** * @notice Invokes the process function on the strategy to process teh pending actions * @dev executed deposit or withdrawal and compound of the reward tokens * * @param strategy Strategy address * @param slippages Array of slippage parameters to apply when depositing or withdrawing * @param harvestRewards Whether to harvest (swap and deposit) strategy rewards or not * @param swapData Array containig data to swap unclaimed strategy reward tokens for underlying asset */ function _process( address strategy, uint256[] memory slippages, bool harvestRewards, SwapData[] memory swapData ) internal { _relay( strategy, abi.encodeWithSelector( IBaseStrategy.process.selector, slippages, harvestRewards, swapData ) ); } /** * @notice Invoke process reallocation for a strategy * @dev This is the first par of the strategy DHW when reallocating * * @param strategy Strategy address * @param slippages Array of slippage parameters to apply when withdrawing * @param processReallocationData Reallocation values used when processing * @return withdrawnUnderlying Actual withdrawn reallocation underlying assets received */ function _processReallocation( address strategy, uint256[] memory slippages, ProcessReallocationData memory processReallocationData ) internal returns(uint128) { bytes memory data = _relay( strategy, abi.encodeWithSelector( IBaseStrategy.processReallocation.selector, slippages, processReallocationData ) ); // return actual withdrawn reallocation underlying assets received return abi.decode(data, (uint128)); } /** * @notice Invoke process deposit for a strategy * @param strategy Strategy address * @param slippages Array of slippage parameters to apply when depositing */ function _processDeposit( address strategy, uint256[] memory slippages ) internal { _relay( strategy, abi.encodeWithSelector( IBaseStrategy.processDeposit.selector, slippages ) ); } /** * @notice Invoke fast withdraw for a strategy * @param strategy Strategy to withdraw from * @param underlying Asset to withdraw * @param shares Amount of shares to withdraw * @param slippages Array of slippage parameters to apply when withdrawing * @param swapData Swap slippage and path array * @return Withdrawn amount */ function _fastWithdrawStrat( address strategy, address underlying, uint256 shares, uint256[] memory slippages, SwapData[] memory swapData ) internal returns(uint128) { bytes memory data = _relay( strategy, abi.encodeWithSelector( IBaseStrategy.fastWithdraw.selector, shares, slippages, swapData ) ); (uint128 withdrawnAmount) = abi.decode(data, (uint128)); IERC20(underlying).safeTransfer(msg.sender, withdrawnAmount); return withdrawnAmount; } /** * @notice Invoke claim rewards for a strategy * @param strategy Strategy address * @param swapData Swap slippage and path */ function _claimRewards( address strategy, SwapData[] memory swapData ) internal { _relay( strategy, abi.encodeWithSelector( IBaseStrategy.claimRewards.selector, swapData ) ); } /** * @notice Invokes the emergencyWithdraw function on a strategy * @param strategy Strategy to which to relay the call to * @param recipient Address to which to withdraw to * @param data Strategy specific data to perorm energency withdraw on a strategy */ function _emergencyWithdraw(address strategy, address recipient, uint256[] memory data) internal { _relay( strategy, abi.encodeWithSelector( IBaseStrategy.emergencyWithdraw.selector, recipient, data ) ); } /** * @notice Initializes strategy specific values * @param strategy Strategy to initialize */ function _initializeStrategy(address strategy) internal { _relay( strategy, abi.encodeWithSelector(IBaseStrategy.initialize.selector) ); } /** * @notice Cleans strategy specific values after disabling * @param strategy Strategy to disable */ function _disableStrategy(address strategy) internal { _relay( strategy, abi.encodeWithSelector(IBaseStrategy.disable.selector) ); } }
Returns pending rewards for a strategy strat Strategy for which to return rewards reward Reward address return Pending rewards/
function getPendingRewards(address strat, address reward) external view returns(uint256) { return strategies[strat].pendingRewards[reward]; }
11,832,807
pragma solidity ^0.4.15; //import './lib/safeMath.sol'; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal constant returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal constant returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } // import './ERC20.sol'; contract ERC20 { uint256 public totalSupply; function transferFrom(address from, address to, uint256 value) returns (bool); function transfer(address to, uint256 value) returns (bool); function approve(address spender, uint256 value) returns (bool); function allowance(address owner, address spender) constant returns (uint256); function balanceOf(address who) constant returns (uint256); event Approval(address indexed owner, address indexed spender, uint256 value); event Transfer(address indexed from, address indexed to, uint256 value); } // import './helpers/BasicToken.sol'; contract BasicToken is ERC20 { using SafeMath for uint256; mapping(address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) returns (bool) { if (balances[msg.sender] >= _value && balances[_to] + _value > balances[_to]) { balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } return false; } /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amout of tokens to be transfered */ function transferFrom(address _from, address _to, uint256 _value) returns (bool) { if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value > balances[_to]) { uint256 _allowance = allowed[_from][msg.sender]; allowed[_from][msg.sender] = _allowance.sub(_value); balances[_to] = balances[_to].add(_value); balances[_from] = balances[_from].sub(_value); Transfer(_from, _to, _value); return true; } return false; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) returns (bool) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifing the amount of tokens still avaible for the spender. */ function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } } // import './BiQToken.sol'; contract BiQToken is BasicToken { using SafeMath for uint256; string public name = "BurstIQ Token"; //name of the token string public symbol = "BiQ"; // symbol of the token uint8 public decimals = 18; // decimals uint256 public totalSupply = 1000000000 * 10**18; // total supply of BiQ Tokens // variables uint256 public keyEmployeesAllocatedFund; // fund allocated to key employees uint256 public advisorsAllocation; // fund allocated to advisors uint256 public marketIncentivesAllocation; // fund allocated to Market uint256 public vestingFounderAllocation; // funds allocated to founders that in under vesting period uint256 public totalAllocatedTokens; // variable to keep track of funds allocated uint256 public tokensAllocatedToCrowdFund; // funds allocated to crowdfund uint256 public saftInvestorAllocation; // funds allocated to private presales and instituational investors bool public isPublicTokenReleased = false; // flag to track the release the public token // addresses address public founderMultiSigAddress; // multi sign address of founders which hold address public advisorAddress; // advisor address which hold advisorsAllocation funds address public vestingFounderAddress; // address of founder that hold vestingFounderAllocation address public crowdFundAddress; // address of crowdfund contract // vesting period uint256 public preAllocatedTokensVestingTime; // crowdfund start time + 6 months //events event ChangeFoundersWalletAddress(uint256 _blockTimeStamp, address indexed _foundersWalletAddress); event TransferPreAllocatedFunds(uint256 _blockTimeStamp , address _to , uint256 _value); event PublicTokenReleased(uint256 _blockTimeStamp); //modifiers modifier onlyCrowdFundAddress() { require(msg.sender == crowdFundAddress); _; } modifier nonZeroAddress(address _to) { require(_to != 0x0); _; } modifier onlyFounders() { require(msg.sender == founderMultiSigAddress); _; } modifier onlyVestingFounderAddress() { require(msg.sender == vestingFounderAddress); _; } modifier onlyAdvisorAddress() { require(msg.sender == advisorAddress); _; } modifier isPublicTokenNotReleased() { require(isPublicTokenReleased == false); _; } // creation of the token contract function BiQToken (address _crowdFundAddress, address _founderMultiSigAddress, address _advisorAddress, address _vestingFounderAddress) { crowdFundAddress = _crowdFundAddress; founderMultiSigAddress = _founderMultiSigAddress; vestingFounderAddress = _vestingFounderAddress; advisorAddress = _advisorAddress; // Token Distribution vestingFounderAllocation = 18 * 10 ** 25 ; // 18 % allocation of totalSupply keyEmployeesAllocatedFund = 2 * 10 ** 25 ; // 2 % allocation of totalSupply advisorsAllocation = 5 * 10 ** 25 ; // 5 % allocation of totalSupply tokensAllocatedToCrowdFund = 60 * 10 ** 25 ; // 60 % allocation of totalSupply marketIncentivesAllocation = 5 * 10 ** 25 ; // 5 % allocation of totalSupply saftInvestorAllocation = 10 * 10 ** 25 ; // 10 % alloaction of totalSupply // Assigned balances to respective stakeholders balances[founderMultiSigAddress] = keyEmployeesAllocatedFund + saftInvestorAllocation; balances[crowdFundAddress] = tokensAllocatedToCrowdFund; totalAllocatedTokens = balances[founderMultiSigAddress]; preAllocatedTokensVestingTime = now + 180 * 1 days; // it should be 6 months period for vesting } // function to keep track of the total token allocation function changeTotalSupply(uint256 _amount) onlyCrowdFundAddress { totalAllocatedTokens = totalAllocatedTokens.add(_amount); tokensAllocatedToCrowdFund = tokensAllocatedToCrowdFund.sub(_amount); } // function to change founder multisig wallet address function changeFounderMultiSigAddress(address _newFounderMultiSigAddress) onlyFounders nonZeroAddress(_newFounderMultiSigAddress) { founderMultiSigAddress = _newFounderMultiSigAddress; ChangeFoundersWalletAddress(now, founderMultiSigAddress); } // function for releasing the public tokens called once by the founder only function releaseToken() onlyFounders isPublicTokenNotReleased { isPublicTokenReleased = !isPublicTokenReleased; PublicTokenReleased(now); } // function to transfer market Incentives fund function transferMarketIncentivesFund(address _to, uint _value) onlyFounders nonZeroAddress(_to) returns (bool) { if (marketIncentivesAllocation >= _value) { marketIncentivesAllocation = marketIncentivesAllocation.sub(_value); balances[_to] = balances[_to].add(_value); totalAllocatedTokens = totalAllocatedTokens.add(_value); TransferPreAllocatedFunds(now, _to, _value); return true; } return false; } // fund transferred to vesting Founders address after 6 months function getVestedFounderTokens() onlyVestingFounderAddress returns (bool) { if (now >= preAllocatedTokensVestingTime && vestingFounderAllocation > 0) { balances[vestingFounderAddress] = balances[vestingFounderAddress].add(vestingFounderAllocation); totalAllocatedTokens = totalAllocatedTokens.add(vestingFounderAllocation); vestingFounderAllocation = 0; TransferPreAllocatedFunds(now, vestingFounderAddress, vestingFounderAllocation); return true; } return false; } // fund transferred to vesting advisor address after 6 months function getVestedAdvisorTokens() onlyAdvisorAddress returns (bool) { if (now >= preAllocatedTokensVestingTime && advisorsAllocation > 0) { balances[advisorAddress] = balances[advisorAddress].add(advisorsAllocation); totalAllocatedTokens = totalAllocatedTokens.add(advisorsAllocation); advisorsAllocation = 0; TransferPreAllocatedFunds(now, advisorAddress, advisorsAllocation); return true; } else { return false; } } // overloaded transfer function to restrict the investor to transfer the token before the ICO sale ends function transfer(address _to, uint256 _value) returns (bool) { if (msg.sender == crowdFundAddress) { return super.transfer(_to,_value); } else { if (isPublicTokenReleased) { return super.transfer(_to,_value); } return false; } } // overloaded transferFrom function to restrict the investor to transfer the token before the ICO sale ends function transferFrom(address _from, address _to, uint256 _value) returns (bool) { if (msg.sender == crowdFundAddress) { return super.transferFrom(_from, _to, _value); } else { if (isPublicTokenReleased) { return super.transferFrom(_from, _to, _value); } return false; } } // fallback function to restrict direct sending of ether function () { revert(); } } contract BiQCrowdFund { using SafeMath for uint256; BiQToken public token; // Token contract reference //variables uint256 public crowdfundStartTime; // Starting time of CrowdFund uint256 public crowdfundEndTime; // End time of Crowdfund uint256 public totalWeiRaised = 0; // Counter to track the amount raised uint256 public exchangeRate = 2307; // Calculated using priceOfEtherInUSD/priceOfBiQToken so 276.84/0.12 uint256 internal minAmount = 36.1219 * 10 ** 18; // Calculated using 10k USD / 276.84 USD bool public isCrowdFundActive = false; // Flag to track the crowdfund active or not bool internal isTokenDeployed = false; // Flag to track the token deployment -- only can be set once bool internal hasCrowdFundStarted = false; // Flag to track if the crowdfund started // addresses address public founderMultiSigAddress; // Founders multisig address address public remainingTokenHolder; // Address to hold the remaining tokens after crowdfund end address public authorizerAddress; // Address of Authorizer who will authorize the investor // mapping mapping (address => uint256) auth; // KYC authentication enum State { PreSale, CrowdFund } //events event TokenPurchase(address indexed beneficiary, uint256 value, uint256 amount); event CrowdFundClosed(uint256 _blockTimeStamp); event ChangeFoundersWalletAddress(uint256 _blockTimeStamp, address indexed _foundersWalletAddress); //Modifiers modifier tokenIsDeployed() { require(isTokenDeployed == true); _; } modifier nonZeroEth() { require(msg.value > 0); _; } modifier nonZeroAddress(address _to) { require(_to != 0x0); _; } modifier checkCrowdFundActive() { require(isCrowdFundActive == true); _; } modifier onlyFounders() { require(msg.sender == founderMultiSigAddress); _; } modifier onlyPublic() { require(msg.sender != founderMultiSigAddress); _; } modifier onlyAuthorizer() { require(msg.sender == authorizerAddress); _; } modifier inState(State state) { require(getState() == state); _; } // Constructor to initialize the local variables function BiQCrowdFund (address _founderWalletAddress, address _remainingTokenHolder, address _authorizerAddress) { founderMultiSigAddress = _founderWalletAddress; remainingTokenHolder = _remainingTokenHolder; authorizerAddress = _authorizerAddress; } // Function to change the founders multisig address function setFounderMultiSigAddress(address _newFounderAddress) onlyFounders nonZeroAddress(_newFounderAddress) { founderMultiSigAddress = _newFounderAddress; ChangeFoundersWalletAddress(now, founderMultiSigAddress); } function setAuthorizerAddress(address _newAuthorizerAddress) onlyFounders nonZeroAddress(_newAuthorizerAddress) { authorizerAddress = _newAuthorizerAddress; } function setRemainingTokenHolder(address _newRemainingTokenHolder) onlyFounders nonZeroAddress(_newRemainingTokenHolder) { remainingTokenHolder = _newRemainingTokenHolder; } // Attach the token contract, can only be done once function setTokenAddress(address _tokenAddress) onlyFounders nonZeroAddress(_tokenAddress) { require(isTokenDeployed == false); token = BiQToken(_tokenAddress); isTokenDeployed = true; } // change the state of crowdfund function changeCrowdfundState() tokenIsDeployed onlyFounders inState(State.CrowdFund) { isCrowdFundActive = !isCrowdFundActive; } // for KYC/AML function authorize(address _to, uint256 max_amount) onlyAuthorizer { auth[_to] = max_amount * 1 ether; } // Buy token function call only in duration of crowdfund active function buyTokens(address beneficiary) nonZeroEth tokenIsDeployed onlyPublic nonZeroAddress(beneficiary) payable returns(bool) { // Only allow a certain amount for every investor if (auth[beneficiary] < msg.value) { revert(); } auth[beneficiary] = auth[beneficiary].sub(msg.value); if (getState() == State.PreSale) { if (buyPreSaleTokens(beneficiary)) { return true; } revert(); } else { require(now < crowdfundEndTime && isCrowdFundActive); fundTransfer(msg.value); uint256 amount = getNoOfTokens(exchangeRate, msg.value); if (token.transfer(beneficiary, amount)) { token.changeTotalSupply(amount); totalWeiRaised = totalWeiRaised.add(msg.value); TokenPurchase(beneficiary, msg.value, amount); return true; } revert(); } } // function to transfer the funds to founders account function fundTransfer(uint256 weiAmount) internal { founderMultiSigAddress.transfer(weiAmount); } ///////////////////////////////////// Constant Functions ///////////////////////////////////// // function to get the current state of the crowdsale function getState() public constant returns(State) { if (!isCrowdFundActive && !hasCrowdFundStarted) { return State.PreSale; } return State.CrowdFund; } // To get the authorized amount corresponding to an address function getPreAuthorizedAmount(address _address) constant returns(uint256) { return auth[_address]; } // get the amount of tokens a user would receive for a specific amount of ether function calculateTotalTokenPerContribution(uint256 _totalETHContribution) public constant returns(uint256) { if (getState() == State.PreSale) { return getTokensForPreSale(exchangeRate, _totalETHContribution * 1 ether).div(10 ** 18); } return getNoOfTokens(exchangeRate, _totalETHContribution); } // provides the bonus % function currentBonus(uint256 _ethContribution) public constant returns (uint8) { if (getState() == State.PreSale) { return getPreSaleBonusRate(_ethContribution * 1 ether); } return getCurrentBonusRate(); } ///////////////////////////////////// Presale Functions ///////////////////////////////////// // function to buy the tokens at presale with minimum investment = 10k USD function buyPreSaleTokens(address beneficiary) internal returns(bool) { // check the minimum investment should be 10k USD if (msg.value < minAmount) { revert(); } else { fundTransfer(msg.value); uint256 amount = getTokensForPreSale(exchangeRate, msg.value); if (token.transfer(beneficiary, amount)) { token.changeTotalSupply(amount); totalWeiRaised = totalWeiRaised.add(msg.value); TokenPurchase(beneficiary, msg.value, amount); return true; } return false; } } // function calculate the total no of tokens with bonus multiplication in the duration of presale function getTokensForPreSale(uint256 _exchangeRate, uint256 _amount) internal returns (uint256) { uint256 noOfToken = _amount.mul(_exchangeRate); uint256 preSaleTokenQuantity = ((100 + getPreSaleBonusRate(_amount)) * noOfToken ).div(100); return preSaleTokenQuantity; } function getPreSaleBonusRate(uint256 _ethAmount) internal returns (uint8) { if ( _ethAmount >= minAmount.mul(5) && _ethAmount < minAmount.mul(10)) { return 30; } if (_ethAmount >= minAmount.mul(10)) { return 35; } if (_ethAmount >= minAmount) { return 25; } } ///////////////////////////////////// Crowdfund Functions ///////////////////////////////////// // Starts the crowdfund, can only be called once function startCrowdfund(uint256 _exchangeRate) onlyFounders tokenIsDeployed inState(State.PreSale) { if (_exchangeRate > 0 && !hasCrowdFundStarted) { exchangeRate = _exchangeRate; crowdfundStartTime = now; crowdfundEndTime = crowdfundStartTime + 5 * 1 weeks; // end date is 5 weeks after the starting date isCrowdFundActive = !isCrowdFundActive; hasCrowdFundStarted = !hasCrowdFundStarted; } else { revert(); } } // function call after crowdFundEndTime. // It transfers the remaining tokens to remainingTokenHolder address function endCrowdfund() onlyFounders returns (bool) { require(now > crowdfundEndTime); uint256 remainingToken = token.balanceOf(this); // remaining tokens if (remainingToken != 0 && token.transfer(remainingTokenHolder, remainingToken)) { return true; } else { return false; } CrowdFundClosed(now); } // function to calculate the total no of tokens with bonus multiplication function getNoOfTokens(uint256 _exchangeRate, uint256 _amount) internal returns (uint256) { uint256 noOfToken = _amount.mul(_exchangeRate); uint256 noOfTokenWithBonus = ((100 + getCurrentBonusRate()) * noOfToken).div(100); return noOfTokenWithBonus; } // function provide the current bonus rate function getCurrentBonusRate() internal returns (uint8) { if (now > crowdfundStartTime + 4 weeks) { return 0; } if (now > crowdfundStartTime + 3 weeks) { return 5; } if (now > crowdfundStartTime + 2 weeks) { return 10; } if (now > crowdfundStartTime + 1 weeks) { return 15; } if (now > crowdfundStartTime) { return 20; } } // Crowdfund entry // send ether to the contract address // With at least 200 000 gas function() public payable { buyTokens(msg.sender); } }
Function to change the founders multisig address
function setFounderMultiSigAddress(address _newFounderAddress) onlyFounders nonZeroAddress(_newFounderAddress) { founderMultiSigAddress = _newFounderAddress; ChangeFoundersWalletAddress(now, founderMultiSigAddress); }
931,203
pragma solidity ^0.4.23; // // Helper Contracts // /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". * By OpenZeppelin. MIT License. https://github.com/OpenZeppelin/zeppelin-solidity * This method has been modified by Glossy for two-step transfers since a mistake would be fatal. */ contract Ownable { address public owner; address public pendingOwner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; pendingOwner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Approve transfer as step one prior to transfer * @param newOwner The address to transfer ownership to. */ function approveOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); pendingOwner = newOwner; } /** * @dev Allows the pending owner to transfer control of the contract. */ function transferOwnership() public { require(msg.sender == pendingOwner); emit OwnershipTransferred(owner, pendingOwner); owner = pendingOwner; } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. * By OpenZeppelin. MIT License. https://github.com/OpenZeppelin/zeppelin-solidity */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } } /** @title TXGuard * @dev The purpose of this contract is to determine transfer fees to be sent to creators **/ interface TXGuard { function getTxAmount(uint256 _tokenId) external pure returns (uint256); function getOwnerPercent(address _owner) external view returns (uint256); } /** @title ERC721MetadataExt * @dev Metadata (externally) for the contract **/ interface ERC721MetadataExt { function getTokenURI(uint256 _tokenId) external pure returns (bytes32[4] buffer, uint16 count); function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256 _tokenId); } /** @title ERC721ERC721TokenReceiver **/ interface ERC721TokenReceiver { function onERC721Received(address _from, uint256 _tokenId, bytes data) external returns(bytes4); } /// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens /// @author Dieter Shirley <dete@axiomzen.co> (https://github.com/dete) contract ERC721 { // Required methods function totalSupply() public view returns (uint256 total); function balanceOf(address _owner) external view returns (uint256 balance); function ownerOf(uint256 _tokenId) public view returns (address owner); function approve(address _to, uint256 _tokenId) external payable; function transfer(address _to, uint256 _tokenId) external payable; function transferFrom(address _from, address _to, uint256 _tokenId) external payable; // Events event Transfer(address indexed _from, address indexed _to, uint256 _tokenId); // New Card is to ensure there is a record of card purchase in case an error occurs event NewCard(address indexed _from, uint256 _cardId); event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId); event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved); event ContractUpgrade(address _newContract); // Not in the standard, but using "Birth" to be consistent with announcing newly issued cards event Birth(uint256 _newCardIndex, address _creator, string _metadata, uint256 _price, uint16 _max); // Optional // function name() public view returns (string name); // function symbol() public view returns (string symbol); // function tokensOfOwner(address _owner) external view returns (uint256[] tokenIds); // function tokenMetadata(uint256 _tokenId, string _preferredTransport) public view returns (string infoUrl); // ERC-165 Compatibility (https://github.com/ethereum/EIPs/issues/165) function supportsInterface(bytes4 _interfaceID) external view returns (bool); } /** @title Glossy * @dev This is the main Glossy contract **/ contract Glossy is Pausable, ERC721 { bytes4 constant InterfaceSignature_ERC165 = bytes4(keccak256('supportsInterface(bytes4)')); // From CryptoKitties. This is supported as well as the new 721 defs bytes4 constant InterfaceSignature_ERC721 = bytes4(keccak256('name()')) ^ bytes4(keccak256('symbol()')) ^ bytes4(keccak256('totalSupply()')) ^ bytes4(keccak256('balanceOf(address)')) ^ bytes4(keccak256('ownerOf(uint256)')) ^ bytes4(keccak256('approve(address,uint256)')) ^ bytes4(keccak256('transfer(address,uint256)')) ^ bytes4(keccak256('transferFrom(address,address,uint256)')) ^ bytes4(keccak256('tokensOfOwner(address)')) ^ bytes4(keccak256('tokenMetadata(uint256,string)')); bytes4 private constant ERC721_RECEIVED = 0xf0b9e5ba; /** @dev ERC165 implemented. This implements the original ERC721 interface * as well as the "official" interface. * @param _interfaceID the combined keccak256 hash of the interface methods **/ function supportsInterface(bytes4 _interfaceID) external view returns (bool) { return (_interfaceID == InterfaceSignature_ERC165 || _interfaceID == InterfaceSignature_ERC721 || _interfaceID == 0x80ac58cd || _interfaceID == 0x5b5e139f || _interfaceID == 0x780e9d63 ); } uint256 public minimumPrice; uint256 public globalCut; address public pendingMaster; address public masterAddress; address public workerAddress; string public metadataURL; address public newContract; address public txGuard; address public erc721Metadata; /* ERC20 Compatibility */ string public constant name = "Glossy"; string public constant symbol = "GLSY"; mapping (uint256 => address) public tokenIndexToOwner; mapping (address => uint256) public ownershipTokenCount; mapping (uint256 => address) public tokenIndexToApproved; mapping (address => mapping (address => bool)) public operatorApprovals; modifier canOperate(uint256 _tokenId) { address owner = tokenIndexToOwner[_tokenId]; require(msg.sender == owner || operatorApprovals[owner][msg.sender]); _; } modifier canTransfer(uint256 _tokenId) { address owner = tokenIndexToOwner[_tokenId]; require(msg.sender == owner || msg.sender == tokenIndexToApproved[_tokenId] || operatorApprovals[owner][msg.sender]); _; } modifier onlyMaster() { require(msg.sender == masterAddress); _; } modifier onlyWorker() { require(msg.sender == workerAddress); _; } // // Setting addresses for control and contract helpers // /** @dev Set the master address responsible for function level contract control * @param _newMaster New Address for master **/ function setMaster(address _newMaster) external onlyMaster { require(_newMaster != address(0)); pendingMaster = _newMaster; } /** @dev Accept master address **/ function acceptMaster() external { require(pendingMaster != address(0)); require(pendingMaster == msg.sender); masterAddress = pendingMaster; } /** @dev Set the worker address responsible for card creation * @param _newWorker New Worker for card creation **/ function setWorker(address _newWorker) external onlyMaster { require(_newWorker != address(0)); workerAddress = _newWorker; } /** @dev Set new contract address, emits a ContractUpgrade * @param _newContract The address of the new contract **/ function setContract(address _newContract) external onlyOwner { require(_newContract != address(0)); emit ContractUpgrade(_newContract); newContract = _newContract; } /** @dev Set contract for txGuard, a contract used to recover funds on transfers * @param _txGuard address for txGuard **/ function setTxGuard(address _txGuard) external onlyMaster { require(_txGuard != address(0)); txGuard = _txGuard; } /** @dev Set ERC721Metadata contract * @param _erc721Metadata is the contract address **/ function setErc721Metadata(address _erc721Metadata) external onlyMaster { require(_erc721Metadata != address(0)); erc721Metadata = _erc721Metadata; } /* This structure attempts to minimize data stored in contract. On average, assuming 10 cards, it would use 128 bits which is reasonable in terms of storage. CK uses 512 bits per token. Baseline 512 bits Single 1024 bits Average (1024 + 256) / 10 = 128 bits */ struct Card { uint16 count; // 16 uint16 max; // 16 uint256 price; // 256 address creator; // 160 string dataHash; // 256 string metadata; // 320 } // Structure done this way for readability struct Token { uint256 card; } Card[] cards; Token[] tokens; constructor(address _workerAddress, uint256 _minimumPrice, uint256 _globalCut, string _metadataURL) public { masterAddress = msg.sender; workerAddress = _workerAddress; minimumPrice = _minimumPrice; globalCut = _globalCut; metadataURL = _metadataURL; // Create a card 0, necessary as a placeholder for new card creation _newCard(0,0,0,address(0),"",""); } // // Enumerated // /** @dev Total supply of Glossy cards **/ function totalSupply() public view returns (uint256 _totalTokens) { return tokens.length; } /** @dev A token identifier for the given index * @param _index the index of the token **/ function tokenByIndex(uint256 _index) external pure returns (uint256) { return _index + 1; } // // // /** @dev Balance for a particular address. * @param _owner The owner of the returned balance **/ function balanceOf(address _owner) external view returns (uint256 _balance) { return ownershipTokenCount[_owner]; } /**** ERC721 ****/ function _newCard(uint16 _count, uint16 _max, uint256 _price, address _creator, string _dataHash, string _metadata) internal returns (uint256 newCardIndex){ Card memory card = Card({ count:_count, max:_max, price:_price, creator:_creator, dataHash:_dataHash, metadata:_metadata }); newCardIndex = cards.push(card) - 1; emit Birth(newCardIndex, _creator, _metadata, _price, _max); } // Worker will populate a card and assign it to the token function populateNew(uint16 _max, uint256 _price, address _creator, string _dataHash, string _metadata, uint256 _tokenId) external onlyWorker { uint16 count = (_tokenId == 0 ? 0 : 1); uint256 newCardIndex = _newCard(count, _max, _price, _creator, _dataHash, _metadata); // If we are creating a new series entirely programmatically if(_tokenId == 0) { return; } // Make sure the token at the index isn't already populated. require(tokens[_tokenId].card == 0); // Set the card to the newly added card index tokens[_tokenId].card = newCardIndex; // We have to transfer at this point rather than purchaseNew uint256 cutAmount = _getCut(uint128(_price), _creator); uint256 amount = _price - cutAmount; _creator.transfer(amount); } // Hopefully never needed. function correctNew(uint256 _cardId, uint256 _tokenId) external onlyWorker { // Make sure the token at the index isn't already populated. require(tokens[_tokenId].card == 0); // Set the card to the newly added card index tokens[_tokenId].card = _cardId; } // Purchase hot off the press // Accept funds and let backend authorize the rest function purchaseNew(uint256 _cardId) external payable whenNotPaused returns (uint256 tokenId) { // Must be minimum purchase price to prevent empty tokens being bought for ~0 require(msg.value >= minimumPrice); // // Transfer the token, step 1 of a two step process. tokenId = tokens.push(Token({card:0})) - 1; tokenIndexToOwner[tokenId] = msg.sender; ownershipTokenCount[msg.sender]++; emit NewCard(msg.sender, _cardId); emit Transfer(address(0), msg.sender, tokenId); } // Standard purchase, website is responsible for calling this OR purchaseNew function purchase(uint256 _cardId) public payable whenNotPaused { Card storage card = cards[_cardId]; address creator = card.creator; require(card.count < card.max); require(msg.value == card.price); card.count++; uint256 tokenId = tokens.push(Token({card:_cardId})) - 1; tokenIndexToOwner[tokenId] = msg.sender; ownershipTokenCount[msg.sender]++; emit Transfer(address(0), msg.sender, tokenId); uint256 amount = msg.value - _getCut(uint128(msg.value), creator); creator.transfer(amount); } /* Internal transfer method */ function _transfer(address _from, address _to, uint256 _tokenId) internal { // Update ownership counts ownershipTokenCount[_from]--; ownershipTokenCount[_to]++; // Transfer ownership tokenIndexToOwner[_tokenId] = _to; // Emit transfer event emit Transfer(_from, _to, _tokenId); } /** @dev Transfer asset to a particular address. * @param _to Address receiving the asset * @param _tokenId ID of asset **/ function transfer(address _to, uint256 _tokenId) external payable whenNotPaused { require(_to != address(0)); require(_to != address(this)); require(msg.sender == ownerOf(_tokenId)); // txGuard is a mechanism that allows a percentage of the transaction to be accepted to benefit asset holders if(txGuard != address(0)) { require(TXGuard(txGuard).getTxAmount(_tokenId) == msg.value); transferCut(msg.value, _tokenId); } _transfer(msg.sender, _to, _tokenId); } /** @dev Transfer asset to a particular address by worker * @param _to Address receiving the asset * @param _tokenId ID of asset **/ function transferByWorker(address _to, uint256 _tokenId) external onlyWorker { require(_to != address(0)); require(_to != address(this)); _transfer(msg.sender, _to, _tokenId); } /* Two step transfer to ensure ownership */ function approve(address _approved, uint256 _tokenId) external payable canOperate(_tokenId) { address _owner = tokenIndexToOwner[_tokenId]; if (_owner == address(0)) { _owner = address(this); } tokenIndexToApproved[_tokenId] = _approved; emit Approval(_owner, _approved, _tokenId); } function setApprovalForAll(address _operator, bool _approved) external { operatorApprovals[msg.sender][_operator] = _approved; emit ApprovalForAll(msg.sender, _operator, _approved); } function getApproved(uint256 _tokenId) external view returns (address) { return tokenIndexToApproved[_tokenId]; } function isApprovedForAll(address _owner, address _operator) external view returns (bool) { return operatorApprovals[_owner][_operator]; } function transferFrom(address _from, address _to, uint256 _tokenId) payable whenNotPaused external { require(_to != address(0)); require(_to != address(this)); require(tokenIndexToApproved[_tokenId] == msg.sender); require(_from == ownerOf(_tokenId)); // txGuard is a mechanism that allows a percentage of the transaction to be accepted to benefit asset holders if(txGuard != address(0)) { require(TXGuard(txGuard).getTxAmount(_tokenId) == msg.value); transferCut(msg.value, _tokenId); } _transfer(_from, _to, _tokenId); } function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes data) external payable whenNotPaused { _safeTransferFrom(_from, _to, _tokenId, data); } function safeTransferFrom(address _from, address _to, uint256 _tokenId) external payable whenNotPaused { _safeTransferFrom(_from, _to, _tokenId, ""); } function _safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes data) private canTransfer(_tokenId) { address owner = tokenIndexToOwner[_tokenId]; if (owner == address(0)) { owner = address(this); } require(owner == _from); require(_to != address(0)); if(txGuard != address(0)) { require(TXGuard(txGuard).getTxAmount(_tokenId) == msg.value); transferCut(msg.value, _tokenId); } _transfer(_from, _to, _tokenId); uint256 codeSize; assembly { codeSize := extcodesize(_to) } if(codeSize == 0) { return; } bytes4 retval = ERC721TokenReceiver(_to).onERC721Received(_from, _tokenId, data); require(retval == ERC721_RECEIVED); } /** @dev Take a token and attempt to transfer copies to multiple addresses. * This can only be executed by a worker. * @param _to Addresses receiving the asset. * @param _cardId The card for which tokens should be assigned **/ function multiTransfer(address[] _to, uint256 _cardId) external onlyWorker { Card storage _card = cards[_cardId]; require(_card.count + _to.length <= _card.max); _card.count = _card.count + uint8(_to.length); for(uint16 i = 0; i < _to.length; i++) { uint256 tokenId = tokens.push(Token({card:_cardId})) - 1; address newOwner = _to[i]; tokenIndexToOwner[tokenId] = newOwner; ownershipTokenCount[newOwner]++; emit Transfer(address(0), newOwner, tokenId); } } /** @dev Returns the owner of the token index given. * @param _tokenId The token index whose owner is queried. **/ function ownerOf(uint256 _tokenId) public view returns (address owner) { owner = tokenIndexToOwner[_tokenId]; } function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256 _tokenId) { require(erc721Metadata != address(0)); _tokenId = ERC721MetadataExt(erc721Metadata).tokenOfOwnerByIndex(_owner, _index); } function tokensOfOwner(address _owner) external view returns (uint256[] tokenIds) { require(erc721Metadata != address(0)); uint256 bal = this.balanceOf(_owner); uint256[] memory _tokenIds = new uint256[](bal); uint256 _index = 0; for(; _index < bal; _index++) { _tokenIds[_index] = this.tokenOfOwnerByIndex(_owner, _index); } return _tokenIds; } /** @dev This returns the metadata for the given token. * tokenURI points to another contract, by default at address 0. * Metadata is still being debated, and the current implementation requires * some verbose JSON which seems against the spirit of data efficiency. The * ERC721 tokenMetadata method is implemented for compatibility. * @param _tokenId The token index for which the metadata should be returned. **/ function tokenURI(uint256 _tokenId) external view returns (string infoUrl) { require(erc721Metadata != address(0)); // URL for metadata bytes32[4] memory buffer; uint256 count; (buffer, count) = ERC721MetadataExt(erc721Metadata).getTokenURI(_tokenId); return _toString(buffer, count); } /** @dev This returns the metadata for the given token. * This is currently supported while tokenURI is not. * @param _tokenId The token index for which the metadata should be returned. * @param _preferredTransport The protocol (https, ipfs) of the metadata source. **/ function tokenMetadata(uint256 _tokenId, string _preferredTransport) external view returns (string metadata) { Token storage _token = tokens[_tokenId]; Card storage _card = cards[_token.card]; if(keccak256(_preferredTransport) == keccak256("http")) { return _concat(metadataURL, _card.metadata); } return _card.metadata; } /** @dev Set the metadata URL * @param _metadataURL New URL **/ function setMetadataURL(string _metadataURL) external onlyMaster { metadataURL = _metadataURL; } function setMinimumPrice(uint256 _minimumPrice) external onlyMaster { minimumPrice = _minimumPrice; } function setCreatorAddress(address _newAddress, uint256 _cardId) external whenNotPaused { Card storage card = cards[_cardId]; address creator = card.creator; require(_newAddress != address(0)); require(msg.sender == creator); card.creator = _newAddress; } /** @dev This is a withdrawl method, though it isn't intended to be used often or for much. * @param _amount Amount to be moved **/ function withdrawAmount(uint256 _amount) external onlyMaster { uint256 balance = address(this).balance; require(_amount <= balance); masterAddress.transfer(_amount); } /** @dev This returns the amount required to send the contract for a transfer. * @param _tokenId The token index to be checked **/ function getTxAmount(uint256 _tokenId) external view returns (uint256 _amount) { if(txGuard == address(0)) return 0; return TXGuard(txGuard).getTxAmount(_tokenId); } /** @dev Transfer a fixed cut to the asset owner * @param _cutAmount amount of cut **/ function transferCut(uint256 _cutAmount, uint256 _tokenId) internal { Token storage _token = tokens[_tokenId]; Card storage _card = cards[_token.card]; address creatorAddress = _card.creator; uint256 creatorAmount = _cutAmount - _getCut(uint128(_cutAmount * 15), creatorAddress); creatorAddress.transfer(creatorAmount); } /** @dev Set the global cut * @param _cut percentage of asset transaction **/ function setGlobalCut(uint256 _cut) external onlyMaster { globalCut = _cut; } /** @dev Get the cut for contract operations * @param _amount Total price of item **/ function _getCut(uint128 _amount, address _creator) internal view returns (uint256) { if(txGuard != address(0)) { return _amount * TXGuard(txGuard).getOwnerPercent(_creator) / 10000; } return _amount * globalCut / 10000; } // Helper Functions /** @dev Via CryptoKitties: Adapted from memcpy() by @arachnid (Nick Johnson <arachnid@notdot.net>) * This method is licenced under the Apache License. * Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol **/ function _memcpy(uint _dest, uint _src, uint _len) private pure { // Copy word-length chunks while possible for(; _len >= 32; _len -= 32) { assembly { mstore(_dest, mload(_src)) } _dest += 32; _src += 32; } // Copy remaining bytes uint256 mask = 256 ** (32 - _len) - 1; assembly { let srcpart := and(mload(_src), not(mask)) let destpart := and(mload(_dest), mask) mstore(_dest, or(destpart, srcpart)) } } /** @dev Via CryptoKitties: Adapted from toString(slice) by @arachnid (Nick Johnson <arachnid@notdot.net>) * This method is licenced under the Apache License. * Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol **/ function _toString(bytes32[4] _rawBytes, uint256 _stringLength) internal pure returns (string outputString) { outputString = new string(_stringLength); uint256 outputPtr; uint256 bytesPtr; assembly { outputPtr := add(outputString, 32) bytesPtr := _rawBytes } _memcpy(outputPtr, bytesPtr, _stringLength); } /** @dev This method takes two strings, concatenates the bytes, and then returns a string. * @param _first First string * @param _second Second string **/ function _concat(string _first, string _second) internal pure returns (string _result){ bytes memory __first = bytes(_first); bytes memory __second = bytes(_second); _result = new string(__first.length + __second.length); bytes memory __result = bytes(_result); uint ptr = 0; uint i = 0; for (; i < __first.length; i++) __result[ptr++] = __first[i]; for (i = 0; i < __second.length; i++) __result[ptr++] = __second[i]; _result = string(__result); } }
This returns the amount required to send the contract for a transfer. _tokenId The token index to be checked/
function getTxAmount(uint256 _tokenId) external view returns (uint256 _amount) { if(txGuard == address(0)) return 0; return TXGuard(txGuard).getTxAmount(_tokenId); }
14,017,916
// SPDX-License-Identifier: AGPL-3.0-only /** * DepositBoxEth.sol - SKALE Interchain Messaging Agent * Copyright (C) 2019-Present SKALE Labs * @author Artem Payvin * * SKALE IMA is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * SKALE IMA is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with SKALE IMA. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.8.6; import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol"; import "@skalenetwork/ima-interfaces/mainnet/DepositBoxes/IDepositBoxEth.sol"; import "../DepositBox.sol"; import "../../Messages.sol"; /** * @title DepositBoxEth * @dev Runs on mainnet, * accepts messages from schain, * stores deposits of ETH. */ contract DepositBoxEth is DepositBox, IDepositBoxEth { using AddressUpgradeable for address payable; mapping(address => uint256) public approveTransfers; mapping(bytes32 => uint256) public transferredAmount; mapping(bytes32 => bool) public activeEthTransfers; event ActiveEthTransfers(bytes32 indexed schainHash, bool active); receive() external payable override { revert("Use deposit function"); } /** * @dev Allows `msg.sender` to send ETH from mainnet to schain. * * Requirements: * * - Schain name must not be `Mainnet`. * - Receiver contract should be added as twin contract on schain. * - Schain that receives tokens should not be killed. */ function deposit(string memory schainName) external payable override rightTransaction(schainName, msg.sender) whenNotKilled(keccak256(abi.encodePacked(schainName))) { bytes32 schainHash = keccak256(abi.encodePacked(schainName)); address contractReceiver = schainLinks[schainHash]; require(contractReceiver != address(0), "Unconnected chain"); _saveTransferredAmount(schainHash, msg.value); messageProxy.postOutgoingMessage( schainHash, contractReceiver, Messages.encodeTransferEthMessage(msg.sender, msg.value) ); } /** * @dev Allows MessageProxyForMainnet contract to execute transferring ERC20 token from schain to mainnet. * * Requirements: * * - Schain from which the eth came should not be killed. * - Sender contract should be defined and schain name cannot be `Mainnet`. * - Amount of eth on DepositBoxEth should be equal or more than transferred amount. */ function postMessage( bytes32 schainHash, address sender, bytes calldata data ) external override onlyMessageProxy whenNotKilled(schainHash) checkReceiverChain(schainHash, sender) { Messages.TransferEthMessage memory message = Messages.decodeTransferEthMessage(data); require( message.amount <= address(this).balance, "Not enough money to finish this transaction" ); _removeTransferredAmount(schainHash, message.amount); if (!activeEthTransfers[schainHash]) { approveTransfers[message.receiver] += message.amount; } else { payable(message.receiver).sendValue(message.amount); } } /** * @dev Transfers a user's ETH. * * Requirements: * * - DepositBoxETh must have sufficient ETH. * - User must be approved for ETH transfer. */ function getMyEth() external override { require(approveTransfers[msg.sender] > 0, "User has insufficient ETH"); uint256 amount = approveTransfers[msg.sender]; approveTransfers[msg.sender] = 0; payable(msg.sender).sendValue(amount); } /** * @dev Allows Schain owner to return each user their ETH. * * Requirements: * * - Amount of ETH on schain should be equal or more than transferred amount. * - Receiver address must not be null. * - msg.sender should be an owner of schain * - IMA transfers Mainnet <-> schain should be killed */ function getFunds(string calldata schainName, address payable receiver, uint amount) external override onlySchainOwner(schainName) whenKilled(keccak256(abi.encodePacked(schainName))) { require(receiver != address(0), "Receiver address has to be set"); bytes32 schainHash = keccak256(abi.encodePacked(schainName)); require(transferredAmount[schainHash] >= amount, "Incorrect amount"); _removeTransferredAmount(schainHash, amount); receiver.sendValue(amount); } /** * @dev Allows Schain owner to switch on or switch off active eth transfers. * * Requirements: * * - msg.sender should be an owner of schain * - IMA transfers Mainnet <-> schain should be killed */ function enableActiveEthTransfers(string calldata schainName) external override onlySchainOwner(schainName) whenNotKilled(keccak256(abi.encodePacked(schainName))) { bytes32 schainHash = keccak256(abi.encodePacked(schainName)); require(!activeEthTransfers[schainHash], "Active eth transfers enabled"); emit ActiveEthTransfers(schainHash, true); activeEthTransfers[schainHash] = true; } /** * @dev Allows Schain owner to switch on or switch off active eth transfers. * * Requirements: * * - msg.sender should be an owner of schain * - IMA transfers Mainnet <-> schain should be killed */ function disableActiveEthTransfers(string calldata schainName) external override onlySchainOwner(schainName) whenNotKilled(keccak256(abi.encodePacked(schainName))) { bytes32 schainHash = keccak256(abi.encodePacked(schainName)); require(activeEthTransfers[schainHash], "Active eth transfers disabled"); emit ActiveEthTransfers(schainHash, false); activeEthTransfers[schainHash] = false; } /** * @dev Returns receiver of message. * * Requirements: * * - Sender contract should be defined and schain name cannot be `Mainnet`. */ function gasPayer( bytes32 schainHash, address sender, bytes calldata data ) external view override checkReceiverChain(schainHash, sender) returns (address) { Messages.TransferEthMessage memory message = Messages.decodeTransferEthMessage(data); return message.receiver; } /** * @dev Creates a new DepositBoxEth contract. */ function initialize( IContractManager contractManagerOfSkaleManagerValue, ILinker linkerValue, IMessageProxyForMainnet messageProxyValue ) public override(DepositBox, IDepositBox) initializer { DepositBox.initialize(contractManagerOfSkaleManagerValue, linkerValue, messageProxyValue); } /** * @dev Saves amount of ETH that was transferred to schain. */ function _saveTransferredAmount(bytes32 schainHash, uint256 amount) private { transferredAmount[schainHash] += amount; } /** * @dev Removes amount of ETH that was transferred from schain. */ function _removeTransferredAmount(bytes32 schainHash, uint256 amount) private { transferredAmount[schainHash] -= amount; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: AGPL-3.0-only /** * IDepositBoxEth.sol - SKALE Interchain Messaging Agent * Copyright (C) 2021-Present SKALE Labs * @author Dmytro Stebaiev * * SKALE IMA is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * SKALE IMA is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with SKALE IMA. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity >=0.6.10 <0.9.0; import "../IDepositBox.sol"; interface IDepositBoxEth is IDepositBox { receive() external payable; function deposit(string memory schainName) external payable; function getMyEth() external; function getFunds(string calldata schainName, address payable receiver, uint amount) external; function enableActiveEthTransfers(string calldata schainName) external; function disableActiveEthTransfers(string calldata schainName) external; } // SPDX-License-Identifier: AGPL-3.0-only /** * DepositBox.sol - SKALE Interchain Messaging Agent * Copyright (C) 2021-Present SKALE Labs * @author Artem Payvin * @author Dmytro Stebaiev * * SKALE IMA is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * SKALE IMA is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with SKALE IMA. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.8.6; import "@skalenetwork/ima-interfaces/mainnet/IDepositBox.sol"; import "./Twin.sol"; /** * @title DepositBox * @dev Abstract contracts for DepositBoxes on mainnet. */ abstract contract DepositBox is IDepositBox, Twin { ILinker public linker; // schainHash => true if automatic deployment tokens on schain was enabled mapping(bytes32 => bool) private _automaticDeploy; bytes32 public constant DEPOSIT_BOX_MANAGER_ROLE = keccak256("DEPOSIT_BOX_MANAGER_ROLE"); /** * @dev Modifier for checking whether schain was not killed. */ modifier whenNotKilled(bytes32 schainHash) { require(linker.isNotKilled(schainHash), "Schain is killed"); _; } /** * @dev Modifier for checking whether schain was killed. */ modifier whenKilled(bytes32 schainHash) { require(!linker.isNotKilled(schainHash), "Schain is not killed"); _; } /** * @dev Modifier for checking whether schainName is not equal to `Mainnet` * and address of receiver is not equal to null before transferring funds from mainnet to schain. */ modifier rightTransaction(string memory schainName, address to) { require( keccak256(abi.encodePacked(schainName)) != keccak256(abi.encodePacked("Mainnet")), "SKALE chain name cannot be Mainnet" ); require(to != address(0), "Receiver address cannot be null"); _; } /** * @dev Modifier for checking whether schainHash is not equal to `Mainnet` * and sender contract was added as contract processor on schain. */ modifier checkReceiverChain(bytes32 schainHash, address sender) { require( schainHash != keccak256(abi.encodePacked("Mainnet")) && sender == schainLinks[schainHash], "Receiver chain is incorrect" ); _; } /** * @dev Allows Schain owner turn on whitelist of tokens. */ function enableWhitelist(string memory schainName) external override onlySchainOwner(schainName) { _automaticDeploy[keccak256(abi.encodePacked(schainName))] = false; } /** * @dev Allows Schain owner turn off whitelist of tokens. */ function disableWhitelist(string memory schainName) external override onlySchainOwner(schainName) { _automaticDeploy[keccak256(abi.encodePacked(schainName))] = true; } function initialize( IContractManager contractManagerOfSkaleManagerValue, ILinker newLinker, IMessageProxyForMainnet messageProxyValue ) public override virtual initializer { Twin.initialize(contractManagerOfSkaleManagerValue, messageProxyValue); _setupRole(LINKER_ROLE, address(newLinker)); linker = newLinker; } /** * @dev Returns is whitelist enabled on schain. */ function isWhitelisted(string memory schainName) public view override returns (bool) { return !_automaticDeploy[keccak256(abi.encodePacked(schainName))]; } } // SPDX-License-Identifier: AGPL-3.0-only /** * Messages.sol - SKALE Interchain Messaging Agent * Copyright (C) 2021-Present SKALE Labs * @author Dmytro Stebaiev * * SKALE IMA is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * SKALE IMA is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with SKALE IMA. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.8.6; /** * @title Messages * @dev Library for encoding and decoding messages * for transferring from Mainnet to Schain and vice versa. */ library Messages { /** * @dev Enumerator that describes all supported message types. */ enum MessageType { EMPTY, TRANSFER_ETH, TRANSFER_ERC20, TRANSFER_ERC20_AND_TOTAL_SUPPLY, TRANSFER_ERC20_AND_TOKEN_INFO, TRANSFER_ERC721, TRANSFER_ERC721_AND_TOKEN_INFO, USER_STATUS, INTERCHAIN_CONNECTION, TRANSFER_ERC1155, TRANSFER_ERC1155_AND_TOKEN_INFO, TRANSFER_ERC1155_BATCH, TRANSFER_ERC1155_BATCH_AND_TOKEN_INFO, TRANSFER_ERC721_WITH_METADATA, TRANSFER_ERC721_WITH_METADATA_AND_TOKEN_INFO } /** * @dev Structure for base message. */ struct BaseMessage { MessageType messageType; } /** * @dev Structure for describing ETH. */ struct TransferEthMessage { BaseMessage message; address receiver; uint256 amount; } /** * @dev Structure for user status. */ struct UserStatusMessage { BaseMessage message; address receiver; bool isActive; } /** * @dev Structure for describing ERC20 token. */ struct TransferErc20Message { BaseMessage message; address token; address receiver; uint256 amount; } /** * @dev Structure for describing additional data for ERC20 token. */ struct Erc20TokenInfo { string name; uint8 decimals; string symbol; } /** * @dev Structure for describing ERC20 with token supply. */ struct TransferErc20AndTotalSupplyMessage { TransferErc20Message baseErc20transfer; uint256 totalSupply; } /** * @dev Structure for describing ERC20 with token info. */ struct TransferErc20AndTokenInfoMessage { TransferErc20Message baseErc20transfer; uint256 totalSupply; Erc20TokenInfo tokenInfo; } /** * @dev Structure for describing base ERC721. */ struct TransferErc721Message { BaseMessage message; address token; address receiver; uint256 tokenId; } /** * @dev Structure for describing base ERC721 with metadata. */ struct TransferErc721MessageWithMetadata { TransferErc721Message erc721message; string tokenURI; } /** * @dev Structure for describing ERC20 with token info. */ struct Erc721TokenInfo { string name; string symbol; } /** * @dev Structure for describing additional data for ERC721 token. */ struct TransferErc721AndTokenInfoMessage { TransferErc721Message baseErc721transfer; Erc721TokenInfo tokenInfo; } /** * @dev Structure for describing additional data for ERC721 token with metadata. */ struct TransferErc721WithMetadataAndTokenInfoMessage { TransferErc721MessageWithMetadata baseErc721transferWithMetadata; Erc721TokenInfo tokenInfo; } /** * @dev Structure for describing whether interchain connection is allowed. */ struct InterchainConnectionMessage { BaseMessage message; bool isAllowed; } /** * @dev Structure for describing whether interchain connection is allowed. */ struct TransferErc1155Message { BaseMessage message; address token; address receiver; uint256 id; uint256 amount; } /** * @dev Structure for describing ERC1155 token in batches. */ struct TransferErc1155BatchMessage { BaseMessage message; address token; address receiver; uint256[] ids; uint256[] amounts; } /** * @dev Structure for describing ERC1155 token info. */ struct Erc1155TokenInfo { string uri; } /** * @dev Structure for describing message for transferring ERC1155 token with info. */ struct TransferErc1155AndTokenInfoMessage { TransferErc1155Message baseErc1155transfer; Erc1155TokenInfo tokenInfo; } /** * @dev Structure for describing message for transferring ERC1155 token in batches with info. */ struct TransferErc1155BatchAndTokenInfoMessage { TransferErc1155BatchMessage baseErc1155Batchtransfer; Erc1155TokenInfo tokenInfo; } /** * @dev Returns type of message for encoded data. */ function getMessageType(bytes calldata data) internal pure returns (MessageType) { uint256 firstWord = abi.decode(data, (uint256)); if (firstWord % 32 == 0) { return getMessageType(data[firstWord:]); } else { return abi.decode(data, (Messages.MessageType)); } } /** * @dev Encodes message for transferring ETH. Returns encoded message. */ function encodeTransferEthMessage(address receiver, uint256 amount) internal pure returns (bytes memory) { TransferEthMessage memory message = TransferEthMessage( BaseMessage(MessageType.TRANSFER_ETH), receiver, amount ); return abi.encode(message); } /** * @dev Decodes message for transferring ETH. Returns structure `TransferEthMessage`. */ function decodeTransferEthMessage( bytes calldata data ) internal pure returns (TransferEthMessage memory) { require(getMessageType(data) == MessageType.TRANSFER_ETH, "Message type is not ETH transfer"); return abi.decode(data, (TransferEthMessage)); } /** * @dev Encodes message for transferring ETH. Returns encoded message. */ function encodeTransferErc20Message( address token, address receiver, uint256 amount ) internal pure returns (bytes memory) { TransferErc20Message memory message = TransferErc20Message( BaseMessage(MessageType.TRANSFER_ERC20), token, receiver, amount ); return abi.encode(message); } /** * @dev Encodes message for transferring ERC20 with total supply. Returns encoded message. */ function encodeTransferErc20AndTotalSupplyMessage( address token, address receiver, uint256 amount, uint256 totalSupply ) internal pure returns (bytes memory) { TransferErc20AndTotalSupplyMessage memory message = TransferErc20AndTotalSupplyMessage( TransferErc20Message( BaseMessage(MessageType.TRANSFER_ERC20_AND_TOTAL_SUPPLY), token, receiver, amount ), totalSupply ); return abi.encode(message); } /** * @dev Decodes message for transferring ERC20. Returns structure `TransferErc20Message`. */ function decodeTransferErc20Message( bytes calldata data ) internal pure returns (TransferErc20Message memory) { require(getMessageType(data) == MessageType.TRANSFER_ERC20, "Message type is not ERC20 transfer"); return abi.decode(data, (TransferErc20Message)); } /** * @dev Decodes message for transferring ERC20 with total supply. * Returns structure `TransferErc20AndTotalSupplyMessage`. */ function decodeTransferErc20AndTotalSupplyMessage( bytes calldata data ) internal pure returns (TransferErc20AndTotalSupplyMessage memory) { require( getMessageType(data) == MessageType.TRANSFER_ERC20_AND_TOTAL_SUPPLY, "Message type is not ERC20 transfer and total supply" ); return abi.decode(data, (TransferErc20AndTotalSupplyMessage)); } /** * @dev Encodes message for transferring ERC20 with token info. * Returns encoded message. */ function encodeTransferErc20AndTokenInfoMessage( address token, address receiver, uint256 amount, uint256 totalSupply, Erc20TokenInfo memory tokenInfo ) internal pure returns (bytes memory) { TransferErc20AndTokenInfoMessage memory message = TransferErc20AndTokenInfoMessage( TransferErc20Message( BaseMessage(MessageType.TRANSFER_ERC20_AND_TOKEN_INFO), token, receiver, amount ), totalSupply, tokenInfo ); return abi.encode(message); } /** * @dev Decodes message for transferring ERC20 with token info. * Returns structure `TransferErc20AndTokenInfoMessage`. */ function decodeTransferErc20AndTokenInfoMessage( bytes calldata data ) internal pure returns (TransferErc20AndTokenInfoMessage memory) { require( getMessageType(data) == MessageType.TRANSFER_ERC20_AND_TOKEN_INFO, "Message type is not ERC20 transfer with token info" ); return abi.decode(data, (TransferErc20AndTokenInfoMessage)); } /** * @dev Encodes message for transferring ERC721. * Returns encoded message. */ function encodeTransferErc721Message( address token, address receiver, uint256 tokenId ) internal pure returns (bytes memory) { TransferErc721Message memory message = TransferErc721Message( BaseMessage(MessageType.TRANSFER_ERC721), token, receiver, tokenId ); return abi.encode(message); } /** * @dev Decodes message for transferring ERC721. * Returns structure `TransferErc721Message`. */ function decodeTransferErc721Message( bytes calldata data ) internal pure returns (TransferErc721Message memory) { require(getMessageType(data) == MessageType.TRANSFER_ERC721, "Message type is not ERC721 transfer"); return abi.decode(data, (TransferErc721Message)); } /** * @dev Encodes message for transferring ERC721 with token info. * Returns encoded message. */ function encodeTransferErc721AndTokenInfoMessage( address token, address receiver, uint256 tokenId, Erc721TokenInfo memory tokenInfo ) internal pure returns (bytes memory) { TransferErc721AndTokenInfoMessage memory message = TransferErc721AndTokenInfoMessage( TransferErc721Message( BaseMessage(MessageType.TRANSFER_ERC721_AND_TOKEN_INFO), token, receiver, tokenId ), tokenInfo ); return abi.encode(message); } /** * @dev Decodes message for transferring ERC721 with token info. * Returns structure `TransferErc721AndTokenInfoMessage`. */ function decodeTransferErc721AndTokenInfoMessage( bytes calldata data ) internal pure returns (TransferErc721AndTokenInfoMessage memory) { require( getMessageType(data) == MessageType.TRANSFER_ERC721_AND_TOKEN_INFO, "Message type is not ERC721 transfer with token info" ); return abi.decode(data, (TransferErc721AndTokenInfoMessage)); } /** * @dev Encodes message for transferring ERC721. * Returns encoded message. */ function encodeTransferErc721MessageWithMetadata( address token, address receiver, uint256 tokenId, string memory tokenURI ) internal pure returns (bytes memory) { TransferErc721MessageWithMetadata memory message = TransferErc721MessageWithMetadata( TransferErc721Message( BaseMessage(MessageType.TRANSFER_ERC721_WITH_METADATA), token, receiver, tokenId ), tokenURI ); return abi.encode(message); } /** * @dev Decodes message for transferring ERC721. * Returns structure `TransferErc721MessageWithMetadata`. */ function decodeTransferErc721MessageWithMetadata( bytes calldata data ) internal pure returns (TransferErc721MessageWithMetadata memory) { require( getMessageType(data) == MessageType.TRANSFER_ERC721_WITH_METADATA, "Message type is not ERC721 transfer" ); return abi.decode(data, (TransferErc721MessageWithMetadata)); } /** * @dev Encodes message for transferring ERC721 with token info. * Returns encoded message. */ function encodeTransferErc721WithMetadataAndTokenInfoMessage( address token, address receiver, uint256 tokenId, string memory tokenURI, Erc721TokenInfo memory tokenInfo ) internal pure returns (bytes memory) { TransferErc721WithMetadataAndTokenInfoMessage memory message = TransferErc721WithMetadataAndTokenInfoMessage( TransferErc721MessageWithMetadata( TransferErc721Message( BaseMessage(MessageType.TRANSFER_ERC721_WITH_METADATA_AND_TOKEN_INFO), token, receiver, tokenId ), tokenURI ), tokenInfo ); return abi.encode(message); } /** * @dev Decodes message for transferring ERC721 with token info. * Returns structure `TransferErc721WithMetadataAndTokenInfoMessage`. */ function decodeTransferErc721WithMetadataAndTokenInfoMessage( bytes calldata data ) internal pure returns (TransferErc721WithMetadataAndTokenInfoMessage memory) { require( getMessageType(data) == MessageType.TRANSFER_ERC721_WITH_METADATA_AND_TOKEN_INFO, "Message type is not ERC721 transfer with token info" ); return abi.decode(data, (TransferErc721WithMetadataAndTokenInfoMessage)); } /** * @dev Encodes message for activating user on schain. * Returns encoded message. */ function encodeActivateUserMessage(address receiver) internal pure returns (bytes memory){ return _encodeUserStatusMessage(receiver, true); } /** * @dev Encodes message for locking user on schain. * Returns encoded message. */ function encodeLockUserMessage(address receiver) internal pure returns (bytes memory){ return _encodeUserStatusMessage(receiver, false); } /** * @dev Decodes message for user status. * Returns structure UserStatusMessage. */ function decodeUserStatusMessage(bytes calldata data) internal pure returns (UserStatusMessage memory) { require(getMessageType(data) == MessageType.USER_STATUS, "Message type is not User Status"); return abi.decode(data, (UserStatusMessage)); } /** * @dev Encodes message for allowing interchain connection. * Returns encoded message. */ function encodeInterchainConnectionMessage(bool isAllowed) internal pure returns (bytes memory) { InterchainConnectionMessage memory message = InterchainConnectionMessage( BaseMessage(MessageType.INTERCHAIN_CONNECTION), isAllowed ); return abi.encode(message); } /** * @dev Decodes message for allowing interchain connection. * Returns structure `InterchainConnectionMessage`. */ function decodeInterchainConnectionMessage(bytes calldata data) internal pure returns (InterchainConnectionMessage memory) { require(getMessageType(data) == MessageType.INTERCHAIN_CONNECTION, "Message type is not Interchain connection"); return abi.decode(data, (InterchainConnectionMessage)); } /** * @dev Encodes message for transferring ERC1155 token. * Returns encoded message. */ function encodeTransferErc1155Message( address token, address receiver, uint256 id, uint256 amount ) internal pure returns (bytes memory) { TransferErc1155Message memory message = TransferErc1155Message( BaseMessage(MessageType.TRANSFER_ERC1155), token, receiver, id, amount ); return abi.encode(message); } /** * @dev Decodes message for transferring ERC1155 token. * Returns structure `TransferErc1155Message`. */ function decodeTransferErc1155Message( bytes calldata data ) internal pure returns (TransferErc1155Message memory) { require(getMessageType(data) == MessageType.TRANSFER_ERC1155, "Message type is not ERC1155 transfer"); return abi.decode(data, (TransferErc1155Message)); } /** * @dev Encodes message for transferring ERC1155 with token info. * Returns encoded message. */ function encodeTransferErc1155AndTokenInfoMessage( address token, address receiver, uint256 id, uint256 amount, Erc1155TokenInfo memory tokenInfo ) internal pure returns (bytes memory) { TransferErc1155AndTokenInfoMessage memory message = TransferErc1155AndTokenInfoMessage( TransferErc1155Message( BaseMessage(MessageType.TRANSFER_ERC1155_AND_TOKEN_INFO), token, receiver, id, amount ), tokenInfo ); return abi.encode(message); } /** * @dev Decodes message for transferring ERC1155 with token info. * Returns structure `TransferErc1155AndTokenInfoMessage`. */ function decodeTransferErc1155AndTokenInfoMessage( bytes calldata data ) internal pure returns (TransferErc1155AndTokenInfoMessage memory) { require( getMessageType(data) == MessageType.TRANSFER_ERC1155_AND_TOKEN_INFO, "Message type is not ERC1155AndTokenInfo transfer" ); return abi.decode(data, (TransferErc1155AndTokenInfoMessage)); } /** * @dev Encodes message for transferring ERC1155 token in batches. * Returns encoded message. */ function encodeTransferErc1155BatchMessage( address token, address receiver, uint256[] memory ids, uint256[] memory amounts ) internal pure returns (bytes memory) { TransferErc1155BatchMessage memory message = TransferErc1155BatchMessage( BaseMessage(MessageType.TRANSFER_ERC1155_BATCH), token, receiver, ids, amounts ); return abi.encode(message); } /** * @dev Decodes message for transferring ERC1155 token in batches. * Returns structure `TransferErc1155BatchMessage`. */ function decodeTransferErc1155BatchMessage( bytes calldata data ) internal pure returns (TransferErc1155BatchMessage memory) { require( getMessageType(data) == MessageType.TRANSFER_ERC1155_BATCH, "Message type is not ERC1155Batch transfer" ); return abi.decode(data, (TransferErc1155BatchMessage)); } /** * @dev Encodes message for transferring ERC1155 token in batches with token info. * Returns encoded message. */ function encodeTransferErc1155BatchAndTokenInfoMessage( address token, address receiver, uint256[] memory ids, uint256[] memory amounts, Erc1155TokenInfo memory tokenInfo ) internal pure returns (bytes memory) { TransferErc1155BatchAndTokenInfoMessage memory message = TransferErc1155BatchAndTokenInfoMessage( TransferErc1155BatchMessage( BaseMessage(MessageType.TRANSFER_ERC1155_BATCH_AND_TOKEN_INFO), token, receiver, ids, amounts ), tokenInfo ); return abi.encode(message); } /** * @dev Decodes message for transferring ERC1155 token in batches with token info. * Returns structure `TransferErc1155BatchAndTokenInfoMessage`. */ function decodeTransferErc1155BatchAndTokenInfoMessage( bytes calldata data ) internal pure returns (TransferErc1155BatchAndTokenInfoMessage memory) { require( getMessageType(data) == MessageType.TRANSFER_ERC1155_BATCH_AND_TOKEN_INFO, "Message type is not ERC1155BatchAndTokenInfo transfer" ); return abi.decode(data, (TransferErc1155BatchAndTokenInfoMessage)); } /** * @dev Encodes message for transferring user status on schain. * Returns encoded message. */ function _encodeUserStatusMessage(address receiver, bool isActive) private pure returns (bytes memory) { UserStatusMessage memory message = UserStatusMessage( BaseMessage(MessageType.USER_STATUS), receiver, isActive ); return abi.encode(message); } } // SPDX-License-Identifier: AGPL-3.0-only /** * IDepositBox.sol - SKALE Interchain Messaging Agent * Copyright (C) 2021-Present SKALE Labs * @author Dmytro Stebaiev * * SKALE IMA is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * SKALE IMA is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with SKALE IMA. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity >=0.6.10 <0.9.0; import "@skalenetwork/skale-manager-interfaces/IContractManager.sol"; import "../IGasReimbursable.sol"; import "../IMessageReceiver.sol"; import "./ILinker.sol"; import "./IMessageProxyForMainnet.sol"; import "./ITwin.sol"; interface IDepositBox is ITwin, IMessageReceiver, IGasReimbursable { function initialize( IContractManager contractManagerOfSkaleManagerValue, ILinker newLinker, IMessageProxyForMainnet messageProxyValue ) external; function enableWhitelist(string memory schainName) external; function disableWhitelist(string memory schainName) external; function isWhitelisted(string memory schainName) external view returns (bool); } // SPDX-License-Identifier: AGPL-3.0-only /* IContractManager.sol - SKALE Manager Interfaces Copyright (C) 2021-Present SKALE Labs @author Dmytro Stebaeiv SKALE Manager Interfaces is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager Interfaces is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager Interfaces. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity >=0.6.10 <0.9.0; interface IContractManager { /** * @dev Emitted when contract is upgraded. */ event ContractUpgraded(string contractsName, address contractsAddress); function initialize() external; function setContractsAddress(string calldata contractsName, address newContractsAddress) external; function contracts(bytes32 nameHash) external view returns (address); function getDelegationPeriodManager() external view returns (address); function getBounty() external view returns (address); function getValidatorService() external view returns (address); function getTimeHelpers() external view returns (address); function getConstantsHolder() external view returns (address); function getSkaleToken() external view returns (address); function getTokenState() external view returns (address); function getPunisher() external view returns (address); function getContract(string calldata name) external view returns (address); } // SPDX-License-Identifier: AGPL-3.0-only /** * IGasReimbursable.sol - SKALE Interchain Messaging Agent * Copyright (C) 2021-Present SKALE Labs * @author Artem Payvin * * SKALE IMA is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * SKALE IMA is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with SKALE IMA. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity >=0.6.10 <0.9.0; import "./IMessageReceiver.sol"; interface IGasReimbursable is IMessageReceiver { function gasPayer( bytes32 schainHash, address sender, bytes calldata data ) external returns (address); } // SPDX-License-Identifier: AGPL-3.0-only /** * IMessageReceiver.sol - SKALE Interchain Messaging Agent * Copyright (C) 2021-Present SKALE Labs * @author Dmytro Stebaiev * * SKALE IMA is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * SKALE IMA is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with SKALE IMA. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity >=0.6.10 <0.9.0; interface IMessageReceiver { function postMessage( bytes32 schainHash, address sender, bytes calldata data ) external; } // SPDX-License-Identifier: AGPL-3.0-only /** * ILinker.sol - SKALE Interchain Messaging Agent * Copyright (C) 2021-Present SKALE Labs * @author Dmytro Stebaiev * * SKALE IMA is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * SKALE IMA is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with SKALE IMA. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity >=0.6.10 <0.9.0; import "./ITwin.sol"; interface ILinker is ITwin { function registerMainnetContract(address newMainnetContract) external; function removeMainnetContract(address mainnetContract) external; function connectSchain(string calldata schainName, address[] calldata schainContracts) external; function kill(string calldata schainName) external; function disconnectSchain(string calldata schainName) external; function isNotKilled(bytes32 schainHash) external view returns (bool); function hasMainnetContract(address mainnetContract) external view returns (bool); function hasSchain(string calldata schainName) external view returns (bool connected); } // SPDX-License-Identifier: AGPL-3.0-only /** * IMessageProxyForMainnet.sol - SKALE Interchain Messaging Agent * Copyright (C) 2021-Present SKALE Labs * @author Dmytro Stebaiev * * SKALE IMA is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * SKALE IMA is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with SKALE IMA. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity >=0.6.10 <0.9.0; import "../IMessageProxy.sol"; import "./ICommunityPool.sol"; interface IMessageProxyForMainnet is IMessageProxy { function setCommunityPool(ICommunityPool newCommunityPoolAddress) external; function setNewHeaderMessageGasCost(uint256 newHeaderMessageGasCost) external; function setNewMessageGasCost(uint256 newMessageGasCost) external; function messageInProgress() external view returns (bool); } // SPDX-License-Identifier: AGPL-3.0-only /** * ITwin.sol - SKALE Interchain Messaging Agent * Copyright (C) 2021-Present SKALE Labs * @author Dmytro Stebaiev * * SKALE IMA is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * SKALE IMA is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with SKALE IMA. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity >=0.6.10 <0.9.0; import "./ISkaleManagerClient.sol"; interface ITwin is ISkaleManagerClient { function addSchainContract(string calldata schainName, address contractReceiver) external; function removeSchainContract(string calldata schainName) external; function hasSchainContract(string calldata schainName) external view returns (bool); } // SPDX-License-Identifier: AGPL-3.0-only /** * ISkaleManagerClient.sol - SKALE Interchain Messaging Agent * Copyright (C) 2021-Present SKALE Labs * @author Dmytro Stebaiev * * SKALE IMA is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * SKALE IMA is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with SKALE IMA. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity >=0.6.10 <0.9.0; import "@skalenetwork/skale-manager-interfaces/IContractManager.sol"; interface ISkaleManagerClient { function initialize(IContractManager newContractManagerOfSkaleManager) external; function isSchainOwner(address sender, bytes32 schainHash) external view returns (bool); } // SPDX-License-Identifier: AGPL-3.0-only /** * IMessageProxy.sol - SKALE Interchain Messaging Agent * Copyright (C) 2021-Present SKALE Labs * @author Dmytro Stebaiev * * SKALE IMA is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * SKALE IMA is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with SKALE IMA. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity >=0.6.10 <0.9.0; interface IMessageProxy { /** * @dev Structure that describes message. Should contain sender of message, * destination contract on schain that will receiver message, * data that contains all needed info about token or ETH. */ struct Message { address sender; address destinationContract; bytes data; } /** * @dev Structure that contains fields for bls signature. */ struct Signature { uint256[2] blsSignature; uint256 hashA; uint256 hashB; uint256 counter; } function addConnectedChain(string calldata schainName) external; function postIncomingMessages( string calldata fromSchainName, uint256 startingCounter, Message[] calldata messages, Signature calldata sign ) external; function setNewGasLimit(uint256 newGasLimit) external; function registerExtraContractForAll(address extraContract) external; function removeExtraContractForAll(address extraContract) external; function removeConnectedChain(string memory schainName) external; function postOutgoingMessage( bytes32 targetChainHash, address targetContract, bytes memory data ) external; function registerExtraContract(string memory chainName, address extraContract) external; function removeExtraContract(string memory schainName, address extraContract) external; function setVersion(string calldata newVersion) external; function isContractRegistered( bytes32 schainHash, address contractAddress ) external view returns (bool); function getContractRegisteredLength(bytes32 schainHash) external view returns (uint256); function getContractRegisteredRange( bytes32 schainHash, uint256 from, uint256 to ) external view returns (address[] memory); function getOutgoingMessagesCounter(string calldata targetSchainName) external view returns (uint256); function getIncomingMessagesCounter(string calldata fromSchainName) external view returns (uint256); function isConnectedChain(string memory schainName) external view returns (bool); } // SPDX-License-Identifier: AGPL-3.0-only /** * ICommunityPool.sol - SKALE Interchain Messaging Agent * Copyright (C) 2021-Present SKALE Labs * @author Dmytro Stebaiev * * SKALE IMA is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * SKALE IMA is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with SKALE IMA. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity >=0.6.10 <0.9.0; import "@skalenetwork/skale-manager-interfaces/IContractManager.sol"; import "./ILinker.sol"; import "./IMessageProxyForMainnet.sol"; import "./ITwin.sol"; interface ICommunityPool is ITwin { function initialize( IContractManager contractManagerOfSkaleManagerValue, ILinker linker, IMessageProxyForMainnet messageProxyValue ) external; function refundGasByUser(bytes32 schainHash, address payable node, address user, uint gas) external returns (uint); function rechargeUserWallet(string calldata schainName, address user) external payable; function withdrawFunds(string calldata schainName, uint amount) external; function setMinTransactionGas(uint newMinTransactionGas) external; function refundGasBySchainWallet( bytes32 schainHash, address payable node, uint gas ) external returns (bool); function getBalance(address user, string calldata schainName) external view returns (uint); function checkUserBalance(bytes32 schainHash, address receiver) external view returns (bool); } // SPDX-License-Identifier: AGPL-3.0-only /** * Twin.sol - SKALE Interchain Messaging Agent * Copyright (C) 2021-Present SKALE Labs * @author Artem Payvin * @author Dmytro Stebaiev * @author Vadim Yavorsky * * SKALE IMA is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * SKALE IMA is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with SKALE IMA. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.8.6; import "@skalenetwork/ima-interfaces/mainnet/ITwin.sol"; import "./MessageProxyForMainnet.sol"; import "./SkaleManagerClient.sol"; /** * @title Twin * @dev Runs on Mainnet, * contains logic for connecting paired contracts on Mainnet and on Schain. */ abstract contract Twin is SkaleManagerClient, ITwin { IMessageProxyForMainnet public messageProxy; mapping(bytes32 => address) public schainLinks; bytes32 public constant LINKER_ROLE = keccak256("LINKER_ROLE"); /** * @dev Modifier for checking whether caller is MessageProxy contract. */ modifier onlyMessageProxy() { require(msg.sender == address(messageProxy), "Sender is not a MessageProxy"); _; } /** * @dev Binds a contract on mainnet with their twin on schain. * * Requirements: * * - `msg.sender` must be schain owner or has required role. * - SKALE chain must not already be added. * - Address of contract on schain must be non-zero. */ function addSchainContract(string calldata schainName, address contractReceiver) external override { bytes32 schainHash = keccak256(abi.encodePacked(schainName)); require( hasRole(LINKER_ROLE, msg.sender) || isSchainOwner(msg.sender, schainHash), "Not authorized caller" ); require(schainLinks[schainHash] == address(0), "SKALE chain is already set"); require(contractReceiver != address(0), "Incorrect address of contract receiver on Schain"); schainLinks[schainHash] = contractReceiver; } /** * @dev Removes connection with contract on schain. * * Requirements: * * - `msg.sender` must be schain owner or has required role. * - SKALE chain must already be set. */ function removeSchainContract(string calldata schainName) external override { bytes32 schainHash = keccak256(abi.encodePacked(schainName)); require( hasRole(LINKER_ROLE, msg.sender) || isSchainOwner(msg.sender, schainHash), "Not authorized caller" ); require(schainLinks[schainHash] != address(0), "SKALE chain is not set"); delete schainLinks[schainHash]; } /** * @dev Returns true if mainnet contract and schain contract are connected together for transferring messages. */ function hasSchainContract(string calldata schainName) external view override returns (bool) { return schainLinks[keccak256(abi.encodePacked(schainName))] != address(0); } function initialize( IContractManager contractManagerOfSkaleManagerValue, IMessageProxyForMainnet newMessageProxy ) public virtual initializer { SkaleManagerClient.initialize(contractManagerOfSkaleManagerValue); messageProxy = newMessageProxy; } } // SPDX-License-Identifier: AGPL-3.0-only /** * MessageProxyForMainnet.sol - SKALE Interchain Messaging Agent * Copyright (C) 2019-Present SKALE Labs * @author Artem Payvin * * SKALE IMA is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * SKALE IMA is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with SKALE IMA. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.8.6; import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol"; import "@skalenetwork/skale-manager-interfaces/IWallets.sol"; import "@skalenetwork/skale-manager-interfaces/ISchains.sol"; import "@skalenetwork/ima-interfaces/mainnet/IMessageProxyForMainnet.sol"; import "@skalenetwork/ima-interfaces/mainnet/ICommunityPool.sol"; import "@skalenetwork/skale-manager-interfaces/ISchainsInternal.sol"; import "../MessageProxy.sol"; import "./SkaleManagerClient.sol"; import "./CommunityPool.sol"; interface IMessageProxyForMainnetInitializeFunction is IMessageProxyForMainnet { function initializeAllRegisteredContracts( bytes32 schainHash, address[] calldata contracts ) external; } /** * @title Message Proxy for Mainnet * @dev Runs on Mainnet, contains functions to manage the incoming messages from * `targetSchainName` and outgoing messages to `fromSchainName`. Every SKALE chain with * IMA is therefore connected to MessageProxyForMainnet. * * Messages from SKALE chains are signed using BLS threshold signatures from the * nodes in the chain. Since Ethereum Mainnet has no BLS public key, mainnet * messages do not need to be signed. */ contract MessageProxyForMainnet is SkaleManagerClient, MessageProxy, IMessageProxyForMainnetInitializeFunction { using AddressUpgradeable for address; using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet; /** * 16 Agents * Synchronize time with time.nist.gov * Every agent checks if it is their time slot * Time slots are in increments of 10 seconds * At the start of their slot each agent: * For each connected schain: * Read incoming counter on the dst chain * Read outgoing counter on the src chain * Calculate the difference outgoing - incoming * Call postIncomingMessages function passing (un)signed message array * ID of this schain, Chain 0 represents ETH mainnet, */ ICommunityPool public communityPool; uint256 public headerMessageGasCost; uint256 public messageGasCost; mapping(bytes32 => EnumerableSetUpgradeable.AddressSet) private _registryContracts; string public version; bool public override messageInProgress; /** * @dev Emitted when gas cost for message header was changed. */ event GasCostMessageHeaderWasChanged( uint256 oldValue, uint256 newValue ); /** * @dev Emitted when gas cost for message was changed. */ event GasCostMessageWasChanged( uint256 oldValue, uint256 newValue ); /** * @dev Reentrancy guard for postIncomingMessages. */ modifier messageInProgressLocker() { require(!messageInProgress, "Message is in progress"); messageInProgress = true; _; messageInProgress = false; } /** * @dev Allows DEFAULT_ADMIN_ROLE to initialize registered contracts * Notice - this function will be executed only once during upgrade * * Requirements: * * `msg.sender` should have DEFAULT_ADMIN_ROLE */ function initializeAllRegisteredContracts( bytes32 schainHash, address[] calldata contracts ) external override { require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "Sender is not authorized"); for (uint256 i = 0; i < contracts.length; i++) { if ( deprecatedRegistryContracts[schainHash][contracts[i]] && !_registryContracts[schainHash].contains(contracts[i]) ) { _registryContracts[schainHash].add(contracts[i]); delete deprecatedRegistryContracts[schainHash][contracts[i]]; } } } /** * @dev Allows `msg.sender` to connect schain with MessageProxyOnMainnet for transferring messages. * * Requirements: * * - Schain name must not be `Mainnet`. */ function addConnectedChain(string calldata schainName) external override { bytes32 schainHash = keccak256(abi.encodePacked(schainName)); require(ISchainsInternal( contractManagerOfSkaleManager.getContract("SchainsInternal") ).isSchainExist(schainHash), "SKALE chain must exist"); _addConnectedChain(schainHash); } /** * @dev Allows owner of the contract to set CommunityPool address for gas reimbursement. * * Requirements: * * - `msg.sender` must be granted as DEFAULT_ADMIN_ROLE. * - Address of CommunityPool contract must not be null. */ function setCommunityPool(ICommunityPool newCommunityPoolAddress) external override { require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "Not authorized caller"); require(address(newCommunityPoolAddress) != address(0), "CommunityPool address has to be set"); communityPool = newCommunityPoolAddress; } /** * @dev Allows `msg.sender` to register extra contract for being able to transfer messages from custom contracts. * * Requirements: * * - `msg.sender` must be granted as EXTRA_CONTRACT_REGISTRAR_ROLE. * - Schain name must not be `Mainnet`. */ function registerExtraContract(string memory schainName, address extraContract) external override { bytes32 schainHash = keccak256(abi.encodePacked(schainName)); require( hasRole(EXTRA_CONTRACT_REGISTRAR_ROLE, msg.sender) || isSchainOwner(msg.sender, schainHash), "Not enough permissions to register extra contract" ); require(schainHash != MAINNET_HASH, "Schain hash can not be equal Mainnet"); _registerExtraContract(schainHash, extraContract); } /** * @dev Allows `msg.sender` to remove extra contract, * thus `extraContract` will no longer be available to transfer messages from mainnet to schain. * * Requirements: * * - `msg.sender` must be granted as EXTRA_CONTRACT_REGISTRAR_ROLE. * - Schain name must not be `Mainnet`. */ function removeExtraContract(string memory schainName, address extraContract) external override { bytes32 schainHash = keccak256(abi.encodePacked(schainName)); require( hasRole(EXTRA_CONTRACT_REGISTRAR_ROLE, msg.sender) || isSchainOwner(msg.sender, schainHash), "Not enough permissions to register extra contract" ); require(schainHash != MAINNET_HASH, "Schain hash can not be equal Mainnet"); _removeExtraContract(schainHash, extraContract); } /** * @dev Posts incoming message from `fromSchainName`. * * Requirements: * * - `msg.sender` must be authorized caller. * - `fromSchainName` must be initialized. * - `startingCounter` must be equal to the chain's incoming message counter. * - If destination chain is Mainnet, message signature must be valid. */ function postIncomingMessages( string calldata fromSchainName, uint256 startingCounter, Message[] calldata messages, Signature calldata sign ) external override(IMessageProxy, MessageProxy) messageInProgressLocker { uint256 gasTotal = gasleft(); bytes32 fromSchainHash = keccak256(abi.encodePacked(fromSchainName)); require(_checkSchainBalance(fromSchainHash), "Schain wallet has not enough funds"); require(connectedChains[fromSchainHash].inited, "Chain is not initialized"); require(messages.length <= MESSAGES_LENGTH, "Too many messages"); require( startingCounter == connectedChains[fromSchainHash].incomingMessageCounter, "Starting counter is not equal to incoming message counter"); require(_verifyMessages( fromSchainName, _hashedArray(messages, startingCounter, fromSchainName), sign), "Signature is not verified"); uint additionalGasPerMessage = (gasTotal - gasleft() + headerMessageGasCost + messages.length * messageGasCost) / messages.length; uint notReimbursedGas = 0; connectedChains[fromSchainHash].incomingMessageCounter += messages.length; for (uint256 i = 0; i < messages.length; i++) { gasTotal = gasleft(); if (isContractRegistered(bytes32(0), messages[i].destinationContract)) { address receiver = _getGasPayer(fromSchainHash, messages[i], startingCounter + i); _callReceiverContract(fromSchainHash, messages[i], startingCounter + i); notReimbursedGas += communityPool.refundGasByUser( fromSchainHash, payable(msg.sender), receiver, gasTotal - gasleft() + additionalGasPerMessage ); } else { _callReceiverContract(fromSchainHash, messages[i], startingCounter + i); notReimbursedGas += gasTotal - gasleft() + additionalGasPerMessage; } } communityPool.refundGasBySchainWallet(fromSchainHash, payable(msg.sender), notReimbursedGas); } /** * @dev Sets headerMessageGasCost to a new value. * * Requirements: * * - `msg.sender` must be granted as CONSTANT_SETTER_ROLE. */ function setNewHeaderMessageGasCost(uint256 newHeaderMessageGasCost) external override onlyConstantSetter { emit GasCostMessageHeaderWasChanged(headerMessageGasCost, newHeaderMessageGasCost); headerMessageGasCost = newHeaderMessageGasCost; } /** * @dev Sets messageGasCost to a new value. * * Requirements: * * - `msg.sender` must be granted as CONSTANT_SETTER_ROLE. */ function setNewMessageGasCost(uint256 newMessageGasCost) external override onlyConstantSetter { emit GasCostMessageWasChanged(messageGasCost, newMessageGasCost); messageGasCost = newMessageGasCost; } /** * @dev Sets new version of contracts on mainnet * * Requirements: * * - `msg.sender` must be granted DEFAULT_ADMIN_ROLE. */ function setVersion(string calldata newVersion) external override { require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "DEFAULT_ADMIN_ROLE is required"); emit VersionUpdated(version, newVersion); version = newVersion; } /** * @dev Creates a new MessageProxyForMainnet contract. */ function initialize(IContractManager contractManagerOfSkaleManagerValue) public virtual override initializer { SkaleManagerClient.initialize(contractManagerOfSkaleManagerValue); MessageProxy.initializeMessageProxy(1e6); headerMessageGasCost = 73800; messageGasCost = 9000; } /** * @dev Checks whether chain is currently connected. * * Note: Mainnet chain does not have a public key, and is implicitly * connected to MessageProxy. * * Requirements: * * - `schainName` must not be Mainnet. */ function isConnectedChain( string memory schainName ) public view override(IMessageProxy, MessageProxy) returns (bool) { require(keccak256(abi.encodePacked(schainName)) != MAINNET_HASH, "Schain id can not be equal Mainnet"); return super.isConnectedChain(schainName); } // private function _authorizeOutgoingMessageSender(bytes32 targetChainHash) internal view override { require( isContractRegistered(bytes32(0), msg.sender) || isContractRegistered(targetChainHash, msg.sender) || isSchainOwner(msg.sender, targetChainHash), "Sender contract is not registered" ); } /** * @dev Converts calldata structure to memory structure and checks * whether message BLS signature is valid. */ function _verifyMessages( string calldata fromSchainName, bytes32 hashedMessages, MessageProxyForMainnet.Signature calldata sign ) internal view returns (bool) { return ISchains( contractManagerOfSkaleManager.getContract("Schains") ).verifySchainSignature( sign.blsSignature[0], sign.blsSignature[1], hashedMessages, sign.counter, sign.hashA, sign.hashB, fromSchainName ); } /** * @dev Checks whether balance of schain wallet is sufficient for * for reimbursement custom message. */ function _checkSchainBalance(bytes32 schainHash) internal view returns (bool) { return IWallets( payable(contractManagerOfSkaleManager.getContract("Wallets")) ).getSchainBalance(schainHash) >= (MESSAGES_LENGTH + 1) * gasLimit * tx.gasprice; } /** * @dev Returns list of registered custom extra contracts. */ function _getRegistryContracts() internal view override returns (mapping(bytes32 => EnumerableSetUpgradeable.AddressSet) storage) { return _registryContracts; } } // SPDX-License-Identifier: AGPL-3.0-only /** * SkaleManagerClient.sol - SKALE Interchain Messaging Agent * Copyright (C) 2021-Present SKALE Labs * @author Artem Payvin * * SKALE IMA is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * SKALE IMA is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with SKALE IMA. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.8.6; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/access/AccessControlEnumerableUpgradeable.sol"; import "@skalenetwork/skale-manager-interfaces/IContractManager.sol"; import "@skalenetwork/skale-manager-interfaces/ISchainsInternal.sol"; import "@skalenetwork/ima-interfaces/mainnet/ISkaleManagerClient.sol"; /** * @title SkaleManagerClient - contract that knows ContractManager * and makes calls to SkaleManager contracts. */ contract SkaleManagerClient is Initializable, AccessControlEnumerableUpgradeable, ISkaleManagerClient { IContractManager public contractManagerOfSkaleManager; /** * @dev Modifier for checking whether caller is owner of SKALE chain. */ modifier onlySchainOwner(string memory schainName) { require( isSchainOwner(msg.sender, keccak256(abi.encodePacked(schainName))), "Sender is not an Schain owner" ); _; } /** * @dev initialize - sets current address of ContractManager of SkaleManager. * @param newContractManagerOfSkaleManager - current address of ContractManager of SkaleManager. */ function initialize( IContractManager newContractManagerOfSkaleManager ) public override virtual initializer { AccessControlEnumerableUpgradeable.__AccessControlEnumerable_init(); _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); contractManagerOfSkaleManager = newContractManagerOfSkaleManager; } /** * @dev Checks whether sender is owner of SKALE chain */ function isSchainOwner(address sender, bytes32 schainHash) public view override returns (bool) { address skaleChainsInternal = contractManagerOfSkaleManager.getContract("SchainsInternal"); return ISchainsInternal(skaleChainsInternal).isOwnerAddress(sender, schainHash); } } // SPDX-License-Identifier: AGPL-3.0-only /* IWallets - SKALE Manager Interfaces Copyright (C) 2021-Present SKALE Labs @author Dmytro Stebaeiv SKALE Manager Interfaces is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager Interfaces is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager Interfaces. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity >=0.6.10 <0.9.0; interface IWallets { /** * @dev Emitted when the validator wallet was funded */ event ValidatorWalletRecharged(address sponsor, uint amount, uint validatorId); /** * @dev Emitted when the schain wallet was funded */ event SchainWalletRecharged(address sponsor, uint amount, bytes32 schainHash); /** * @dev Emitted when the node received a refund from validator to its wallet */ event NodeRefundedByValidator(address node, uint validatorId, uint amount); /** * @dev Emitted when the node received a refund from schain to its wallet */ event NodeRefundedBySchain(address node, bytes32 schainHash, uint amount); /** * @dev Emitted when the validator withdrawn funds from validator wallet */ event WithdrawFromValidatorWallet(uint indexed validatorId, uint amount); /** * @dev Emitted when the schain owner withdrawn funds from schain wallet */ event WithdrawFromSchainWallet(bytes32 indexed schainHash, uint amount); receive() external payable; function refundGasByValidator(uint validatorId, address payable spender, uint spentGas) external; function refundGasByValidatorToSchain(uint validatorId, bytes32 schainHash) external; function refundGasBySchain(bytes32 schainId, address payable spender, uint spentGas, bool isDebt) external; function withdrawFundsFromSchainWallet(address payable schainOwner, bytes32 schainHash) external; function withdrawFundsFromValidatorWallet(uint amount) external; function rechargeValidatorWallet(uint validatorId) external payable; function rechargeSchainWallet(bytes32 schainId) external payable; function getSchainBalance(bytes32 schainHash) external view returns (uint); function getValidatorBalance(uint validatorId) external view returns (uint); } // SPDX-License-Identifier: AGPL-3.0-only /* ISchains.sol - SKALE Manager Interfaces Copyright (C) 2021-Present SKALE Labs @author Dmytro Stebaeiv SKALE Manager Interfaces is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager Interfaces is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager Interfaces. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity >=0.6.10 <0.9.0; interface ISchains { struct SchainOption { string name; bytes value; } /** * @dev Emitted when an schain is created. */ event SchainCreated( string name, address owner, uint partOfNode, uint lifetime, uint numberOfNodes, uint deposit, uint16 nonce, bytes32 schainHash ); /** * @dev Emitted when an schain is deleted. */ event SchainDeleted( address owner, string name, bytes32 indexed schainHash ); /** * @dev Emitted when a node in an schain is rotated. */ event NodeRotated( bytes32 schainHash, uint oldNode, uint newNode ); /** * @dev Emitted when a node is added to an schain. */ event NodeAdded( bytes32 schainHash, uint newNode ); /** * @dev Emitted when a group of nodes is created for an schain. */ event SchainNodes( string name, bytes32 schainHash, uint[] nodesInGroup ); function addSchain(address from, uint deposit, bytes calldata data) external; function addSchainByFoundation( uint lifetime, uint8 typeOfSchain, uint16 nonce, string calldata name, address schainOwner, address schainOriginator, SchainOption[] calldata options ) external payable; function deleteSchain(address from, string calldata name) external; function deleteSchainByRoot(string calldata name) external; function restartSchainCreation(string calldata name) external; function verifySchainSignature( uint256 signA, uint256 signB, bytes32 hash, uint256 counter, uint256 hashA, uint256 hashB, string calldata schainName ) external view returns (bool); function getSchainPrice(uint typeOfSchain, uint lifetime) external view returns (uint); function getOption(bytes32 schainHash, string calldata optionName) external view returns (bytes memory); function getOptions(bytes32 schainHash) external view returns (SchainOption[] memory); } // SPDX-License-Identifier: AGPL-3.0-only /* ISchainsInternal - SKALE Manager Interfaces Copyright (C) 2021-Present SKALE Labs @author Dmytro Stebaeiv SKALE Manager Interfaces is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager Interfaces is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager Interfaces. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity >=0.6.10 <0.9.0; interface ISchainsInternal { struct Schain { string name; address owner; uint indexInOwnerList; uint8 partOfNode; uint lifetime; uint startDate; uint startBlock; uint deposit; uint64 index; uint generation; address originator; } struct SchainType { uint8 partOfNode; uint numberOfNodes; } /** * @dev Emitted when schain type added. */ event SchainTypeAdded(uint indexed schainType, uint partOfNode, uint numberOfNodes); /** * @dev Emitted when schain type removed. */ event SchainTypeRemoved(uint indexed schainType); function initializeSchain( string calldata name, address from, address originator, uint lifetime, uint deposit) external; function createGroupForSchain( bytes32 schainHash, uint numberOfNodes, uint8 partOfNode ) external returns (uint[] memory); function changeLifetime(bytes32 schainHash, uint lifetime, uint deposit) external; function removeSchain(bytes32 schainHash, address from) external; function removeNodeFromSchain(uint nodeIndex, bytes32 schainHash) external; function deleteGroup(bytes32 schainHash) external; function setException(bytes32 schainHash, uint nodeIndex) external; function setNodeInGroup(bytes32 schainHash, uint nodeIndex) external; function removeHolesForSchain(bytes32 schainHash) external; function addSchainType(uint8 partOfNode, uint numberOfNodes) external; function removeSchainType(uint typeOfSchain) external; function setNumberOfSchainTypes(uint newNumberOfSchainTypes) external; function removeNodeFromAllExceptionSchains(uint nodeIndex) external; function removeAllNodesFromSchainExceptions(bytes32 schainHash) external; function makeSchainNodesInvisible(bytes32 schainHash) external; function makeSchainNodesVisible(bytes32 schainHash) external; function newGeneration() external; function addSchainForNode(uint nodeIndex, bytes32 schainHash) external; function removeSchainForNode(uint nodeIndex, uint schainIndex) external; function removeNodeFromExceptions(bytes32 schainHash, uint nodeIndex) external; function isSchainActive(bytes32 schainHash) external view returns (bool); function schainsAtSystem(uint index) external view returns (bytes32); function numberOfSchains() external view returns (uint64); function getSchains() external view returns (bytes32[] memory); function getSchainsPartOfNode(bytes32 schainHash) external view returns (uint8); function getSchainListSize(address from) external view returns (uint); function getSchainHashesByAddress(address from) external view returns (bytes32[] memory); function getSchainIdsByAddress(address from) external view returns (bytes32[] memory); function getSchainHashesForNode(uint nodeIndex) external view returns (bytes32[] memory); function getSchainIdsForNode(uint nodeIndex) external view returns (bytes32[] memory); function getSchainOwner(bytes32 schainHash) external view returns (address); function getSchainOriginator(bytes32 schainHash) external view returns (address); function isSchainNameAvailable(string calldata name) external view returns (bool); function isTimeExpired(bytes32 schainHash) external view returns (bool); function isOwnerAddress(address from, bytes32 schainId) external view returns (bool); function getSchainName(bytes32 schainHash) external view returns (string memory); function getActiveSchain(uint nodeIndex) external view returns (bytes32); function getActiveSchains(uint nodeIndex) external view returns (bytes32[] memory activeSchains); function getNumberOfNodesInGroup(bytes32 schainHash) external view returns (uint); function getNodesInGroup(bytes32 schainHash) external view returns (uint[] memory); function isNodeAddressesInGroup(bytes32 schainId, address sender) external view returns (bool); function getNodeIndexInGroup(bytes32 schainHash, uint nodeId) external view returns (uint); function isAnyFreeNode(bytes32 schainHash) external view returns (bool); function checkException(bytes32 schainHash, uint nodeIndex) external view returns (bool); function checkHoleForSchain(bytes32 schainHash, uint indexOfNode) external view returns (bool); function checkSchainOnNode(uint nodeIndex, bytes32 schainHash) external view returns (bool); function getSchainType(uint typeOfSchain) external view returns(uint8, uint); function getGeneration(bytes32 schainHash) external view returns (uint); function isSchainExist(bytes32 schainHash) external view returns (bool); } // SPDX-License-Identifier: AGPL-3.0-only /** * MessageProxy.sol - SKALE Interchain Messaging Agent * Copyright (C) 2021-Present SKALE Labs * @author Dmytro Stebaiev * * SKALE IMA is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * SKALE IMA is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with SKALE IMA. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.8.6; import "@openzeppelin/contracts-upgradeable/access/AccessControlEnumerableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol"; import "@skalenetwork/ima-interfaces/IGasReimbursable.sol"; import "@skalenetwork/ima-interfaces/IMessageProxy.sol"; import "@skalenetwork/ima-interfaces/IMessageReceiver.sol"; /** * @title MessageProxy * @dev Abstract contract for MessageProxyForMainnet and MessageProxyForSchain. */ abstract contract MessageProxy is AccessControlEnumerableUpgradeable, IMessageProxy { using AddressUpgradeable for address; using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet; /** * @dev Structure that stores counters for outgoing and incoming messages. */ struct ConnectedChainInfo { // message counters start with 0 uint256 incomingMessageCounter; uint256 outgoingMessageCounter; bool inited; } bytes32 public constant MAINNET_HASH = keccak256(abi.encodePacked("Mainnet")); bytes32 public constant CHAIN_CONNECTOR_ROLE = keccak256("CHAIN_CONNECTOR_ROLE"); bytes32 public constant EXTRA_CONTRACT_REGISTRAR_ROLE = keccak256("EXTRA_CONTRACT_REGISTRAR_ROLE"); bytes32 public constant CONSTANT_SETTER_ROLE = keccak256("CONSTANT_SETTER_ROLE"); uint256 public constant MESSAGES_LENGTH = 10; uint256 public constant REVERT_REASON_LENGTH = 64; // schainHash => ConnectedChainInfo mapping(bytes32 => ConnectedChainInfo) public connectedChains; // schainHash => contract address => allowed // solhint-disable-next-line private-vars-leading-underscore mapping(bytes32 => mapping(address => bool)) internal deprecatedRegistryContracts; uint256 public gasLimit; /** * @dev Emitted for every outgoing message to schain. */ event OutgoingMessage( bytes32 indexed dstChainHash, uint256 indexed msgCounter, address indexed srcContract, address dstContract, bytes data ); /** * @dev Emitted when function `postMessage` returns revert. * Used to prevent stuck loop inside function `postIncomingMessages`. */ event PostMessageError( uint256 indexed msgCounter, bytes message ); /** * @dev Emitted when gas limit per one call of `postMessage` was changed. */ event GasLimitWasChanged( uint256 oldValue, uint256 newValue ); /** * @dev Emitted when the version was updated */ event VersionUpdated(string oldVersion, string newVersion); /** * @dev Emitted when extra contract was added. */ event ExtraContractRegistered( bytes32 indexed chainHash, address contractAddress ); /** * @dev Emitted when extra contract was removed. */ event ExtraContractRemoved( bytes32 indexed chainHash, address contractAddress ); /** * @dev Modifier to make a function callable only if caller is granted with {CHAIN_CONNECTOR_ROLE}. */ modifier onlyChainConnector() { require(hasRole(CHAIN_CONNECTOR_ROLE, msg.sender), "CHAIN_CONNECTOR_ROLE is required"); _; } /** * @dev Modifier to make a function callable only if caller is granted with {EXTRA_CONTRACT_REGISTRAR_ROLE}. */ modifier onlyExtraContractRegistrar() { require(hasRole(EXTRA_CONTRACT_REGISTRAR_ROLE, msg.sender), "EXTRA_CONTRACT_REGISTRAR_ROLE is required"); _; } /** * @dev Modifier to make a function callable only if caller is granted with {CONSTANT_SETTER_ROLE}. */ modifier onlyConstantSetter() { require(hasRole(CONSTANT_SETTER_ROLE, msg.sender), "Not enough permissions to set constant"); _; } /** * @dev Sets gasLimit to a new value. * * Requirements: * * - `msg.sender` must be granted CONSTANT_SETTER_ROLE. */ function setNewGasLimit(uint256 newGasLimit) external override onlyConstantSetter { emit GasLimitWasChanged(gasLimit, newGasLimit); gasLimit = newGasLimit; } /** * @dev Virtual function for `postIncomingMessages`. */ function postIncomingMessages( string calldata fromSchainName, uint256 startingCounter, Message[] calldata messages, Signature calldata sign ) external virtual override; /** * @dev Allows `msg.sender` to register extra contract for all schains * for being able to transfer messages from custom contracts. * * Requirements: * * - `msg.sender` must be granted as EXTRA_CONTRACT_REGISTRAR_ROLE. * - Passed address should be contract. * - Extra contract must not be registered. */ function registerExtraContractForAll(address extraContract) external override onlyExtraContractRegistrar { require(extraContract.isContract(), "Given address is not a contract"); require(!_getRegistryContracts()[bytes32(0)].contains(extraContract), "Extra contract is already registered"); _getRegistryContracts()[bytes32(0)].add(extraContract); emit ExtraContractRegistered(bytes32(0), extraContract); } /** * @dev Allows `msg.sender` to remove extra contract for all schains. * Extra contract will no longer be able to send messages through MessageProxy. * * Requirements: * * - `msg.sender` must be granted as EXTRA_CONTRACT_REGISTRAR_ROLE. */ function removeExtraContractForAll(address extraContract) external override onlyExtraContractRegistrar { require(_getRegistryContracts()[bytes32(0)].contains(extraContract), "Extra contract is not registered"); _getRegistryContracts()[bytes32(0)].remove(extraContract); emit ExtraContractRemoved(bytes32(0), extraContract); } /** * @dev Should return length of contract registered by schainHash. */ function getContractRegisteredLength(bytes32 schainHash) external view override returns (uint256) { return _getRegistryContracts()[schainHash].length(); } /** * @dev Should return a range of contracts registered by schainHash. * * Requirements: * range should be less or equal 10 contracts */ function getContractRegisteredRange( bytes32 schainHash, uint256 from, uint256 to ) external view override returns (address[] memory contractsInRange) { require( from < to && to - from <= 10 && to <= _getRegistryContracts()[schainHash].length(), "Range is incorrect" ); contractsInRange = new address[](to - from); for (uint256 i = from; i < to; i++) { contractsInRange[i - from] = _getRegistryContracts()[schainHash].at(i); } } /** * @dev Returns number of outgoing messages. * * Requirements: * * - Target schain must be initialized. */ function getOutgoingMessagesCounter(string calldata targetSchainName) external view override returns (uint256) { bytes32 dstChainHash = keccak256(abi.encodePacked(targetSchainName)); require(connectedChains[dstChainHash].inited, "Destination chain is not initialized"); return connectedChains[dstChainHash].outgoingMessageCounter; } /** * @dev Returns number of incoming messages. * * Requirements: * * - Source schain must be initialized. */ function getIncomingMessagesCounter(string calldata fromSchainName) external view override returns (uint256) { bytes32 srcChainHash = keccak256(abi.encodePacked(fromSchainName)); require(connectedChains[srcChainHash].inited, "Source chain is not initialized"); return connectedChains[srcChainHash].incomingMessageCounter; } function initializeMessageProxy(uint newGasLimit) public initializer { AccessControlEnumerableUpgradeable.__AccessControlEnumerable_init(); _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setupRole(CHAIN_CONNECTOR_ROLE, msg.sender); _setupRole(EXTRA_CONTRACT_REGISTRAR_ROLE, msg.sender); _setupRole(CONSTANT_SETTER_ROLE, msg.sender); gasLimit = newGasLimit; } /** * @dev Posts message from this contract to `targetChainHash` MessageProxy contract. * This is called by a smart contract to make a cross-chain call. * * Emits an {OutgoingMessage} event. * * Requirements: * * - Target chain must be initialized. * - Target chain must be registered as external contract. */ function postOutgoingMessage( bytes32 targetChainHash, address targetContract, bytes memory data ) public override virtual { require(connectedChains[targetChainHash].inited, "Destination chain is not initialized"); _authorizeOutgoingMessageSender(targetChainHash); emit OutgoingMessage( targetChainHash, connectedChains[targetChainHash].outgoingMessageCounter, msg.sender, targetContract, data ); connectedChains[targetChainHash].outgoingMessageCounter += 1; } /** * @dev Allows CHAIN_CONNECTOR_ROLE to remove connected chain from this contract. * * Requirements: * * - `msg.sender` must be granted CHAIN_CONNECTOR_ROLE. * - `schainName` must be initialized. */ function removeConnectedChain(string memory schainName) public virtual override onlyChainConnector { bytes32 schainHash = keccak256(abi.encodePacked(schainName)); require(connectedChains[schainHash].inited, "Chain is not initialized"); delete connectedChains[schainHash]; } /** * @dev Checks whether chain is currently connected. */ function isConnectedChain( string memory schainName ) public view virtual override returns (bool) { return connectedChains[keccak256(abi.encodePacked(schainName))].inited; } /** * @dev Checks whether contract is currently registered as extra contract. */ function isContractRegistered( bytes32 schainHash, address contractAddress ) public view override returns (bool) { return _getRegistryContracts()[schainHash].contains(contractAddress); } /** * @dev Allows MessageProxy to register extra contract for being able to transfer messages from custom contracts. * * Requirements: * * - Extra contract address must be contract. * - Extra contract must not be registered. * - Extra contract must not be registered for all chains. */ function _registerExtraContract( bytes32 chainHash, address extraContract ) internal { require(extraContract.isContract(), "Given address is not a contract"); require(!_getRegistryContracts()[chainHash].contains(extraContract), "Extra contract is already registered"); require( !_getRegistryContracts()[bytes32(0)].contains(extraContract), "Extra contract is already registered for all chains" ); _getRegistryContracts()[chainHash].add(extraContract); emit ExtraContractRegistered(chainHash, extraContract); } /** * @dev Allows MessageProxy to remove extra contract, * thus `extraContract` will no longer be available to transfer messages from mainnet to schain. * * Requirements: * * - Extra contract must be registered. */ function _removeExtraContract( bytes32 chainHash, address extraContract ) internal { require(_getRegistryContracts()[chainHash].contains(extraContract), "Extra contract is not registered"); _getRegistryContracts()[chainHash].remove(extraContract); emit ExtraContractRemoved(chainHash, extraContract); } /** * @dev Allows MessageProxy to connect schain with MessageProxyOnMainnet for transferring messages. * * Requirements: * * - `msg.sender` must be granted CHAIN_CONNECTOR_ROLE. * - SKALE chain must not be connected. */ function _addConnectedChain(bytes32 schainHash) internal onlyChainConnector { require(!connectedChains[schainHash].inited,"Chain is already connected"); connectedChains[schainHash] = ConnectedChainInfo({ incomingMessageCounter: 0, outgoingMessageCounter: 0, inited: true }); } /** * @dev Allows MessageProxy to send messages from schain to mainnet. * Destination contract must implement `postMessage` method. */ function _callReceiverContract( bytes32 schainHash, Message calldata message, uint counter ) internal { if (!message.destinationContract.isContract()) { emit PostMessageError( counter, "Destination contract is not a contract" ); return; } try IMessageReceiver(message.destinationContract).postMessage{gas: gasLimit}( schainHash, message.sender, message.data ) { return; } catch Error(string memory reason) { emit PostMessageError( counter, _getSlice(bytes(reason), REVERT_REASON_LENGTH) ); } catch Panic(uint errorCode) { emit PostMessageError( counter, abi.encodePacked(errorCode) ); } catch (bytes memory revertData) { emit PostMessageError( counter, _getSlice(revertData, REVERT_REASON_LENGTH) ); } } /** * @dev Returns receiver of message. */ function _getGasPayer( bytes32 schainHash, Message calldata message, uint counter ) internal returns (address) { try IGasReimbursable(message.destinationContract).gasPayer{gas: gasLimit}( schainHash, message.sender, message.data ) returns (address receiver) { return receiver; } catch Error(string memory reason) { emit PostMessageError( counter, _getSlice(bytes(reason), REVERT_REASON_LENGTH) ); return address(0); } catch Panic(uint errorCode) { emit PostMessageError( counter, abi.encodePacked(errorCode) ); return address(0); } catch (bytes memory revertData) { emit PostMessageError( counter, _getSlice(revertData, REVERT_REASON_LENGTH) ); return address(0); } } /** * @dev Checks whether msg.sender is registered as custom extra contract. */ function _authorizeOutgoingMessageSender(bytes32 targetChainHash) internal view virtual { require( isContractRegistered(bytes32(0), msg.sender) || isContractRegistered(targetChainHash, msg.sender), "Sender contract is not registered" ); } /** * @dev Returns list of registered custom extra contracts. */ function _getRegistryContracts() internal view virtual returns (mapping(bytes32 => EnumerableSetUpgradeable.AddressSet) storage); /** * @dev Returns hash of message array. */ function _hashedArray( Message[] calldata messages, uint256 startingCounter, string calldata fromChainName ) internal pure returns (bytes32) { bytes32 sourceHash = keccak256(abi.encodePacked(fromChainName)); bytes32 hash = keccak256(abi.encodePacked(sourceHash, bytes32(startingCounter))); for (uint256 i = 0; i < messages.length; i++) { hash = keccak256( abi.encodePacked( abi.encode( hash, messages[i].sender, messages[i].destinationContract ), messages[i].data ) ); } return hash; } function _getSlice(bytes memory text, uint end) private pure returns (bytes memory) { uint slicedEnd = end < text.length ? end : text.length; bytes memory sliced = new bytes(slicedEnd); for(uint i = 0; i < slicedEnd; i++){ sliced[i] = text[i]; } return sliced; } } // SPDX-License-Identifier: AGPL-3.0-only /* CommunityPool.sol - SKALE Manager Copyright (C) 2021-Present SKALE Labs @author Dmytro Stebaiev @author Artem Payvin @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.8.6; import "@skalenetwork/ima-interfaces/mainnet/ICommunityPool.sol"; import "@skalenetwork/skale-manager-interfaces/IWallets.sol"; import "../Messages.sol"; import "./Twin.sol"; /** * @title CommunityPool * @dev Contract contains logic to perform automatic self-recharging ETH for nodes. */ contract CommunityPool is Twin, ICommunityPool { using AddressUpgradeable for address payable; bytes32 public constant CONSTANT_SETTER_ROLE = keccak256("CONSTANT_SETTER_ROLE"); // address of user => schainHash => balance of gas wallet in ETH mapping(address => mapping(bytes32 => uint)) private _userWallets; // address of user => schainHash => true if unlocked for transferring mapping(address => mapping(bytes32 => bool)) public activeUsers; uint public minTransactionGas; /** * @dev Emitted when minimal value in gas for transactions from schain to mainnet was changed */ event MinTransactionGasWasChanged( uint oldValue, uint newValue ); function initialize( IContractManager contractManagerOfSkaleManagerValue, ILinker linker, IMessageProxyForMainnet messageProxyValue ) external override initializer { Twin.initialize(contractManagerOfSkaleManagerValue, messageProxyValue); _setupRole(LINKER_ROLE, address(linker)); minTransactionGas = 1e6; } /** * @dev Allows MessageProxyForMainnet to reimburse gas for transactions * that transfer funds from schain to mainnet. * * Requirements: * * - User that receives funds should have enough funds in their gas wallet. * - Address that should be reimbursed for executing transaction must not be null. */ function refundGasByUser( bytes32 schainHash, address payable node, address user, uint gas ) external override onlyMessageProxy returns (uint) { require(node != address(0), "Node address must be set"); if (!activeUsers[user][schainHash]) { return gas; } uint amount = tx.gasprice * gas; if (amount > _userWallets[user][schainHash]) { amount = _userWallets[user][schainHash]; } _userWallets[user][schainHash] = _userWallets[user][schainHash] - amount; if (!_balanceIsSufficient(schainHash, user, 0)) { activeUsers[user][schainHash] = false; messageProxy.postOutgoingMessage( schainHash, schainLinks[schainHash], Messages.encodeLockUserMessage(user) ); } node.sendValue(amount); return (tx.gasprice * gas - amount) / tx.gasprice; } function refundGasBySchainWallet( bytes32 schainHash, address payable node, uint gas ) external override onlyMessageProxy returns (bool) { if (gas > 0) { IWallets(payable(contractManagerOfSkaleManager.getContract("Wallets"))).refundGasBySchain( schainHash, node, gas, false ); } return true; } /** * @dev Allows `msg.sender` to recharge their wallet for further gas reimbursement. * * Requirements: * * - 'msg.sender` should recharge their gas wallet for amount that enough to reimburse any * transaction from schain to mainnet. */ function rechargeUserWallet(string calldata schainName, address user) external payable override { bytes32 schainHash = keccak256(abi.encodePacked(schainName)); require( _balanceIsSufficient(schainHash, user, msg.value), "Not enough ETH for transaction" ); _userWallets[user][schainHash] = _userWallets[user][schainHash] + msg.value; if (!activeUsers[user][schainHash]) { activeUsers[user][schainHash] = true; messageProxy.postOutgoingMessage( schainHash, schainLinks[schainHash], Messages.encodeActivateUserMessage(user) ); } } /** * @dev Allows `msg.sender` to withdraw funds from their gas wallet. * If `msg.sender` withdraws too much funds, * then he will no longer be able to transfer their tokens on ETH from schain to mainnet. * * Requirements: * * - 'msg.sender` must have sufficient amount of ETH on their gas wallet. */ function withdrawFunds(string calldata schainName, uint amount) external override { bytes32 schainHash = keccak256(abi.encodePacked(schainName)); require(amount <= _userWallets[msg.sender][schainHash], "Balance is too low"); require(!messageProxy.messageInProgress(), "Message is in progress"); _userWallets[msg.sender][schainHash] = _userWallets[msg.sender][schainHash] - amount; if ( !_balanceIsSufficient(schainHash, msg.sender, 0) && activeUsers[msg.sender][schainHash] ) { activeUsers[msg.sender][schainHash] = false; messageProxy.postOutgoingMessage( schainHash, schainLinks[schainHash], Messages.encodeLockUserMessage(msg.sender) ); } payable(msg.sender).sendValue(amount); } /** * @dev Allows `msg.sender` set the amount of gas that should be * enough for reimbursing any transaction from schain to mainnet. * * Requirements: * * - 'msg.sender` must have sufficient amount of ETH on their gas wallet. */ function setMinTransactionGas(uint newMinTransactionGas) external override { require(hasRole(CONSTANT_SETTER_ROLE, msg.sender), "CONSTANT_SETTER_ROLE is required"); emit MinTransactionGasWasChanged(minTransactionGas, newMinTransactionGas); minTransactionGas = newMinTransactionGas; } /** * @dev Returns the amount of ETH on gas wallet for particular user. */ function getBalance(address user, string calldata schainName) external view override returns (uint) { return _userWallets[user][keccak256(abi.encodePacked(schainName))]; } /** * @dev Checks whether user is active and wallet was recharged for sufficient amount. */ function checkUserBalance(bytes32 schainHash, address receiver) external view override returns (bool) { return activeUsers[receiver][schainHash] && _balanceIsSufficient(schainHash, receiver, 0); } /** * @dev Checks whether user wallet was recharged for sufficient amount. */ function _balanceIsSufficient(bytes32 schainHash, address receiver, uint256 delta) private view returns (bool) { return delta + _userWallets[receiver][schainHash] >= minTransactionGas * tx.gasprice; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IAccessControlEnumerableUpgradeable.sol"; import "./AccessControlUpgradeable.sol"; import "../utils/structs/EnumerableSetUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Extension of {AccessControl} that allows enumerating the members of each role. */ abstract contract AccessControlEnumerableUpgradeable is Initializable, IAccessControlEnumerableUpgradeable, AccessControlUpgradeable { function __AccessControlEnumerable_init() internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __AccessControl_init_unchained(); __AccessControlEnumerable_init_unchained(); } function __AccessControlEnumerable_init_unchained() internal initializer { } using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet; mapping(bytes32 => EnumerableSetUpgradeable.AddressSet) private _roleMembers; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlEnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view override returns (address) { return _roleMembers[role].at(index); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view override returns (uint256) { return _roleMembers[role].length(); } /** * @dev Overload {grantRole} to track enumerable memberships */ function grantRole(bytes32 role, address account) public virtual override(AccessControlUpgradeable, IAccessControlUpgradeable) { super.grantRole(role, account); _roleMembers[role].add(account); } /** * @dev Overload {revokeRole} to track enumerable memberships */ function revokeRole(bytes32 role, address account) public virtual override(AccessControlUpgradeable, IAccessControlUpgradeable) { super.revokeRole(role, account); _roleMembers[role].remove(account); } /** * @dev Overload {renounceRole} to track enumerable memberships */ function renounceRole(bytes32 role, address account) public virtual override(AccessControlUpgradeable, IAccessControlUpgradeable) { super.renounceRole(role, account); _roleMembers[role].remove(account); } /** * @dev Overload {_setupRole} to track enumerable memberships */ function _setupRole(bytes32 role, address account) internal virtual override { super._setupRole(role, account); _roleMembers[role].add(account); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSetUpgradeable { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; if (lastIndex != toDeleteIndex) { bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex } // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { return set._values[index]; } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function _values(Set storage set) private view returns (bytes32[] memory) { return set._values; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(Bytes32Set storage set) internal view returns (bytes32[] memory) { return _values(set._inner); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(AddressSet storage set) internal view returns (address[] memory) { bytes32[] memory store = _values(set._inner); address[] memory result; assembly { result := store } return result; } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(UintSet storage set) internal view returns (uint256[] memory) { bytes32[] memory store = _values(set._inner); uint256[] memory result; assembly { result := store } return result; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IAccessControlUpgradeable.sol"; /** * @dev External interface of AccessControlEnumerable declared to support ERC165 detection. */ interface IAccessControlEnumerableUpgradeable is IAccessControlUpgradeable { /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) external view returns (address); /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IAccessControlUpgradeable.sol"; import "../utils/ContextUpgradeable.sol"; import "../utils/StringsUpgradeable.sol"; import "../utils/introspection/ERC165Upgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable { function __AccessControl_init() internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal initializer { } struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", StringsUpgradeable.toHexString(uint160(account), 20), " is missing role ", StringsUpgradeable.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } function _grantRole(bytes32 role, address account) private { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControlUpgradeable { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library StringsUpgradeable { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { function __ERC165_init() internal initializer { __ERC165_init_unchained(); } function __ERC165_init_unchained() internal initializer { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); }
Sets headerMessageGasCost to a new value. Requirements: - `msg.sender` must be granted as CONSTANT_SETTER_ROLE./
function setNewHeaderMessageGasCost(uint256 newHeaderMessageGasCost) external override onlyConstantSetter { emit GasCostMessageHeaderWasChanged(headerMessageGasCost, newHeaderMessageGasCost); headerMessageGasCost = newHeaderMessageGasCost; }
1,152,624
pragma solidity ^0.4.19; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting '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; } c = _a * _b; assert(c / _a == _b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { // assert(_b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return _a / _b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { assert(_b <= _a); return _a - _b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) { c = _a + _b; assert(c >= _a); return c; } } contract SyscoinDepositsManager { using SafeMath for uint; mapping(address => uint) public deposits; event DepositMade(address who, uint amount); event DepositWithdrawn(address who, uint amount); // @dev – fallback to calling makeDeposit when ether is sent directly to contract. function() public payable { makeDeposit(); } // @dev – returns an account's deposit // @param who – the account's address. // @return – the account's deposit. function getDeposit(address who) constant public returns (uint) { return deposits[who]; } // @dev – allows a user to deposit eth. // @return – sender's updated deposit amount. function makeDeposit() public payable returns (uint) { increaseDeposit(msg.sender, msg.value); return deposits[msg.sender]; } // @dev – increases an account's deposit. // @return – the given user's updated deposit amount. function increaseDeposit(address who, uint amount) internal { deposits[who] = deposits[who].add(amount); require(deposits[who] <= address(this).balance); emit DepositMade(who, amount); } // @dev – allows a user to withdraw eth from their deposit. // @param amount – how much eth to withdraw // @return – sender's updated deposit amount. function withdrawDeposit(uint amount) public returns (uint) { require(deposits[msg.sender] >= amount); deposits[msg.sender] = deposits[msg.sender].sub(amount); msg.sender.transfer(amount); emit DepositWithdrawn(msg.sender, amount); return deposits[msg.sender]; } } // Interface contract to be implemented by SyscoinToken contract SyscoinTransactionProcessor { function processTransaction(uint txHash, uint value, address destinationAddress, uint32 _assetGUID, address superblockSubmitterAddress) public returns (uint); function burn(uint _value, uint32 _assetGUID, bytes syscoinWitnessProgram) payable public returns (bool success); } // Bitcoin transaction parsing library - modified for SYSCOIN // Copyright 2016 rain <https://keybase.io/rain> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // https://en.bitcoin.it/wiki/Protocol_documentation#tx // // Raw Bitcoin transaction structure: // // field | size | type | description // version | 4 | int32 | transaction version number // n_tx_in | 1-9 | var_int | number of transaction inputs // tx_in | 41+ | tx_in[] | list of transaction inputs // n_tx_out | 1-9 | var_int | number of transaction outputs // tx_out | 9+ | tx_out[] | list of transaction outputs // lock_time | 4 | uint32 | block number / timestamp at which tx locked // // Transaction input (tx_in) structure: // // field | size | type | description // previous | 36 | outpoint | Previous output transaction reference // script_len | 1-9 | var_int | Length of the signature script // sig_script | ? | uchar[] | Script for confirming transaction authorization // sequence | 4 | uint32 | Sender transaction version // // OutPoint structure: // // field | size | type | description // hash | 32 | char[32] | The hash of the referenced transaction // index | 4 | uint32 | The index of this output in the referenced transaction // // Transaction output (tx_out) structure: // // field | size | type | description // value | 8 | int64 | Transaction value (Satoshis) // pk_script_len | 1-9 | var_int | Length of the public key script // pk_script | ? | uchar[] | Public key as a Bitcoin script. // // Variable integers (var_int) can be encoded differently depending // on the represented value, to save space. Variable integers always // precede an array of a variable length data type (e.g. tx_in). // // Variable integer encodings as a function of represented value: // // value | bytes | format // <0xFD (253) | 1 | uint8 // <=0xFFFF (65535)| 3 | 0xFD followed by length as uint16 // <=0xFFFF FFFF | 5 | 0xFE followed by length as uint32 // - | 9 | 0xFF followed by length as uint64 // // Public key scripts `pk_script` are set on the output and can // take a number of forms. The regular transaction script is // called 'pay-to-pubkey-hash' (P2PKH): // // OP_DUP OP_HASH160 <pubKeyHash> OP_EQUALVERIFY OP_CHECKSIG // // OP_x are Bitcoin script opcodes. The bytes representation (including // the 0x14 20-byte stack push) is: // // 0x76 0xA9 0x14 <pubKeyHash> 0x88 0xAC // // The <pubKeyHash> is the ripemd160 hash of the sha256 hash of // the public key, preceded by a network version byte. (21 bytes total) // // Network version bytes: 0x00 (mainnet); 0x6f (testnet); 0x34 (namecoin) // // The Bitcoin address is derived from the pubKeyHash. The binary form is the // pubKeyHash, plus a checksum at the end. The checksum is the first 4 bytes // of the (32 byte) double sha256 of the pubKeyHash. (25 bytes total) // This is converted to base58 to form the publicly used Bitcoin address. // Mainnet P2PKH transaction scripts are to addresses beginning with '1'. // // P2SH ('pay to script hash') scripts only supply a script hash. The spender // must then provide the script that would allow them to redeem this output. // This allows for arbitrarily complex scripts to be funded using only a // hash of the script, and moves the onus on providing the script from // the spender to the redeemer. // // The P2SH script format is simple: // // OP_HASH160 <scriptHash> OP_EQUAL // // 0xA9 0x14 <scriptHash> 0x87 // // The <scriptHash> is the ripemd160 hash of the sha256 hash of the // redeem script. The P2SH address is derived from the scriptHash. // Addresses are the scriptHash with a version prefix of 5, encoded as // Base58check. These addresses begin with a '3'. // parse a raw Syscoin transaction byte array library SyscoinMessageLibrary { uint constant p = 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f; // secp256k1 uint constant q = (p + 1) / 4; // Error codes uint constant ERR_INVALID_HEADER = 10050; uint constant ERR_COINBASE_INDEX = 10060; // coinbase tx index within Litecoin merkle isn't 0 uint constant ERR_NOT_MERGE_MINED = 10070; // trying to check AuxPoW on a block that wasn't merge mined uint constant ERR_FOUND_TWICE = 10080; // 0xfabe6d6d found twice uint constant ERR_NO_MERGE_HEADER = 10090; // 0xfabe6d6d not found uint constant ERR_NOT_IN_FIRST_20 = 10100; // chain Merkle root isn't in the first 20 bytes of coinbase tx uint constant ERR_CHAIN_MERKLE = 10110; uint constant ERR_PARENT_MERKLE = 10120; uint constant ERR_PROOF_OF_WORK = 10130; uint constant ERR_INVALID_HEADER_HASH = 10140; uint constant ERR_PROOF_OF_WORK_AUXPOW = 10150; uint constant ERR_PARSE_TX_OUTPUT_LENGTH = 10160; uint constant ERR_PARSE_TX_SYS = 10170; enum Network { MAINNET, TESTNET, REGTEST } uint32 constant SYSCOIN_TX_VERSION_ASSET_ALLOCATION_BURN = 0x7407; uint32 constant SYSCOIN_TX_VERSION_BURN = 0x7401; // AuxPoW block fields struct AuxPoW { uint blockHash; uint txHash; uint coinbaseMerkleRoot; // Merkle root of auxiliary block hash tree; stored in coinbase tx field uint[] chainMerkleProof; // proves that a given Syscoin block hash belongs to a tree with the above root uint syscoinHashIndex; // index of Syscoin block hash within block hash tree uint coinbaseMerkleRootCode; // encodes whether or not the root was found properly uint parentMerkleRoot; // Merkle root of transaction tree from parent Litecoin block header uint[] parentMerkleProof; // proves that coinbase tx belongs to a tree with the above root uint coinbaseTxIndex; // index of coinbase tx within Litecoin tx tree uint parentNonce; } // Syscoin block header stored as a struct, mostly for readability purposes. // BlockHeader structs can be obtained by parsing a block header's first 80 bytes // with parseHeaderBytes. struct BlockHeader { uint32 bits; uint blockHash; } // Convert a variable integer into something useful and return it and // the index to after it. function parseVarInt(bytes memory txBytes, uint pos) private pure returns (uint, uint) { // the first byte tells us how big the integer is uint8 ibit = uint8(txBytes[pos]); pos += 1; // skip ibit if (ibit < 0xfd) { return (ibit, pos); } else if (ibit == 0xfd) { return (getBytesLE(txBytes, pos, 16), pos + 2); } else if (ibit == 0xfe) { return (getBytesLE(txBytes, pos, 32), pos + 4); } else if (ibit == 0xff) { return (getBytesLE(txBytes, pos, 64), pos + 8); } } // convert little endian bytes to uint function getBytesLE(bytes memory data, uint pos, uint bits) internal pure returns (uint) { if (bits == 8) { return uint8(data[pos]); } else if (bits == 16) { return uint16(data[pos]) + uint16(data[pos + 1]) * 2 ** 8; } else if (bits == 32) { return uint32(data[pos]) + uint32(data[pos + 1]) * 2 ** 8 + uint32(data[pos + 2]) * 2 ** 16 + uint32(data[pos + 3]) * 2 ** 24; } else if (bits == 64) { return uint64(data[pos]) + uint64(data[pos + 1]) * 2 ** 8 + uint64(data[pos + 2]) * 2 ** 16 + uint64(data[pos + 3]) * 2 ** 24 + uint64(data[pos + 4]) * 2 ** 32 + uint64(data[pos + 5]) * 2 ** 40 + uint64(data[pos + 6]) * 2 ** 48 + uint64(data[pos + 7]) * 2 ** 56; } } // @dev - Parses a syscoin tx // // @param txBytes - tx byte array // Outputs // @return output_value - amount sent to the lock address in satoshis // @return destinationAddress - ethereum destination address function parseTransaction(bytes memory txBytes) internal pure returns (uint, uint, address, uint32) { uint output_value; uint32 assetGUID; address destinationAddress; uint32 version; uint pos = 0; version = bytesToUint32Flipped(txBytes, pos); if(version != SYSCOIN_TX_VERSION_ASSET_ALLOCATION_BURN && version != SYSCOIN_TX_VERSION_BURN){ return (ERR_PARSE_TX_SYS, output_value, destinationAddress, assetGUID); } pos = skipInputs(txBytes, 4); (output_value, destinationAddress, assetGUID) = scanBurns(txBytes, version, pos); return (0, output_value, destinationAddress, assetGUID); } // skips witnesses and saves first script position/script length to extract pubkey of first witness scriptSig function skipWitnesses(bytes memory txBytes, uint pos, uint n_inputs) private pure returns (uint) { uint n_stack; (n_stack, pos) = parseVarInt(txBytes, pos); uint script_len; for (uint i = 0; i < n_inputs; i++) { for (uint j = 0; j < n_stack; j++) { (script_len, pos) = parseVarInt(txBytes, pos); pos += script_len; } } return n_stack; } function skipInputs(bytes memory txBytes, uint pos) private pure returns (uint) { uint n_inputs; uint script_len; (n_inputs, pos) = parseVarInt(txBytes, pos); // if dummy 0x00 is present this is a witness transaction if(n_inputs == 0x00){ (n_inputs, pos) = parseVarInt(txBytes, pos); // flag assert(n_inputs != 0x00); // after dummy/flag the real var int comes for txins (n_inputs, pos) = parseVarInt(txBytes, pos); } require(n_inputs < 100); for (uint i = 0; i < n_inputs; i++) { pos += 36; // skip outpoint (script_len, pos) = parseVarInt(txBytes, pos); pos += script_len + 4; // skip sig_script, seq } return pos; } // scan the burn outputs and return the value and script data of first burned output. function scanBurns(bytes memory txBytes, uint32 version, uint pos) private pure returns (uint, address, uint32) { uint script_len; uint output_value; uint32 assetGUID = 0; address destinationAddress; uint n_outputs; (n_outputs, pos) = parseVarInt(txBytes, pos); require(n_outputs < 10); for (uint i = 0; i < n_outputs; i++) { // output if(version == SYSCOIN_TX_VERSION_BURN){ output_value = getBytesLE(txBytes, pos, 64); } pos += 8; // varint (script_len, pos) = parseVarInt(txBytes, pos); if(!isOpReturn(txBytes, pos)){ // output script pos += script_len; output_value = 0; continue; } // skip opreturn marker pos += 1; if(version == SYSCOIN_TX_VERSION_ASSET_ALLOCATION_BURN){ (output_value, destinationAddress, assetGUID) = scanAssetDetails(txBytes, pos); } else if(version == SYSCOIN_TX_VERSION_BURN){ destinationAddress = scanSyscoinDetails(txBytes, pos); } // only one opreturn data allowed per transaction break; } return (output_value, destinationAddress, assetGUID); } function skipOutputs(bytes memory txBytes, uint pos) private pure returns (uint) { uint n_outputs; uint script_len; (n_outputs, pos) = parseVarInt(txBytes, pos); require(n_outputs < 10); for (uint i = 0; i < n_outputs; i++) { pos += 8; (script_len, pos) = parseVarInt(txBytes, pos); pos += script_len; } return pos; } // get final position of inputs, outputs and lock time // this is a helper function to slice a byte array and hash the inputs, outputs and lock time function getSlicePos(bytes memory txBytes, uint pos) private pure returns (uint slicePos) { slicePos = skipInputs(txBytes, pos + 4); slicePos = skipOutputs(txBytes, slicePos); slicePos += 4; // skip lock time } // scan a Merkle branch. // return array of values and the end position of the sibling hashes. // takes a 'stop' argument which sets the maximum number of // siblings to scan through. stop=0 => scan all. function scanMerkleBranch(bytes memory txBytes, uint pos, uint stop) private pure returns (uint[], uint) { uint n_siblings; uint halt; (n_siblings, pos) = parseVarInt(txBytes, pos); if (stop == 0 || stop > n_siblings) { halt = n_siblings; } else { halt = stop; } uint[] memory sibling_values = new uint[](halt); for (uint i = 0; i < halt; i++) { sibling_values[i] = flip32Bytes(sliceBytes32Int(txBytes, pos)); pos += 32; } return (sibling_values, pos); } // Slice 20 contiguous bytes from bytes `data`, starting at `start` function sliceBytes20(bytes memory data, uint start) private pure returns (bytes20) { uint160 slice = 0; // FIXME: With solc v0.4.24 and optimizations enabled // using uint160 for index i will generate an error // "Error: VM Exception while processing transaction: Error: redPow(normalNum)" for (uint i = 0; i < 20; i++) { slice += uint160(data[i + start]) << (8 * (19 - i)); } return bytes20(slice); } // Slice 32 contiguous bytes from bytes `data`, starting at `start` function sliceBytes32Int(bytes memory data, uint start) private pure returns (uint slice) { for (uint i = 0; i < 32; i++) { if (i + start < data.length) { slice += uint(data[i + start]) << (8 * (31 - i)); } } } // @dev returns a portion of a given byte array specified by its starting and ending points // Should be private, made internal for testing // Breaks underscore naming convention for parameters because it raises a compiler error // if `offset` is changed to `_offset`. // // @param _rawBytes - array to be sliced // @param offset - first byte of sliced array // @param _endIndex - last byte of sliced array function sliceArray(bytes memory _rawBytes, uint offset, uint _endIndex) internal view returns (bytes) { uint len = _endIndex - offset; bytes memory result = new bytes(len); assembly { // Call precompiled contract to copy data if iszero(staticcall(gas, 0x04, add(add(_rawBytes, 0x20), offset), len, add(result, 0x20), len)) { revert(0, 0) } } return result; } // Returns true if the tx output is an OP_RETURN output function isOpReturn(bytes memory txBytes, uint pos) private pure returns (bool) { // scriptPub format is // 0x6a OP_RETURN return txBytes[pos] == byte(0x6a); } // Returns syscoin data parsed from the op_return data output from syscoin burn transaction function scanSyscoinDetails(bytes memory txBytes, uint pos) private pure returns (address) { uint8 op; (op, pos) = getOpcode(txBytes, pos); // ethereum addresses are 20 bytes (without the 0x) require(op == 0x14); return readEthereumAddress(txBytes, pos); } // Returns asset data parsed from the op_return data output from syscoin asset burn transaction function scanAssetDetails(bytes memory txBytes, uint pos) private pure returns (uint, address, uint32) { uint32 assetGUID; address destinationAddress; uint output_value; uint8 op; // vchAsset (op, pos) = getOpcode(txBytes, pos); // guid length should be 4 bytes require(op == 0x04); assetGUID = bytesToUint32(txBytes, pos); pos += op; // amount (op, pos) = getOpcode(txBytes, pos); require(op == 0x08); output_value = bytesToUint64(txBytes, pos); pos += op; // destination address (op, pos) = getOpcode(txBytes, pos); // ethereum contracts are 20 bytes (without the 0x) require(op == 0x14); destinationAddress = readEthereumAddress(txBytes, pos); return (output_value, destinationAddress, assetGUID); } // Read the ethereum address embedded in the tx output function readEthereumAddress(bytes memory txBytes, uint pos) private pure returns (address) { uint256 data; assembly { data := mload(add(add(txBytes, 20), pos)) } return address(uint160(data)); } // Read next opcode from script function getOpcode(bytes memory txBytes, uint pos) private pure returns (uint8, uint) { require(pos < txBytes.length); return (uint8(txBytes[pos]), pos + 1); } // @dev - convert an unsigned integer from little-endian to big-endian representation // // @param _input - little-endian value // @return - input value in big-endian format function flip32Bytes(uint _input) internal pure returns (uint result) { assembly { let pos := mload(0x40) for { let i := 0 } lt(i, 32) { i := add(i, 1) } { mstore8(add(pos, i), byte(sub(31, i), _input)) } result := mload(pos) } } // helpers for flip32Bytes struct UintWrapper { uint value; } function ptr(UintWrapper memory uw) private pure returns (uint addr) { assembly { addr := uw } } function parseAuxPoW(bytes memory rawBytes, uint pos) internal view returns (AuxPoW memory auxpow) { // we need to traverse the bytes with a pointer because some fields are of variable length pos += 80; // skip non-AuxPoW header uint slicePos; (slicePos) = getSlicePos(rawBytes, pos); auxpow.txHash = dblShaFlipMem(rawBytes, pos, slicePos - pos); pos = slicePos; // parent block hash, skip and manually hash below pos += 32; (auxpow.parentMerkleProof, pos) = scanMerkleBranch(rawBytes, pos, 0); auxpow.coinbaseTxIndex = getBytesLE(rawBytes, pos, 32); pos += 4; (auxpow.chainMerkleProof, pos) = scanMerkleBranch(rawBytes, pos, 0); auxpow.syscoinHashIndex = getBytesLE(rawBytes, pos, 32); pos += 4; // calculate block hash instead of reading it above, as some are LE and some are BE, we cannot know endianness and have to calculate from parent block header auxpow.blockHash = dblShaFlipMem(rawBytes, pos, 80); pos += 36; // skip parent version and prev block auxpow.parentMerkleRoot = sliceBytes32Int(rawBytes, pos); pos += 40; // skip root that was just read, parent block timestamp and bits auxpow.parentNonce = getBytesLE(rawBytes, pos, 32); uint coinbaseMerkleRootPosition; (auxpow.coinbaseMerkleRoot, coinbaseMerkleRootPosition, auxpow.coinbaseMerkleRootCode) = findCoinbaseMerkleRoot(rawBytes); } // @dev - looks for {0xfa, 0xbe, 'm', 'm'} byte sequence // returns the following 32 bytes if it appears once and only once, // 0 otherwise // also returns the position where the bytes first appear function findCoinbaseMerkleRoot(bytes memory rawBytes) private pure returns (uint, uint, uint) { uint position; bool found = false; for (uint i = 0; i < rawBytes.length; ++i) { if (rawBytes[i] == 0xfa && rawBytes[i+1] == 0xbe && rawBytes[i+2] == 0x6d && rawBytes[i+3] == 0x6d) { if (found) { // found twice return (0, position - 4, ERR_FOUND_TWICE); } else { found = true; position = i + 4; } } } if (!found) { // no merge mining header return (0, position - 4, ERR_NO_MERGE_HEADER); } else { return (sliceBytes32Int(rawBytes, position), position - 4, 1); } } // @dev - Evaluate the merkle root // // Given an array of hashes it calculates the // root of the merkle tree. // // @return root of merkle tree function makeMerkle(bytes32[] hashes2) external pure returns (bytes32) { bytes32[] memory hashes = hashes2; uint length = hashes.length; if (length == 1) return hashes[0]; require(length > 0); uint i; uint j; uint k; k = 0; while (length > 1) { k = 0; for (i = 0; i < length; i += 2) { j = i+1<length ? i+1 : length-1; hashes[k] = bytes32(concatHash(uint(hashes[i]), uint(hashes[j]))); k += 1; } length = k; } return hashes[0]; } // @dev - For a valid proof, returns the root of the Merkle tree. // // @param _txHash - transaction hash // @param _txIndex - transaction's index within the block it's assumed to be in // @param _siblings - transaction's Merkle siblings // @return - Merkle tree root of the block the transaction belongs to if the proof is valid, // garbage if it's invalid function computeMerkle(uint _txHash, uint _txIndex, uint[] memory _siblings) internal pure returns (uint) { uint resultHash = _txHash; uint i = 0; while (i < _siblings.length) { uint proofHex = _siblings[i]; uint sideOfSiblings = _txIndex % 2; // 0 means _siblings is on the right; 1 means left uint left; uint right; if (sideOfSiblings == 1) { left = proofHex; right = resultHash; } else if (sideOfSiblings == 0) { left = resultHash; right = proofHex; } resultHash = concatHash(left, right); _txIndex /= 2; i += 1; } return resultHash; } // @dev - calculates the Merkle root of a tree containing Litecoin transactions // in order to prove that `ap`'s coinbase tx is in that Litecoin block. // // @param _ap - AuxPoW information // @return - Merkle root of Litecoin block that the Syscoin block // with this info was mined in if AuxPoW Merkle proof is correct, // garbage otherwise function computeParentMerkle(AuxPoW memory _ap) internal pure returns (uint) { return flip32Bytes(computeMerkle(_ap.txHash, _ap.coinbaseTxIndex, _ap.parentMerkleProof)); } // @dev - calculates the Merkle root of a tree containing auxiliary block hashes // in order to prove that the Syscoin block identified by _blockHash // was merge-mined in a Litecoin block. // // @param _blockHash - SHA-256 hash of a certain Syscoin block // @param _ap - AuxPoW information corresponding to said block // @return - Merkle root of auxiliary chain tree // if AuxPoW Merkle proof is correct, garbage otherwise function computeChainMerkle(uint _blockHash, AuxPoW memory _ap) internal pure returns (uint) { return computeMerkle(_blockHash, _ap.syscoinHashIndex, _ap.chainMerkleProof); } // @dev - Helper function for Merkle root calculation. // Given two sibling nodes in a Merkle tree, calculate their parent. // Concatenates hashes `_tx1` and `_tx2`, then hashes the result. // // @param _tx1 - Merkle node (either root or internal node) // @param _tx2 - Merkle node (either root or internal node), has to be `_tx1`'s sibling // @return - `_tx1` and `_tx2`'s parent, i.e. the result of concatenating them, // hashing that twice and flipping the bytes. function concatHash(uint _tx1, uint _tx2) internal pure returns (uint) { return flip32Bytes(uint(sha256(abi.encodePacked(sha256(abi.encodePacked(flip32Bytes(_tx1), flip32Bytes(_tx2))))))); } // @dev - checks if a merge-mined block's Merkle proofs are correct, // i.e. Syscoin block hash is in coinbase Merkle tree // and coinbase transaction is in parent Merkle tree. // // @param _blockHash - SHA-256 hash of the block whose Merkle proofs are being checked // @param _ap - AuxPoW struct corresponding to the block // @return 1 if block was merge-mined and coinbase index, chain Merkle root and Merkle proofs are correct, // respective error code otherwise function checkAuxPoW(uint _blockHash, AuxPoW memory _ap) internal pure returns (uint) { if (_ap.coinbaseTxIndex != 0) { return ERR_COINBASE_INDEX; } if (_ap.coinbaseMerkleRootCode != 1) { return _ap.coinbaseMerkleRootCode; } if (computeChainMerkle(_blockHash, _ap) != _ap.coinbaseMerkleRoot) { return ERR_CHAIN_MERKLE; } if (computeParentMerkle(_ap) != _ap.parentMerkleRoot) { return ERR_PARENT_MERKLE; } return 1; } function sha256mem(bytes memory _rawBytes, uint offset, uint len) internal view returns (bytes32 result) { assembly { // Call sha256 precompiled contract (located in address 0x02) to copy data. // Assign to ptr the next available memory position (stored in memory position 0x40). let ptr := mload(0x40) if iszero(staticcall(gas, 0x02, add(add(_rawBytes, 0x20), offset), len, ptr, 0x20)) { revert(0, 0) } result := mload(ptr) } } // @dev - Bitcoin-way of hashing // @param _dataBytes - raw data to be hashed // @return - result of applying SHA-256 twice to raw data and then flipping the bytes function dblShaFlip(bytes _dataBytes) internal pure returns (uint) { return flip32Bytes(uint(sha256(abi.encodePacked(sha256(abi.encodePacked(_dataBytes)))))); } // @dev - Bitcoin-way of hashing // @param _dataBytes - raw data to be hashed // @return - result of applying SHA-256 twice to raw data and then flipping the bytes function dblShaFlipMem(bytes memory _rawBytes, uint offset, uint len) internal view returns (uint) { return flip32Bytes(uint(sha256(abi.encodePacked(sha256mem(_rawBytes, offset, len))))); } // @dev – Read a bytes32 from an offset in the byte array function readBytes32(bytes memory data, uint offset) internal pure returns (bytes32) { bytes32 result; assembly { result := mload(add(add(data, 0x20), offset)) } return result; } // @dev – Read an uint32 from an offset in the byte array function readUint32(bytes memory data, uint offset) internal pure returns (uint32) { uint32 result; assembly { result := mload(add(add(data, 0x20), offset)) } return result; } // @dev - Bitcoin-way of computing the target from the 'bits' field of a block header // based on http://www.righto.com/2014/02/bitcoin-mining-hard-way-algorithms.html//ref3 // // @param _bits - difficulty in bits format // @return - difficulty in target format function targetFromBits(uint32 _bits) internal pure returns (uint) { uint exp = _bits / 0x1000000; // 2**24 uint mant = _bits & 0xffffff; return mant * 256**(exp - 3); } uint constant SYSCOIN_DIFFICULTY_ONE = 0xFFFFF * 256**(0x1e - 3); // @dev - Calculate syscoin difficulty from target // https://en.bitcoin.it/wiki/Difficulty // Min difficulty for bitcoin is 0x1d00ffff // Min difficulty for syscoin is 0x1e0fffff function targetToDiff(uint target) internal pure returns (uint) { return SYSCOIN_DIFFICULTY_ONE / target; } // 0x00 version // 0x04 prev block hash // 0x24 merkle root // 0x44 timestamp // 0x48 bits // 0x4c nonce // @dev - extract previous block field from a raw Syscoin block header // // @param _blockHeader - Syscoin block header bytes // @param pos - where to start reading hash from // @return - hash of block's parent in big endian format function getHashPrevBlock(bytes memory _blockHeader) internal pure returns (uint) { uint hashPrevBlock; assembly { hashPrevBlock := mload(add(add(_blockHeader, 32), 0x04)) } return flip32Bytes(hashPrevBlock); } // @dev - extract Merkle root field from a raw Syscoin block header // // @param _blockHeader - Syscoin block header bytes // @param pos - where to start reading root from // @return - block's Merkle root in big endian format function getHeaderMerkleRoot(bytes memory _blockHeader) public pure returns (uint) { uint merkle; assembly { merkle := mload(add(add(_blockHeader, 32), 0x24)) } return flip32Bytes(merkle); } // @dev - extract timestamp field from a raw Syscoin block header // // @param _blockHeader - Syscoin block header bytes // @param pos - where to start reading bits from // @return - block's timestamp in big-endian format function getTimestamp(bytes memory _blockHeader) internal pure returns (uint32 time) { return bytesToUint32Flipped(_blockHeader, 0x44); } // @dev - extract bits field from a raw Syscoin block header // // @param _blockHeader - Syscoin block header bytes // @param pos - where to start reading bits from // @return - block's difficulty in bits format, also big-endian function getBits(bytes memory _blockHeader) internal pure returns (uint32 bits) { return bytesToUint32Flipped(_blockHeader, 0x48); } // @dev - converts raw bytes representation of a Syscoin block header to struct representation // // @param _rawBytes - first 80 bytes of a block header // @return - exact same header information in BlockHeader struct form function parseHeaderBytes(bytes memory _rawBytes, uint pos) internal view returns (BlockHeader bh) { bh.bits = getBits(_rawBytes); bh.blockHash = dblShaFlipMem(_rawBytes, pos, 80); } uint32 constant VERSION_AUXPOW = (1 << 8); // @dev - Converts a bytes of size 4 to uint32, // e.g. for input [0x01, 0x02, 0x03 0x04] returns 0x01020304 function bytesToUint32Flipped(bytes memory input, uint pos) internal pure returns (uint32 result) { result = uint32(input[pos]) + uint32(input[pos + 1])*(2**8) + uint32(input[pos + 2])*(2**16) + uint32(input[pos + 3])*(2**24); } function bytesToUint64(bytes memory input, uint pos) internal pure returns (uint64 result) { result = uint64(input[pos+7]) + uint64(input[pos + 6])*(2**8) + uint64(input[pos + 5])*(2**16) + uint64(input[pos + 4])*(2**24) + uint64(input[pos + 3])*(2**32) + uint64(input[pos + 2])*(2**40) + uint64(input[pos + 1])*(2**48) + uint64(input[pos])*(2**56); } function bytesToUint32(bytes memory input, uint pos) internal pure returns (uint32 result) { result = uint32(input[pos+3]) + uint32(input[pos + 2])*(2**8) + uint32(input[pos + 1])*(2**16) + uint32(input[pos])*(2**24); } // @dev - checks version to determine if a block has merge mining information function isMergeMined(bytes memory _rawBytes, uint pos) internal pure returns (bool) { return bytesToUint32Flipped(_rawBytes, pos) & VERSION_AUXPOW != 0; } // @dev - Verify block header // @param _blockHeaderBytes - array of bytes with the block header // @param _pos - starting position of the block header // @param _proposedBlockHash - proposed block hash computing from block header bytes // @return - [ErrorCode, IsMergeMined] function verifyBlockHeader(bytes _blockHeaderBytes, uint _pos, uint _proposedBlockHash) external view returns (uint, bool) { BlockHeader memory blockHeader = parseHeaderBytes(_blockHeaderBytes, _pos); uint blockSha256Hash = blockHeader.blockHash; // must confirm that the header hash passed in and computing hash matches if(blockSha256Hash != _proposedBlockHash){ return (ERR_INVALID_HEADER_HASH, true); } uint target = targetFromBits(blockHeader.bits); if (_blockHeaderBytes.length > 80 && isMergeMined(_blockHeaderBytes, 0)) { AuxPoW memory ap = parseAuxPoW(_blockHeaderBytes, _pos); if (ap.blockHash > target) { return (ERR_PROOF_OF_WORK_AUXPOW, true); } uint auxPoWCode = checkAuxPoW(blockSha256Hash, ap); if (auxPoWCode != 1) { return (auxPoWCode, true); } return (0, true); } else { if (_proposedBlockHash > target) { return (ERR_PROOF_OF_WORK, false); } return (0, false); } } // For verifying Syscoin difficulty int64 constant TARGET_TIMESPAN = int64(21600); int64 constant TARGET_TIMESPAN_DIV_4 = TARGET_TIMESPAN / int64(4); int64 constant TARGET_TIMESPAN_MUL_4 = TARGET_TIMESPAN * int64(4); int64 constant TARGET_TIMESPAN_ADJUSTMENT = int64(360); // 6 hour uint constant INITIAL_CHAIN_WORK = 0x100001; uint constant POW_LIMIT = 0x00000fffffffffffffffffffffffffffffffffffffffffffffffffffffffffff; // @dev - Calculate difficulty from compact representation (bits) found in block function diffFromBits(uint32 bits) external pure returns (uint) { return targetToDiff(targetFromBits(bits))*INITIAL_CHAIN_WORK; } function difficultyAdjustmentInterval() external pure returns (int64) { return TARGET_TIMESPAN_ADJUSTMENT; } // @param _actualTimespan - time elapsed from previous block creation til current block creation; // i.e., how much time it took to mine the current block // @param _bits - previous block header difficulty (in bits) // @return - expected difficulty for the next block function calculateDifficulty(int64 _actualTimespan, uint32 _bits) external pure returns (uint32 result) { int64 actualTimespan = _actualTimespan; // Limit adjustment step if (_actualTimespan < TARGET_TIMESPAN_DIV_4) { actualTimespan = TARGET_TIMESPAN_DIV_4; } else if (_actualTimespan > TARGET_TIMESPAN_MUL_4) { actualTimespan = TARGET_TIMESPAN_MUL_4; } // Retarget uint bnNew = targetFromBits(_bits); bnNew = bnNew * uint(actualTimespan); bnNew = uint(bnNew) / uint(TARGET_TIMESPAN); if (bnNew > POW_LIMIT) { bnNew = POW_LIMIT; } return toCompactBits(bnNew); } // @dev - shift information to the right by a specified number of bits // // @param _val - value to be shifted // @param _shift - number of bits to shift // @return - `_val` shifted `_shift` bits to the right, i.e. divided by 2**`_shift` function shiftRight(uint _val, uint _shift) private pure returns (uint) { return _val / uint(2)**_shift; } // @dev - shift information to the left by a specified number of bits // // @param _val - value to be shifted // @param _shift - number of bits to shift // @return - `_val` shifted `_shift` bits to the left, i.e. multiplied by 2**`_shift` function shiftLeft(uint _val, uint _shift) private pure returns (uint) { return _val * uint(2)**_shift; } // @dev - get the number of bits required to represent a given integer value without losing information // // @param _val - unsigned integer value // @return - given value's bit length function bitLen(uint _val) private pure returns (uint length) { uint int_type = _val; while (int_type > 0) { int_type = shiftRight(int_type, 1); length += 1; } } // @dev - Convert uint256 to compact encoding // based on https://github.com/petertodd/python-bitcoinlib/blob/2a5dda45b557515fb12a0a18e5dd48d2f5cd13c2/bitcoin/core/serialize.py // Analogous to arith_uint256::GetCompact from C++ implementation // // @param _val - difficulty in target format // @return - difficulty in bits format function toCompactBits(uint _val) private pure returns (uint32) { uint nbytes = uint (shiftRight((bitLen(_val) + 7), 3)); uint32 compact = 0; if (nbytes <= 3) { compact = uint32 (shiftLeft((_val & 0xFFFFFF), 8 * (3 - nbytes))); } else { compact = uint32 (shiftRight(_val, 8 * (nbytes - 3))); compact = uint32 (compact & 0xFFFFFF); } // If the sign bit (0x00800000) is set, divide the mantissa by 256 and // increase the exponent to get an encoding without it set. if ((compact & 0x00800000) > 0) { compact = uint32(shiftRight(compact, 8)); nbytes += 1; } return compact | uint32(shiftLeft(nbytes, 24)); } } // @dev - SyscoinSuperblocks error codes contract SyscoinErrorCodes { // Error codes uint constant ERR_SUPERBLOCK_OK = 0; uint constant ERR_SUPERBLOCK_BAD_STATUS = 50020; uint constant ERR_SUPERBLOCK_BAD_SYSCOIN_STATUS = 50025; uint constant ERR_SUPERBLOCK_NO_TIMEOUT = 50030; uint constant ERR_SUPERBLOCK_BAD_TIMESTAMP = 50035; uint constant ERR_SUPERBLOCK_INVALID_MERKLE = 50040; uint constant ERR_SUPERBLOCK_BAD_PARENT = 50050; uint constant ERR_SUPERBLOCK_OWN_CHALLENGE = 50055; uint constant ERR_SUPERBLOCK_MIN_DEPOSIT = 50060; uint constant ERR_SUPERBLOCK_NOT_CLAIMMANAGER = 50070; uint constant ERR_SUPERBLOCK_BAD_CLAIM = 50080; uint constant ERR_SUPERBLOCK_VERIFICATION_PENDING = 50090; uint constant ERR_SUPERBLOCK_CLAIM_DECIDED = 50100; uint constant ERR_SUPERBLOCK_BAD_CHALLENGER = 50110; uint constant ERR_SUPERBLOCK_BAD_ACCUMULATED_WORK = 50120; uint constant ERR_SUPERBLOCK_BAD_BITS = 50130; uint constant ERR_SUPERBLOCK_MISSING_CONFIRMATIONS = 50140; uint constant ERR_SUPERBLOCK_BAD_LASTBLOCK = 50150; uint constant ERR_SUPERBLOCK_BAD_BLOCKHEIGHT = 50160; // error codes for verifyTx uint constant ERR_BAD_FEE = 20010; uint constant ERR_CONFIRMATIONS = 20020; uint constant ERR_CHAIN = 20030; uint constant ERR_SUPERBLOCK = 20040; uint constant ERR_MERKLE_ROOT = 20050; uint constant ERR_TX_64BYTE = 20060; // error codes for relayTx uint constant ERR_RELAY_VERIFY = 30010; // Minimum gas requirements uint constant public minReward = 1000000000000000000; uint constant public superblockCost = 440000; uint constant public challengeCost = 34000; uint constant public minProposalDeposit = challengeCost + minReward; uint constant public minChallengeDeposit = superblockCost + minReward; uint constant public respondMerkleRootHashesCost = 378000; // TODO: measure this with 60 hashes uint constant public respondBlockHeaderCost = 40000; uint constant public verifySuperblockCost = 220000; } // @dev - Manages superblocks // // Management of superblocks and status transitions contract SyscoinSuperblocks is SyscoinErrorCodes { // @dev - Superblock status enum Status { Unitialized, New, InBattle, SemiApproved, Approved, Invalid } struct SuperblockInfo { bytes32 blocksMerkleRoot; uint accumulatedWork; uint timestamp; uint prevTimestamp; bytes32 lastHash; bytes32 parentId; address submitter; bytes32 ancestors; uint32 lastBits; uint32 index; uint32 height; uint32 blockHeight; Status status; } // Mapping superblock id => superblock data mapping (bytes32 => SuperblockInfo) superblocks; // Index to superblock id mapping (uint32 => bytes32) private indexSuperblock; struct ProcessTransactionParams { uint value; address destinationAddress; uint32 assetGUID; address superblockSubmitterAddress; SyscoinTransactionProcessor untrustedTargetContract; } mapping (uint => ProcessTransactionParams) private txParams; uint32 indexNextSuperblock; bytes32 public bestSuperblock; uint public bestSuperblockAccumulatedWork; event NewSuperblock(bytes32 superblockHash, address who); event ApprovedSuperblock(bytes32 superblockHash, address who); event ChallengeSuperblock(bytes32 superblockHash, address who); event SemiApprovedSuperblock(bytes32 superblockHash, address who); event InvalidSuperblock(bytes32 superblockHash, address who); event ErrorSuperblock(bytes32 superblockHash, uint err); event VerifyTransaction(bytes32 txHash, uint returnCode); event RelayTransaction(bytes32 txHash, uint returnCode); // SyscoinClaimManager address public trustedClaimManager; modifier onlyClaimManager() { require(msg.sender == trustedClaimManager); _; } // @dev – the constructor constructor() public {} // @dev - sets ClaimManager instance associated with managing superblocks. // Once trustedClaimManager has been set, it cannot be changed. // @param _claimManager - address of the ClaimManager contract to be associated with function setClaimManager(address _claimManager) public { require(address(trustedClaimManager) == 0x0 && _claimManager != 0x0); trustedClaimManager = _claimManager; } // @dev - Initializes superblocks contract // // Initializes the superblock contract. It can only be called once. // // @param _blocksMerkleRoot Root of the merkle tree of blocks contained in a superblock // @param _accumulatedWork Accumulated proof of work of the last block in the superblock // @param _timestamp Timestamp of the last block in the superblock // @param _prevTimestamp Timestamp of the block when the last difficulty adjustment happened (every 360 blocks) // @param _lastHash Hash of the last block in the superblock // @param _lastBits Difficulty bits of the last block in the superblock // @param _parentId Id of the parent superblock // @param _blockHeight Block height of last block in superblock // @return Error code and superblockHash function initialize( bytes32 _blocksMerkleRoot, uint _accumulatedWork, uint _timestamp, uint _prevTimestamp, bytes32 _lastHash, uint32 _lastBits, bytes32 _parentId, uint32 _blockHeight ) public returns (uint, bytes32) { require(bestSuperblock == 0); require(_parentId == 0); bytes32 superblockHash = calcSuperblockHash(_blocksMerkleRoot, _accumulatedWork, _timestamp, _prevTimestamp, _lastHash, _lastBits, _parentId, _blockHeight); SuperblockInfo storage superblock = superblocks[superblockHash]; require(superblock.status == Status.Unitialized); indexSuperblock[indexNextSuperblock] = superblockHash; superblock.blocksMerkleRoot = _blocksMerkleRoot; superblock.accumulatedWork = _accumulatedWork; superblock.timestamp = _timestamp; superblock.prevTimestamp = _prevTimestamp; superblock.lastHash = _lastHash; superblock.parentId = _parentId; superblock.submitter = msg.sender; superblock.index = indexNextSuperblock; superblock.height = 1; superblock.lastBits = _lastBits; superblock.status = Status.Approved; superblock.ancestors = 0x0; superblock.blockHeight = _blockHeight; indexNextSuperblock++; emit NewSuperblock(superblockHash, msg.sender); bestSuperblock = superblockHash; bestSuperblockAccumulatedWork = _accumulatedWork; emit ApprovedSuperblock(superblockHash, msg.sender); return (ERR_SUPERBLOCK_OK, superblockHash); } // @dev - Proposes a new superblock // // To be accepted, a new superblock needs to have its parent // either approved or semi-approved. // // @param _blocksMerkleRoot Root of the merkle tree of blocks contained in a superblock // @param _accumulatedWork Accumulated proof of work of the last block in the superblock // @param _timestamp Timestamp of the last block in the superblock // @param _prevTimestamp Timestamp of the block when the last difficulty adjustment happened (every 360 blocks) // @param _lastHash Hash of the last block in the superblock // @param _lastBits Difficulty bits of the last block in the superblock // @param _parentId Id of the parent superblock // @param _blockHeight Block height of last block in superblock // @return Error code and superblockHash function propose( bytes32 _blocksMerkleRoot, uint _accumulatedWork, uint _timestamp, uint _prevTimestamp, bytes32 _lastHash, uint32 _lastBits, bytes32 _parentId, uint32 _blockHeight, address submitter ) public returns (uint, bytes32) { if (msg.sender != trustedClaimManager) { emit ErrorSuperblock(0, ERR_SUPERBLOCK_NOT_CLAIMMANAGER); return (ERR_SUPERBLOCK_NOT_CLAIMMANAGER, 0); } SuperblockInfo storage parent = superblocks[_parentId]; if (parent.status != Status.SemiApproved && parent.status != Status.Approved) { emit ErrorSuperblock(superblockHash, ERR_SUPERBLOCK_BAD_PARENT); return (ERR_SUPERBLOCK_BAD_PARENT, 0); } bytes32 superblockHash = calcSuperblockHash(_blocksMerkleRoot, _accumulatedWork, _timestamp, _prevTimestamp, _lastHash, _lastBits, _parentId, _blockHeight); SuperblockInfo storage superblock = superblocks[superblockHash]; if (superblock.status == Status.Unitialized) { indexSuperblock[indexNextSuperblock] = superblockHash; superblock.blocksMerkleRoot = _blocksMerkleRoot; superblock.accumulatedWork = _accumulatedWork; superblock.timestamp = _timestamp; superblock.prevTimestamp = _prevTimestamp; superblock.lastHash = _lastHash; superblock.parentId = _parentId; superblock.submitter = submitter; superblock.index = indexNextSuperblock; superblock.height = parent.height + 1; superblock.lastBits = _lastBits; superblock.status = Status.New; superblock.blockHeight = _blockHeight; superblock.ancestors = updateAncestors(parent.ancestors, parent.index, parent.height); indexNextSuperblock++; emit NewSuperblock(superblockHash, submitter); } return (ERR_SUPERBLOCK_OK, superblockHash); } // @dev - Confirm a proposed superblock // // An unchallenged superblock can be confirmed after a timeout. // A challenged superblock is confirmed if it has enough descendants // in the main chain. // // @param _superblockHash Id of the superblock to confirm // @param _validator Address requesting superblock confirmation // @return Error code and superblockHash function confirm(bytes32 _superblockHash, address _validator) public returns (uint, bytes32) { if (msg.sender != trustedClaimManager) { emit ErrorSuperblock(_superblockHash, ERR_SUPERBLOCK_NOT_CLAIMMANAGER); return (ERR_SUPERBLOCK_NOT_CLAIMMANAGER, 0); } SuperblockInfo storage superblock = superblocks[_superblockHash]; if (superblock.status != Status.New && superblock.status != Status.SemiApproved) { emit ErrorSuperblock(_superblockHash, ERR_SUPERBLOCK_BAD_STATUS); return (ERR_SUPERBLOCK_BAD_STATUS, 0); } SuperblockInfo storage parent = superblocks[superblock.parentId]; if (parent.status != Status.Approved) { emit ErrorSuperblock(_superblockHash, ERR_SUPERBLOCK_BAD_PARENT); return (ERR_SUPERBLOCK_BAD_PARENT, 0); } superblock.status = Status.Approved; if (superblock.accumulatedWork > bestSuperblockAccumulatedWork) { bestSuperblock = _superblockHash; bestSuperblockAccumulatedWork = superblock.accumulatedWork; } emit ApprovedSuperblock(_superblockHash, _validator); return (ERR_SUPERBLOCK_OK, _superblockHash); } // @dev - Challenge a proposed superblock // // A new superblock can be challenged to start a battle // to verify the correctness of the data submitted. // // @param _superblockHash Id of the superblock to challenge // @param _challenger Address requesting a challenge // @return Error code and superblockHash function challenge(bytes32 _superblockHash, address _challenger) public returns (uint, bytes32) { if (msg.sender != trustedClaimManager) { emit ErrorSuperblock(_superblockHash, ERR_SUPERBLOCK_NOT_CLAIMMANAGER); return (ERR_SUPERBLOCK_NOT_CLAIMMANAGER, 0); } SuperblockInfo storage superblock = superblocks[_superblockHash]; if (superblock.status != Status.New && superblock.status != Status.InBattle) { emit ErrorSuperblock(_superblockHash, ERR_SUPERBLOCK_BAD_STATUS); return (ERR_SUPERBLOCK_BAD_STATUS, 0); } if(superblock.submitter == _challenger){ emit ErrorSuperblock(_superblockHash, ERR_SUPERBLOCK_OWN_CHALLENGE); return (ERR_SUPERBLOCK_OWN_CHALLENGE, 0); } superblock.status = Status.InBattle; emit ChallengeSuperblock(_superblockHash, _challenger); return (ERR_SUPERBLOCK_OK, _superblockHash); } // @dev - Semi-approve a challenged superblock // // A challenged superblock can be marked as semi-approved // if it satisfies all the queries or when all challengers have // stopped participating. // // @param _superblockHash Id of the superblock to semi-approve // @param _validator Address requesting semi approval // @return Error code and superblockHash function semiApprove(bytes32 _superblockHash, address _validator) public returns (uint, bytes32) { if (msg.sender != trustedClaimManager) { emit ErrorSuperblock(_superblockHash, ERR_SUPERBLOCK_NOT_CLAIMMANAGER); return (ERR_SUPERBLOCK_NOT_CLAIMMANAGER, 0); } SuperblockInfo storage superblock = superblocks[_superblockHash]; if (superblock.status != Status.InBattle && superblock.status != Status.New) { emit ErrorSuperblock(_superblockHash, ERR_SUPERBLOCK_BAD_STATUS); return (ERR_SUPERBLOCK_BAD_STATUS, 0); } superblock.status = Status.SemiApproved; emit SemiApprovedSuperblock(_superblockHash, _validator); return (ERR_SUPERBLOCK_OK, _superblockHash); } // @dev - Invalidates a superblock // // A superblock with incorrect data can be invalidated immediately. // Superblocks that are not in the main chain can be invalidated // if not enough superblocks follow them, i.e. they don't have // enough descendants. // // @param _superblockHash Id of the superblock to invalidate // @param _validator Address requesting superblock invalidation // @return Error code and superblockHash function invalidate(bytes32 _superblockHash, address _validator) public returns (uint, bytes32) { if (msg.sender != trustedClaimManager) { emit ErrorSuperblock(_superblockHash, ERR_SUPERBLOCK_NOT_CLAIMMANAGER); return (ERR_SUPERBLOCK_NOT_CLAIMMANAGER, 0); } SuperblockInfo storage superblock = superblocks[_superblockHash]; if (superblock.status != Status.InBattle && superblock.status != Status.SemiApproved) { emit ErrorSuperblock(_superblockHash, ERR_SUPERBLOCK_BAD_STATUS); return (ERR_SUPERBLOCK_BAD_STATUS, 0); } superblock.status = Status.Invalid; emit InvalidSuperblock(_superblockHash, _validator); return (ERR_SUPERBLOCK_OK, _superblockHash); } // @dev - relays transaction `_txBytes` to `_untrustedTargetContract`'s processTransaction() method. // Also logs the value of processTransaction. // Note: callers cannot be 100% certain when an ERR_RELAY_VERIFY occurs because // it may also have been returned by processTransaction(). Callers should be // aware of the contract that they are relaying transactions to and // understand what that contract's processTransaction method returns. // // @param _txBytes - transaction bytes // @param _txIndex - transaction's index within the block // @param _txSiblings - transaction's Merkle siblings // @param _syscoinBlockHeader - block header containing transaction // @param _syscoinBlockIndex - block's index withing superblock // @param _syscoinBlockSiblings - block's merkle siblings // @param _superblockHash - superblock containing block header // @param _untrustedTargetContract - the contract that is going to process the transaction function relayTx( bytes memory _txBytes, uint _txIndex, uint[] _txSiblings, bytes memory _syscoinBlockHeader, uint _syscoinBlockIndex, uint[] memory _syscoinBlockSiblings, bytes32 _superblockHash, SyscoinTransactionProcessor _untrustedTargetContract ) public returns (uint) { // Check if Syscoin block belongs to given superblock if (bytes32(SyscoinMessageLibrary.computeMerkle(SyscoinMessageLibrary.dblShaFlip(_syscoinBlockHeader), _syscoinBlockIndex, _syscoinBlockSiblings)) != getSuperblockMerkleRoot(_superblockHash)) { // Syscoin block is not in superblock emit RelayTransaction(bytes32(0), ERR_SUPERBLOCK); return ERR_SUPERBLOCK; } uint txHash = verifyTx(_txBytes, _txIndex, _txSiblings, _syscoinBlockHeader, _superblockHash); if (txHash != 0) { uint ret = parseTxHelper(_txBytes, txHash, _untrustedTargetContract); if(ret != 0){ emit RelayTransaction(bytes32(0), ret); return ret; } ProcessTransactionParams memory params = txParams[txHash]; params.superblockSubmitterAddress = superblocks[_superblockHash].submitter; txParams[txHash] = params; return verifyTxHelper(txHash); } emit RelayTransaction(bytes32(0), ERR_RELAY_VERIFY); return(ERR_RELAY_VERIFY); } function parseTxHelper(bytes memory _txBytes, uint txHash, SyscoinTransactionProcessor _untrustedTargetContract) private returns (uint) { uint value; address destinationAddress; uint32 _assetGUID; uint ret; (ret, value, destinationAddress, _assetGUID) = SyscoinMessageLibrary.parseTransaction(_txBytes); if(ret != 0){ return ret; } ProcessTransactionParams memory params; params.value = value; params.destinationAddress = destinationAddress; params.assetGUID = _assetGUID; params.untrustedTargetContract = _untrustedTargetContract; txParams[txHash] = params; return 0; } function verifyTxHelper(uint txHash) private returns (uint) { ProcessTransactionParams memory params = txParams[txHash]; uint returnCode = params.untrustedTargetContract.processTransaction(txHash, params.value, params.destinationAddress, params.assetGUID, params.superblockSubmitterAddress); emit RelayTransaction(bytes32(txHash), returnCode); return (returnCode); } // @dev - Checks whether the transaction given by `_txBytes` is in the block identified by `_txBlockHeaderBytes`. // First it guards against a Merkle tree collision attack by raising an error if the transaction is exactly 64 bytes long, // then it calls helperVerifyHash to do the actual check. // // @param _txBytes - transaction bytes // @param _txIndex - transaction's index within the block // @param _siblings - transaction's Merkle siblings // @param _txBlockHeaderBytes - block header containing transaction // @param _txsuperblockHash - superblock containing block header // @return - SHA-256 hash of _txBytes if the transaction is in the block, 0 otherwise // TODO: this can probably be made private function verifyTx( bytes memory _txBytes, uint _txIndex, uint[] memory _siblings, bytes memory _txBlockHeaderBytes, bytes32 _txsuperblockHash ) public returns (uint) { uint txHash = SyscoinMessageLibrary.dblShaFlip(_txBytes); if (_txBytes.length == 64) { // todo: is check 32 also needed? emit VerifyTransaction(bytes32(txHash), ERR_TX_64BYTE); return 0; } if (helperVerifyHash(txHash, _txIndex, _siblings, _txBlockHeaderBytes, _txsuperblockHash) == 1) { return txHash; } else { // log is done via helperVerifyHash return 0; } } // @dev - Checks whether the transaction identified by `_txHash` is in the block identified by `_blockHeaderBytes` // and whether the block is in the Syscoin main chain. Transaction check is done via Merkle proof. // Note: no verification is performed to prevent txHash from just being an // internal hash in the Merkle tree. Thus this helper method should NOT be used // directly and is intended to be private. // // @param _txHash - transaction hash // @param _txIndex - transaction's index within the block // @param _siblings - transaction's Merkle siblings // @param _blockHeaderBytes - block header containing transaction // @param _txsuperblockHash - superblock containing block header // @return - 1 if the transaction is in the block and the block is in the main chain, // 20020 (ERR_CONFIRMATIONS) if the block is not in the main chain, // 20050 (ERR_MERKLE_ROOT) if the block is in the main chain but the Merkle proof fails. function helperVerifyHash( uint256 _txHash, uint _txIndex, uint[] memory _siblings, bytes memory _blockHeaderBytes, bytes32 _txsuperblockHash ) private returns (uint) { //TODO: Verify superblock is in superblock's main chain if (!isApproved(_txsuperblockHash) || !inMainChain(_txsuperblockHash)) { emit VerifyTransaction(bytes32(_txHash), ERR_CHAIN); return (ERR_CHAIN); } // Verify tx Merkle root uint merkle = SyscoinMessageLibrary.getHeaderMerkleRoot(_blockHeaderBytes); if (SyscoinMessageLibrary.computeMerkle(_txHash, _txIndex, _siblings) != merkle) { emit VerifyTransaction(bytes32(_txHash), ERR_MERKLE_ROOT); return (ERR_MERKLE_ROOT); } emit VerifyTransaction(bytes32(_txHash), 1); return (1); } // @dev - Calculate superblock hash from superblock data // // @param _blocksMerkleRoot Root of the merkle tree of blocks contained in a superblock // @param _accumulatedWork Accumulated proof of work of the last block in the superblock // @param _timestamp Timestamp of the last block in the superblock // @param _prevTimestamp Timestamp of the block when the last difficulty adjustment happened (every 360 blocks) // @param _lastHash Hash of the last block in the superblock // @param _lastBits Difficulty bits of the last block in the superblock // @param _parentId Id of the parent superblock // @param _blockHeight Block height of last block in superblock // @return Superblock id function calcSuperblockHash( bytes32 _blocksMerkleRoot, uint _accumulatedWork, uint _timestamp, uint _prevTimestamp, bytes32 _lastHash, uint32 _lastBits, bytes32 _parentId, uint32 _blockHeight ) public pure returns (bytes32) { return keccak256(abi.encodePacked( _blocksMerkleRoot, _accumulatedWork, _timestamp, _prevTimestamp, _lastHash, _lastBits, _parentId, _blockHeight )); } // @dev - Returns the confirmed superblock with the most accumulated work // // @return Best superblock hash function getBestSuperblock() public view returns (bytes32) { return bestSuperblock; } // @dev - Returns the superblock data for the supplied superblock hash // // @return { // bytes32 _blocksMerkleRoot, // uint _accumulatedWork, // uint _timestamp, // uint _prevTimestamp, // bytes32 _lastHash, // uint32 _lastBits, // bytes32 _parentId, // address _submitter, // Status _status, // uint32 _blockHeight, // } Superblock data function getSuperblock(bytes32 superblockHash) public view returns ( bytes32 _blocksMerkleRoot, uint _accumulatedWork, uint _timestamp, uint _prevTimestamp, bytes32 _lastHash, uint32 _lastBits, bytes32 _parentId, address _submitter, Status _status, uint32 _blockHeight ) { SuperblockInfo storage superblock = superblocks[superblockHash]; return ( superblock.blocksMerkleRoot, superblock.accumulatedWork, superblock.timestamp, superblock.prevTimestamp, superblock.lastHash, superblock.lastBits, superblock.parentId, superblock.submitter, superblock.status, superblock.blockHeight ); } // @dev - Returns superblock height function getSuperblockHeight(bytes32 superblockHash) public view returns (uint32) { return superblocks[superblockHash].height; } // @dev - Returns superblock internal index function getSuperblockIndex(bytes32 superblockHash) public view returns (uint32) { return superblocks[superblockHash].index; } // @dev - Return superblock ancestors' indexes function getSuperblockAncestors(bytes32 superblockHash) public view returns (bytes32) { return superblocks[superblockHash].ancestors; } // @dev - Return superblock blocks' Merkle root function getSuperblockMerkleRoot(bytes32 _superblockHash) public view returns (bytes32) { return superblocks[_superblockHash].blocksMerkleRoot; } // @dev - Return superblock timestamp function getSuperblockTimestamp(bytes32 _superblockHash) public view returns (uint) { return superblocks[_superblockHash].timestamp; } // @dev - Return superblock prevTimestamp function getSuperblockPrevTimestamp(bytes32 _superblockHash) public view returns (uint) { return superblocks[_superblockHash].prevTimestamp; } // @dev - Return superblock last block hash function getSuperblockLastHash(bytes32 _superblockHash) public view returns (bytes32) { return superblocks[_superblockHash].lastHash; } // @dev - Return superblock parent function getSuperblockParentId(bytes32 _superblockHash) public view returns (bytes32) { return superblocks[_superblockHash].parentId; } // @dev - Return superblock accumulated work function getSuperblockAccumulatedWork(bytes32 _superblockHash) public view returns (uint) { return superblocks[_superblockHash].accumulatedWork; } // @dev - Return superblock status function getSuperblockStatus(bytes32 _superblockHash) public view returns (Status) { return superblocks[_superblockHash].status; } // @dev - Return indexNextSuperblock function getIndexNextSuperblock() public view returns (uint32) { return indexNextSuperblock; } // @dev - Calculate Merkle root from Syscoin block hashes function makeMerkle(bytes32[] hashes) public pure returns (bytes32) { return SyscoinMessageLibrary.makeMerkle(hashes); } function isApproved(bytes32 _superblockHash) public view returns (bool) { return (getSuperblockStatus(_superblockHash) == Status.Approved); } function getChainHeight() public view returns (uint) { return superblocks[bestSuperblock].height; } // @dev - write `_fourBytes` into `_word` starting from `_position` // This is useful for writing 32bit ints inside one 32 byte word // // @param _word - information to be partially overwritten // @param _position - position to start writing from // @param _eightBytes - information to be written function writeUint32(bytes32 _word, uint _position, uint32 _fourBytes) private pure returns (bytes32) { bytes32 result; assembly { let pointer := mload(0x40) mstore(pointer, _word) mstore8(add(pointer, _position), byte(28, _fourBytes)) mstore8(add(pointer, add(_position,1)), byte(29, _fourBytes)) mstore8(add(pointer, add(_position,2)), byte(30, _fourBytes)) mstore8(add(pointer, add(_position,3)), byte(31, _fourBytes)) result := mload(pointer) } return result; } uint constant ANCESTOR_STEP = 5; uint constant NUM_ANCESTOR_DEPTHS = 8; // @dev - Update ancestor to the new height function updateAncestors(bytes32 ancestors, uint32 index, uint height) internal pure returns (bytes32) { uint step = ANCESTOR_STEP; ancestors = writeUint32(ancestors, 0, index); uint i = 1; while (i<NUM_ANCESTOR_DEPTHS && (height % step == 1)) { ancestors = writeUint32(ancestors, 4*i, index); step *= ANCESTOR_STEP; ++i; } return ancestors; } // @dev - Returns a list of superblock hashes (9 hashes maximum) that helps an agent find out what // superblocks are missing. // The first position contains bestSuperblock, then // bestSuperblock - 1, // (bestSuperblock-1) - ((bestSuperblock-1) % 5), then // (bestSuperblock-1) - ((bestSuperblock-1) % 25), ... until // (bestSuperblock-1) - ((bestSuperblock-1) % 78125) // // @return - list of up to 9 ancestor supeerblock id function getSuperblockLocator() public view returns (bytes32[9]) { bytes32[9] memory locator; locator[0] = bestSuperblock; bytes32 ancestors = getSuperblockAncestors(bestSuperblock); uint i = NUM_ANCESTOR_DEPTHS; while (i > 0) { locator[i] = indexSuperblock[uint32(ancestors & 0xFFFFFFFF)]; ancestors >>= 32; --i; } return locator; } // @dev - Return ancestor at given index function getSuperblockAncestor(bytes32 superblockHash, uint index) internal view returns (bytes32) { bytes32 ancestors = superblocks[superblockHash].ancestors; uint32 ancestorsIndex = uint32(ancestors[4*index + 0]) * 0x1000000 + uint32(ancestors[4*index + 1]) * 0x10000 + uint32(ancestors[4*index + 2]) * 0x100 + uint32(ancestors[4*index + 3]) * 0x1; return indexSuperblock[ancestorsIndex]; } // dev - returns depth associated with an ancestor index; applies to any superblock // // @param _index - index of ancestor to be looked up; an integer between 0 and 7 // @return - depth corresponding to said index, i.e. 5**index function getAncDepth(uint _index) private pure returns (uint) { return ANCESTOR_STEP**(uint(_index)); } // @dev - return superblock hash at a given height in superblock main chain // // @param _height - superblock height // @return - hash corresponding to block of height _blockHeight function getSuperblockAt(uint _height) public view returns (bytes32) { bytes32 superblockHash = bestSuperblock; uint index = NUM_ANCESTOR_DEPTHS - 1; while (getSuperblockHeight(superblockHash) > _height) { while (getSuperblockHeight(superblockHash) - _height < getAncDepth(index) && index > 0) { index -= 1; } superblockHash = getSuperblockAncestor(superblockHash, index); } return superblockHash; } // @dev - Checks if a superblock is in superblock main chain // // @param _blockHash - hash of the block being searched for in the main chain // @return - true if the block identified by _blockHash is in the main chain, // false otherwise function inMainChain(bytes32 _superblockHash) internal view returns (bool) { uint height = getSuperblockHeight(_superblockHash); if (height == 0) return false; return (getSuperblockAt(height) == _superblockHash); } } // @dev - Manages a battle session between superblock submitter and challenger contract SyscoinBattleManager is SyscoinErrorCodes { enum ChallengeState { Unchallenged, // Unchallenged submission Challenged, // Claims was challenged QueryMerkleRootHashes, // Challenger expecting block hashes RespondMerkleRootHashes, // Blcok hashes were received and verified QueryBlockHeader, // Challenger is requesting block headers RespondBlockHeader, // All block headers were received PendingVerification, // Pending superblock verification SuperblockVerified, // Superblock verified SuperblockFailed // Superblock not valid } enum BlockInfoStatus { Uninitialized, Requested, Verified } struct BlockInfo { bytes32 prevBlock; uint64 timestamp; uint32 bits; BlockInfoStatus status; bytes powBlockHeader; bytes32 blockHash; } struct BattleSession { bytes32 id; bytes32 superblockHash; address submitter; address challenger; uint lastActionTimestamp; // Last action timestamp uint lastActionClaimant; // Number last action submitter uint lastActionChallenger; // Number last action challenger uint actionsCounter; // Counter session actions bytes32[] blockHashes; // Block hashes uint countBlockHeaderQueries; // Number of block header queries uint countBlockHeaderResponses; // Number of block header responses mapping (bytes32 => BlockInfo) blocksInfo; ChallengeState challengeState; // Claim state } mapping (bytes32 => BattleSession) public sessions; uint public sessionsCount = 0; uint public superblockDuration; // Superblock duration (in seconds) uint public superblockTimeout; // Timeout action (in seconds) // network that the stored blocks belong to SyscoinMessageLibrary.Network private net; // Syscoin claim manager SyscoinClaimManager trustedSyscoinClaimManager; // Superblocks contract SyscoinSuperblocks trustedSuperblocks; event NewBattle(bytes32 superblockHash, bytes32 sessionId, address submitter, address challenger); event ChallengerConvicted(bytes32 superblockHash, bytes32 sessionId, address challenger); event SubmitterConvicted(bytes32 superblockHash, bytes32 sessionId, address submitter); event QueryMerkleRootHashes(bytes32 superblockHash, bytes32 sessionId, address submitter); event RespondMerkleRootHashes(bytes32 superblockHash, bytes32 sessionId, address challenger, bytes32[] blockHashes); event QueryBlockHeader(bytes32 superblockHash, bytes32 sessionId, address submitter, bytes32 blockSha256Hash); event RespondBlockHeader(bytes32 superblockHash, bytes32 sessionId, address challenger, bytes blockHeader, bytes powBlockHeader); event ErrorBattle(bytes32 sessionId, uint err); modifier onlyFrom(address sender) { require(msg.sender == sender); _; } modifier onlyClaimant(bytes32 sessionId) { require(msg.sender == sessions[sessionId].submitter); _; } modifier onlyChallenger(bytes32 sessionId) { require(msg.sender == sessions[sessionId].challenger); _; } // @dev – Configures the contract managing superblocks battles // @param _network Network type to use for block difficulty validation // @param _superblocks Contract that manages superblocks // @param _superblockDuration Superblock duration (in seconds) // @param _superblockTimeout Time to wait for challenges (in seconds) constructor( SyscoinMessageLibrary.Network _network, SyscoinSuperblocks _superblocks, uint _superblockDuration, uint _superblockTimeout ) public { net = _network; trustedSuperblocks = _superblocks; superblockDuration = _superblockDuration; superblockTimeout = _superblockTimeout; } function setSyscoinClaimManager(SyscoinClaimManager _syscoinClaimManager) public { require(address(trustedSyscoinClaimManager) == 0x0 && address(_syscoinClaimManager) != 0x0); trustedSyscoinClaimManager = _syscoinClaimManager; } // @dev - Start a battle session function beginBattleSession(bytes32 superblockHash, address submitter, address challenger) onlyFrom(trustedSyscoinClaimManager) public returns (bytes32) { bytes32 sessionId = keccak256(abi.encode(superblockHash, msg.sender, sessionsCount)); BattleSession storage session = sessions[sessionId]; session.id = sessionId; session.superblockHash = superblockHash; session.submitter = submitter; session.challenger = challenger; session.lastActionTimestamp = block.timestamp; session.lastActionChallenger = 0; session.lastActionClaimant = 1; // Force challenger to start session.actionsCounter = 1; session.challengeState = ChallengeState.Challenged; sessionsCount += 1; emit NewBattle(superblockHash, sessionId, submitter, challenger); return sessionId; } // @dev - Challenger makes a query for superblock hashes function doQueryMerkleRootHashes(BattleSession storage session) internal returns (uint) { if (!hasDeposit(msg.sender, respondMerkleRootHashesCost)) { return ERR_SUPERBLOCK_MIN_DEPOSIT; } if (session.challengeState == ChallengeState.Challenged) { session.challengeState = ChallengeState.QueryMerkleRootHashes; assert(msg.sender == session.challenger); (uint err, ) = bondDeposit(session.superblockHash, msg.sender, respondMerkleRootHashesCost); if (err != ERR_SUPERBLOCK_OK) { return err; } return ERR_SUPERBLOCK_OK; } return ERR_SUPERBLOCK_BAD_STATUS; } // @dev - Challenger makes a query for superblock hashes function queryMerkleRootHashes(bytes32 superblockHash, bytes32 sessionId) onlyChallenger(sessionId) public { BattleSession storage session = sessions[sessionId]; uint err = doQueryMerkleRootHashes(session); if (err != ERR_SUPERBLOCK_OK) { emit ErrorBattle(sessionId, err); } else { session.actionsCounter += 1; session.lastActionTimestamp = block.timestamp; session.lastActionChallenger = session.actionsCounter; emit QueryMerkleRootHashes(superblockHash, sessionId, session.submitter); } } // @dev - Submitter sends hashes to verify superblock merkle root function doVerifyMerkleRootHashes(BattleSession storage session, bytes32[] blockHashes) internal returns (uint) { if (!hasDeposit(msg.sender, verifySuperblockCost)) { return ERR_SUPERBLOCK_MIN_DEPOSIT; } require(session.blockHashes.length == 0); if (session.challengeState == ChallengeState.QueryMerkleRootHashes) { (bytes32 merkleRoot, , , , bytes32 lastHash, , , ,,) = getSuperblockInfo(session.superblockHash); if (lastHash != blockHashes[blockHashes.length - 1]){ return ERR_SUPERBLOCK_BAD_LASTBLOCK; } if (merkleRoot != SyscoinMessageLibrary.makeMerkle(blockHashes)) { return ERR_SUPERBLOCK_INVALID_MERKLE; } (uint err, ) = bondDeposit(session.superblockHash, msg.sender, verifySuperblockCost); if (err != ERR_SUPERBLOCK_OK) { return err; } session.blockHashes = blockHashes; session.challengeState = ChallengeState.RespondMerkleRootHashes; return ERR_SUPERBLOCK_OK; } return ERR_SUPERBLOCK_BAD_STATUS; } // @dev - For the submitter to respond to challenger queries function respondMerkleRootHashes(bytes32 superblockHash, bytes32 sessionId, bytes32[] blockHashes) onlyClaimant(sessionId) public { BattleSession storage session = sessions[sessionId]; uint err = doVerifyMerkleRootHashes(session, blockHashes); if (err != 0) { emit ErrorBattle(sessionId, err); } else { session.actionsCounter += 1; session.lastActionTimestamp = block.timestamp; session.lastActionClaimant = session.actionsCounter; emit RespondMerkleRootHashes(superblockHash, sessionId, session.challenger, blockHashes); } } // @dev - Challenger makes a query for block header data for a hash function doQueryBlockHeader(BattleSession storage session, bytes32 blockHash) internal returns (uint) { if (!hasDeposit(msg.sender, respondBlockHeaderCost)) { return ERR_SUPERBLOCK_MIN_DEPOSIT; } if ((session.countBlockHeaderQueries == 0 && session.challengeState == ChallengeState.RespondMerkleRootHashes) || (session.countBlockHeaderQueries > 0 && session.challengeState == ChallengeState.RespondBlockHeader)) { require(session.countBlockHeaderQueries < session.blockHashes.length); require(session.blocksInfo[blockHash].status == BlockInfoStatus.Uninitialized); (uint err, ) = bondDeposit(session.superblockHash, msg.sender, respondBlockHeaderCost); if (err != ERR_SUPERBLOCK_OK) { return err; } session.countBlockHeaderQueries += 1; session.blocksInfo[blockHash].status = BlockInfoStatus.Requested; session.challengeState = ChallengeState.QueryBlockHeader; return ERR_SUPERBLOCK_OK; } return ERR_SUPERBLOCK_BAD_STATUS; } // @dev - For the challenger to start a query function queryBlockHeader(bytes32 superblockHash, bytes32 sessionId, bytes32 blockHash) onlyChallenger(sessionId) public { BattleSession storage session = sessions[sessionId]; uint err = doQueryBlockHeader(session, blockHash); if (err != ERR_SUPERBLOCK_OK) { emit ErrorBattle(sessionId, err); } else { session.actionsCounter += 1; session.lastActionTimestamp = block.timestamp; session.lastActionChallenger = session.actionsCounter; emit QueryBlockHeader(superblockHash, sessionId, session.submitter, blockHash); } } // @dev - Verify that block timestamp is in the superblock timestamp interval function verifyTimestamp(bytes32 superblockHash, bytes blockHeader) internal view returns (bool) { uint blockTimestamp = SyscoinMessageLibrary.getTimestamp(blockHeader); uint superblockTimestamp; (, , superblockTimestamp, , , , , ,,) = getSuperblockInfo(superblockHash); // Block timestamp to be within the expected timestamp of the superblock return (blockTimestamp <= superblockTimestamp) && (blockTimestamp / superblockDuration >= superblockTimestamp / superblockDuration - 1); } // @dev - Verify Syscoin block AuxPoW function verifyBlockAuxPoW( BlockInfo storage blockInfo, bytes32 blockHash, bytes blockHeader ) internal returns (uint, bytes) { (uint err, bool isMergeMined) = SyscoinMessageLibrary.verifyBlockHeader(blockHeader, 0, uint(blockHash)); if (err != 0) { return (err, new bytes(0)); } bytes memory powBlockHeader = (isMergeMined) ? SyscoinMessageLibrary.sliceArray(blockHeader, blockHeader.length - 80, blockHeader.length) : SyscoinMessageLibrary.sliceArray(blockHeader, 0, 80); blockInfo.timestamp = SyscoinMessageLibrary.getTimestamp(blockHeader); blockInfo.bits = SyscoinMessageLibrary.getBits(blockHeader); blockInfo.prevBlock = bytes32(SyscoinMessageLibrary.getHashPrevBlock(blockHeader)); blockInfo.blockHash = blockHash; blockInfo.powBlockHeader = powBlockHeader; return (ERR_SUPERBLOCK_OK, powBlockHeader); } // @dev - Verify block header sent by challenger function doVerifyBlockHeader( BattleSession storage session, bytes memory blockHeader ) internal returns (uint, bytes) { if (!hasDeposit(msg.sender, respondBlockHeaderCost)) { return (ERR_SUPERBLOCK_MIN_DEPOSIT, new bytes(0)); } if (session.challengeState == ChallengeState.QueryBlockHeader) { bytes32 blockSha256Hash = bytes32(SyscoinMessageLibrary.dblShaFlipMem(blockHeader, 0, 80)); BlockInfo storage blockInfo = session.blocksInfo[blockSha256Hash]; if (blockInfo.status != BlockInfoStatus.Requested) { return (ERR_SUPERBLOCK_BAD_SYSCOIN_STATUS, new bytes(0)); } if (!verifyTimestamp(session.superblockHash, blockHeader)) { return (ERR_SUPERBLOCK_BAD_TIMESTAMP, new bytes(0)); } // pass in blockSha256Hash here instead of proposedScryptHash because we // don't need a proposed hash (we already calculated it here, syscoin uses // sha256 just like bitcoin) (uint err, bytes memory powBlockHeader) = verifyBlockAuxPoW(blockInfo, blockSha256Hash, blockHeader); if (err != ERR_SUPERBLOCK_OK) { return (err, new bytes(0)); } // set to verify block header status blockInfo.status = BlockInfoStatus.Verified; (err, ) = bondDeposit(session.superblockHash, msg.sender, respondBlockHeaderCost); if (err != ERR_SUPERBLOCK_OK) { return (err, new bytes(0)); } session.countBlockHeaderResponses += 1; // if header responses matches num block hashes we skip to respond block header instead of pending verification if (session.countBlockHeaderResponses == session.blockHashes.length) { session.challengeState = ChallengeState.PendingVerification; } else { session.challengeState = ChallengeState.RespondBlockHeader; } return (ERR_SUPERBLOCK_OK, powBlockHeader); } return (ERR_SUPERBLOCK_BAD_STATUS, new bytes(0)); } // @dev - For the submitter to respond to challenger queries function respondBlockHeader( bytes32 superblockHash, bytes32 sessionId, bytes memory blockHeader ) onlyClaimant(sessionId) public { BattleSession storage session = sessions[sessionId]; (uint err, bytes memory powBlockHeader) = doVerifyBlockHeader(session, blockHeader); if (err != 0) { emit ErrorBattle(sessionId, err); } else { session.actionsCounter += 1; session.lastActionTimestamp = block.timestamp; session.lastActionClaimant = session.actionsCounter; emit RespondBlockHeader(superblockHash, sessionId, session.challenger, blockHeader, powBlockHeader); } } // @dev - Validate superblock information from last blocks function validateLastBlocks(BattleSession storage session) internal view returns (uint) { if (session.blockHashes.length <= 0) { return ERR_SUPERBLOCK_BAD_LASTBLOCK; } uint lastTimestamp; uint prevTimestamp; uint32 lastBits; bytes32 parentId; (, , lastTimestamp, prevTimestamp, , lastBits, parentId,,,) = getSuperblockInfo(session.superblockHash); bytes32 blockSha256Hash = session.blockHashes[session.blockHashes.length - 1]; if (session.blocksInfo[blockSha256Hash].timestamp != lastTimestamp) { return ERR_SUPERBLOCK_BAD_TIMESTAMP; } if (session.blocksInfo[blockSha256Hash].bits != lastBits) { return ERR_SUPERBLOCK_BAD_BITS; } if (prevTimestamp > lastTimestamp) { return ERR_SUPERBLOCK_BAD_TIMESTAMP; } return ERR_SUPERBLOCK_OK; } // @dev - Validate superblock accumulated work function validateProofOfWork(BattleSession storage session) internal view returns (uint) { uint accWork; bytes32 prevBlock; uint32 prevHeight; uint32 proposedHeight; uint prevTimestamp; (, accWork, , prevTimestamp, , , prevBlock, ,,proposedHeight) = getSuperblockInfo(session.superblockHash); uint parentTimestamp; uint32 prevBits; uint work; (, work, parentTimestamp, , prevBlock, prevBits, , , ,prevHeight) = getSuperblockInfo(prevBlock); if (proposedHeight != (prevHeight+uint32(session.blockHashes.length))) { return ERR_SUPERBLOCK_BAD_BLOCKHEIGHT; } uint ret = validateSuperblockProofOfWork(session, parentTimestamp, prevHeight, work, accWork, prevTimestamp, prevBits, prevBlock); if(ret != 0){ return ret; } return ERR_SUPERBLOCK_OK; } function validateSuperblockProofOfWork(BattleSession storage session, uint parentTimestamp, uint32 prevHeight, uint work, uint accWork, uint prevTimestamp, uint32 prevBits, bytes32 prevBlock) internal view returns (uint){ uint32 idx = 0; while (idx < session.blockHashes.length) { bytes32 blockSha256Hash = session.blockHashes[idx]; uint32 bits = session.blocksInfo[blockSha256Hash].bits; if (session.blocksInfo[blockSha256Hash].prevBlock != prevBlock) { return ERR_SUPERBLOCK_BAD_PARENT; } if (net != SyscoinMessageLibrary.Network.REGTEST) { uint32 newBits; if (net == SyscoinMessageLibrary.Network.TESTNET && session.blocksInfo[blockSha256Hash].timestamp - parentTimestamp > 120) { newBits = 0x1e0fffff; } else if((prevHeight+idx+1) % SyscoinMessageLibrary.difficultyAdjustmentInterval() != 0){ newBits = prevBits; } else{ newBits = SyscoinMessageLibrary.calculateDifficulty(int64(parentTimestamp) - int64(prevTimestamp), prevBits); prevTimestamp = parentTimestamp; prevBits = bits; } if (bits != newBits) { return ERR_SUPERBLOCK_BAD_BITS; } } work += SyscoinMessageLibrary.diffFromBits(bits); prevBlock = blockSha256Hash; parentTimestamp = session.blocksInfo[blockSha256Hash].timestamp; idx += 1; } if (net != SyscoinMessageLibrary.Network.REGTEST && work != accWork) { return ERR_SUPERBLOCK_BAD_ACCUMULATED_WORK; } return 0; } // @dev - Verify whether a superblock's data is consistent // Only should be called when all blocks header were submitted function doVerifySuperblock(BattleSession storage session, bytes32 sessionId) internal returns (uint) { if (session.challengeState == ChallengeState.PendingVerification) { uint err; err = validateLastBlocks(session); if (err != 0) { emit ErrorBattle(sessionId, err); return 2; } err = validateProofOfWork(session); if (err != 0) { emit ErrorBattle(sessionId, err); return 2; } return 1; } else if (session.challengeState == ChallengeState.SuperblockFailed) { return 2; } return 0; } // @dev - Perform final verification once all blocks were submitted function verifySuperblock(bytes32 sessionId) public { BattleSession storage session = sessions[sessionId]; uint status = doVerifySuperblock(session, sessionId); if (status == 1) { convictChallenger(sessionId, session.challenger, session.superblockHash); } else if (status == 2) { convictSubmitter(sessionId, session.submitter, session.superblockHash); } } // @dev - Trigger conviction if response is not received in time function timeout(bytes32 sessionId) public returns (uint) { BattleSession storage session = sessions[sessionId]; if (session.challengeState == ChallengeState.SuperblockFailed || (session.lastActionChallenger > session.lastActionClaimant && block.timestamp > session.lastActionTimestamp + superblockTimeout)) { convictSubmitter(sessionId, session.submitter, session.superblockHash); return ERR_SUPERBLOCK_OK; } else if (session.lastActionClaimant > session.lastActionChallenger && block.timestamp > session.lastActionTimestamp + superblockTimeout) { convictChallenger(sessionId, session.challenger, session.superblockHash); return ERR_SUPERBLOCK_OK; } emit ErrorBattle(sessionId, ERR_SUPERBLOCK_NO_TIMEOUT); return ERR_SUPERBLOCK_NO_TIMEOUT; } // @dev - To be called when a challenger is convicted function convictChallenger(bytes32 sessionId, address challenger, bytes32 superblockHash) internal { BattleSession storage session = sessions[sessionId]; sessionDecided(sessionId, superblockHash, session.submitter, session.challenger); disable(sessionId); emit ChallengerConvicted(superblockHash, sessionId, challenger); } // @dev - To be called when a submitter is convicted function convictSubmitter(bytes32 sessionId, address submitter, bytes32 superblockHash) internal { BattleSession storage session = sessions[sessionId]; sessionDecided(sessionId, superblockHash, session.challenger, session.submitter); disable(sessionId); emit SubmitterConvicted(superblockHash, sessionId, submitter); } // @dev - Disable session // It should be called only when either the submitter or the challenger were convicted. function disable(bytes32 sessionId) internal { delete sessions[sessionId]; } // @dev - Check if a session's challenger did not respond before timeout function getChallengerHitTimeout(bytes32 sessionId) public view returns (bool) { BattleSession storage session = sessions[sessionId]; return (session.lastActionClaimant > session.lastActionChallenger && block.timestamp > session.lastActionTimestamp + superblockTimeout); } // @dev - Check if a session's submitter did not respond before timeout function getSubmitterHitTimeout(bytes32 sessionId) public view returns (bool) { BattleSession storage session = sessions[sessionId]; return (session.lastActionChallenger > session.lastActionClaimant && block.timestamp > session.lastActionTimestamp + superblockTimeout); } // @dev - Return Syscoin block hashes associated with a certain battle session function getSyscoinBlockHashes(bytes32 sessionId) public view returns (bytes32[]) { return sessions[sessionId].blockHashes; } // @dev - To be called when a battle sessions was decided function sessionDecided(bytes32 sessionId, bytes32 superblockHash, address winner, address loser) internal { trustedSyscoinClaimManager.sessionDecided(sessionId, superblockHash, winner, loser); } // @dev - Retrieve superblock information function getSuperblockInfo(bytes32 superblockHash) internal view returns ( bytes32 _blocksMerkleRoot, uint _accumulatedWork, uint _timestamp, uint _prevTimestamp, bytes32 _lastHash, uint32 _lastBits, bytes32 _parentId, address _submitter, SyscoinSuperblocks.Status _status, uint32 _height ) { return trustedSuperblocks.getSuperblock(superblockHash); } // @dev - Verify whether a user has a certain amount of deposits or more function hasDeposit(address who, uint amount) internal view returns (bool) { return trustedSyscoinClaimManager.getDeposit(who) >= amount; } // @dev – locks up part of a user's deposit into a claim. function bondDeposit(bytes32 superblockHash, address account, uint amount) internal returns (uint, uint) { return trustedSyscoinClaimManager.bondDeposit(superblockHash, account, amount); } } // @dev - Manager of superblock claims // // Manages superblocks proposal and challenges contract SyscoinClaimManager is SyscoinDepositsManager, SyscoinErrorCodes { using SafeMath for uint; struct SuperblockClaim { bytes32 superblockHash; // Superblock Id address submitter; // Superblock submitter uint createdAt; // Superblock creation time address[] challengers; // List of challengers mapping (address => uint) bondedDeposits; // Deposit associated to challengers uint currentChallenger; // Index of challenger in current session mapping (address => bytes32) sessions; // Challenge sessions uint challengeTimeout; // Claim timeout bool verificationOngoing; // Challenge session has started bool decided; // If the claim was decided bool invalid; // If superblock is invalid } // Active superblock claims mapping (bytes32 => SuperblockClaim) public claims; // Superblocks contract SyscoinSuperblocks public trustedSuperblocks; // Battle manager contract SyscoinBattleManager public trustedSyscoinBattleManager; // Confirmations required to confirm semi approved superblocks uint public superblockConfirmations; // Monetary reward for opponent in case battle is lost uint public battleReward; uint public superblockDelay; // Delay required to submit superblocks (in seconds) uint public superblockTimeout; // Timeout for action (in seconds) event DepositBonded(bytes32 superblockHash, address account, uint amount); event DepositUnbonded(bytes32 superblockHash, address account, uint amount); event SuperblockClaimCreated(bytes32 superblockHash, address submitter); event SuperblockClaimChallenged(bytes32 superblockHash, address challenger); event SuperblockBattleDecided(bytes32 sessionId, address winner, address loser); event SuperblockClaimSuccessful(bytes32 superblockHash, address submitter); event SuperblockClaimPending(bytes32 superblockHash, address submitter); event SuperblockClaimFailed(bytes32 superblockHash, address submitter); event VerificationGameStarted(bytes32 superblockHash, address submitter, address challenger, bytes32 sessionId); event ErrorClaim(bytes32 superblockHash, uint err); modifier onlyBattleManager() { require(msg.sender == address(trustedSyscoinBattleManager)); _; } modifier onlyMeOrBattleManager() { require(msg.sender == address(trustedSyscoinBattleManager) || msg.sender == address(this)); _; } // @dev – Sets up the contract managing superblock challenges // @param _superblocks Contract that manages superblocks // @param _battleManager Contract that manages battles // @param _superblockDelay Delay to accept a superblock submission (in seconds) // @param _superblockTimeout Time to wait for challenges (in seconds) // @param _superblockConfirmations Confirmations required to confirm semi approved superblocks constructor( SyscoinSuperblocks _superblocks, SyscoinBattleManager _syscoinBattleManager, uint _superblockDelay, uint _superblockTimeout, uint _superblockConfirmations, uint _battleReward ) public { trustedSuperblocks = _superblocks; trustedSyscoinBattleManager = _syscoinBattleManager; superblockDelay = _superblockDelay; superblockTimeout = _superblockTimeout; superblockConfirmations = _superblockConfirmations; battleReward = _battleReward; } // @dev – locks up part of a user's deposit into a claim. // @param superblockHash – claim id. // @param account – user's address. // @param amount – amount of deposit to lock up. // @return – user's deposit bonded for the claim. function bondDeposit(bytes32 superblockHash, address account, uint amount) onlyMeOrBattleManager external returns (uint, uint) { SuperblockClaim storage claim = claims[superblockHash]; if (!claimExists(claim)) { return (ERR_SUPERBLOCK_BAD_CLAIM, 0); } if (deposits[account] < amount) { return (ERR_SUPERBLOCK_MIN_DEPOSIT, deposits[account]); } deposits[account] = deposits[account].sub(amount); claim.bondedDeposits[account] = claim.bondedDeposits[account].add(amount); emit DepositBonded(superblockHash, account, amount); return (ERR_SUPERBLOCK_OK, claim.bondedDeposits[account]); } // @dev – accessor for a claim's bonded deposits. // @param superblockHash – claim id. // @param account – user's address. // @return – user's deposit bonded for the claim. function getBondedDeposit(bytes32 superblockHash, address account) public view returns (uint) { SuperblockClaim storage claim = claims[superblockHash]; require(claimExists(claim)); return claim.bondedDeposits[account]; } function getDeposit(address account) public view returns (uint) { return deposits[account]; } // @dev – unlocks a user's bonded deposits from a claim. // @param superblockHash – claim id. // @param account – user's address. // @return – user's deposit which was unbonded from the claim. function unbondDeposit(bytes32 superblockHash, address account) internal returns (uint, uint) { SuperblockClaim storage claim = claims[superblockHash]; if (!claimExists(claim)) { return (ERR_SUPERBLOCK_BAD_CLAIM, 0); } if (!claim.decided) { return (ERR_SUPERBLOCK_BAD_STATUS, 0); } uint bondedDeposit = claim.bondedDeposits[account]; delete claim.bondedDeposits[account]; deposits[account] = deposits[account].add(bondedDeposit); emit DepositUnbonded(superblockHash, account, bondedDeposit); return (ERR_SUPERBLOCK_OK, bondedDeposit); } // @dev – Propose a new superblock. // // @param _blocksMerkleRoot Root of the merkle tree of blocks contained in a superblock // @param _accumulatedWork Accumulated proof of work of the last block in the superblock // @param _timestamp Timestamp of the last block in the superblock // @param _prevTimestamp Timestamp of the block when the last difficulty adjustment happened // @param _lastHash Hash of the last block in the superblock // @param _lastBits Difficulty bits of the last block in the superblock // @param _parentHash Id of the parent superblock // @return Error code and superblockHash function proposeSuperblock( bytes32 _blocksMerkleRoot, uint _accumulatedWork, uint _timestamp, uint _prevTimestamp, bytes32 _lastHash, uint32 _lastBits, bytes32 _parentHash, uint32 _blockHeight ) public returns (uint, bytes32) { require(address(trustedSuperblocks) != 0); if (deposits[msg.sender] < minProposalDeposit) { emit ErrorClaim(0, ERR_SUPERBLOCK_MIN_DEPOSIT); return (ERR_SUPERBLOCK_MIN_DEPOSIT, 0); } if (_timestamp + superblockDelay > block.timestamp) { emit ErrorClaim(0, ERR_SUPERBLOCK_BAD_TIMESTAMP); return (ERR_SUPERBLOCK_BAD_TIMESTAMP, 0); } uint err; bytes32 superblockHash; (err, superblockHash) = trustedSuperblocks.propose(_blocksMerkleRoot, _accumulatedWork, _timestamp, _prevTimestamp, _lastHash, _lastBits, _parentHash, _blockHeight,msg.sender); if (err != 0) { emit ErrorClaim(superblockHash, err); return (err, superblockHash); } SuperblockClaim storage claim = claims[superblockHash]; // allow to propose an existing claim only if its invalid and decided and its a different submitter or not on the tip // those are the ones that may actually be stuck and need to be proposed again, // but we want to ensure its not the same submitter submitting the same thing if (claimExists(claim)) { bool allowed = claim.invalid == true && claim.decided == true && claim.submitter != msg.sender; if(allowed){ // we also want to ensure that if parent is approved we are building on the tip and not anywhere else if(trustedSuperblocks.getSuperblockStatus(_parentHash) == SyscoinSuperblocks.Status.Approved){ allowed = trustedSuperblocks.getBestSuperblock() == _parentHash; } // or if its semi approved allow to build on top as well else if(trustedSuperblocks.getSuperblockStatus(_parentHash) == SyscoinSuperblocks.Status.SemiApproved){ allowed = true; } else{ allowed = false; } } if(!allowed){ emit ErrorClaim(superblockHash, ERR_SUPERBLOCK_BAD_CLAIM); return (ERR_SUPERBLOCK_BAD_CLAIM, superblockHash); } } claim.superblockHash = superblockHash; claim.submitter = msg.sender; claim.currentChallenger = 0; claim.decided = false; claim.invalid = false; claim.verificationOngoing = false; claim.createdAt = block.timestamp; claim.challengeTimeout = block.timestamp + superblockTimeout; claim.challengers.length = 0; (err, ) = this.bondDeposit(superblockHash, msg.sender, battleReward); assert(err == ERR_SUPERBLOCK_OK); emit SuperblockClaimCreated(superblockHash, msg.sender); return (ERR_SUPERBLOCK_OK, superblockHash); } // @dev – challenge a superblock claim. // @param superblockHash – Id of the superblock to challenge. // @return - Error code and claim Id function challengeSuperblock(bytes32 superblockHash) public returns (uint, bytes32) { require(address(trustedSuperblocks) != 0); SuperblockClaim storage claim = claims[superblockHash]; if (!claimExists(claim)) { emit ErrorClaim(superblockHash, ERR_SUPERBLOCK_BAD_CLAIM); return (ERR_SUPERBLOCK_BAD_CLAIM, superblockHash); } if (claim.decided) { emit ErrorClaim(superblockHash, ERR_SUPERBLOCK_CLAIM_DECIDED); return (ERR_SUPERBLOCK_CLAIM_DECIDED, superblockHash); } if (deposits[msg.sender] < minChallengeDeposit) { emit ErrorClaim(superblockHash, ERR_SUPERBLOCK_MIN_DEPOSIT); return (ERR_SUPERBLOCK_MIN_DEPOSIT, superblockHash); } uint err; (err, ) = trustedSuperblocks.challenge(superblockHash, msg.sender); if (err != 0) { emit ErrorClaim(superblockHash, err); return (err, 0); } (err, ) = this.bondDeposit(superblockHash, msg.sender, battleReward); assert(err == ERR_SUPERBLOCK_OK); claim.challengeTimeout = block.timestamp + superblockTimeout; claim.challengers.push(msg.sender); emit SuperblockClaimChallenged(superblockHash, msg.sender); if (!claim.verificationOngoing) { runNextBattleSession(superblockHash); } return (ERR_SUPERBLOCK_OK, superblockHash); } // @dev – runs a battle session to verify a superblock for the next challenger // @param superblockHash – claim id. function runNextBattleSession(bytes32 superblockHash) internal returns (bool) { SuperblockClaim storage claim = claims[superblockHash]; if (!claimExists(claim)) { emit ErrorClaim(superblockHash, ERR_SUPERBLOCK_BAD_CLAIM); return false; } // superblocks marked as invalid do not have to run remaining challengers if (claim.decided || claim.invalid) { emit ErrorClaim(superblockHash, ERR_SUPERBLOCK_CLAIM_DECIDED); return false; } if (claim.verificationOngoing) { emit ErrorClaim(superblockHash, ERR_SUPERBLOCK_VERIFICATION_PENDING); return false; } if (claim.currentChallenger < claim.challengers.length) { bytes32 sessionId = trustedSyscoinBattleManager.beginBattleSession(superblockHash, claim.submitter, claim.challengers[claim.currentChallenger]); claim.sessions[claim.challengers[claim.currentChallenger]] = sessionId; emit VerificationGameStarted(superblockHash, claim.submitter, claim.challengers[claim.currentChallenger], sessionId); claim.verificationOngoing = true; claim.currentChallenger += 1; } return true; } // @dev – check whether a claim has successfully withstood all challenges. // If successful without challenges, it will mark the superblock as confirmed. // If successful with at least one challenge, it will mark the superblock as semi-approved. // If verification failed, it will mark the superblock as invalid. // // @param superblockHash – claim ID. function checkClaimFinished(bytes32 superblockHash) public returns (bool) { SuperblockClaim storage claim = claims[superblockHash]; if (!claimExists(claim)) { emit ErrorClaim(superblockHash, ERR_SUPERBLOCK_BAD_CLAIM); return false; } // check that there is no ongoing verification game. if (claim.verificationOngoing) { emit ErrorClaim(superblockHash, ERR_SUPERBLOCK_VERIFICATION_PENDING); return false; } // an invalid superblock can be rejected immediately if (claim.invalid) { // The superblock is invalid, submitter abandoned // or superblock data is inconsistent claim.decided = true; trustedSuperblocks.invalidate(claim.superblockHash, msg.sender); emit SuperblockClaimFailed(superblockHash, claim.submitter); doPayChallengers(superblockHash, claim); return false; } // check that the claim has exceeded the claim's specific challenge timeout. if (block.timestamp <= claim.challengeTimeout) { emit ErrorClaim(superblockHash, ERR_SUPERBLOCK_NO_TIMEOUT); return false; } // check that all verification games have been played. if (claim.currentChallenger < claim.challengers.length) { emit ErrorClaim(superblockHash, ERR_SUPERBLOCK_VERIFICATION_PENDING); return false; } claim.decided = true; bool confirmImmediately = false; // No challengers and parent approved; confirm immediately if (claim.challengers.length == 0) { bytes32 parentId = trustedSuperblocks.getSuperblockParentId(claim.superblockHash); SyscoinSuperblocks.Status status = trustedSuperblocks.getSuperblockStatus(parentId); if (status == SyscoinSuperblocks.Status.Approved) { confirmImmediately = true; } } if (confirmImmediately) { trustedSuperblocks.confirm(claim.superblockHash, msg.sender); unbondDeposit(superblockHash, claim.submitter); emit SuperblockClaimSuccessful(superblockHash, claim.submitter); } else { trustedSuperblocks.semiApprove(claim.superblockHash, msg.sender); emit SuperblockClaimPending(superblockHash, claim.submitter); } return true; } // @dev – confirm semi approved superblock. // // A semi approved superblock can be confirmed if it has several descendant // superblocks that are also semi-approved. // If none of the descendants were challenged they will also be confirmed. // // @param superblockHash – the claim ID. // @param descendantId - claim ID descendants function confirmClaim(bytes32 superblockHash, bytes32 descendantId) public returns (bool) { uint numSuperblocks = 0; bool confirmDescendants = true; bytes32 id = descendantId; SuperblockClaim storage claim = claims[id]; while (id != superblockHash) { if (!claimExists(claim)) { emit ErrorClaim(superblockHash, ERR_SUPERBLOCK_BAD_CLAIM); return false; } if (trustedSuperblocks.getSuperblockStatus(id) != SyscoinSuperblocks.Status.SemiApproved) { emit ErrorClaim(superblockHash, ERR_SUPERBLOCK_BAD_STATUS); return false; } if (confirmDescendants && claim.challengers.length > 0) { confirmDescendants = false; } id = trustedSuperblocks.getSuperblockParentId(id); claim = claims[id]; numSuperblocks += 1; } if (numSuperblocks < superblockConfirmations) { emit ErrorClaim(superblockHash, ERR_SUPERBLOCK_MISSING_CONFIRMATIONS); return false; } if (trustedSuperblocks.getSuperblockStatus(id) != SyscoinSuperblocks.Status.SemiApproved) { emit ErrorClaim(superblockHash, ERR_SUPERBLOCK_BAD_STATUS); return false; } bytes32 parentId = trustedSuperblocks.getSuperblockParentId(superblockHash); if (trustedSuperblocks.getSuperblockStatus(parentId) != SyscoinSuperblocks.Status.Approved) { emit ErrorClaim(superblockHash, ERR_SUPERBLOCK_BAD_STATUS); return false; } (uint err, ) = trustedSuperblocks.confirm(superblockHash, msg.sender); if (err != ERR_SUPERBLOCK_OK) { emit ErrorClaim(superblockHash, err); return false; } emit SuperblockClaimSuccessful(superblockHash, claim.submitter); doPaySubmitter(superblockHash, claim); unbondDeposit(superblockHash, claim.submitter); if (confirmDescendants) { bytes32[] memory descendants = new bytes32[](numSuperblocks); id = descendantId; uint idx = 0; while (id != superblockHash) { descendants[idx] = id; id = trustedSuperblocks.getSuperblockParentId(id); idx += 1; } while (idx > 0) { idx -= 1; id = descendants[idx]; claim = claims[id]; (err, ) = trustedSuperblocks.confirm(id, msg.sender); require(err == ERR_SUPERBLOCK_OK); emit SuperblockClaimSuccessful(id, claim.submitter); doPaySubmitter(id, claim); unbondDeposit(id, claim.submitter); } } return true; } // @dev – Reject a semi approved superblock. // // Superblocks that are not in the main chain can be marked as // invalid. // // @param superblockHash – the claim ID. function rejectClaim(bytes32 superblockHash) public returns (bool) { SuperblockClaim storage claim = claims[superblockHash]; if (!claimExists(claim)) { emit ErrorClaim(superblockHash, ERR_SUPERBLOCK_BAD_CLAIM); return false; } uint height = trustedSuperblocks.getSuperblockHeight(superblockHash); bytes32 id = trustedSuperblocks.getBestSuperblock(); if (trustedSuperblocks.getSuperblockHeight(id) < height + superblockConfirmations) { emit ErrorClaim(superblockHash, ERR_SUPERBLOCK_MISSING_CONFIRMATIONS); return false; } id = trustedSuperblocks.getSuperblockAt(height); if (id != superblockHash) { SyscoinSuperblocks.Status status = trustedSuperblocks.getSuperblockStatus(superblockHash); if (status != SyscoinSuperblocks.Status.SemiApproved) { emit ErrorClaim(superblockHash, ERR_SUPERBLOCK_BAD_STATUS); return false; } if (!claim.decided) { emit ErrorClaim(superblockHash, ERR_SUPERBLOCK_CLAIM_DECIDED); return false; } trustedSuperblocks.invalidate(superblockHash, msg.sender); emit SuperblockClaimFailed(superblockHash, claim.submitter); doPayChallengers(superblockHash, claim); return true; } return false; } // @dev – called when a battle session has ended. // // @param sessionId – session Id. // @param superblockHash - claim Id // @param winner – winner of verification game. // @param loser – loser of verification game. function sessionDecided(bytes32 sessionId, bytes32 superblockHash, address winner, address loser) public onlyBattleManager { SuperblockClaim storage claim = claims[superblockHash]; require(claimExists(claim)); claim.verificationOngoing = false; if (claim.submitter == loser) { // the claim is over. // Trigger end of verification game claim.invalid = true; } else if (claim.submitter == winner) { // the claim continues. // It should not fail when called from sessionDecided runNextBattleSession(superblockHash); } else { revert(); } emit SuperblockBattleDecided(sessionId, winner, loser); } // @dev - Pay challengers than ran their battles with submitter deposits // Challengers that did not run will be returned their deposits function doPayChallengers(bytes32 superblockHash, SuperblockClaim storage claim) internal { uint rewards = claim.bondedDeposits[claim.submitter]; claim.bondedDeposits[claim.submitter] = 0; uint totalDeposits = 0; uint idx = 0; for (idx = 0; idx < claim.currentChallenger; ++idx) { totalDeposits = totalDeposits.add(claim.bondedDeposits[claim.challengers[idx]]); } address challenger; uint reward = 0; if(totalDeposits == 0 && claim.currentChallenger > 0){ reward = rewards.div(claim.currentChallenger); } for (idx = 0; idx < claim.currentChallenger; ++idx) { reward = 0; challenger = claim.challengers[idx]; if(totalDeposits > 0){ reward = rewards.mul(claim.bondedDeposits[challenger]).div(totalDeposits); } claim.bondedDeposits[challenger] = claim.bondedDeposits[challenger].add(reward); } uint bondedDeposit; for (idx = 0; idx < claim.challengers.length; ++idx) { challenger = claim.challengers[idx]; bondedDeposit = claim.bondedDeposits[challenger]; deposits[challenger] = deposits[challenger].add(bondedDeposit); claim.bondedDeposits[challenger] = 0; emit DepositUnbonded(superblockHash, challenger, bondedDeposit); } } // @dev - Pay submitter with challenger deposits function doPaySubmitter(bytes32 superblockHash, SuperblockClaim storage claim) internal { address challenger; uint bondedDeposit; for (uint idx=0; idx < claim.challengers.length; ++idx) { challenger = claim.challengers[idx]; bondedDeposit = claim.bondedDeposits[challenger]; claim.bondedDeposits[challenger] = 0; claim.bondedDeposits[claim.submitter] = claim.bondedDeposits[claim.submitter].add(bondedDeposit); } unbondDeposit(superblockHash, claim.submitter); } // @dev - Check if a superblock can be semi approved by calling checkClaimFinished function getInBattleAndSemiApprovable(bytes32 superblockHash) public view returns (bool) { SuperblockClaim storage claim = claims[superblockHash]; return (trustedSuperblocks.getSuperblockStatus(superblockHash) == SyscoinSuperblocks.Status.InBattle && !claim.invalid && !claim.verificationOngoing && block.timestamp > claim.challengeTimeout && claim.currentChallenger >= claim.challengers.length); } // @dev – Check if a claim exists function claimExists(SuperblockClaim claim) private pure returns (bool) { return (claim.submitter != 0x0); } // @dev - Return a given superblock's submitter function getClaimSubmitter(bytes32 superblockHash) public view returns (address) { return claims[superblockHash].submitter; } // @dev - Return superblock submission timestamp function getNewSuperblockEventTimestamp(bytes32 superblockHash) public view returns (uint) { return claims[superblockHash].createdAt; } // @dev - Return whether or not a claim has already been made function getClaimExists(bytes32 superblockHash) public view returns (bool) { return claimExists(claims[superblockHash]); } // @dev - Return claim status function getClaimDecided(bytes32 superblockHash) public view returns (bool) { return claims[superblockHash].decided; } // @dev - Check if a claim is invalid function getClaimInvalid(bytes32 superblockHash) public view returns (bool) { // TODO: see if this is redundant with superblock status return claims[superblockHash].invalid; } // @dev - Check if a claim has a verification game in progress function getClaimVerificationOngoing(bytes32 superblockHash) public view returns (bool) { return claims[superblockHash].verificationOngoing; } // @dev - Returns timestamp of challenge timeout function getClaimChallengeTimeout(bytes32 superblockHash) public view returns (uint) { return claims[superblockHash].challengeTimeout; } // @dev - Return the number of challengers whose battles haven't been decided yet function getClaimRemainingChallengers(bytes32 superblockHash) public view returns (uint) { SuperblockClaim storage claim = claims[superblockHash]; return claim.challengers.length - (claim.currentChallenger); } // @dev – Return session by challenger function getSession(bytes32 superblockHash, address challenger) public view returns(bytes32) { return claims[superblockHash].sessions[challenger]; } function getClaimChallengers(bytes32 superblockHash) public view returns (address[]) { SuperblockClaim storage claim = claims[superblockHash]; return claim.challengers; } function getSuperblockInfo(bytes32 superblockHash) internal view returns ( bytes32 _blocksMerkleRoot, uint _accumulatedWork, uint _timestamp, uint _prevTimestamp, bytes32 _lastHash, uint32 _lastBits, bytes32 _parentId, address _submitter, SyscoinSuperblocks.Status _status, uint32 _height ) { return trustedSuperblocks.getSuperblock(superblockHash); } }
- Validate superblock information from last blocks
function validateLastBlocks(BattleSession storage session) internal view returns (uint) { if (session.blockHashes.length <= 0) { return ERR_SUPERBLOCK_BAD_LASTBLOCK; } uint lastTimestamp; uint prevTimestamp; uint32 lastBits; bytes32 parentId; (, , lastTimestamp, prevTimestamp, , lastBits, parentId,,,) = getSuperblockInfo(session.superblockHash); bytes32 blockSha256Hash = session.blockHashes[session.blockHashes.length - 1]; if (session.blocksInfo[blockSha256Hash].timestamp != lastTimestamp) { return ERR_SUPERBLOCK_BAD_TIMESTAMP; } if (session.blocksInfo[blockSha256Hash].bits != lastBits) { return ERR_SUPERBLOCK_BAD_BITS; } if (prevTimestamp > lastTimestamp) { return ERR_SUPERBLOCK_BAD_TIMESTAMP; } return ERR_SUPERBLOCK_OK; }
6,390,692
// File: contracts\modules\Ownable.sol pragma solidity =0.5.16; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable { address internal _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: contracts\modules\Managerable.sol pragma solidity =0.5.16; contract Managerable is Ownable { address private _managerAddress; /** * @dev modifier, Only manager can be granted exclusive access to specific functions. * */ modifier onlyManager() { require(_managerAddress == msg.sender,"Managerable: caller is not the Manager"); _; } /** * @dev set manager by owner. * */ function setManager(address managerAddress) public onlyOwner { _managerAddress = managerAddress; } /** * @dev get manager address. * */ function getManager()public view returns (address) { return _managerAddress; } } // File: contracts\interfaces\IFNXOracle.sol pragma solidity =0.5.16; interface IFNXOracle { /** * @notice retrieves price of an asset * @dev function to get price for an asset * @param asset Asset for which to get the price * @return uint mantissa of asset price (scaled by 1e8) or zero if unset or contract paused */ function getPrice(address asset) external view returns (uint256); function getUnderlyingPrice(uint256 cToken) external view returns (uint256); function getPrices(uint256[] calldata assets) external view returns (uint256[]memory); function getAssetAndUnderlyingPrice(address asset,uint256 underlying) external view returns (uint256,uint256); // function getSellOptionsPrice(address oToken) external view returns (uint256); // function getBuyOptionsPrice(address oToken) external view returns (uint256); } contract ImportOracle is Ownable{ IFNXOracle internal _oracle; function oraclegetPrices(uint256[] memory assets) internal view returns (uint256[]memory){ uint256[] memory prices = _oracle.getPrices(assets); uint256 len = assets.length; for (uint i=0;i<len;i++){ require(prices[i] >= 100 && prices[i] <= 1e30); } return prices; } function oraclePrice(address asset) internal view returns (uint256){ uint256 price = _oracle.getPrice(asset); require(price >= 100 && price <= 1e30); return price; } function oracleUnderlyingPrice(uint256 cToken) internal view returns (uint256){ uint256 price = _oracle.getUnderlyingPrice(cToken); require(price >= 100 && price <= 1e30); return price; } function oracleAssetAndUnderlyingPrice(address asset,uint256 cToken) internal view returns (uint256,uint256){ (uint256 price1,uint256 price2) = _oracle.getAssetAndUnderlyingPrice(asset,cToken); require(price1 >= 100 && price1 <= 1e30); require(price2 >= 100 && price2 <= 1e30); return (price1,price2); } function getOracleAddress() public view returns(address){ return address(_oracle); } function setOracleAddress(address oracle)public onlyOwner{ _oracle = IFNXOracle(oracle); } } // File: contracts\modules\whiteList.sol pragma solidity =0.5.16; /** * @dev Implementation of a whitelist which filters a eligible uint32. */ library whiteListUint32 { /** * @dev add uint32 into white list. * @param whiteList the storage whiteList. * @param temp input value */ function addWhiteListUint32(uint32[] storage whiteList,uint32 temp) internal{ if (!isEligibleUint32(whiteList,temp)){ whiteList.push(temp); } } /** * @dev remove uint32 from whitelist. */ function removeWhiteListUint32(uint32[] storage whiteList,uint32 temp)internal returns (bool) { uint256 len = whiteList.length; uint256 i=0; for (;i<len;i++){ if (whiteList[i] == temp) break; } if (i<len){ if (i!=len-1) { whiteList[i] = whiteList[len-1]; } whiteList.length--; return true; } return false; } function isEligibleUint32(uint32[] memory whiteList,uint32 temp) internal pure returns (bool){ uint256 len = whiteList.length; for (uint256 i=0;i<len;i++){ if (whiteList[i] == temp) return true; } return false; } function _getEligibleIndexUint32(uint32[] memory whiteList,uint32 temp) internal pure returns (uint256){ uint256 len = whiteList.length; uint256 i=0; for (;i<len;i++){ if (whiteList[i] == temp) break; } return i; } } /** * @dev Implementation of a whitelist which filters a eligible uint256. */ library whiteListUint256 { // add whiteList function addWhiteListUint256(uint256[] storage whiteList,uint256 temp) internal{ if (!isEligibleUint256(whiteList,temp)){ whiteList.push(temp); } } function removeWhiteListUint256(uint256[] storage whiteList,uint256 temp)internal returns (bool) { uint256 len = whiteList.length; uint256 i=0; for (;i<len;i++){ if (whiteList[i] == temp) break; } if (i<len){ if (i!=len-1) { whiteList[i] = whiteList[len-1]; } whiteList.length--; return true; } return false; } function isEligibleUint256(uint256[] memory whiteList,uint256 temp) internal pure returns (bool){ uint256 len = whiteList.length; for (uint256 i=0;i<len;i++){ if (whiteList[i] == temp) return true; } return false; } function _getEligibleIndexUint256(uint256[] memory whiteList,uint256 temp) internal pure returns (uint256){ uint256 len = whiteList.length; uint256 i=0; for (;i<len;i++){ if (whiteList[i] == temp) break; } return i; } } /** * @dev Implementation of a whitelist which filters a eligible address. */ library whiteListAddress { // add whiteList function addWhiteListAddress(address[] storage whiteList,address temp) internal{ if (!isEligibleAddress(whiteList,temp)){ whiteList.push(temp); } } function removeWhiteListAddress(address[] storage whiteList,address temp)internal returns (bool) { uint256 len = whiteList.length; uint256 i=0; for (;i<len;i++){ if (whiteList[i] == temp) break; } if (i<len){ if (i!=len-1) { whiteList[i] = whiteList[len-1]; } whiteList.length--; return true; } return false; } function isEligibleAddress(address[] memory whiteList,address temp) internal pure returns (bool){ uint256 len = whiteList.length; for (uint256 i=0;i<len;i++){ if (whiteList[i] == temp) return true; } return false; } function _getEligibleIndexAddress(address[] memory whiteList,address temp) internal pure returns (uint256){ uint256 len = whiteList.length; uint256 i=0; for (;i<len;i++){ if (whiteList[i] == temp) break; } return i; } } // File: contracts\modules\underlyingAssets.sol pragma solidity =0.5.16; /** * @dev Implementation of a underlyingAssets filters a eligible underlying. */ contract UnderlyingAssets is Ownable { using whiteListUint32 for uint32[]; // The eligible underlying list uint32[] internal underlyingAssets; /** * @dev Implementation of add an eligible underlying into the underlyingAssets. * @param underlying new eligible underlying. */ function addUnderlyingAsset(uint32 underlying)public onlyOwner{ underlyingAssets.addWhiteListUint32(underlying); } function setUnderlyingAsset(uint32[] memory underlyings)public onlyOwner{ underlyingAssets = underlyings; } /** * @dev Implementation of revoke an invalid underlying from the underlyingAssets. * @param removeUnderlying revoked underlying. */ function removeUnderlyingAssets(uint32 removeUnderlying)public onlyOwner returns(bool) { return underlyingAssets.removeWhiteListUint32(removeUnderlying); } /** * @dev Implementation of getting the eligible underlyingAssets. */ function getUnderlyingAssets()public view returns (uint32[] memory){ return underlyingAssets; } /** * @dev Implementation of testing whether the input underlying is eligible. * @param underlying input underlying for testing. */ function isEligibleUnderlyingAsset(uint32 underlying) public view returns (bool){ return underlyingAssets.isEligibleUint32(underlying); } function _getEligibleUnderlyingIndex(uint32 underlying) internal view returns (uint256){ return underlyingAssets._getEligibleIndexUint32(underlying); } } // File: contracts\interfaces\IVolatility.sol pragma solidity =0.5.16; interface IVolatility { function calculateIv(uint32 underlying,uint8 optType,uint256 expiration,uint256 currentPrice,uint256 strikePrice)external view returns (uint256); } contract ImportVolatility is Ownable{ IVolatility internal _volatility; function getVolatilityAddress() public view returns(address){ return address(_volatility); } function setVolatilityAddress(address volatility)public onlyOwner{ _volatility = IVolatility(volatility); } } // File: contracts\interfaces\IOptionsPrice.sol pragma solidity =0.5.16; interface IOptionsPrice { function getOptionsPrice(uint256 currentPrice, uint256 strikePrice, uint256 expiration,uint32 underlying,uint8 optType)external view returns (uint256); function getOptionsPrice_iv(uint256 currentPrice, uint256 strikePrice, uint256 expiration, uint256 ivNumerator,uint8 optType)external view returns (uint256); function calOptionsPriceRatio(uint256 selfOccupied,uint256 totalOccupied,uint256 totalCollateral) external view returns (uint256); } contract ImportOptionsPrice is Ownable{ IOptionsPrice internal _optionsPrice; function getOptionsPriceAddress() public view returns(address){ return address(_optionsPrice); } function setOptionsPriceAddress(address optionsPrice)public onlyOwner{ _optionsPrice = IOptionsPrice(optionsPrice); } } // File: contracts\modules\Operator.sol pragma solidity =0.5.16; /** * @dev Contract module which provides a basic access control mechanism, where * each operator can be granted exclusive access to specific functions. * */ contract Operator is Ownable { using whiteListAddress for address[]; address[] private _operatorList; /** * @dev modifier, every operator can be granted exclusive access to specific functions. * */ modifier onlyOperator() { require(_operatorList.isEligibleAddress(msg.sender),"Managerable: caller is not the Operator"); _; } /** * @dev modifier, Only indexed operator can be granted exclusive access to specific functions. * */ modifier onlyOperatorIndex(uint256 index) { require(_operatorList.length>index && _operatorList[index] == msg.sender,"Operator: caller is not the eligible Operator"); _; } /** * @dev add a new operator by owner. * */ function addOperator(address addAddress)public onlyOwner{ _operatorList.addWhiteListAddress(addAddress); } /** * @dev modify indexed operator by owner. * */ function setOperator(uint256 index,address addAddress)public onlyOwner{ _operatorList[index] = addAddress; } /** * @dev remove operator by owner. * */ function removeOperator(address removeAddress)public onlyOwner returns (bool){ return _operatorList.removeWhiteListAddress(removeAddress); } /** * @dev get all operators. * */ function getOperator()public view returns (address[] memory) { return _operatorList; } /** * @dev set all operators by owner. * */ function setOperators(address[] memory operators)public onlyOwner { _operatorList = operators; } } // File: contracts\modules\ImputRange.sol pragma solidity =0.5.16; contract ImputRange is Ownable { //The maximum input amount limit. uint256 private maxAmount = 1e30; //The minimum input amount limit. uint256 private minAmount = 1e2; modifier InRange(uint256 amount) { require(maxAmount>=amount && minAmount<=amount,"input amount is out of input amount range"); _; } /** * @dev Determine whether the input amount is within the valid range * @param Amount Test value which is user input */ function isInputAmountInRange(uint256 Amount)public view returns (bool){ return(maxAmount>=Amount && minAmount<=Amount); } /* function isInputAmountSmaller(uint256 Amount)public view returns (bool){ return maxAmount>=amount; } function isInputAmountLarger(uint256 Amount)public view returns (bool){ return minAmount<=amount; } */ modifier Smaller(uint256 amount) { require(maxAmount>=amount,"input amount is larger than maximium"); _; } modifier Larger(uint256 amount) { require(minAmount<=amount,"input amount is smaller than maximium"); _; } /** * @dev get the valid range of input amount */ function getInputAmountRange() public view returns(uint256,uint256) { return (minAmount,maxAmount); } /** * @dev set the valid range of input amount * @param _minAmount the minimum input amount limit * @param _maxAmount the maximum input amount limit */ function setInputAmountRange(uint256 _minAmount,uint256 _maxAmount) public onlyOwner{ minAmount = _minAmount; maxAmount = _maxAmount; } } // File: contracts\OptionsPool\OptionsData.sol pragma solidity =0.5.16; contract OptionsData is UnderlyingAssets,ImputRange,Managerable,ImportOracle,ImportVolatility,ImportOptionsPrice,Operator{ // store option info struct OptionsInfo { address owner; // option's owner uint8 optType; //0 for call, 1 for put uint24 underlying; // underlying ID, 1 for BTC,2 for ETH uint64 optionsPrice; address settlement; //user's settlement paying for option. uint64 createTime; uint32 expiration; // uint128 amount; uint128 settlePrice; uint128 strikePrice; // strike price uint32 priceRate; //underlying Price uint64 iv; uint32 extra; } uint256 internal limitation = 1 hours; //all options information list OptionsInfo[] internal allOptions; //user options balances mapping(address=>uint64[]) internal optionsBalances; //expiration whitelist uint32[] internal expirationList; // first option position which is needed calculate. uint256 internal netWorthirstOption; // options latest networth balance. store all options's net worth share started from first option. mapping(address=>int256) internal optionsLatestNetWorth; // first option position which is needed calculate. uint256 internal occupiedFirstOption; //latest calcutated Options Occupied value. uint256 internal callOccupied; uint256 internal putOccupied; //latest Options volatile occupied value when bought or selled options. int256 internal callLatestOccupied; int256 internal putLatestOccupied; /** * @dev Emitted when `owner` create a new option. * @param owner new option's owner * @param optionID new option's id * @param optionID new option's type * @param underlying new option's underlying * @param expiration new option's expiration timestamp * @param strikePrice new option's strikePrice * @param amount new option's amount */ event CreateOption(address indexed owner,uint256 indexed optionID,uint8 optType,uint32 underlying,uint256 expiration,uint256 strikePrice,uint256 amount); /** * @dev Emitted when `owner` burn `amount` his option which id is `optionID`. */ event BurnOption(address indexed owner,uint256 indexed optionID,uint amount); event DebugEvent(uint256 id,uint256 value1,uint256 value2); } /* contract OptionsDataV2 is OptionsData{ // store option info struct OptionsInfoV2 { uint64 optionID; //an increasing nubmer id, begin from one. uint64 expiration; // Expiration timestamp uint128 strikePrice; //strike price uint8 optType; //0 for call, 1 for put uint32 underlying; // underlying ID, 1 for BTC,2 for ETH address owner; // option's owner uint256 amount; // mint amount } // store option extra info struct OptionsInfoExV2 { address settlement; //user's settlement paying for option. uint128 tokenTimePrice; //option's buying price based on settlement, used for options share calculation uint128 underlyingPrice;//underlying price when option is created. uint128 fullPrice; //option's buying price. uint128 ivNumerator; // option's iv numerator when option is created. // uint256 ivDenominator;// option's iv denominator when option is created. } //all options information list OptionsInfoV2[] internal allOptionsV2; // all option's extra information map mapping(uint256=>OptionsInfoExV2) internal optionExtraMapV2; //user options balances // mapping(address=>uint64[]) internal optionsBalancesV2; } */ // File: contracts\Proxy\baseProxy.sol pragma solidity =0.5.16; /** * @title baseProxy Contract */ contract baseProxy is Ownable { address public implementation; constructor(address implementation_) public { // Creator of the contract is admin during initialization implementation = implementation_; (bool success,) = implementation_.delegatecall(abi.encodeWithSignature("initialize()")); require(success); } function getImplementation()public view returns(address){ return implementation; } function setImplementation(address implementation_)public onlyOwner{ implementation = implementation_; (bool success,) = implementation_.delegatecall(abi.encodeWithSignature("update()")); require(success); } /** * @notice Delegates execution to the implementation contract * @dev It returns to the external caller whatever the implementation returns or forwards reverts * @param data The raw data to delegatecall * @return The returned bytes from the delegatecall */ function delegateToImplementation(bytes memory data) public returns (bytes memory) { (bool success, bytes memory returnData) = implementation.delegatecall(data); assembly { if eq(success, 0) { revert(add(returnData, 0x20), returndatasize) } } return returnData; } /** * @notice Delegates execution to an implementation contract * @dev It returns to the external caller whatever the implementation returns or forwards reverts * There are an additional 2 prefix uints from the wrapper returndata, which we ignore since we make an extra hop. * @param data The raw data to delegatecall * @return The returned bytes from the delegatecall */ function delegateToViewImplementation(bytes memory data) public view returns (bytes memory) { (bool success, bytes memory returnData) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", data)); assembly { if eq(success, 0) { revert(add(returnData, 0x20), returndatasize) } } return abi.decode(returnData, (bytes)); } function delegateToViewAndReturn() internal view returns (bytes memory) { (bool success, ) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", msg.data)); assembly { let free_mem_ptr := mload(0x40) returndatacopy(free_mem_ptr, 0, returndatasize) switch success case 0 { revert(free_mem_ptr, returndatasize) } default { return(add(free_mem_ptr, 0x40), returndatasize) } } } function delegateAndReturn() internal returns (bytes memory) { (bool success, ) = implementation.delegatecall(msg.data); assembly { let free_mem_ptr := mload(0x40) returndatacopy(free_mem_ptr, 0, returndatasize) switch success case 0 { revert(free_mem_ptr, returndatasize) } default { return(free_mem_ptr, returndatasize) } } } } // File: contracts\OptionsPool\OptionsProxy.sol pragma solidity =0.5.16; /** * @title Erc20Delegator Contract */ contract OptionsProxy is OptionsData,baseProxy{ /** * @dev constructor function , setting contract address. * oracleAddr FNX oracle contract address * optionsPriceAddr options price contract address * ivAddress implied volatility contract address */ constructor(address implementation_,address oracleAddr,address optionsPriceAddr,address ivAddress) baseProxy(implementation_) public { _oracle = IFNXOracle(oracleAddr); _optionsPrice = IOptionsPrice(optionsPriceAddr); _volatility = IVolatility(ivAddress); } function setTimeLimitation(uint256 /*_limit*/)public{ delegateAndReturn(); } function getTimeLimitation()public view returns(uint256){ delegateToViewAndReturn(); } /** * @dev retrieve user's options' id. * user user's account. */ function getUserOptionsID(address /*user*/)public view returns(uint64[] memory){ delegateToViewAndReturn(); } /** * @dev retrieve user's `size` number of options' id. * user user's account. * from user's option list begin positon. * size retrieve size. */ function getUserOptionsID(address /*user*/,uint256 /*from*/,uint256 /*size*/)public view returns(uint64[] memory){ delegateToViewAndReturn(); } /** * @dev retrieve all option list length. */ function getOptionInfoLength()public view returns (uint256){ delegateToViewAndReturn(); } /** * @dev retrieve `size` number of options' information. * from all option list begin positon. * size retrieve size. */ function getOptionInfoList(uint256 /*from*/,uint256 /*size*/)public view returns(address[] memory,uint256[] memory,uint256[] memory,uint256[] memory,uint256[] memory){ delegateToViewAndReturn(); } /** * @dev retrieve given `ids` options' information. * ids retrieved options' id. */ function getOptionInfoListFromID(uint256[] memory /*ids*/)public view returns(address[] memory,uint256[] memory,uint256[] memory,uint256[] memory,uint256[] memory){ delegateToViewAndReturn(); } /** * @dev retrieve given `optionsId` option's burned limit timestamp. * optionsId retrieved option's id. */ function getOptionsLimitTimeById(uint256 /*optionsId*/)public view returns(uint256){ delegateToViewAndReturn(); } /** * @dev retrieve given `optionsId` option's information. * optionsId retrieved option's id. */ function getOptionsById(uint256 /*optionsId*/)public view returns(uint256,address,uint8,uint32,uint256,uint256,uint256){ delegateToViewAndReturn(); } /** * @dev retrieve given `optionsId` option's extra information. * optionsId retrieved option's id. */ function getOptionsExtraById(uint256 /*optionsId*/)public view returns(address,uint256,uint256,uint256,uint256){ delegateToViewAndReturn(); } /** * @dev calculate option's exercise worth. * optionsId option's id * amount option's amount */ function getExerciseWorth(uint256 /*optionsId*/,uint256 /*amount*/)public view returns(uint256){ delegateToViewAndReturn(); } /** * @dev check option's underlying and expiration. * expiration option's expiration * underlying option's underlying */ // function buyOptionCheck(uint32 /*expiration*/,uint32 /*underlying*/)public view{ // delegateToViewAndReturn(); // } /** * @dev Implementation of add an eligible expiration into the expirationList. * expiration new eligible expiration. */ function addExpiration(uint32 /*expiration*/)public{ delegateAndReturn(); } /** * @dev Implementation of revoke an invalid expiration from the expirationList. * removeExpiration revoked expiration. */ function removeExpirationList(uint32 /*removeExpiration*/)public returns(bool) { delegateAndReturn(); } /** * @dev Implementation of getting the eligible expirationList. */ function getExpirationList()public view returns (uint32[] memory){ delegateToViewAndReturn(); } /** * @dev Implementation of testing whether the input expiration is eligible. * expiration input expiration for testing. */ function isEligibleExpiration(uint256 /*expiration*/) public view returns (bool){ delegateToViewAndReturn(); } /** * @dev check option's expiration. * expiration option's expiration */ function checkExpiration(uint256 /*expiration*/) public view{ delegateToViewAndReturn(); } /** * @dev calculate `amount` number of Option's full price when option is burned. * optionID option's optionID * amount option's amount */ function getBurnedFullPay(uint256 /*optionID*/,uint256 /*amount*/) public view returns(address,uint256){ delegateToViewAndReturn(); } /** * @dev retrieve collateral occupied calculation information. */ function getOccupiedCalInfo()public view returns(uint256,int256,int256){ delegateToViewAndReturn(); } /** * @dev calculate collateral occupied value, and modify database, only foundation operator can modify database. */ function setOccupiedCollateral() public { delegateAndReturn(); } /** * @dev calculate collateral occupied value. * lastOption last option's position. * beginOption begin option's poisiton. * endOption end option's poisiton. */ function calculatePhaseOccupiedCollateral(uint256 /*lastOption*/,uint256 /*beginOption*/,uint256 /*endOption*/) public view returns(uint256,uint256,uint256,bool){ delegateToViewAndReturn(); } /** * @dev set collateral occupied value, only foundation operator can modify database. * totalCallOccupied new call options occupied collateral calculation result. * totalPutOccupied new put options occupied collateral calculation result. * beginOption new first valid option's positon. * latestCallOccpied latest call options' occupied value when operater invoke collateral occupied calculation. * latestPutOccpied latest put options' occupied value when operater invoke collateral occupied calculation. */ function setCollateralPhase(uint256 /*totalCallOccupied*/,uint256 /*totalPutOccupied*/, uint256 /*beginOption*/,int256 /*latestCallOccpied*/,int256 /*latestPutOccpied*/) public{ delegateAndReturn(); } function getAllTotalOccupiedCollateral() public view returns (uint256,uint256){ delegateToViewAndReturn(); } /** * @dev get call options total collateral occupied value. */ function getCallTotalOccupiedCollateral() public view returns (uint256) { delegateToViewAndReturn(); } /** * @dev get put options total collateral occupied value. */ function getPutTotalOccupiedCollateral() public view returns (uint256) { delegateToViewAndReturn(); } /** * @dev get real total collateral occupied value. */ function getTotalOccupiedCollateral() public view returns (uint256) { delegateToViewAndReturn(); } /** * @dev retrieve all information for net worth calculation. * whiteList collateral address whitelist. */ function getNetWrothCalInfo(address[] memory /*whiteList*/)public view returns(uint256,int256[] memory){ delegateToViewAndReturn(); } /** * @dev retrieve latest options net worth which paid in settlement coin. * settlement settlement coin address. */ function getNetWrothLatestWorth(address /*settlement*/)public view returns(int256){ delegateToViewAndReturn(); } /** * @dev set latest options net worth balance, only manager contract can modify database. * newFirstOption new first valid option position. * latestNetWorth latest options net worth. * whiteList eligible collateral address white list. */ function setSharedState(uint256 /*newFirstOption*/,int256[] memory /*latestNetWorth*/,address[] memory /*whiteList*/) public{ delegateAndReturn(); } /** * @dev calculate options time shared value,from begin to end in the alloptionsList. * lastOption the last option position. * begin the begin options position. * end the end options position. * whiteList eligible collateral address white list. */ function calRangeSharedPayment(uint256 /*lastOption*/,uint256 /*begin*/,uint256 /*end*/,address[] memory /*whiteList*/) public view returns(int256[] memory,uint256[] memory,uint256){ delegateToViewAndReturn(); } /** * @dev calculate options payback fall value,from begin to end in the alloptionsList. * lastOption the last option position. * begin the begin options position. * end the end options position. * whiteList eligible collateral address white list. */ function calculatePhaseOptionsFall(uint256 /*lastOption*/,uint256 /*begin*/,uint256 /*end*/,address[] memory /*whiteList*/) public view returns(int256[] memory){ delegateToViewAndReturn(); } /** * @dev retrieve all information for collateral occupied and net worth calculation. * whiteList settlement address whitelist. */ function getOptionCalRangeAll(address[] memory /*whiteList*/)public view returns(uint256,int256,int256,uint256,int256[] memory,uint256,uint256){ delegateToViewAndReturn(); } /** * @dev create new option,modify collateral occupied and net worth value, only manager contract can invoke this. * from user's address. * settlement user's input settlement coin. * type_ly_exp tuple64 for option type,underlying,expiration. * strikePrice user's input new option's strike price. * optionPrice current new option's price, calculated by options price contract. * amount user's input new option's amount. */ function createOptions(address /*from*/,address /*settlement*/,uint256 /*type_ly_exp*/, uint128 /*strikePrice*/,uint128 /*underlyingPrice*/,uint128 /*amount*/,uint128 /*settlePrice*/) public returns(uint256) { delegateAndReturn(); } /** * @dev burn option,modify collateral occupied and net worth value, only manager contract can invoke this. * from user's address. * id user's input option's id. * amount user's input burned option's amount. * optionPrice current new option's price, calculated by options price contract. */ function burnOptions(address /*from*/,uint256 /*id*/,uint256 /*amount*/,uint256 /*optionPrice*/)public{ delegateAndReturn(); } function getUserAllOptionInfo(address /*user*/)public view returns(address[] memory,uint256[] memory,uint256[] memory,uint256[] memory,uint256[] memory){ delegateToViewAndReturn(); } }
retrieve collateral occupied calculation information./
function getOccupiedCalInfo()public view returns(uint256,int256,int256){ delegateToViewAndReturn(); }
10,419,411
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; import { iOVM_BondManager } from "../../iOVM/verification/iOVM_BondManager.sol"; import { Lib_AddressResolver } from "../../libraries/resolver/Lib_AddressResolver.sol"; /// Minimal contract to be inherited by contracts consumed by users that provide /// data for fraud proofs abstract contract Abs_FraudContributor is Lib_AddressResolver { /// Decorate your functions with this modifier to store how much total gas was /// consumed by the sender, to reward users fairly modifier contributesToFraudProof(bytes32 preStateRoot, bytes32 txHash) { uint256 startGas = gasleft(); _; uint256 gasSpent = startGas - gasleft(); iOVM_BondManager(resolve('OVM_BondManager')).recordGasSpent(preStateRoot, txHash, msg.sender, gasSpent); } } // SPDX-License-Identifier: MIT // @unsupported: ovm pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol"; import { Lib_AddressResolver } from "../../libraries/resolver/Lib_AddressResolver.sol"; import { Lib_EthUtils } from "../../libraries/utils/Lib_EthUtils.sol"; import { Lib_Bytes32Utils } from "../../libraries/utils/Lib_Bytes32Utils.sol"; import { Lib_BytesUtils } from "../../libraries/utils/Lib_BytesUtils.sol"; import { Lib_SecureMerkleTrie } from "../../libraries/trie/Lib_SecureMerkleTrie.sol"; import { Lib_RLPWriter } from "../../libraries/rlp/Lib_RLPWriter.sol"; import { Lib_RLPReader } from "../../libraries/rlp/Lib_RLPReader.sol"; /* Interface Imports */ import { iOVM_StateTransitioner } from "../../iOVM/verification/iOVM_StateTransitioner.sol"; import { iOVM_BondManager } from "../../iOVM/verification/iOVM_BondManager.sol"; import { iOVM_ExecutionManager } from "../../iOVM/execution/iOVM_ExecutionManager.sol"; import { iOVM_StateManager } from "../../iOVM/execution/iOVM_StateManager.sol"; import { iOVM_StateManagerFactory } from "../../iOVM/execution/iOVM_StateManagerFactory.sol"; /* Contract Imports */ import { Abs_FraudContributor } from "./Abs_FraudContributor.sol"; /** * @title OVM_StateTransitioner * @dev The State Transitioner coordinates the execution of a state transition during the evaluation of a * fraud proof. It feeds verified input to the Execution Manager's run(), and controls a State Manager (which is * uniquely created for each fraud proof). * Once a fraud proof has been initialized, this contract is provided with the pre-state root and verifies * that the OVM storage slots committed to the State Mangager are contained in that state * This contract controls the State Manager and Execution Manager, and uses them to calculate the * post-state root by applying the transaction. The Fraud Verifier can then check for fraud by comparing * the calculated post-state root with the proposed post-state root. * * Compiler used: solc * Runtime target: EVM */ contract OVM_StateTransitioner is Lib_AddressResolver, Abs_FraudContributor, iOVM_StateTransitioner { /******************* * Data Structures * *******************/ enum TransitionPhase { PRE_EXECUTION, POST_EXECUTION, COMPLETE } /******************************************* * Contract Variables: Contract References * *******************************************/ iOVM_StateManager public ovmStateManager; /******************************************* * Contract Variables: Internal Accounting * *******************************************/ bytes32 internal preStateRoot; bytes32 internal postStateRoot; TransitionPhase public phase; uint256 internal stateTransitionIndex; bytes32 internal transactionHash; /************* * Constants * *************/ bytes32 internal constant EMPTY_ACCOUNT_CODE_HASH = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; bytes32 internal constant EMPTY_ACCOUNT_STORAGE_ROOT = 0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421; /*************** * Constructor * ***************/ /** * @param _libAddressManager Address of the Address Manager. * @param _stateTransitionIndex Index of the state transition being verified. * @param _preStateRoot State root before the transition was executed. * @param _transactionHash Hash of the executed transaction. */ constructor( address _libAddressManager, uint256 _stateTransitionIndex, bytes32 _preStateRoot, bytes32 _transactionHash ) Lib_AddressResolver(_libAddressManager) { stateTransitionIndex = _stateTransitionIndex; preStateRoot = _preStateRoot; postStateRoot = _preStateRoot; transactionHash = _transactionHash; ovmStateManager = iOVM_StateManagerFactory(resolve("OVM_StateManagerFactory")).create(address(this)); } /********************** * Function Modifiers * **********************/ /** * Checks that a function is only run during a specific phase. * @param _phase Phase the function must run within. */ modifier onlyDuringPhase( TransitionPhase _phase ) { require( phase == _phase, "Function must be called during the correct phase." ); _; } /********************************** * Public Functions: State Access * **********************************/ /** * Retrieves the state root before execution. * @return _preStateRoot State root before execution. */ function getPreStateRoot() override external view returns ( bytes32 _preStateRoot ) { return preStateRoot; } /** * Retrieves the state root after execution. * @return _postStateRoot State root after execution. */ function getPostStateRoot() override external view returns ( bytes32 _postStateRoot ) { return postStateRoot; } /** * Checks whether the transitioner is complete. * @return _complete Whether or not the transition process is finished. */ function isComplete() override external view returns ( bool _complete ) { return phase == TransitionPhase.COMPLETE; } /*********************************** * Public Functions: Pre-Execution * ***********************************/ /** * Allows a user to prove the initial state of a contract. * @param _ovmContractAddress Address of the contract on the OVM. * @param _ethContractAddress Address of the corresponding contract on L1. * @param _stateTrieWitness Proof of the account state. */ function proveContractState( address _ovmContractAddress, address _ethContractAddress, bytes memory _stateTrieWitness ) override external onlyDuringPhase(TransitionPhase.PRE_EXECUTION) contributesToFraudProof(preStateRoot, transactionHash) { // Exit quickly to avoid unnecessary work. require( ( ovmStateManager.hasAccount(_ovmContractAddress) == false && ovmStateManager.hasEmptyAccount(_ovmContractAddress) == false ), "Account state has already been proven." ); // Function will fail if the proof is not a valid inclusion or exclusion proof. ( bool exists, bytes memory encodedAccount ) = Lib_SecureMerkleTrie.get( abi.encodePacked(_ovmContractAddress), _stateTrieWitness, preStateRoot ); if (exists == true) { // Account exists, this was an inclusion proof. Lib_OVMCodec.EVMAccount memory account = Lib_OVMCodec.decodeEVMAccount( encodedAccount ); address ethContractAddress = _ethContractAddress; if (account.codeHash == EMPTY_ACCOUNT_CODE_HASH) { // Use a known empty contract to prevent an attack in which a user provides a // contract address here and then later deploys code to it. ethContractAddress = 0x0000000000000000000000000000000000000000; } else { // Otherwise, make sure that the code at the provided eth address matches the hash // of the code stored on L2. require( Lib_EthUtils.getCodeHash(ethContractAddress) == account.codeHash, "OVM_StateTransitioner: Provided L1 contract code hash does not match L2 contract code hash." ); } ovmStateManager.putAccount( _ovmContractAddress, Lib_OVMCodec.Account({ nonce: account.nonce, balance: account.balance, storageRoot: account.storageRoot, codeHash: account.codeHash, ethAddress: ethContractAddress, isFresh: false }) ); } else { // Account does not exist, this was an exclusion proof. ovmStateManager.putEmptyAccount(_ovmContractAddress); } } /** * Allows a user to prove the initial state of a contract storage slot. * @param _ovmContractAddress Address of the contract on the OVM. * @param _key Claimed account slot key. * @param _storageTrieWitness Proof of the storage slot. */ function proveStorageSlot( address _ovmContractAddress, bytes32 _key, bytes memory _storageTrieWitness ) override external onlyDuringPhase(TransitionPhase.PRE_EXECUTION) contributesToFraudProof(preStateRoot, transactionHash) { // Exit quickly to avoid unnecessary work. require( ovmStateManager.hasContractStorage(_ovmContractAddress, _key) == false, "Storage slot has already been proven." ); require( ovmStateManager.hasAccount(_ovmContractAddress) == true, "Contract must be verified before proving a storage slot." ); bytes32 storageRoot = ovmStateManager.getAccountStorageRoot(_ovmContractAddress); bytes32 value; if (storageRoot == EMPTY_ACCOUNT_STORAGE_ROOT) { // Storage trie was empty, so the user is always allowed to insert zero-byte values. value = bytes32(0); } else { // Function will fail if the proof is not a valid inclusion or exclusion proof. ( bool exists, bytes memory encodedValue ) = Lib_SecureMerkleTrie.get( abi.encodePacked(_key), _storageTrieWitness, storageRoot ); if (exists == true) { // Inclusion proof. // Stored values are RLP encoded, with leading zeros removed. value = Lib_BytesUtils.toBytes32PadLeft( Lib_RLPReader.readBytes(encodedValue) ); } else { // Exclusion proof, can only be zero bytes. value = bytes32(0); } } ovmStateManager.putContractStorage( _ovmContractAddress, _key, value ); } /******************************* * Public Functions: Execution * *******************************/ /** * Executes the state transition. * @param _transaction OVM transaction to execute. */ function applyTransaction( Lib_OVMCodec.Transaction memory _transaction ) override external onlyDuringPhase(TransitionPhase.PRE_EXECUTION) contributesToFraudProof(preStateRoot, transactionHash) { require( Lib_OVMCodec.hashTransaction(_transaction) == transactionHash, "Invalid transaction provided." ); // We require gas to complete the logic here in run() before/after execution, // But must ensure the full _tx.gasLimit can be given to the ovmCALL (determinism) // This includes 1/64 of the gas getting lost because of EIP-150 (lost twice--first // going into EM, then going into the code contract). require( gasleft() >= 100000 + _transaction.gasLimit * 1032 / 1000, // 1032/1000 = 1.032 = (64/63)^2 rounded up "Not enough gas to execute transaction deterministically." ); iOVM_ExecutionManager ovmExecutionManager = iOVM_ExecutionManager(resolve("OVM_ExecutionManager")); // We call `setExecutionManager` right before `run` (and not earlier) just in case the // OVM_ExecutionManager address was updated between the time when this contract was created // and when `applyTransaction` was called. ovmStateManager.setExecutionManager(address(ovmExecutionManager)); // `run` always succeeds *unless* the user hasn't provided enough gas to `applyTransaction` // or an INVALID_STATE_ACCESS flag was triggered. Either way, we won't get beyond this line // if that's the case. ovmExecutionManager.run(_transaction, address(ovmStateManager)); // Prevent the Execution Manager from calling this SM again. ovmStateManager.setExecutionManager(address(0)); phase = TransitionPhase.POST_EXECUTION; } /************************************ * Public Functions: Post-Execution * ************************************/ /** * Allows a user to commit the final state of a contract. * @param _ovmContractAddress Address of the contract on the OVM. * @param _stateTrieWitness Proof of the account state. */ function commitContractState( address _ovmContractAddress, bytes memory _stateTrieWitness ) override external onlyDuringPhase(TransitionPhase.POST_EXECUTION) contributesToFraudProof(preStateRoot, transactionHash) { require( ovmStateManager.getTotalUncommittedContractStorage() == 0, "All storage must be committed before committing account states." ); require ( ovmStateManager.commitAccount(_ovmContractAddress) == true, "Account state wasn't changed or has already been committed." ); Lib_OVMCodec.Account memory account = ovmStateManager.getAccount(_ovmContractAddress); postStateRoot = Lib_SecureMerkleTrie.update( abi.encodePacked(_ovmContractAddress), Lib_OVMCodec.encodeEVMAccount( Lib_OVMCodec.toEVMAccount(account) ), _stateTrieWitness, postStateRoot ); // Emit an event to help clients figure out the proof ordering. emit AccountCommitted( _ovmContractAddress ); } /** * Allows a user to commit the final state of a contract storage slot. * @param _ovmContractAddress Address of the contract on the OVM. * @param _key Claimed account slot key. * @param _storageTrieWitness Proof of the storage slot. */ function commitStorageSlot( address _ovmContractAddress, bytes32 _key, bytes memory _storageTrieWitness ) override external onlyDuringPhase(TransitionPhase.POST_EXECUTION) contributesToFraudProof(preStateRoot, transactionHash) { require( ovmStateManager.commitContractStorage(_ovmContractAddress, _key) == true, "Storage slot value wasn't changed or has already been committed." ); Lib_OVMCodec.Account memory account = ovmStateManager.getAccount(_ovmContractAddress); bytes32 value = ovmStateManager.getContractStorage(_ovmContractAddress, _key); account.storageRoot = Lib_SecureMerkleTrie.update( abi.encodePacked(_key), Lib_RLPWriter.writeBytes( Lib_Bytes32Utils.removeLeadingZeros(value) ), _storageTrieWitness, account.storageRoot ); ovmStateManager.putAccount(_ovmContractAddress, account); // Emit an event to help clients figure out the proof ordering. emit ContractStorageCommitted( _ovmContractAddress, _key ); } /********************************** * Public Functions: Finalization * **********************************/ /** * Finalizes the transition process. */ function completeTransition() override external onlyDuringPhase(TransitionPhase.POST_EXECUTION) { require( ovmStateManager.getTotalUncommittedAccounts() == 0, "All accounts must be committed before completing a transition." ); require( ovmStateManager.getTotalUncommittedContractStorage() == 0, "All storage must be committed before completing a transition." ); phase = TransitionPhase.COMPLETE; } } // SPDX-License-Identifier: MIT // @unsupported: ovm pragma solidity >0.5.0 <0.8.0; /* Library Imports */ import { Lib_AddressResolver } from "../../libraries/resolver/Lib_AddressResolver.sol"; /* Interface Imports */ import { iOVM_StateTransitioner } from "../../iOVM/verification/iOVM_StateTransitioner.sol"; import { iOVM_StateTransitionerFactory } from "../../iOVM/verification/iOVM_StateTransitionerFactory.sol"; import { iOVM_FraudVerifier } from "../../iOVM/verification/iOVM_FraudVerifier.sol"; /* Contract Imports */ import { OVM_StateTransitioner } from "./OVM_StateTransitioner.sol"; /** * @title OVM_StateTransitionerFactory * @dev The State Transitioner Factory is used by the Fraud Verifier to create a new State * Transitioner during the initialization of a fraud proof. * * Compiler used: solc * Runtime target: EVM */ contract OVM_StateTransitionerFactory is iOVM_StateTransitionerFactory, Lib_AddressResolver { /*************** * Constructor * ***************/ constructor( address _libAddressManager ) Lib_AddressResolver(_libAddressManager) {} /******************** * Public Functions * ********************/ /** * Creates a new OVM_StateTransitioner * @param _libAddressManager Address of the Address Manager. * @param _stateTransitionIndex Index of the state transition being verified. * @param _preStateRoot State root before the transition was executed. * @param _transactionHash Hash of the executed transaction. * @return New OVM_StateTransitioner instance. */ function create( address _libAddressManager, uint256 _stateTransitionIndex, bytes32 _preStateRoot, bytes32 _transactionHash ) override public returns ( iOVM_StateTransitioner ) { require( msg.sender == resolve("OVM_FraudVerifier"), "Create can only be done by the OVM_FraudVerifier." ); return new OVM_StateTransitioner( _libAddressManager, _stateTransitionIndex, _preStateRoot, _transactionHash ); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol"; interface iOVM_ExecutionManager { /********** * Enums * *********/ enum RevertFlag { OUT_OF_GAS, INTENTIONAL_REVERT, EXCEEDS_NUISANCE_GAS, INVALID_STATE_ACCESS, UNSAFE_BYTECODE, CREATE_COLLISION, STATIC_VIOLATION, CREATOR_NOT_ALLOWED } enum GasMetadataKey { CURRENT_EPOCH_START_TIMESTAMP, CUMULATIVE_SEQUENCER_QUEUE_GAS, CUMULATIVE_L1TOL2_QUEUE_GAS, PREV_EPOCH_SEQUENCER_QUEUE_GAS, PREV_EPOCH_L1TOL2_QUEUE_GAS } /*********** * Structs * ***********/ struct GasMeterConfig { uint256 minTransactionGasLimit; uint256 maxTransactionGasLimit; uint256 maxGasPerQueuePerEpoch; uint256 secondsPerEpoch; } struct GlobalContext { uint256 ovmCHAINID; } struct TransactionContext { Lib_OVMCodec.QueueOrigin ovmL1QUEUEORIGIN; uint256 ovmTIMESTAMP; uint256 ovmNUMBER; uint256 ovmGASLIMIT; uint256 ovmTXGASLIMIT; address ovmL1TXORIGIN; } struct TransactionRecord { uint256 ovmGasRefund; } struct MessageContext { address ovmCALLER; address ovmADDRESS; bool isStatic; } struct MessageRecord { uint256 nuisanceGasLeft; } /************************************ * Transaction Execution Entrypoint * ************************************/ function run( Lib_OVMCodec.Transaction calldata _transaction, address _txStateManager ) external returns (bytes memory); /******************* * Context Opcodes * *******************/ function ovmCALLER() external view returns (address _caller); function ovmADDRESS() external view returns (address _address); function ovmTIMESTAMP() external view returns (uint256 _timestamp); function ovmNUMBER() external view returns (uint256 _number); function ovmGASLIMIT() external view returns (uint256 _gasLimit); function ovmCHAINID() external view returns (uint256 _chainId); /********************** * L2 Context Opcodes * **********************/ function ovmL1QUEUEORIGIN() external view returns (Lib_OVMCodec.QueueOrigin _queueOrigin); function ovmL1TXORIGIN() external view returns (address _l1TxOrigin); /******************* * Halting Opcodes * *******************/ function ovmREVERT(bytes memory _data) external; /***************************** * Contract Creation Opcodes * *****************************/ function ovmCREATE(bytes memory _bytecode) external returns (address _contract, bytes memory _revertdata); function ovmCREATE2(bytes memory _bytecode, bytes32 _salt) external returns (address _contract, bytes memory _revertdata); /******************************* * Account Abstraction Opcodes * ******************************/ function ovmGETNONCE() external returns (uint256 _nonce); function ovmINCREMENTNONCE() external; function ovmCREATEEOA(bytes32 _messageHash, uint8 _v, bytes32 _r, bytes32 _s) external; /**************************** * Contract Calling Opcodes * ****************************/ function ovmCALL(uint256 _gasLimit, address _address, bytes memory _calldata) external returns (bool _success, bytes memory _returndata); function ovmSTATICCALL(uint256 _gasLimit, address _address, bytes memory _calldata) external returns (bool _success, bytes memory _returndata); function ovmDELEGATECALL(uint256 _gasLimit, address _address, bytes memory _calldata) external returns (bool _success, bytes memory _returndata); /**************************** * Contract Storage Opcodes * ****************************/ function ovmSLOAD(bytes32 _key) external returns (bytes32 _value); function ovmSSTORE(bytes32 _key, bytes32 _value) external; /************************* * Contract Code Opcodes * *************************/ function ovmEXTCODECOPY(address _contract, uint256 _offset, uint256 _length) external returns (bytes memory _code); function ovmEXTCODESIZE(address _contract) external returns (uint256 _size); function ovmEXTCODEHASH(address _contract) external returns (bytes32 _hash); /*************************************** * Public Functions: Execution Context * ***************************************/ function getMaxTransactionGasLimit() external view returns (uint _maxTransactionGasLimit); } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol"; /** * @title iOVM_StateManager */ interface iOVM_StateManager { /******************* * Data Structures * *******************/ enum ItemState { ITEM_UNTOUCHED, ITEM_LOADED, ITEM_CHANGED, ITEM_COMMITTED } /*************************** * Public Functions: Misc * ***************************/ function isAuthenticated(address _address) external view returns (bool); /*************************** * Public Functions: Setup * ***************************/ function owner() external view returns (address _owner); function ovmExecutionManager() external view returns (address _ovmExecutionManager); function setExecutionManager(address _ovmExecutionManager) external; /************************************ * Public Functions: Account Access * ************************************/ function putAccount(address _address, Lib_OVMCodec.Account memory _account) external; function putEmptyAccount(address _address) external; function getAccount(address _address) external view returns (Lib_OVMCodec.Account memory _account); function hasAccount(address _address) external view returns (bool _exists); function hasEmptyAccount(address _address) external view returns (bool _exists); function setAccountNonce(address _address, uint256 _nonce) external; function getAccountNonce(address _address) external view returns (uint256 _nonce); function getAccountEthAddress(address _address) external view returns (address _ethAddress); function getAccountStorageRoot(address _address) external view returns (bytes32 _storageRoot); function initPendingAccount(address _address) external; function commitPendingAccount(address _address, address _ethAddress, bytes32 _codeHash) external; function testAndSetAccountLoaded(address _address) external returns (bool _wasAccountAlreadyLoaded); function testAndSetAccountChanged(address _address) external returns (bool _wasAccountAlreadyChanged); function commitAccount(address _address) external returns (bool _wasAccountCommitted); function incrementTotalUncommittedAccounts() external; function getTotalUncommittedAccounts() external view returns (uint256 _total); function wasAccountChanged(address _address) external view returns (bool); function wasAccountCommitted(address _address) external view returns (bool); /************************************ * Public Functions: Storage Access * ************************************/ function putContractStorage(address _contract, bytes32 _key, bytes32 _value) external; function getContractStorage(address _contract, bytes32 _key) external view returns (bytes32 _value); function hasContractStorage(address _contract, bytes32 _key) external view returns (bool _exists); function testAndSetContractStorageLoaded(address _contract, bytes32 _key) external returns (bool _wasContractStorageAlreadyLoaded); function testAndSetContractStorageChanged(address _contract, bytes32 _key) external returns (bool _wasContractStorageAlreadyChanged); function commitContractStorage(address _contract, bytes32 _key) external returns (bool _wasContractStorageCommitted); function incrementTotalUncommittedContractStorage() external; function getTotalUncommittedContractStorage() external view returns (uint256 _total); function wasContractStorageChanged(address _contract, bytes32 _key) external view returns (bool); function wasContractStorageCommitted(address _contract, bytes32 _key) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /* Contract Imports */ import { iOVM_StateManager } from "./iOVM_StateManager.sol"; /** * @title iOVM_StateManagerFactory */ interface iOVM_StateManagerFactory { /*************************************** * Public Functions: Contract Creation * ***************************************/ function create( address _owner ) external returns ( iOVM_StateManager _ovmStateManager ); } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; interface ERC20 { function transfer(address, uint256) external returns (bool); function transferFrom(address, address, uint256) external returns (bool); } /// All the errors which may be encountered on the bond manager library Errors { string constant ERC20_ERR = "BondManager: Could not post bond"; string constant ALREADY_FINALIZED = "BondManager: Fraud proof for this pre-state root has already been finalized"; string constant SLASHED = "BondManager: Cannot finalize withdrawal, you probably got slashed"; string constant WRONG_STATE = "BondManager: Wrong bond state for proposer"; string constant CANNOT_CLAIM = "BondManager: Cannot claim yet. Dispute must be finalized first"; string constant WITHDRAWAL_PENDING = "BondManager: Withdrawal already pending"; string constant TOO_EARLY = "BondManager: Too early to finalize your withdrawal"; string constant ONLY_TRANSITIONER = "BondManager: Only the transitioner for this pre-state root may call this function"; string constant ONLY_FRAUD_VERIFIER = "BondManager: Only the fraud verifier may call this function"; string constant ONLY_STATE_COMMITMENT_CHAIN = "BondManager: Only the state commitment chain may call this function"; string constant WAIT_FOR_DISPUTES = "BondManager: Wait for other potential disputes"; } /** * @title iOVM_BondManager */ interface iOVM_BondManager { /******************* * Data Structures * *******************/ /// The lifecycle of a proposer's bond enum State { // Before depositing or after getting slashed, a user is uncollateralized NOT_COLLATERALIZED, // After depositing, a user is collateralized COLLATERALIZED, // After a user has initiated a withdrawal WITHDRAWING } /// A bond posted by a proposer struct Bond { // The user's state State state; // The timestamp at which a proposer issued their withdrawal request uint32 withdrawalTimestamp; // The time when the first disputed was initiated for this bond uint256 firstDisputeAt; // The earliest observed state root for this bond which has had fraud bytes32 earliestDisputedStateRoot; // The state root's timestamp uint256 earliestTimestamp; } // Per pre-state root, store the number of state provisions that were made // and how many of these calls were made by each user. Payouts will then be // claimed by users proportionally for that dispute. struct Rewards { // Flag to check if rewards for a fraud proof are claimable bool canClaim; // Total number of `recordGasSpent` calls made uint256 total; // The gas spent by each user to provide witness data. The sum of all // values inside this map MUST be equal to the value of `total` mapping(address => uint256) gasSpent; } /******************** * Public Functions * ********************/ function recordGasSpent( bytes32 _preStateRoot, bytes32 _txHash, address _who, uint256 _gasSpent ) external; function finalize( bytes32 _preStateRoot, address _publisher, uint256 _timestamp ) external; function deposit() external; function startWithdrawal() external; function finalizeWithdrawal() external; function claim( address _who ) external; function isCollateralized( address _who ) external view returns (bool); function getGasSpent( bytes32 _preStateRoot, address _who ) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol"; /* Interface Imports */ import { iOVM_StateTransitioner } from "./iOVM_StateTransitioner.sol"; /** * @title iOVM_FraudVerifier */ interface iOVM_FraudVerifier { /********** * Events * **********/ event FraudProofInitialized( bytes32 _preStateRoot, uint256 _preStateRootIndex, bytes32 _transactionHash, address _who ); event FraudProofFinalized( bytes32 _preStateRoot, uint256 _preStateRootIndex, bytes32 _transactionHash, address _who ); /*************************************** * Public Functions: Transition Status * ***************************************/ function getStateTransitioner(bytes32 _preStateRoot, bytes32 _txHash) external view returns (iOVM_StateTransitioner _transitioner); /**************************************** * Public Functions: Fraud Verification * ****************************************/ function initializeFraudVerification( bytes32 _preStateRoot, Lib_OVMCodec.ChainBatchHeader calldata _preStateRootBatchHeader, Lib_OVMCodec.ChainInclusionProof calldata _preStateRootProof, Lib_OVMCodec.Transaction calldata _transaction, Lib_OVMCodec.TransactionChainElement calldata _txChainElement, Lib_OVMCodec.ChainBatchHeader calldata _transactionBatchHeader, Lib_OVMCodec.ChainInclusionProof calldata _transactionProof ) external; function finalizeFraudVerification( bytes32 _preStateRoot, Lib_OVMCodec.ChainBatchHeader calldata _preStateRootBatchHeader, Lib_OVMCodec.ChainInclusionProof calldata _preStateRootProof, bytes32 _txHash, bytes32 _postStateRoot, Lib_OVMCodec.ChainBatchHeader calldata _postStateRootBatchHeader, Lib_OVMCodec.ChainInclusionProof calldata _postStateRootProof ) external; } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol"; /** * @title iOVM_StateTransitioner */ interface iOVM_StateTransitioner { /********** * Events * **********/ event AccountCommitted( address _address ); event ContractStorageCommitted( address _address, bytes32 _key ); /********************************** * Public Functions: State Access * **********************************/ function getPreStateRoot() external view returns (bytes32 _preStateRoot); function getPostStateRoot() external view returns (bytes32 _postStateRoot); function isComplete() external view returns (bool _complete); /*********************************** * Public Functions: Pre-Execution * ***********************************/ function proveContractState( address _ovmContractAddress, address _ethContractAddress, bytes calldata _stateTrieWitness ) external; function proveStorageSlot( address _ovmContractAddress, bytes32 _key, bytes calldata _storageTrieWitness ) external; /******************************* * Public Functions: Execution * *******************************/ function applyTransaction( Lib_OVMCodec.Transaction calldata _transaction ) external; /************************************ * Public Functions: Post-Execution * ************************************/ function commitContractState( address _ovmContractAddress, bytes calldata _stateTrieWitness ) external; function commitStorageSlot( address _ovmContractAddress, bytes32 _key, bytes calldata _storageTrieWitness ) external; /********************************** * Public Functions: Finalization * **********************************/ function completeTransition() external; } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /* Contract Imports */ import { iOVM_StateTransitioner } from "./iOVM_StateTransitioner.sol"; /** * @title iOVM_StateTransitionerFactory */ interface iOVM_StateTransitionerFactory { /*************************************** * Public Functions: Contract Creation * ***************************************/ function create( address _proxyManager, uint256 _stateTransitionIndex, bytes32 _preStateRoot, bytes32 _transactionHash ) external returns ( iOVM_StateTransitioner _ovmStateTransitioner ); } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_RLPReader } from "../rlp/Lib_RLPReader.sol"; import { Lib_RLPWriter } from "../rlp/Lib_RLPWriter.sol"; import { Lib_BytesUtils } from "../utils/Lib_BytesUtils.sol"; import { Lib_Bytes32Utils } from "../utils/Lib_Bytes32Utils.sol"; /** * @title Lib_OVMCodec */ library Lib_OVMCodec { /********* * Enums * *********/ enum QueueOrigin { SEQUENCER_QUEUE, L1TOL2_QUEUE } /*********** * Structs * ***********/ struct Account { uint256 nonce; uint256 balance; bytes32 storageRoot; bytes32 codeHash; address ethAddress; bool isFresh; } struct EVMAccount { uint256 nonce; uint256 balance; bytes32 storageRoot; bytes32 codeHash; } struct ChainBatchHeader { uint256 batchIndex; bytes32 batchRoot; uint256 batchSize; uint256 prevTotalElements; bytes extraData; } struct ChainInclusionProof { uint256 index; bytes32[] siblings; } struct Transaction { uint256 timestamp; uint256 blockNumber; QueueOrigin l1QueueOrigin; address l1TxOrigin; address entrypoint; uint256 gasLimit; bytes data; } struct TransactionChainElement { bool isSequenced; uint256 queueIndex; // QUEUED TX ONLY uint256 timestamp; // SEQUENCER TX ONLY uint256 blockNumber; // SEQUENCER TX ONLY bytes txData; // SEQUENCER TX ONLY } struct QueueElement { bytes32 transactionHash; uint40 timestamp; uint40 blockNumber; } /********************** * Internal Functions * **********************/ /** * Encodes a standard OVM transaction. * @param _transaction OVM transaction to encode. * @return Encoded transaction bytes. */ function encodeTransaction( Transaction memory _transaction ) internal pure returns ( bytes memory ) { return abi.encodePacked( _transaction.timestamp, _transaction.blockNumber, _transaction.l1QueueOrigin, _transaction.l1TxOrigin, _transaction.entrypoint, _transaction.gasLimit, _transaction.data ); } /** * Hashes a standard OVM transaction. * @param _transaction OVM transaction to encode. * @return Hashed transaction */ function hashTransaction( Transaction memory _transaction ) internal pure returns ( bytes32 ) { return keccak256(encodeTransaction(_transaction)); } /** * Converts an OVM account to an EVM account. * @param _in OVM account to convert. * @return Converted EVM account. */ function toEVMAccount( Account memory _in ) internal pure returns ( EVMAccount memory ) { return EVMAccount({ nonce: _in.nonce, balance: _in.balance, storageRoot: _in.storageRoot, codeHash: _in.codeHash }); } /** * @notice RLP-encodes an account state struct. * @param _account Account state struct. * @return RLP-encoded account state. */ function encodeEVMAccount( EVMAccount memory _account ) internal pure returns ( bytes memory ) { bytes[] memory raw = new bytes[](4); // Unfortunately we can't create this array outright because // Lib_RLPWriter.writeList will reject fixed-size arrays. Assigning // index-by-index circumvents this issue. raw[0] = Lib_RLPWriter.writeBytes( Lib_Bytes32Utils.removeLeadingZeros( bytes32(_account.nonce) ) ); raw[1] = Lib_RLPWriter.writeBytes( Lib_Bytes32Utils.removeLeadingZeros( bytes32(_account.balance) ) ); raw[2] = Lib_RLPWriter.writeBytes(abi.encodePacked(_account.storageRoot)); raw[3] = Lib_RLPWriter.writeBytes(abi.encodePacked(_account.codeHash)); return Lib_RLPWriter.writeList(raw); } /** * @notice Decodes an RLP-encoded account state into a useful struct. * @param _encoded RLP-encoded account state. * @return Account state struct. */ function decodeEVMAccount( bytes memory _encoded ) internal pure returns ( EVMAccount memory ) { Lib_RLPReader.RLPItem[] memory accountState = Lib_RLPReader.readList(_encoded); return EVMAccount({ nonce: Lib_RLPReader.readUint256(accountState[0]), balance: Lib_RLPReader.readUint256(accountState[1]), storageRoot: Lib_RLPReader.readBytes32(accountState[2]), codeHash: Lib_RLPReader.readBytes32(accountState[3]) }); } /** * Calculates a hash for a given batch header. * @param _batchHeader Header to hash. * @return Hash of the header. */ function hashBatchHeader( Lib_OVMCodec.ChainBatchHeader memory _batchHeader ) internal pure returns ( bytes32 ) { return keccak256( abi.encode( _batchHeader.batchRoot, _batchHeader.batchSize, _batchHeader.prevTotalElements, _batchHeader.extraData ) ); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /* External Imports */ import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol"; /** * @title Lib_AddressManager */ contract Lib_AddressManager is Ownable { /********** * Events * **********/ event AddressSet( string _name, address _newAddress ); /************* * Variables * *************/ mapping (bytes32 => address) private addresses; /******************** * Public Functions * ********************/ /** * Changes the address associated with a particular name. * @param _name String name to associate an address with. * @param _address Address to associate with the name. */ function setAddress( string memory _name, address _address ) external onlyOwner { addresses[_getNameHash(_name)] = _address; emit AddressSet( _name, _address ); } /** * Retrieves the address associated with a given name. * @param _name Name to retrieve an address for. * @return Address associated with the given name. */ function getAddress( string memory _name ) external view returns ( address ) { return addresses[_getNameHash(_name)]; } /********************** * Internal Functions * **********************/ /** * Computes the hash of a name. * @param _name Name to compute a hash for. * @return Hash of the given name. */ function _getNameHash( string memory _name ) internal pure returns ( bytes32 ) { return keccak256(abi.encodePacked(_name)); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /* Library Imports */ import { Lib_AddressManager } from "./Lib_AddressManager.sol"; /** * @title Lib_AddressResolver */ abstract contract Lib_AddressResolver { /************* * Variables * *************/ Lib_AddressManager public libAddressManager; /*************** * Constructor * ***************/ /** * @param _libAddressManager Address of the Lib_AddressManager. */ constructor( address _libAddressManager ) { libAddressManager = Lib_AddressManager(_libAddressManager); } /******************** * Public Functions * ********************/ /** * Resolves the address associated with a given name. * @param _name Name to resolve an address for. * @return Address associated with the given name. */ function resolve( string memory _name ) public view returns ( address ) { return libAddressManager.getAddress(_name); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /** * @title Lib_RLPReader * @dev Adapted from "RLPReader" by Hamdi Allam ([email protected]). */ library Lib_RLPReader { /************* * Constants * *************/ uint256 constant internal MAX_LIST_LENGTH = 32; /********* * Enums * *********/ enum RLPItemType { DATA_ITEM, LIST_ITEM } /*********** * Structs * ***********/ struct RLPItem { uint256 length; uint256 ptr; } /********************** * Internal Functions * **********************/ /** * Converts bytes to a reference to memory position and length. * @param _in Input bytes to convert. * @return Output memory reference. */ function toRLPItem( bytes memory _in ) internal pure returns ( RLPItem memory ) { uint256 ptr; assembly { ptr := add(_in, 32) } return RLPItem({ length: _in.length, ptr: ptr }); } /** * Reads an RLP list value into a list of RLP items. * @param _in RLP list value. * @return Decoded RLP list items. */ function readList( RLPItem memory _in ) internal pure returns ( RLPItem[] memory ) { ( uint256 listOffset, , RLPItemType itemType ) = _decodeLength(_in); require( itemType == RLPItemType.LIST_ITEM, "Invalid RLP list value." ); // Solidity in-memory arrays can't be increased in size, but *can* be decreased in size by // writing to the length. Since we can't know the number of RLP items without looping over // the entire input, we'd have to loop twice to accurately size this array. It's easier to // simply set a reasonable maximum list length and decrease the size before we finish. RLPItem[] memory out = new RLPItem[](MAX_LIST_LENGTH); uint256 itemCount = 0; uint256 offset = listOffset; while (offset < _in.length) { require( itemCount < MAX_LIST_LENGTH, "Provided RLP list exceeds max list length." ); ( uint256 itemOffset, uint256 itemLength, ) = _decodeLength(RLPItem({ length: _in.length - offset, ptr: _in.ptr + offset })); out[itemCount] = RLPItem({ length: itemLength + itemOffset, ptr: _in.ptr + offset }); itemCount += 1; offset += itemOffset + itemLength; } // Decrease the array size to match the actual item count. assembly { mstore(out, itemCount) } return out; } /** * Reads an RLP list value into a list of RLP items. * @param _in RLP list value. * @return Decoded RLP list items. */ function readList( bytes memory _in ) internal pure returns ( RLPItem[] memory ) { return readList( toRLPItem(_in) ); } /** * Reads an RLP bytes value into bytes. * @param _in RLP bytes value. * @return Decoded bytes. */ function readBytes( RLPItem memory _in ) internal pure returns ( bytes memory ) { ( uint256 itemOffset, uint256 itemLength, RLPItemType itemType ) = _decodeLength(_in); require( itemType == RLPItemType.DATA_ITEM, "Invalid RLP bytes value." ); return _copy(_in.ptr, itemOffset, itemLength); } /** * Reads an RLP bytes value into bytes. * @param _in RLP bytes value. * @return Decoded bytes. */ function readBytes( bytes memory _in ) internal pure returns ( bytes memory ) { return readBytes( toRLPItem(_in) ); } /** * Reads an RLP string value into a string. * @param _in RLP string value. * @return Decoded string. */ function readString( RLPItem memory _in ) internal pure returns ( string memory ) { return string(readBytes(_in)); } /** * Reads an RLP string value into a string. * @param _in RLP string value. * @return Decoded string. */ function readString( bytes memory _in ) internal pure returns ( string memory ) { return readString( toRLPItem(_in) ); } /** * Reads an RLP bytes32 value into a bytes32. * @param _in RLP bytes32 value. * @return Decoded bytes32. */ function readBytes32( RLPItem memory _in ) internal pure returns ( bytes32 ) { require( _in.length <= 33, "Invalid RLP bytes32 value." ); ( uint256 itemOffset, uint256 itemLength, RLPItemType itemType ) = _decodeLength(_in); require( itemType == RLPItemType.DATA_ITEM, "Invalid RLP bytes32 value." ); uint256 ptr = _in.ptr + itemOffset; bytes32 out; assembly { out := mload(ptr) // Shift the bytes over to match the item size. if lt(itemLength, 32) { out := div(out, exp(256, sub(32, itemLength))) } } return out; } /** * Reads an RLP bytes32 value into a bytes32. * @param _in RLP bytes32 value. * @return Decoded bytes32. */ function readBytes32( bytes memory _in ) internal pure returns ( bytes32 ) { return readBytes32( toRLPItem(_in) ); } /** * Reads an RLP uint256 value into a uint256. * @param _in RLP uint256 value. * @return Decoded uint256. */ function readUint256( RLPItem memory _in ) internal pure returns ( uint256 ) { return uint256(readBytes32(_in)); } /** * Reads an RLP uint256 value into a uint256. * @param _in RLP uint256 value. * @return Decoded uint256. */ function readUint256( bytes memory _in ) internal pure returns ( uint256 ) { return readUint256( toRLPItem(_in) ); } /** * Reads an RLP bool value into a bool. * @param _in RLP bool value. * @return Decoded bool. */ function readBool( RLPItem memory _in ) internal pure returns ( bool ) { require( _in.length == 1, "Invalid RLP boolean value." ); uint256 ptr = _in.ptr; uint256 out; assembly { out := byte(0, mload(ptr)) } require( out == 0 || out == 1, "Lib_RLPReader: Invalid RLP boolean value, must be 0 or 1" ); return out != 0; } /** * Reads an RLP bool value into a bool. * @param _in RLP bool value. * @return Decoded bool. */ function readBool( bytes memory _in ) internal pure returns ( bool ) { return readBool( toRLPItem(_in) ); } /** * Reads an RLP address value into a address. * @param _in RLP address value. * @return Decoded address. */ function readAddress( RLPItem memory _in ) internal pure returns ( address ) { if (_in.length == 1) { return address(0); } require( _in.length == 21, "Invalid RLP address value." ); return address(readUint256(_in)); } /** * Reads an RLP address value into a address. * @param _in RLP address value. * @return Decoded address. */ function readAddress( bytes memory _in ) internal pure returns ( address ) { return readAddress( toRLPItem(_in) ); } /** * Reads the raw bytes of an RLP item. * @param _in RLP item to read. * @return Raw RLP bytes. */ function readRawBytes( RLPItem memory _in ) internal pure returns ( bytes memory ) { return _copy(_in); } /********************* * Private Functions * *********************/ /** * Decodes the length of an RLP item. * @param _in RLP item to decode. * @return Offset of the encoded data. * @return Length of the encoded data. * @return RLP item type (LIST_ITEM or DATA_ITEM). */ function _decodeLength( RLPItem memory _in ) private pure returns ( uint256, uint256, RLPItemType ) { require( _in.length > 0, "RLP item cannot be null." ); uint256 ptr = _in.ptr; uint256 prefix; assembly { prefix := byte(0, mload(ptr)) } if (prefix <= 0x7f) { // Single byte. return (0, 1, RLPItemType.DATA_ITEM); } else if (prefix <= 0xb7) { // Short string. uint256 strLen = prefix - 0x80; require( _in.length > strLen, "Invalid RLP short string." ); return (1, strLen, RLPItemType.DATA_ITEM); } else if (prefix <= 0xbf) { // Long string. uint256 lenOfStrLen = prefix - 0xb7; require( _in.length > lenOfStrLen, "Invalid RLP long string length." ); uint256 strLen; assembly { // Pick out the string length. strLen := div( mload(add(ptr, 1)), exp(256, sub(32, lenOfStrLen)) ) } require( _in.length > lenOfStrLen + strLen, "Invalid RLP long string." ); return (1 + lenOfStrLen, strLen, RLPItemType.DATA_ITEM); } else if (prefix <= 0xf7) { // Short list. uint256 listLen = prefix - 0xc0; require( _in.length > listLen, "Invalid RLP short list." ); return (1, listLen, RLPItemType.LIST_ITEM); } else { // Long list. uint256 lenOfListLen = prefix - 0xf7; require( _in.length > lenOfListLen, "Invalid RLP long list length." ); uint256 listLen; assembly { // Pick out the list length. listLen := div( mload(add(ptr, 1)), exp(256, sub(32, lenOfListLen)) ) } require( _in.length > lenOfListLen + listLen, "Invalid RLP long list." ); return (1 + lenOfListLen, listLen, RLPItemType.LIST_ITEM); } } /** * Copies the bytes from a memory location. * @param _src Pointer to the location to read from. * @param _offset Offset to start reading from. * @param _length Number of bytes to read. * @return Copied bytes. */ function _copy( uint256 _src, uint256 _offset, uint256 _length ) private pure returns ( bytes memory ) { bytes memory out = new bytes(_length); if (out.length == 0) { return out; } uint256 src = _src + _offset; uint256 dest; assembly { dest := add(out, 32) } // Copy over as many complete words as we can. for (uint256 i = 0; i < _length / 32; i++) { assembly { mstore(dest, mload(src)) } src += 32; dest += 32; } // Pick out the remaining bytes. uint256 mask = 256 ** (32 - (_length % 32)) - 1; assembly { mstore( dest, or( and(mload(src), not(mask)), and(mload(dest), mask) ) ) } return out; } /** * Copies an RLP item into bytes. * @param _in RLP item to copy. * @return Copied bytes. */ function _copy( RLPItem memory _in ) private pure returns ( bytes memory ) { return _copy(_in.ptr, 0, _in.length); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /** * @title Lib_RLPWriter * @author Bakaoh (with modifications) */ library Lib_RLPWriter { /********************** * Internal Functions * **********************/ /** * RLP encodes a byte string. * @param _in The byte string to encode. * @return The RLP encoded string in bytes. */ function writeBytes( bytes memory _in ) internal pure returns ( bytes memory ) { bytes memory encoded; if (_in.length == 1 && uint8(_in[0]) < 128) { encoded = _in; } else { encoded = abi.encodePacked(_writeLength(_in.length, 128), _in); } return encoded; } /** * RLP encodes a list of RLP encoded byte byte strings. * @param _in The list of RLP encoded byte strings. * @return The RLP encoded list of items in bytes. */ function writeList( bytes[] memory _in ) internal pure returns ( bytes memory ) { bytes memory list = _flatten(_in); return abi.encodePacked(_writeLength(list.length, 192), list); } /** * RLP encodes a string. * @param _in The string to encode. * @return The RLP encoded string in bytes. */ function writeString( string memory _in ) internal pure returns ( bytes memory ) { return writeBytes(bytes(_in)); } /** * RLP encodes an address. * @param _in The address to encode. * @return The RLP encoded address in bytes. */ function writeAddress( address _in ) internal pure returns ( bytes memory ) { return writeBytes(abi.encodePacked(_in)); } /** * RLP encodes a bytes32 value. * @param _in The bytes32 to encode. * @return _out The RLP encoded bytes32 in bytes. */ function writeBytes32( bytes32 _in ) internal pure returns ( bytes memory _out ) { return writeBytes(abi.encodePacked(_in)); } /** * RLP encodes a uint. * @param _in The uint256 to encode. * @return The RLP encoded uint256 in bytes. */ function writeUint( uint256 _in ) internal pure returns ( bytes memory ) { return writeBytes(_toBinary(_in)); } /** * RLP encodes a bool. * @param _in The bool to encode. * @return The RLP encoded bool in bytes. */ function writeBool( bool _in ) internal pure returns ( bytes memory ) { bytes memory encoded = new bytes(1); encoded[0] = (_in ? bytes1(0x01) : bytes1(0x80)); return encoded; } /********************* * Private Functions * *********************/ /** * Encode the first byte, followed by the `len` in binary form if `length` is more than 55. * @param _len The length of the string or the payload. * @param _offset 128 if item is string, 192 if item is list. * @return RLP encoded bytes. */ function _writeLength( uint256 _len, uint256 _offset ) private pure returns ( bytes memory ) { bytes memory encoded; if (_len < 56) { encoded = new bytes(1); encoded[0] = byte(uint8(_len) + uint8(_offset)); } else { uint256 lenLen; uint256 i = 1; while (_len / i != 0) { lenLen++; i *= 256; } encoded = new bytes(lenLen + 1); encoded[0] = byte(uint8(lenLen) + uint8(_offset) + 55); for(i = 1; i <= lenLen; i++) { encoded[i] = byte(uint8((_len / (256**(lenLen-i))) % 256)); } } return encoded; } /** * Encode integer in big endian binary form with no leading zeroes. * @notice TODO: This should be optimized with assembly to save gas costs. * @param _x The integer to encode. * @return RLP encoded bytes. */ function _toBinary( uint256 _x ) private pure returns ( bytes memory ) { bytes memory b = abi.encodePacked(_x); uint256 i = 0; for (; i < 32; i++) { if (b[i] != 0) { break; } } bytes memory res = new bytes(32 - i); for (uint256 j = 0; j < res.length; j++) { res[j] = b[i++]; } return res; } /** * Copies a piece of memory to another location. * @notice From: https://github.com/Arachnid/solidity-stringutils/blob/master/src/strings.sol. * @param _dest Destination location. * @param _src Source location. * @param _len Length of memory to copy. */ function _memcpy( uint256 _dest, uint256 _src, uint256 _len ) private pure { uint256 dest = _dest; uint256 src = _src; uint256 len = _len; for(; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } uint256 mask = 256 ** (32 - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } } /** * Flattens a list of byte strings into one byte string. * @notice From: https://github.com/sammayo/solidity-rlp-encoder/blob/master/RLPEncode.sol. * @param _list List of byte strings to flatten. * @return The flattened byte string. */ function _flatten( bytes[] memory _list ) private pure returns ( bytes memory ) { if (_list.length == 0) { return new bytes(0); } uint256 len; uint256 i = 0; for (; i < _list.length; i++) { len += _list[i].length; } bytes memory flattened = new bytes(len); uint256 flattenedPtr; assembly { flattenedPtr := add(flattened, 0x20) } for(i = 0; i < _list.length; i++) { bytes memory item = _list[i]; uint256 listPtr; assembly { listPtr := add(item, 0x20)} _memcpy(flattenedPtr, listPtr, item.length); flattenedPtr += _list[i].length; } return flattened; } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /* Library Imports */ import { Lib_BytesUtils } from "../utils/Lib_BytesUtils.sol"; import { Lib_RLPReader } from "../rlp/Lib_RLPReader.sol"; import { Lib_RLPWriter } from "../rlp/Lib_RLPWriter.sol"; /** * @title Lib_MerkleTrie */ library Lib_MerkleTrie { /******************* * Data Structures * *******************/ enum NodeType { BranchNode, ExtensionNode, LeafNode } struct TrieNode { bytes encoded; Lib_RLPReader.RLPItem[] decoded; } /********************** * Contract Constants * **********************/ // TREE_RADIX determines the number of elements per branch node. uint256 constant TREE_RADIX = 16; // Branch nodes have TREE_RADIX elements plus an additional `value` slot. uint256 constant BRANCH_NODE_LENGTH = TREE_RADIX + 1; // Leaf nodes and extension nodes always have two elements, a `path` and a `value`. uint256 constant LEAF_OR_EXTENSION_NODE_LENGTH = 2; // Prefixes are prepended to the `path` within a leaf or extension node and // allow us to differentiate between the two node types. `ODD` or `EVEN` is // determined by the number of nibbles within the unprefixed `path`. If the // number of nibbles if even, we need to insert an extra padding nibble so // the resulting prefixed `path` has an even number of nibbles. uint8 constant PREFIX_EXTENSION_EVEN = 0; uint8 constant PREFIX_EXTENSION_ODD = 1; uint8 constant PREFIX_LEAF_EVEN = 2; uint8 constant PREFIX_LEAF_ODD = 3; // Just a utility constant. RLP represents `NULL` as 0x80. bytes1 constant RLP_NULL = bytes1(0x80); bytes constant RLP_NULL_BYTES = hex'80'; bytes32 constant internal KECCAK256_RLP_NULL_BYTES = keccak256(RLP_NULL_BYTES); /********************** * Internal Functions * **********************/ /** * @notice Verifies a proof that a given key/value pair is present in the * Merkle trie. * @param _key Key of the node to search for, as a hex string. * @param _value Value of the node to search for, as a hex string. * @param _proof Merkle trie inclusion proof for the desired node. Unlike * traditional Merkle trees, this proof is executed top-down and consists * of a list of RLP-encoded nodes that make a path down to the target node. * @param _root Known root of the Merkle trie. Used to verify that the * included proof is correctly constructed. * @return _verified `true` if the k/v pair exists in the trie, `false` otherwise. */ function verifyInclusionProof( bytes memory _key, bytes memory _value, bytes memory _proof, bytes32 _root ) internal pure returns ( bool _verified ) { ( bool exists, bytes memory value ) = get(_key, _proof, _root); return ( exists && Lib_BytesUtils.equal(_value, value) ); } /** * @notice Updates a Merkle trie and returns a new root hash. * @param _key Key of the node to update, as a hex string. * @param _value Value of the node to update, as a hex string. * @param _proof Merkle trie inclusion proof for the node *nearest* the * target node. If the key exists, we can simply update the value. * Otherwise, we need to modify the trie to handle the new k/v pair. * @param _root Known root of the Merkle trie. Used to verify that the * included proof is correctly constructed. * @return _updatedRoot Root hash of the newly constructed trie. */ function update( bytes memory _key, bytes memory _value, bytes memory _proof, bytes32 _root ) internal pure returns ( bytes32 _updatedRoot ) { // Special case when inserting the very first node. if (_root == KECCAK256_RLP_NULL_BYTES) { return getSingleNodeRootHash(_key, _value); } TrieNode[] memory proof = _parseProof(_proof); (uint256 pathLength, bytes memory keyRemainder, ) = _walkNodePath(proof, _key, _root); TrieNode[] memory newPath = _getNewPath(proof, pathLength, _key, keyRemainder, _value); return _getUpdatedTrieRoot(newPath, _key); } /** * @notice Retrieves the value associated with a given key. * @param _key Key to search for, as hex bytes. * @param _proof Merkle trie inclusion proof for the key. * @param _root Known root of the Merkle trie. * @return _exists Whether or not the key exists. * @return _value Value of the key if it exists. */ function get( bytes memory _key, bytes memory _proof, bytes32 _root ) internal pure returns ( bool _exists, bytes memory _value ) { TrieNode[] memory proof = _parseProof(_proof); (uint256 pathLength, bytes memory keyRemainder, bool isFinalNode) = _walkNodePath(proof, _key, _root); bool exists = keyRemainder.length == 0; require( exists || isFinalNode, "Provided proof is invalid." ); bytes memory value = exists ? _getNodeValue(proof[pathLength - 1]) : bytes(''); return ( exists, value ); } /** * Computes the root hash for a trie with a single node. * @param _key Key for the single node. * @param _value Value for the single node. * @return _updatedRoot Hash of the trie. */ function getSingleNodeRootHash( bytes memory _key, bytes memory _value ) internal pure returns ( bytes32 _updatedRoot ) { return keccak256(_makeLeafNode( Lib_BytesUtils.toNibbles(_key), _value ).encoded); } /********************* * Private Functions * *********************/ /** * @notice Walks through a proof using a provided key. * @param _proof Inclusion proof to walk through. * @param _key Key to use for the walk. * @param _root Known root of the trie. * @return _pathLength Length of the final path * @return _keyRemainder Portion of the key remaining after the walk. * @return _isFinalNode Whether or not we've hit a dead end. */ function _walkNodePath( TrieNode[] memory _proof, bytes memory _key, bytes32 _root ) private pure returns ( uint256 _pathLength, bytes memory _keyRemainder, bool _isFinalNode ) { uint256 pathLength = 0; bytes memory key = Lib_BytesUtils.toNibbles(_key); bytes32 currentNodeID = _root; uint256 currentKeyIndex = 0; uint256 currentKeyIncrement = 0; TrieNode memory currentNode; // Proof is top-down, so we start at the first element (root). for (uint256 i = 0; i < _proof.length; i++) { currentNode = _proof[i]; currentKeyIndex += currentKeyIncrement; // Keep track of the proof elements we actually need. // It's expensive to resize arrays, so this simply reduces gas costs. pathLength += 1; if (currentKeyIndex == 0) { // First proof element is always the root node. require( keccak256(currentNode.encoded) == currentNodeID, "Invalid root hash" ); } else if (currentNode.encoded.length >= 32) { // Nodes 32 bytes or larger are hashed inside branch nodes. require( keccak256(currentNode.encoded) == currentNodeID, "Invalid large internal hash" ); } else { // Nodes smaller than 31 bytes aren't hashed. require( Lib_BytesUtils.toBytes32(currentNode.encoded) == currentNodeID, "Invalid internal node hash" ); } if (currentNode.decoded.length == BRANCH_NODE_LENGTH) { if (currentKeyIndex == key.length) { // We've hit the end of the key, meaning the value should be within this branch node. break; } else { // We're not at the end of the key yet. // Figure out what the next node ID should be and continue. uint8 branchKey = uint8(key[currentKeyIndex]); Lib_RLPReader.RLPItem memory nextNode = currentNode.decoded[branchKey]; currentNodeID = _getNodeID(nextNode); currentKeyIncrement = 1; continue; } } else if (currentNode.decoded.length == LEAF_OR_EXTENSION_NODE_LENGTH) { bytes memory path = _getNodePath(currentNode); uint8 prefix = uint8(path[0]); uint8 offset = 2 - prefix % 2; bytes memory pathRemainder = Lib_BytesUtils.slice(path, offset); bytes memory keyRemainder = Lib_BytesUtils.slice(key, currentKeyIndex); uint256 sharedNibbleLength = _getSharedNibbleLength(pathRemainder, keyRemainder); if (prefix == PREFIX_LEAF_EVEN || prefix == PREFIX_LEAF_ODD) { if ( pathRemainder.length == sharedNibbleLength && keyRemainder.length == sharedNibbleLength ) { // The key within this leaf matches our key exactly. // Increment the key index to reflect that we have no remainder. currentKeyIndex += sharedNibbleLength; } // We've hit a leaf node, so our next node should be NULL. currentNodeID = bytes32(RLP_NULL); break; } else if (prefix == PREFIX_EXTENSION_EVEN || prefix == PREFIX_EXTENSION_ODD) { if (sharedNibbleLength != pathRemainder.length) { // Our extension node is not identical to the remainder. // We've hit the end of this path, updates will need to modify this extension. currentNodeID = bytes32(RLP_NULL); break; } else { // Our extension shares some nibbles. // Carry on to the next node. currentNodeID = _getNodeID(currentNode.decoded[1]); currentKeyIncrement = sharedNibbleLength; continue; } } else { revert("Received a node with an unknown prefix"); } } else { revert("Received an unparseable node."); } } // If our node ID is NULL, then we're at a dead end. bool isFinalNode = currentNodeID == bytes32(RLP_NULL); return (pathLength, Lib_BytesUtils.slice(key, currentKeyIndex), isFinalNode); } /** * @notice Creates new nodes to support a k/v pair insertion into a given Merkle trie path. * @param _path Path to the node nearest the k/v pair. * @param _pathLength Length of the path. Necessary because the provided path may include * additional nodes (e.g., it comes directly from a proof) and we can't resize in-memory * arrays without costly duplication. * @param _key Full original key. * @param _keyRemainder Portion of the initial key that must be inserted into the trie. * @param _value Value to insert at the given key. * @return _newPath A new path with the inserted k/v pair and extra supporting nodes. */ function _getNewPath( TrieNode[] memory _path, uint256 _pathLength, bytes memory _key, bytes memory _keyRemainder, bytes memory _value ) private pure returns ( TrieNode[] memory _newPath ) { bytes memory keyRemainder = _keyRemainder; // Most of our logic depends on the status of the last node in the path. TrieNode memory lastNode = _path[_pathLength - 1]; NodeType lastNodeType = _getNodeType(lastNode); // Create an array for newly created nodes. // We need up to three new nodes, depending on the contents of the last node. // Since array resizing is expensive, we'll keep track of the size manually. // We're using an explicit `totalNewNodes += 1` after insertions for clarity. TrieNode[] memory newNodes = new TrieNode[](3); uint256 totalNewNodes = 0; // Reference: https://github.com/ethereumjs/merkle-patricia-tree/blob/c0a10395aab37d42c175a47114ebfcbd7efcf059/src/baseTrie.ts#L294-L313 bool matchLeaf = false; if (lastNodeType == NodeType.LeafNode) { uint256 l = 0; if (_path.length > 0) { for (uint256 i = 0; i < _path.length - 1; i++) { if (_getNodeType(_path[i]) == NodeType.BranchNode) { l++; } else { l += _getNodeKey(_path[i]).length; } } } if ( _getSharedNibbleLength( _getNodeKey(lastNode), Lib_BytesUtils.slice(Lib_BytesUtils.toNibbles(_key), l) ) == _getNodeKey(lastNode).length && keyRemainder.length == 0 ) { matchLeaf = true; } } if (matchLeaf) { // We've found a leaf node with the given key. // Simply need to update the value of the node to match. newNodes[totalNewNodes] = _makeLeafNode(_getNodeKey(lastNode), _value); totalNewNodes += 1; } else if (lastNodeType == NodeType.BranchNode) { if (keyRemainder.length == 0) { // We've found a branch node with the given key. // Simply need to update the value of the node to match. newNodes[totalNewNodes] = _editBranchValue(lastNode, _value); totalNewNodes += 1; } else { // We've found a branch node, but it doesn't contain our key. // Reinsert the old branch for now. newNodes[totalNewNodes] = lastNode; totalNewNodes += 1; // Create a new leaf node, slicing our remainder since the first byte points // to our branch node. newNodes[totalNewNodes] = _makeLeafNode(Lib_BytesUtils.slice(keyRemainder, 1), _value); totalNewNodes += 1; } } else { // Our last node is either an extension node or a leaf node with a different key. bytes memory lastNodeKey = _getNodeKey(lastNode); uint256 sharedNibbleLength = _getSharedNibbleLength(lastNodeKey, keyRemainder); if (sharedNibbleLength != 0) { // We've got some shared nibbles between the last node and our key remainder. // We'll need to insert an extension node that covers these shared nibbles. bytes memory nextNodeKey = Lib_BytesUtils.slice(lastNodeKey, 0, sharedNibbleLength); newNodes[totalNewNodes] = _makeExtensionNode(nextNodeKey, _getNodeHash(_value)); totalNewNodes += 1; // Cut down the keys since we've just covered these shared nibbles. lastNodeKey = Lib_BytesUtils.slice(lastNodeKey, sharedNibbleLength); keyRemainder = Lib_BytesUtils.slice(keyRemainder, sharedNibbleLength); } // Create an empty branch to fill in. TrieNode memory newBranch = _makeEmptyBranchNode(); if (lastNodeKey.length == 0) { // Key remainder was larger than the key for our last node. // The value within our last node is therefore going to be shifted into // a branch value slot. newBranch = _editBranchValue(newBranch, _getNodeValue(lastNode)); } else { // Last node key was larger than the key remainder. // We're going to modify some index of our branch. uint8 branchKey = uint8(lastNodeKey[0]); // Move on to the next nibble. lastNodeKey = Lib_BytesUtils.slice(lastNodeKey, 1); if (lastNodeType == NodeType.LeafNode) { // We're dealing with a leaf node. // We'll modify the key and insert the old leaf node into the branch index. TrieNode memory modifiedLastNode = _makeLeafNode(lastNodeKey, _getNodeValue(lastNode)); newBranch = _editBranchIndex(newBranch, branchKey, _getNodeHash(modifiedLastNode.encoded)); } else if (lastNodeKey.length != 0) { // We're dealing with a shrinking extension node. // We need to modify the node to decrease the size of the key. TrieNode memory modifiedLastNode = _makeExtensionNode(lastNodeKey, _getNodeValue(lastNode)); newBranch = _editBranchIndex(newBranch, branchKey, _getNodeHash(modifiedLastNode.encoded)); } else { // We're dealing with an unnecessary extension node. // We're going to delete the node entirely. // Simply insert its current value into the branch index. newBranch = _editBranchIndex(newBranch, branchKey, _getNodeValue(lastNode)); } } if (keyRemainder.length == 0) { // We've got nothing left in the key remainder. // Simply insert the value into the branch value slot. newBranch = _editBranchValue(newBranch, _value); // Push the branch into the list of new nodes. newNodes[totalNewNodes] = newBranch; totalNewNodes += 1; } else { // We've got some key remainder to work with. // We'll be inserting a leaf node into the trie. // First, move on to the next nibble. keyRemainder = Lib_BytesUtils.slice(keyRemainder, 1); // Push the branch into the list of new nodes. newNodes[totalNewNodes] = newBranch; totalNewNodes += 1; // Push a new leaf node for our k/v pair. newNodes[totalNewNodes] = _makeLeafNode(keyRemainder, _value); totalNewNodes += 1; } } // Finally, join the old path with our newly created nodes. // Since we're overwriting the last node in the path, we use `_pathLength - 1`. return _joinNodeArrays(_path, _pathLength - 1, newNodes, totalNewNodes); } /** * @notice Computes the trie root from a given path. * @param _nodes Path to some k/v pair. * @param _key Key for the k/v pair. * @return _updatedRoot Root hash for the updated trie. */ function _getUpdatedTrieRoot( TrieNode[] memory _nodes, bytes memory _key ) private pure returns ( bytes32 _updatedRoot ) { bytes memory key = Lib_BytesUtils.toNibbles(_key); // Some variables to keep track of during iteration. TrieNode memory currentNode; NodeType currentNodeType; bytes memory previousNodeHash; // Run through the path backwards to rebuild our root hash. for (uint256 i = _nodes.length; i > 0; i--) { // Pick out the current node. currentNode = _nodes[i - 1]; currentNodeType = _getNodeType(currentNode); if (currentNodeType == NodeType.LeafNode) { // Leaf nodes are already correctly encoded. // Shift the key over to account for the nodes key. bytes memory nodeKey = _getNodeKey(currentNode); key = Lib_BytesUtils.slice(key, 0, key.length - nodeKey.length); } else if (currentNodeType == NodeType.ExtensionNode) { // Shift the key over to account for the nodes key. bytes memory nodeKey = _getNodeKey(currentNode); key = Lib_BytesUtils.slice(key, 0, key.length - nodeKey.length); // If this node is the last element in the path, it'll be correctly encoded // and we can skip this part. if (previousNodeHash.length > 0) { // Re-encode the node based on the previous node. currentNode = _editExtensionNodeValue(currentNode, previousNodeHash); } } else if (currentNodeType == NodeType.BranchNode) { // If this node is the last element in the path, it'll be correctly encoded // and we can skip this part. if (previousNodeHash.length > 0) { // Re-encode the node based on the previous node. uint8 branchKey = uint8(key[key.length - 1]); key = Lib_BytesUtils.slice(key, 0, key.length - 1); currentNode = _editBranchIndex(currentNode, branchKey, previousNodeHash); } } // Compute the node hash for the next iteration. previousNodeHash = _getNodeHash(currentNode.encoded); } // Current node should be the root at this point. // Simply return the hash of its encoding. return keccak256(currentNode.encoded); } /** * @notice Parses an RLP-encoded proof into something more useful. * @param _proof RLP-encoded proof to parse. * @return _parsed Proof parsed into easily accessible structs. */ function _parseProof( bytes memory _proof ) private pure returns ( TrieNode[] memory _parsed ) { Lib_RLPReader.RLPItem[] memory nodes = Lib_RLPReader.readList(_proof); TrieNode[] memory proof = new TrieNode[](nodes.length); for (uint256 i = 0; i < nodes.length; i++) { bytes memory encoded = Lib_RLPReader.readBytes(nodes[i]); proof[i] = TrieNode({ encoded: encoded, decoded: Lib_RLPReader.readList(encoded) }); } return proof; } /** * @notice Picks out the ID for a node. Node ID is referred to as the * "hash" within the specification, but nodes < 32 bytes are not actually * hashed. * @param _node Node to pull an ID for. * @return _nodeID ID for the node, depending on the size of its contents. */ function _getNodeID( Lib_RLPReader.RLPItem memory _node ) private pure returns ( bytes32 _nodeID ) { bytes memory nodeID; if (_node.length < 32) { // Nodes smaller than 32 bytes are RLP encoded. nodeID = Lib_RLPReader.readRawBytes(_node); } else { // Nodes 32 bytes or larger are hashed. nodeID = Lib_RLPReader.readBytes(_node); } return Lib_BytesUtils.toBytes32(nodeID); } /** * @notice Gets the path for a leaf or extension node. * @param _node Node to get a path for. * @return _path Node path, converted to an array of nibbles. */ function _getNodePath( TrieNode memory _node ) private pure returns ( bytes memory _path ) { return Lib_BytesUtils.toNibbles(Lib_RLPReader.readBytes(_node.decoded[0])); } /** * @notice Gets the key for a leaf or extension node. Keys are essentially * just paths without any prefix. * @param _node Node to get a key for. * @return _key Node key, converted to an array of nibbles. */ function _getNodeKey( TrieNode memory _node ) private pure returns ( bytes memory _key ) { return _removeHexPrefix(_getNodePath(_node)); } /** * @notice Gets the path for a node. * @param _node Node to get a value for. * @return _value Node value, as hex bytes. */ function _getNodeValue( TrieNode memory _node ) private pure returns ( bytes memory _value ) { return Lib_RLPReader.readBytes(_node.decoded[_node.decoded.length - 1]); } /** * @notice Computes the node hash for an encoded node. Nodes < 32 bytes * are not hashed, all others are keccak256 hashed. * @param _encoded Encoded node to hash. * @return _hash Hash of the encoded node. Simply the input if < 32 bytes. */ function _getNodeHash( bytes memory _encoded ) private pure returns ( bytes memory _hash ) { if (_encoded.length < 32) { return _encoded; } else { return abi.encodePacked(keccak256(_encoded)); } } /** * @notice Determines the type for a given node. * @param _node Node to determine a type for. * @return _type Type of the node; BranchNode/ExtensionNode/LeafNode. */ function _getNodeType( TrieNode memory _node ) private pure returns ( NodeType _type ) { if (_node.decoded.length == BRANCH_NODE_LENGTH) { return NodeType.BranchNode; } else if (_node.decoded.length == LEAF_OR_EXTENSION_NODE_LENGTH) { bytes memory path = _getNodePath(_node); uint8 prefix = uint8(path[0]); if (prefix == PREFIX_LEAF_EVEN || prefix == PREFIX_LEAF_ODD) { return NodeType.LeafNode; } else if (prefix == PREFIX_EXTENSION_EVEN || prefix == PREFIX_EXTENSION_ODD) { return NodeType.ExtensionNode; } } revert("Invalid node type"); } /** * @notice Utility; determines the number of nibbles shared between two * nibble arrays. * @param _a First nibble array. * @param _b Second nibble array. * @return _shared Number of shared nibbles. */ function _getSharedNibbleLength( bytes memory _a, bytes memory _b ) private pure returns ( uint256 _shared ) { uint256 i = 0; while (_a.length > i && _b.length > i && _a[i] == _b[i]) { i++; } return i; } /** * @notice Utility; converts an RLP-encoded node into our nice struct. * @param _raw RLP-encoded node to convert. * @return _node Node as a TrieNode struct. */ function _makeNode( bytes[] memory _raw ) private pure returns ( TrieNode memory _node ) { bytes memory encoded = Lib_RLPWriter.writeList(_raw); return TrieNode({ encoded: encoded, decoded: Lib_RLPReader.readList(encoded) }); } /** * @notice Utility; converts an RLP-decoded node into our nice struct. * @param _items RLP-decoded node to convert. * @return _node Node as a TrieNode struct. */ function _makeNode( Lib_RLPReader.RLPItem[] memory _items ) private pure returns ( TrieNode memory _node ) { bytes[] memory raw = new bytes[](_items.length); for (uint256 i = 0; i < _items.length; i++) { raw[i] = Lib_RLPReader.readRawBytes(_items[i]); } return _makeNode(raw); } /** * @notice Creates a new extension node. * @param _key Key for the extension node, unprefixed. * @param _value Value for the extension node. * @return _node New extension node with the given k/v pair. */ function _makeExtensionNode( bytes memory _key, bytes memory _value ) private pure returns ( TrieNode memory _node ) { bytes[] memory raw = new bytes[](2); bytes memory key = _addHexPrefix(_key, false); raw[0] = Lib_RLPWriter.writeBytes(Lib_BytesUtils.fromNibbles(key)); raw[1] = Lib_RLPWriter.writeBytes(_value); return _makeNode(raw); } /** * Creates a new extension node with the same key but a different value. * @param _node Extension node to copy and modify. * @param _value New value for the extension node. * @return New node with the same key and different value. */ function _editExtensionNodeValue( TrieNode memory _node, bytes memory _value ) private pure returns ( TrieNode memory ) { bytes[] memory raw = new bytes[](2); bytes memory key = _addHexPrefix(_getNodeKey(_node), false); raw[0] = Lib_RLPWriter.writeBytes(Lib_BytesUtils.fromNibbles(key)); if (_value.length < 32) { raw[1] = _value; } else { raw[1] = Lib_RLPWriter.writeBytes(_value); } return _makeNode(raw); } /** * @notice Creates a new leaf node. * @dev This function is essentially identical to `_makeExtensionNode`. * Although we could route both to a single method with a flag, it's * more gas efficient to keep them separate and duplicate the logic. * @param _key Key for the leaf node, unprefixed. * @param _value Value for the leaf node. * @return _node New leaf node with the given k/v pair. */ function _makeLeafNode( bytes memory _key, bytes memory _value ) private pure returns ( TrieNode memory _node ) { bytes[] memory raw = new bytes[](2); bytes memory key = _addHexPrefix(_key, true); raw[0] = Lib_RLPWriter.writeBytes(Lib_BytesUtils.fromNibbles(key)); raw[1] = Lib_RLPWriter.writeBytes(_value); return _makeNode(raw); } /** * @notice Creates an empty branch node. * @return _node Empty branch node as a TrieNode struct. */ function _makeEmptyBranchNode() private pure returns ( TrieNode memory _node ) { bytes[] memory raw = new bytes[](BRANCH_NODE_LENGTH); for (uint256 i = 0; i < raw.length; i++) { raw[i] = RLP_NULL_BYTES; } return _makeNode(raw); } /** * @notice Modifies the value slot for a given branch. * @param _branch Branch node to modify. * @param _value Value to insert into the branch. * @return _updatedNode Modified branch node. */ function _editBranchValue( TrieNode memory _branch, bytes memory _value ) private pure returns ( TrieNode memory _updatedNode ) { bytes memory encoded = Lib_RLPWriter.writeBytes(_value); _branch.decoded[_branch.decoded.length - 1] = Lib_RLPReader.toRLPItem(encoded); return _makeNode(_branch.decoded); } /** * @notice Modifies a slot at an index for a given branch. * @param _branch Branch node to modify. * @param _index Slot index to modify. * @param _value Value to insert into the slot. * @return _updatedNode Modified branch node. */ function _editBranchIndex( TrieNode memory _branch, uint8 _index, bytes memory _value ) private pure returns ( TrieNode memory _updatedNode ) { bytes memory encoded = _value.length < 32 ? _value : Lib_RLPWriter.writeBytes(_value); _branch.decoded[_index] = Lib_RLPReader.toRLPItem(encoded); return _makeNode(_branch.decoded); } /** * @notice Utility; adds a prefix to a key. * @param _key Key to prefix. * @param _isLeaf Whether or not the key belongs to a leaf. * @return _prefixedKey Prefixed key. */ function _addHexPrefix( bytes memory _key, bool _isLeaf ) private pure returns ( bytes memory _prefixedKey ) { uint8 prefix = _isLeaf ? uint8(0x02) : uint8(0x00); uint8 offset = uint8(_key.length % 2); bytes memory prefixed = new bytes(2 - offset); prefixed[0] = bytes1(prefix + offset); return abi.encodePacked(prefixed, _key); } /** * @notice Utility; removes a prefix from a path. * @param _path Path to remove the prefix from. * @return _unprefixedKey Unprefixed key. */ function _removeHexPrefix( bytes memory _path ) private pure returns ( bytes memory _unprefixedKey ) { if (uint8(_path[0]) % 2 == 0) { return Lib_BytesUtils.slice(_path, 2); } else { return Lib_BytesUtils.slice(_path, 1); } } /** * @notice Utility; combines two node arrays. Array lengths are required * because the actual lengths may be longer than the filled lengths. * Array resizing is extremely costly and should be avoided. * @param _a First array to join. * @param _aLength Length of the first array. * @param _b Second array to join. * @param _bLength Length of the second array. * @return _joined Combined node array. */ function _joinNodeArrays( TrieNode[] memory _a, uint256 _aLength, TrieNode[] memory _b, uint256 _bLength ) private pure returns ( TrieNode[] memory _joined ) { TrieNode[] memory ret = new TrieNode[](_aLength + _bLength); // Copy elements from the first array. for (uint256 i = 0; i < _aLength; i++) { ret[i] = _a[i]; } // Copy elements from the second array. for (uint256 i = 0; i < _bLength; i++) { ret[i + _aLength] = _b[i]; } return ret; } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_MerkleTrie } from "./Lib_MerkleTrie.sol"; /** * @title Lib_SecureMerkleTrie */ library Lib_SecureMerkleTrie { /********************** * Internal Functions * **********************/ /** * @notice Verifies a proof that a given key/value pair is present in the * Merkle trie. * @param _key Key of the node to search for, as a hex string. * @param _value Value of the node to search for, as a hex string. * @param _proof Merkle trie inclusion proof for the desired node. Unlike * traditional Merkle trees, this proof is executed top-down and consists * of a list of RLP-encoded nodes that make a path down to the target node. * @param _root Known root of the Merkle trie. Used to verify that the * included proof is correctly constructed. * @return _verified `true` if the k/v pair exists in the trie, `false` otherwise. */ function verifyInclusionProof( bytes memory _key, bytes memory _value, bytes memory _proof, bytes32 _root ) internal pure returns ( bool _verified ) { bytes memory key = _getSecureKey(_key); return Lib_MerkleTrie.verifyInclusionProof(key, _value, _proof, _root); } /** * @notice Updates a Merkle trie and returns a new root hash. * @param _key Key of the node to update, as a hex string. * @param _value Value of the node to update, as a hex string. * @param _proof Merkle trie inclusion proof for the node *nearest* the * target node. If the key exists, we can simply update the value. * Otherwise, we need to modify the trie to handle the new k/v pair. * @param _root Known root of the Merkle trie. Used to verify that the * included proof is correctly constructed. * @return _updatedRoot Root hash of the newly constructed trie. */ function update( bytes memory _key, bytes memory _value, bytes memory _proof, bytes32 _root ) internal pure returns ( bytes32 _updatedRoot ) { bytes memory key = _getSecureKey(_key); return Lib_MerkleTrie.update(key, _value, _proof, _root); } /** * @notice Retrieves the value associated with a given key. * @param _key Key to search for, as hex bytes. * @param _proof Merkle trie inclusion proof for the key. * @param _root Known root of the Merkle trie. * @return _exists Whether or not the key exists. * @return _value Value of the key if it exists. */ function get( bytes memory _key, bytes memory _proof, bytes32 _root ) internal pure returns ( bool _exists, bytes memory _value ) { bytes memory key = _getSecureKey(_key); return Lib_MerkleTrie.get(key, _proof, _root); } /** * Computes the root hash for a trie with a single node. * @param _key Key for the single node. * @param _value Value for the single node. * @return _updatedRoot Hash of the trie. */ function getSingleNodeRootHash( bytes memory _key, bytes memory _value ) internal pure returns ( bytes32 _updatedRoot ) { bytes memory key = _getSecureKey(_key); return Lib_MerkleTrie.getSingleNodeRootHash(key, _value); } /********************* * Private Functions * *********************/ /** * Computes the secure counterpart to a key. * @param _key Key to get a secure key from. * @return _secureKey Secure version of the key. */ function _getSecureKey( bytes memory _key ) private pure returns ( bytes memory _secureKey ) { return abi.encodePacked(keccak256(_key)); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /** * @title Lib_Byte32Utils */ library Lib_Bytes32Utils { /********************** * Internal Functions * **********************/ /** * Converts a bytes32 value to a boolean. Anything non-zero will be converted to "true." * @param _in Input bytes32 value. * @return Bytes32 as a boolean. */ function toBool( bytes32 _in ) internal pure returns ( bool ) { return _in != 0; } /** * Converts a boolean to a bytes32 value. * @param _in Input boolean value. * @return Boolean as a bytes32. */ function fromBool( bool _in ) internal pure returns ( bytes32 ) { return bytes32(uint256(_in ? 1 : 0)); } /** * Converts a bytes32 value to an address. Takes the *last* 20 bytes. * @param _in Input bytes32 value. * @return Bytes32 as an address. */ function toAddress( bytes32 _in ) internal pure returns ( address ) { return address(uint160(uint256(_in))); } /** * Converts an address to a bytes32. * @param _in Input address value. * @return Address as a bytes32. */ function fromAddress( address _in ) internal pure returns ( bytes32 ) { return bytes32(uint256(_in)); } /** * Removes the leading zeros from a bytes32 value and returns a new (smaller) bytes value. * @param _in Input bytes32 value. * @return Bytes32 without any leading zeros. */ function removeLeadingZeros( bytes32 _in ) internal pure returns ( bytes memory ) { bytes memory out; assembly { // Figure out how many leading zero bytes to remove. let shift := 0 for { let i := 0 } and(lt(i, 32), eq(byte(i, _in), 0)) { i := add(i, 1) } { shift := add(shift, 1) } // Reserve some space for our output and fix the free memory pointer. out := mload(0x40) mstore(0x40, add(out, 0x40)) // Shift the value and store it into the output bytes. mstore(add(out, 0x20), shl(mul(shift, 8), _in)) // Store the new size (with leading zero bytes removed) in the output byte size. mstore(out, sub(32, shift)) } return out; } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /** * @title Lib_BytesUtils */ library Lib_BytesUtils { /********************** * Internal Functions * **********************/ function slice( bytes memory _bytes, uint256 _start, uint256 _length ) internal pure returns ( bytes memory ) { require(_length + 31 >= _length, "slice_overflow"); require(_start + _length >= _start, "slice_overflow"); require(_bytes.length >= _start + _length, "slice_outOfBounds"); bytes memory tempBytes; assembly { switch iszero(_length) case 0 { // Get a location of some free memory and store it in tempBytes as // Solidity does for memory variables. tempBytes := mload(0x40) // The first word of the slice result is potentially a partial // word read from the original array. To read it, we calculate // the length of that partial word and start copying that many // bytes into the array. The first word we copy will start with // data we don't care about, but the last `lengthmod` bytes will // land at the beginning of the contents of the new array. When // we're done copying, we overwrite the full first word with // the actual length of the slice. let lengthmod := and(_length, 31) // The multiplication in the next line is necessary // because when slicing multiples of 32 bytes (lengthmod == 0) // the following copy loop was copying the origin's length // and then ending prematurely not copying everything it should. let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod))) let end := add(mc, _length) for { // The multiplication in the next line has the same exact purpose // as the one above. let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } mstore(tempBytes, _length) //update free-memory pointer //allocating the array padded to 32 bytes like the compiler does now mstore(0x40, and(add(mc, 31), not(31))) } //if we want a zero-length slice let's just return a zero-length array default { tempBytes := mload(0x40) //zero out the 32 bytes slice we are about to return //we need to do it because Solidity does not garbage collect mstore(tempBytes, 0) mstore(0x40, add(tempBytes, 0x20)) } } return tempBytes; } function slice( bytes memory _bytes, uint256 _start ) internal pure returns ( bytes memory ) { if (_start >= _bytes.length) { return bytes(''); } return slice(_bytes, _start, _bytes.length - _start); } function toBytes32PadLeft( bytes memory _bytes ) internal pure returns ( bytes32 ) { bytes32 ret; uint256 len = _bytes.length <= 32 ? _bytes.length : 32; assembly { ret := shr(mul(sub(32, len), 8), mload(add(_bytes, 32))) } return ret; } function toBytes32( bytes memory _bytes ) internal pure returns ( bytes32 ) { if (_bytes.length < 32) { bytes32 ret; assembly { ret := mload(add(_bytes, 32)) } return ret; } return abi.decode(_bytes,(bytes32)); // will truncate if input length > 32 bytes } function toUint256( bytes memory _bytes ) internal pure returns ( uint256 ) { return uint256(toBytes32(_bytes)); } function toUint24( bytes memory _bytes, uint256 _start ) internal pure returns ( uint24 ) { require(_start + 3 >= _start, "toUint24_overflow"); require(_bytes.length >= _start + 3 , "toUint24_outOfBounds"); uint24 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x3), _start)) } return tempUint; } function toUint8( bytes memory _bytes, uint256 _start ) internal pure returns ( uint8 ) { require(_start + 1 >= _start, "toUint8_overflow"); require(_bytes.length >= _start + 1 , "toUint8_outOfBounds"); uint8 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x1), _start)) } return tempUint; } function toAddress( bytes memory _bytes, uint256 _start ) internal pure returns ( address ) { require(_start + 20 >= _start, "toAddress_overflow"); require(_bytes.length >= _start + 20, "toAddress_outOfBounds"); address tempAddress; assembly { tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000) } return tempAddress; } function toNibbles( bytes memory _bytes ) internal pure returns ( bytes memory ) { bytes memory nibbles = new bytes(_bytes.length * 2); for (uint256 i = 0; i < _bytes.length; i++) { nibbles[i * 2] = _bytes[i] >> 4; nibbles[i * 2 + 1] = bytes1(uint8(_bytes[i]) % 16); } return nibbles; } function fromNibbles( bytes memory _bytes ) internal pure returns ( bytes memory ) { bytes memory ret = new bytes(_bytes.length / 2); for (uint256 i = 0; i < ret.length; i++) { ret[i] = (_bytes[i * 2] << 4) | (_bytes[i * 2 + 1]); } return ret; } function equal( bytes memory _bytes, bytes memory _other ) internal pure returns ( bool ) { return keccak256(_bytes) == keccak256(_other); } } // SPDX-License-Identifier: MIT // @unsupported: ovm pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_RLPWriter } from "../rlp/Lib_RLPWriter.sol"; import { Lib_Bytes32Utils } from "./Lib_Bytes32Utils.sol"; /** * @title Lib_EthUtils */ library Lib_EthUtils { /********************** * Internal Functions * **********************/ /** * Gets the code for a given address. * @param _address Address to get code for. * @param _offset Offset to start reading from. * @param _length Number of bytes to read. * @return Code read from the contract. */ function getCode( address _address, uint256 _offset, uint256 _length ) internal view returns ( bytes memory ) { bytes memory code; assembly { code := mload(0x40) mstore(0x40, add(code, add(_length, 0x20))) mstore(code, _length) extcodecopy(_address, add(code, 0x20), _offset, _length) } return code; } /** * Gets the full code for a given address. * @param _address Address to get code for. * @return Full code of the contract. */ function getCode( address _address ) internal view returns ( bytes memory ) { return getCode( _address, 0, getCodeSize(_address) ); } /** * Gets the size of a contract's code in bytes. * @param _address Address to get code size for. * @return Size of the contract's code in bytes. */ function getCodeSize( address _address ) internal view returns ( uint256 ) { uint256 codeSize; assembly { codeSize := extcodesize(_address) } return codeSize; } /** * Gets the hash of a contract's code. * @param _address Address to get a code hash for. * @return Hash of the contract's code. */ function getCodeHash( address _address ) internal view returns ( bytes32 ) { bytes32 codeHash; assembly { codeHash := extcodehash(_address) } return codeHash; } /** * Creates a contract with some given initialization code. * @param _code Contract initialization code. * @return Address of the created contract. */ function createContract( bytes memory _code ) internal returns ( address ) { address created; assembly { created := create( 0, add(_code, 0x20), mload(_code) ) } return created; } /** * Computes the address that would be generated by CREATE. * @param _creator Address creating the contract. * @param _nonce Creator's nonce. * @return Address to be generated by CREATE. */ function getAddressForCREATE( address _creator, uint256 _nonce ) internal pure returns ( address ) { bytes[] memory encoded = new bytes[](2); encoded[0] = Lib_RLPWriter.writeAddress(_creator); encoded[1] = Lib_RLPWriter.writeUint(_nonce); bytes memory encodedList = Lib_RLPWriter.writeList(encoded); return Lib_Bytes32Utils.toAddress(keccak256(encodedList)); } /** * Computes the address that would be generated by CREATE2. * @param _creator Address creating the contract. * @param _bytecode Bytecode of the contract to be created. * @param _salt 32 byte salt value mixed into the hash. * @return Address to be generated by CREATE2. */ function getAddressForCREATE2( address _creator, bytes memory _bytecode, bytes32 _salt ) internal pure returns ( address ) { bytes32 hashedData = keccak256(abi.encodePacked( byte(0xff), _creator, _salt, keccak256(_bytecode) )); return Lib_Bytes32Utils.toAddress(hashedData); } }
Retrieves the state root after execution. return _postStateRoot State root after execution./
function getPostStateRoot() override external view returns ( bytes32 _postStateRoot ) { return postStateRoot; }
194,599
pragma solidity ^0.4.11; // 請使用solc 0.4.20編譯,否則會有問題 contract Owned { address owner; function Owned() { owner = msg.sender; } modifier onlyOwner() { if(msg.sender!=owner) throw; _; } } // 存放清算銀行客戶的在債券數量,以便於使用清算銀行及客戶帳號為key來查詢 // 注意Owner為TransactionMatcher contract contract Bank_Account is Owned { bytes32 bank_id; uint customers_cnt; bool private isOwnedNode = false; // 使用private transaction來設定flag, // 每個Bank_Account Contract只有在自己跟央行才會設flag // 以便判斷是在那個節點上跑 struct customer { bytes32 [] ids; mapping(bytes32 => securities_account) securities_accounts; // 以id為index mapping(bytes32 => bool) hasCustomer; } struct securities_account { bytes32 [] securities; // 債券清單 uint securities_cnt; mapping(bytes32 => int) total_amounts; // 總數量 以債券代號為index mapping(bytes32 => int) position_amounts; // 持有部位 以債券代號為index mapping(bytes32 => bool) hasSecurities; } customer private customers; function Bank_Account(bytes32 _bank_id) { bank_id = _bank_id; } function setOwnedNode(bool _is_true) onlyOwner { isOwnedNode = _is_true; } function checkOwnedNode() constant returns(bool) { return isOwnedNode; } // 設定客戶擁有債券數量,注意,清算銀行自己本身也有帳號 客戶持有部位也要增加 function setCustomerOwnedSecuritiesAmount(bytes32 _customer_id, bytes32 _securities_id, int _amount_total, bool _is_increase) onlyOwner { if(!customers.hasCustomer[_customer_id]) { customers.ids.push(_customer_id); customers_cnt++; customers.hasCustomer[_customer_id] = true; } if(!customers.securities_accounts[_customer_id].hasSecurities[_securities_id]) { customers.securities_accounts[_customer_id].securities.push(_securities_id); customers.securities_accounts[_customer_id].securities_cnt++; customers.securities_accounts[_customer_id].hasSecurities[_securities_id] = true; } int total_amount = customers.securities_accounts[_customer_id].total_amounts[_securities_id]; if(_is_increase) { total_amount += _amount_total; }else { total_amount -= _amount_total; } customers.securities_accounts[_customer_id].total_amounts[_securities_id] = total_amount; } function setCustomerOwnedSecuritiesPosition(bytes32 _customer_id, bytes32 _securities_id, int _amount, bool _is_increase) onlyOwner { int position_amount = customers.securities_accounts[_customer_id].position_amounts[_securities_id]; if(_is_increase) { position_amount += _amount; }else { position_amount -= _amount; } customers.securities_accounts[_customer_id].position_amounts[_securities_id] = position_amount; } function getCustomerSecuritiesTotalAmount(bytes32 _customer_id, bytes32 _securities_id) constant returns(int) { if(msg.sender != owner) { // do nothing, just return return(0); } return(customers.securities_accounts[_customer_id].total_amounts[_securities_id]); } function getCustomerSecuritiesPosition(bytes32 _customer_id, bytes32 _securities_id) constant returns(int) { if(msg.sender != owner) { // do nothing, just return return(0); } return(customers.securities_accounts[_customer_id].position_amounts[_securities_id]); } function getCustomerSecuritiesList(bytes32 _customer_id, uint index) constant returns (bytes32) { return(customers.securities_accounts[_customer_id].securities[index]); } function getCustomerSecuritiesListLength(bytes32 _customer_id) constant returns (uint) { return(customers.securities_accounts[_customer_id].securities_cnt); } function getCustomerList(uint index) constant returns (bytes32) { return(customers.ids[index]); } function getCustomerListLength() constant returns (uint) { return(customers_cnt); } } // 注意Owner為TransactionMatcher contract contract Securities is Owned{ bytes32 securities_id; // 公債代號 bytes32 owned_bank; uint banks_cnt; int amount; int available; // 還剩多少債券 // int unit_price; int interest_rateX10K; // *10000 i.e 2% interest_rate = 200 精確到小數點第二位 int start_tm; int end_tm; int period; // 單位:Year(每年一期) struct bank { bytes32 [] bank_ids; // 清算銀行list mapping(bytes32 => customers_account) customers_accounts; // 客戶account 以清算銀行為index mapping(bytes32 => bool) hasBank; // 以清算銀行為index mapping(bytes32 => int) banks_total_amount; // 清算銀行總帳(計算利息) 以清算銀行為index mapping(bytes32 => int) banks_position_amount; // 清算銀行持有部位(總帳 - 被圈存總帳) 以清算銀行為index } struct customers_account { bytes32 [] customer_ids; // 客戶帳號list uint customers_cnt; mapping(bytes32 => int) total_amounts; // 客戶擁有數量 以客戶帳號為index mapping(bytes32 => int) position_amounts; // 客戶持有部位(總帳 - 被圈存數量) 以客戶帳號為index mapping(bytes32 => bool) hasCustomer; // 是否有此客戶 以客戶帳號為index } bank private banks; function Securities(bytes32 _securities_id, int _amount, int _interest_rateX10K, int _start_tm, int _end_tm, int _period) { securities_id = _securities_id; owned_bank = "CB"; // centeral bank is the initial owner amount = _amount; available = _amount; //unit_price = _unit_price; interest_rateX10K = _interest_rateX10K; start_tm = _start_tm; end_tm = _end_tm; period = _period; } // 變更客戶擁有債券數量,注意,清算銀行自己本身也有帳號 function setCustomerOwnedSecuritiesAmount(bytes32 _bank_id, bytes32 _customer_id, int _amount_total, bool _is_increase) onlyOwner { if(!banks.hasBank[_bank_id]) { banks.bank_ids.push(_bank_id); banks.hasBank[_bank_id] = true; banks_cnt++; } if(!banks.customers_accounts[_bank_id].hasCustomer[_customer_id]) { banks.customers_accounts[_bank_id].customer_ids.push(_customer_id); banks.customers_accounts[_bank_id].customers_cnt++; banks.customers_accounts[_bank_id].hasCustomer[_customer_id] = true; } int customer_amount = banks.customers_accounts[_bank_id].total_amounts[_customer_id]; int bank_amount = banks.banks_total_amount[_bank_id]; //int customer_position_amount = banks.customers_accounts[_bank_id].position_amounts[_customer_id]; //int bank_position_amount = banks.banks_position_amount[_bank_id]; if(_is_increase) { customer_amount += _amount_total; bank_amount += _amount_total; available -= _amount_total; //customer_position_amount += _amount_total; //bank_position_amount += _amount_total; }else { customer_amount -= _amount_total; bank_amount -= _amount_total; available += _amount_total; //customer_position_amount -= _amount_total; //bank_position_amount -= _amount_total; } banks.customers_accounts[_bank_id].total_amounts[_customer_id] = customer_amount; banks.banks_total_amount[_bank_id] = bank_amount; //banks.customers_accounts[_bank_id].position_amounts[_customer_id] = customer_position_amount; //banks.banks_position_amount[_bank_id] = bank_position_amount; } // 設定圈存 function setCustomerOwnedSecuritiesPosition(bytes32 _bank_id, bytes32 _customer_id, int _amount, bool _is_increase) onlyOwner { int customer_position_amount = banks.customers_accounts[_bank_id].position_amounts[_customer_id]; int bank_position_amount = banks.banks_position_amount[_bank_id]; if(_is_increase) { customer_position_amount += _amount; bank_position_amount += _amount; }else { customer_position_amount -= _amount; bank_position_amount -= _amount; } banks.customers_accounts[_bank_id].position_amounts[_customer_id] = customer_position_amount; banks.banks_position_amount[_bank_id] = bank_position_amount; } function getSecuritiesStatus() constant returns(int, int) { return(amount, available); } function getSecuritiesInfo() constant returns(int, int, int, int) { return(interest_rateX10K, start_tm, end_tm, period); } function getCustomerTotalAmount(bytes32 _bank_id, bytes32 _customer_id) constant returns(int) { if(msg.sender != owner) { // do nothing, just return return(0); } return(banks.customers_accounts[_bank_id].total_amounts[_customer_id]); } function getCustomerPosition(bytes32 _bank_id, bytes32 _customer_id) constant returns(int) { if(msg.sender != owner) { // do nothing, just return return(0); } return(banks.customers_accounts[_bank_id].position_amounts[_customer_id]); } function getBankTotalAmount(bytes32 _bank_id) constant returns(int) { if(msg.sender != owner) { // do nothing, just return return(0); } return(banks.banks_total_amount[_bank_id]); } function getBankPosition(bytes32 _bank_id, bytes32 _customer_id) constant returns(int) { if(msg.sender != owner) { // do nothing, just return return(0); } return(banks.banks_position_amount[_bank_id]); } function getBankList(uint index) constant returns(bytes32) { return(banks.bank_ids[index]); } function getBankListLength() constant returns(uint) { return(banks_cnt); } } // TransactionMatcher必須由央行deploy 如此央行才能成為owner contract TransactionMatcher is Owned { //address private owner; //uint private maxQueueDepth; //uint private timeout; uint ServiceState; // 1: 開機 2: 營業開始 3: 停止接收預告 // 4: 停止接收電文 5: 處理跨行交易 6: 發送結帳資料 7: 關機 bytes32[] shareQueue; // 跨行交易用的queue bytes32[] privateQueue; // 自行交易用的queue function TransactionMatcher() { owner = msg.sender; //maxQueueDepth = 100; } enum TxnState { Pending, Matched, Finished, Cancelled, Waiting4Payment } struct Transaction { bytes32 txnSerNo; // 交易代號 bytes32 from_bank_id; // 賣方清算銀行代號 bytes32 from_customer_id; // 賣方帳號 bytes32 to_bank_id; // 買方清算銀行代號 bytes32 to_customer_id; // 買方帳號 int securities_amount; // 交易面額 int blocked_amount; // 圈存面額 bytes32 securities_id; // 債券代號 int payment; // 紀錄實際成交金額 TxnState state; // 交易狀態 uint timestamp; // 交易發送時間 bytes32 digest; // 交易摘要(MD5) 買賣雙方的交易摘要需相同才可比對 address msg_sender; // 發送交易之區塊鏈帳戶 bytes32 rev_txnSerNo; // 紀錄被更正之交易代號 int return_code; // 紀錄傳回值 } bytes32[] transactionIdx; mapping (bytes32 => Transaction) transactions; mapping (bytes32 => bool) isTransactionWaitingForMatch; // has a transaction registered in the list mapping (bytes32 => bytes32) txnDigest_SerNo1; // txn digest => txnSerNo //mapping (bytes32 => bytes32) txnDigest_SerNo2; // txn digest => txnSerNo bytes32[] banks_list; mapping (bytes32 => address) bankRegistry; //mapping (address => bytes32) acc2Bank; //mapping (bytes32 => address) bankAdmins; bytes32[] securities_list; uint securities_cnt; mapping (bytes32 => address) securitiesRegistry; mapping (bytes32 => bool) hasSecurities; /* modifier isBankOwner(bytes32 _bank_id) { require(msg.sender == owner || acc2Bank[msg.sender] == _bank_id); _; } */ event EventForCreateBank(bytes32 _bank_id); event EventForSetOwnedNode(bytes32 _bank_id); event EventForIssueSecurities(bytes32 _securities_id); event EventForRegisterCustomerOwnedSecuritiesAmount(bytes32 _securities_id, bytes32 _bank_id, bytes32 _customer_id, int _amount, bool _is_increase); event EventForSetServiceState(uint state); //event EventForSetCustomerOwnedSecuritiesPosition(bytes32 _securities_id, bytes32 _bank_id, bytes32 _customer_id, int _amount_total, bool _is_increase); // privateFor[央行與所有清算行] function createBank(bytes32 _bank_id, address _bankOwner) onlyOwner { address bank = new Bank_Account(_bank_id); bankRegistry[_bank_id] = bank; // 清算銀行Bank_Account合約位址 banks_list.push(_bank_id); //bankAdmins[_bank_id] = _bankOwner; EventForCreateBank(_bank_id); } // privateFor[央行與被建立的清算行] // 可以讓被建立的清算行利用checkOwnedNode傳回true判斷是自己的節點 因為節點不會看到別人的Bank_Account Contract function setOwnedNode(bytes32 _bank_id, bool _is_true) onlyOwner { Bank_Account bank = Bank_Account(bankRegistry[_bank_id]); bank.setOwnedNode(true); //bank.setBankContract(_bank_contract); EventForSetOwnedNode(_bank_id); } function issueSecurities(bytes32 _securities_id, int _amount, int _interest_rateX10K, int _start_tm, int _end_tm, int _period) onlyOwner { if(!hasSecurities[_securities_id]) { securities_list.push(_securities_id); hasSecurities[_securities_id]=true; securities_cnt++; } address securities = new Securities(_securities_id, _amount, _interest_rateX10K, _start_tm, _end_tm, _period); securitiesRegistry[_securities_id] = securities; EventForIssueSecurities(_securities_id); } function registerCustomerOwnedSecuritiesAmount(bytes32 _securities_id, bytes32 _bank_id, bytes32 _customer_id, int _amount, bool _is_increase) onlyOwner { setCustomerOwnedSecuritiesAmount(_securities_id,_bank_id,_customer_id,_amount,_is_increase); // 註冊時要順便增加/減少持有部位 setCustomerOwnedSecuritiesPosition(_securities_id,_bank_id,_customer_id,_amount,_is_increase); EventForRegisterCustomerOwnedSecuritiesAmount(_securities_id,_bank_id,_customer_id,_amount,_is_increase); } // 只能internal 呼叫,避免鏈外隨便可以改帳目 function setCustomerOwnedSecuritiesAmount(bytes32 _securities_id, bytes32 _bank_id, bytes32 _customer_id, int _amount, bool _is_increase) internal { Securities securities = Securities(securitiesRegistry[_securities_id]); securities.setCustomerOwnedSecuritiesAmount(_bank_id, _customer_id, _amount, _is_increase); Bank_Account bank = Bank_Account(bankRegistry[_bank_id]); bank.setCustomerOwnedSecuritiesAmount(_customer_id, _securities_id, _amount, _is_increase); //EventForSetCustomerOwnedSecuritiesAmount( _securities_id, _bank_id, _customer_id, _amount, _is_increase); } // 只能internal 呼叫,避免鏈外隨便可以改帳目 function setCustomerOwnedSecuritiesPosition(bytes32 _securities_id, bytes32 _bank_id, bytes32 _customer_id, int _amount, bool _is_increase) internal { Securities securities = Securities(securitiesRegistry[_securities_id]); securities.setCustomerOwnedSecuritiesPosition(_bank_id, _customer_id, _amount, _is_increase); Bank_Account bank = Bank_Account(bankRegistry[_bank_id]); bank.setCustomerOwnedSecuritiesPosition(_customer_id, _securities_id, _amount, _is_increase); //EventForSetCustomerOwnedSecuritiesPosition( _securities_id, _bank_id, _customer_id, _amount, _is_increase); } function getSecuritiesStatus(bytes32 _securities_id) constant returns(int,int) { Securities securities = Securities(securitiesRegistry[_securities_id]); var(a,b) = securities.getSecuritiesStatus(); return(a,b); } function getSecuritiesInfo(bytes32 _securities_id) constant returns(int,int,int,int) { Securities securities = Securities(securitiesRegistry[_securities_id]); var(a,b,c,d) = securities.getSecuritiesInfo(); return(a,b,c,d); } function getBankSecuritiesAmount(bytes32 _securities_id, bytes32 _bank_id) constant returns(int) { Securities securities = Securities(securitiesRegistry[_securities_id]); return(securities.getBankTotalAmount(_bank_id)); } function getCustomerSecuritiesAmount(bytes32 _securities_id, bytes32 _bank_id, bytes32 _customer_id) constant returns(int) { Securities securities = Securities(securitiesRegistry[_securities_id]); return(securities.getCustomerTotalAmount(_bank_id, _customer_id)); } function getCustomerSecuritiesPosition(bytes32 _securities_id, bytes32 _bank_id, bytes32 _customer_id) constant returns(int) { Securities securities = Securities(securitiesRegistry[_securities_id]); return(securities.getCustomerPosition(_bank_id, _customer_id)); } function getCustomerSecuritiesListLength(bytes32 _bank_id, bytes32 _customer_id) constant returns(uint) { Bank_Account bank = Bank_Account(bankRegistry[_bank_id]); return(bank.getCustomerSecuritiesListLength(_customer_id)); } function getCustomerSecuritiesList(bytes32 _bank_id, bytes32 _customer_id, uint index) constant returns(bytes32) { Bank_Account bank = Bank_Account(bankRegistry[_bank_id]); return(bank.getCustomerSecuritiesList(_customer_id, index)); } function getBankListLength(bytes32 _securities_id) constant returns(uint) { Securities securities = Securities(securitiesRegistry[_securities_id]); return(securities.getBankListLength()); } function getBankCustomerList(bytes32 _bank_id, uint index) constant returns(bytes32) { Bank_Account bank = Bank_Account(bankRegistry[_bank_id]); return(bank.getCustomerList(index)); } function getBankCustomerListLength(bytes32 _bank_id) constant returns(uint) { Bank_Account bank = Bank_Account(bankRegistry[_bank_id]); return(bank.getCustomerListLength()); } function getSecuritiesOwnedByBank(bytes32 _securities_id, uint index) constant returns(bytes32) { Securities securities = Securities(securitiesRegistry[_securities_id]); return(securities.getBankList(index)); } function getSecuritiesListLength() constant returns(uint) { return(securities_cnt); } function getSecuritiesList(uint index) constant returns(bytes32) { return(securities_list[index]); } //event EventForSecuritiesTransactionPending(bytes32 _txSerNo); event EventForSecuritiesTransactionPending(bytes32 _txSerNo); event EventForSecuritiesTransactionCancelled(bytes32 _txSerNo, int rc, string _reason); //event EventForSecuritiesTransactionError(bytes32 _txSerNo, int rc); //event EventForSecuritiesTransactionMatched(bytes32 _txSerNo1, bytes32 _txSerNo2); event EventForSecuritiesTransactionFinished(bytes32 _txSerNo1, bytes32 _txSerNo2); event EventForSecuritiesTransactionWaitingForPayment(bytes32 _txSerNo1, bytes32 _txSerNo2); event EventForSecuritiesTransactionPaymentError(bytes32 _txSerNo1, bytes32 _txSerNo2, int rc); // 可能為賣方清算行或是買方清算行呼叫,寫code時需要配合Quorum的private transaction的運作模式,privateFor[對方行,央行] // 注意,每筆交易每個在privateFor的node都會執行,寫code時要有這個思維。 function submitInterBankTransaction(bytes32 _txSerNo, bytes32 _from_bank_id, bytes32 _from_customer_id, bytes32 _to_bank_id, bytes32 _to_customer_id, int _securities_amount, bytes32 _securities_id, int _payment, bytes32 _digest) { Transaction memory this_txn; Bank_Account seller = Bank_Account(bankRegistry[_from_bank_id]); Bank_Account buyer = Bank_Account(bankRegistry[_to_bank_id]); if(seller.checkOwnedNode()) { // 賣方跟央行才能檢查,在買方節點無法檢查賣方的帳戶資料,這段code是必須的,否則在共識階段,買方節點上這交易會被cancel // 若Dapp有檢查,則這段程式跑不到,加這段檢查以防萬一 // 若為賣方清算行打進來的交易,則圈存賣方債券戶(DLT) 賣方跟央行才做這段 因為賣方跟央行都看得到賣方的Bank_Account Contract // 在共識階段,買方清算行節點會跳過這段,結果資料會跟賣方節點不同,但因為買方不需要也不能夠知道賣方的帳戶資料,因此這是必要的。 if(bytes1(uint8(uint(_txSerNo) / (2**((31 - 5) * 8)))) == 'S') { if( getCustomerSecuritiesPosition(_securities_id, _from_bank_id, _from_customer_id) < _securities_amount) { // 賣方(from)券數持有部位不足 this_txn = Transaction(_txSerNo, _from_bank_id, _from_customer_id, _to_bank_id, _to_customer_id, _securities_amount,0, _securities_id, _payment, TxnState.Cancelled, now, _digest, msg.sender, "", 3 ); transactionIdx.push(_txSerNo); transactions[_txSerNo] = this_txn; EventForSecuritiesTransactionCancelled(_txSerNo, 3, ""); return; } setCustomerOwnedSecuritiesPosition(_securities_id, _from_bank_id, _from_customer_id, _securities_amount, false); } } // 須處理買方先打交易 但是賣方券不夠 造成交易變成pending 賣方要打交易將買方節點該交易的狀態設為cancelled // matching transaction 交易比對 if( isTransactionWaitingForMatch[_digest]) { if (msg.sender == transactions[txnDigest_SerNo1[_digest]].msg_sender) { // 同一個msg.sender打相同交易進區塊鍊,設為Pending 因無法判斷是兩筆不同交易或是打錯 this_txn = Transaction(_txSerNo, _from_bank_id, _from_customer_id, _to_bank_id, _to_customer_id, _securities_amount, 0, _securities_id, _payment, TxnState.Pending, now, _digest, msg.sender, "", 0); transactionIdx.push(_txSerNo); transactions[_txSerNo] = this_txn; enShareQueue(_txSerNo); EventForSecuritiesTransactionPending(_txSerNo); return; }else { bytes32 _txSerNo1 = txnDigest_SerNo1[_digest]; setSecuritiesTransactionState(_txSerNo1, uint(TxnState.Waiting4Payment)); // 將前一筆狀態設為Waiting4Payment isTransactionWaitingForMatch[_digest] = false; delete isTransactionWaitingForMatch[_digest]; delete txnDigest_SerNo1[_digest]; // 注意:紀錄圈存額度 // 不管買方或賣方都要記錄圈存數量 this_txn = Transaction(_txSerNo, _from_bank_id, _from_customer_id, _to_bank_id, _to_customer_id, _securities_amount, _securities_amount, _securities_id, _payment, TxnState.Waiting4Payment, now, _digest, msg.sender, "", 0); transactionIdx.push(_txSerNo); transactions[_txSerNo] = this_txn; if(_payment == 0) { // FOP無款交易,不用到同資 // 更新DLT債券戶資訊 賣方跟央行才做這段 // 在共識階段,買方清算行節點會跳過這段,因此資料會跟賣方節點不同,但因為買方不需要也不能夠知道賣方的帳戶資料,因此這是必要的。 if(seller.checkOwnedNode()) { setCustomerOwnedSecuritiesAmount(_securities_id, _from_bank_id, _from_customer_id, _securities_amount, false); // 賣方已圈存,不須再增加持有部位 } // 更新DLT債券戶資訊 買方跟央行才做這段 // 在共識階段,賣方清算行節點會跳過這段,因此資料會跟買方節點不同,但因為賣方不需要也不能夠知道買方的帳戶資料,因此這是必要的。 if(buyer.checkOwnedNode()) { setCustomerOwnedSecuritiesAmount(_securities_id, _to_bank_id, _to_customer_id, _securities_amount, true); // 增加買方持有部位 setCustomerOwnedSecuritiesPosition(_securities_id, _to_bank_id, _to_customer_id, _securities_amount, true); } setSecuritiesTransactionState(_txSerNo, uint(TxnState.Finished)); // 將Transaction設為Finished setSecuritiesTransactionState(_txSerNo1, uint(TxnState.Finished)); // 將Transaction設為Finished // 移出Queue deShareQueue(_txSerNo); deShareQueue(_txSerNo1); EventForSecuritiesTransactionFinished(_txSerNo, _txSerNo1); }else { EventForSecuritiesTransactionWaitingForPayment(_txSerNo, _txSerNo1); } } }else { isTransactionWaitingForMatch[_digest] = true; // 不管買方或賣方都要記錄圈存數量 txnDigest_SerNo1[_digest] = _txSerNo; this_txn = Transaction(_txSerNo, _from_bank_id, _from_customer_id, _to_bank_id, _to_customer_id, _securities_amount, _securities_amount, _securities_id, _payment, TxnState.Pending, now, _digest, msg.sender, "", 0); transactionIdx.push(_txSerNo); transactions[_txSerNo] = this_txn; enShareQueue(_txSerNo); EventForSecuritiesTransactionPending(_txSerNo); } } // privateFor [央行] (交易只會在清算行本身及央行節點上面執行) function submitIntraBankTransaction(bytes32 _txSerNo, bytes32 _from_bank_id, bytes32 _from_customer_id, bytes32 _to_customer_id, int _securities_amount, bytes32 _securities_id, int _payment, bytes32 _digest) { Transaction memory this_txn; if(_from_customer_id == _to_customer_id) { // Do nothing // 賣方與買方為同一人 this_txn = Transaction(_txSerNo, _from_bank_id, _from_customer_id, _from_bank_id, _to_customer_id, _securities_amount, 0, _securities_id, _payment, TxnState.Cancelled, now, _digest, msg.sender, "", 2); transactionIdx.push(_txSerNo); transactions[_txSerNo] = this_txn; //enqueue(_txSerNo); //queued = true; EventForSecuritiesTransactionCancelled(_txSerNo, 2, ""); return; } // 賣方才檢查並圈存, if(bytes1(uint8(uint(_txSerNo) / (2**((31 - 5) * 8)))) == 'S') { if( getCustomerSecuritiesPosition(_securities_id, _from_bank_id, _from_customer_id) < _securities_amount) { // 賣方(from)券數持有部位不足 this_txn = Transaction(_txSerNo, _from_bank_id, _from_customer_id, _from_bank_id, _to_customer_id, _securities_amount, 0, _securities_id, _payment, TxnState.Cancelled, now, _digest, msg.sender, "", 3); transactionIdx.push(_txSerNo); transactions[_txSerNo] = this_txn; //enqueue(_txSerNo); //queued = true; EventForSecuritiesTransactionCancelled(_txSerNo, 3, ""); return; } //自行圈存賣方債券戶(DLT) setCustomerOwnedSecuritiesPosition(_securities_id, _from_bank_id, _from_customer_id, _securities_amount, false); } // matching transaction 交易比對 if( isTransactionWaitingForMatch[_digest]) { //Transaction 是 atomic 不用擔心Double Spending的問題 bytes32 _txSerNo1 = txnDigest_SerNo1[_digest]; setSecuritiesTransactionState(_txSerNo1, uint(TxnState.Matched)); isTransactionWaitingForMatch[_digest] = false; delete isTransactionWaitingForMatch[_digest]; delete txnDigest_SerNo1[_digest]; this_txn = Transaction(_txSerNo, _from_bank_id, _from_customer_id, _from_bank_id, _to_customer_id, _securities_amount, _securities_amount, _securities_id, _payment, TxnState.Matched, now, _digest, msg.sender, "", 0); transactionIdx.push(_txSerNo); transactions[_txSerNo] = this_txn; // 更新DLT債券戶資訊 setCustomerOwnedSecuritiesAmount(_securities_id, _from_bank_id, _from_customer_id, _securities_amount, false); setCustomerOwnedSecuritiesAmount(_securities_id, _from_bank_id, _to_customer_id, _securities_amount, true); // 賣方已圈存,不須再增加持有部位 //setCustomerOwnedSecuritiesPosition(_securities_id, _from_bank_id, _from_customer_id, _securities_amount, false); setCustomerOwnedSecuritiesPosition(_securities_id, _from_bank_id, _to_customer_id, _securities_amount, true); setSecuritiesTransactionState(_txSerNo, uint(TxnState.Finished)); // 將Transaction設為Finished setSecuritiesTransactionState(_txSerNo1, uint(TxnState.Finished)); // 將Transaction設為Finished dePrivateQueue(_txSerNo); dePrivateQueue(_txSerNo1); EventForSecuritiesTransactionFinished(_txSerNo, _txSerNo1); }else { isTransactionWaitingForMatch[_digest] = true; txnDigest_SerNo1[_digest] = _txSerNo; this_txn = Transaction(_txSerNo, _from_bank_id, _from_customer_id, _from_bank_id, _to_customer_id, _securities_amount, _securities_amount, _securities_id, _payment, TxnState.Pending, now, _digest, msg.sender, "", 0); transactionIdx.push(_txSerNo); transactions[_txSerNo] = this_txn; enPrivateQueue(_txSerNo); EventForSecuritiesTransactionPending(_txSerNo); } } // privateFor [央行] (交易只會在清算行本身及央行節點上面執行) // reason 不會存在Trsnactions裡面 但是在傳進來的過程中(Payload) 已經記錄在區塊裡 function submitSetTransactionCancelled(bytes32 _rev_txSerNo, bytes32 _txSerNo, int _rc, string _reason) { Transaction this_txn = transactions[_rev_txSerNo]; // 只有Pending與Waiting4Payment才處理 if( (this_txn.state == TxnState.Pending) || (this_txn.state == TxnState.Waiting4Payment) ) { // End-of-Day 時因為交易沒有發生,要解圈 //if(this_txn.state == TxnState.Waiting4Payment) { int _blocked_amount = this_txn.blocked_amount; bytes32 _securities_id = this_txn.securities_id; bytes32 _from_bank_id = this_txn.from_bank_id; bytes32 _from_customer_id = this_txn.from_customer_id; //買賣方跟央行都做這段,但買方做沒用,只是寫入無意義的別家清算行資料 //if(msg.sender == bankAdmins[_from_bank_id] || msg.sender == owner) { Bank_Account seller = Bank_Account(bankRegistry[_from_bank_id]); if(_rc == 5) { // 只有賣方發的交易才解圈 買方發的交易也會進來 因此用rc 分辨 if(seller.checkOwnedNode() && _blocked_amount > 0) { // 解除圈存 setCustomerOwnedSecuritiesPosition(_securities_id, _from_bank_id, _from_customer_id, _blocked_amount, true); } } //} this_txn.rev_txnSerNo = _txSerNo; this_txn.state = TxnState.Cancelled; this_txn.return_code = _rc; bytes32 _digest = getTransactionDigest(_rev_txSerNo); isTransactionWaitingForMatch[_digest] = false; delete isTransactionWaitingForMatch[_digest]; //setSecuritiesTransactionState(_rev_txSerNo, uint(TxnState.Cancelled)); Transaction _txn = transactions[_txSerNo]; _txn.rev_txnSerNo = _rev_txSerNo; EventForSecuritiesTransactionCancelled(_rev_txSerNo, _rc, _reason); } } // 同資回應後央行節點呼叫,只有央行可發動 function settleInterBankTransaction(bytes32 _txSerNo1, bytes32 _txSerNo2, int _cb_return_code, bool _isNettingSuccess) onlyOwner returns(bool) { Transaction txn1 = transactions[_txSerNo1]; Transaction txn2 = transactions[_txSerNo2]; Bank_Account seller = Bank_Account(bankRegistry[txn1.from_bank_id]); Bank_Account buyer = Bank_Account(bankRegistry[txn1.to_bank_id]); if(_isNettingSuccess == true) { if(seller.checkOwnedNode()) { // 更新DLT債券戶資訊 setCustomerOwnedSecuritiesAmount(txn1.securities_id, txn1.from_bank_id, txn1.from_customer_id, txn1.securities_amount, false); } if(buyer.checkOwnedNode()) { setCustomerOwnedSecuritiesAmount(txn1.securities_id, txn1.to_bank_id, txn1.to_customer_id, txn1.securities_amount, true); // 增加買方持有部位 setCustomerOwnedSecuritiesPosition(txn1.securities_id, txn1.to_bank_id, txn1.to_customer_id, txn1.securities_amount, true); } setSecuritiesTransactionState(_txSerNo1, uint(TxnState.Finished)); // 將Transaction設為Finished setSecuritiesTransactionState(_txSerNo2, uint(TxnState.Finished)); // 將Transaction設為Finished deShareQueue(_txSerNo1); deShareQueue(_txSerNo2); EventForSecuritiesTransactionFinished(_txSerNo1, _txSerNo2); }else { if(_cb_return_code == 500) { if(seller.checkOwnedNode()) { // 同資系統錯誤,解除圈存賣方債券戶(DLT) setCustomerOwnedSecuritiesPosition(txn1.securities_id, txn1.from_bank_id, txn1.from_customer_id, txn1.securities_amount, true); } setSecuritiesTransactionState(_txSerNo1, uint(TxnState.Cancelled)); setSecuritiesTransactionState(_txSerNo2, uint(TxnState.Cancelled)); } txn1.return_code = _cb_return_code; // 設定同資錯誤碼 txn2.return_code = _cb_return_code; // 設定同資錯誤碼 EventForSecuritiesTransactionPaymentError(_txSerNo1, _txSerNo2, _cb_return_code); } return _isNettingSuccess; } function setServiceState(uint state) onlyOwner { ServiceState = state; EventForSetServiceState(state); } function getServiceState() returns(uint) { return ServiceState; } function setSecuritiesTransactionState(bytes32 _txSerNo, uint _txn_state) internal { Transaction this_txn = transactions[_txSerNo]; // Initiate, Confirmed, ReadyToSettle, Settled, Finished, Canceled if( _txn_state == uint(TxnState.Pending)) { this_txn.state = TxnState.Pending; }else if( _txn_state == uint(TxnState.Waiting4Payment)) { this_txn.state = TxnState.Waiting4Payment; }else if( _txn_state == uint(TxnState.Matched)) { this_txn.state = TxnState.Matched; }else if( _txn_state == uint(TxnState.Finished)) { this_txn.state = TxnState.Finished; }else if( _txn_state == uint(TxnState.Cancelled)) { this_txn.state = TxnState.Cancelled; } } /* function setSecuritiesTransactionBlockedAmount(bytes32 _txSerNo, int _blocked_amount) internal { Transaction this_txn = transactions[_txSerNo]; this_txn.blocked_amount = _blocked_amount; } */ function enShareQueue(bytes32 _txSerNo) internal { shareQueue.push(_txSerNo); } function deShareQueue(bytes32 _txSerNo) internal { for(uint i=0; i< shareQueue.length; i++) { if(_txSerNo == shareQueue[i]) { delete shareQueue[i]; break; } } } function enPrivateQueue(bytes32 _txSerNo) internal { privateQueue.push(_txSerNo); } function dePrivateQueue(bytes32 _txSerNo) internal { for(uint i=0; i< privateQueue.length; i++) { if(_txSerNo == privateQueue[i]) { delete privateQueue[i]; break; } } } function getShareQueueDepth() constant returns(uint) { return shareQueue.length; } function getPrivateQueueDepth() constant returns(uint) { return privateQueue.length; } function getShareQueueEntry(uint index) constant returns(bytes32) { return shareQueue[index]; } function getPrivateQueueEntry(uint index) constant returns(bytes32) { return privateQueue[index]; } function clearQueue() onlyOwner { // 清除ShareQueue的所有交易,由央行發動清Queue,因為日終交易發動時機是央行決定的 for (uint i=0; i< shareQueue.length; i++) { delete shareQueue[i]; } shareQueue.length = 0; // 清除PrivateQueue的所有交易,由央行發動清Queue,因為日終交易發動時機是央行決定的 for (uint j=0; j< privateQueue.length; j++) { delete privateQueue[j]; } privateQueue.length = 0; } function getTransactionListLength() constant returns(uint) { return transactionIdx.length; } function getTransactionList(uint index) constant returns(bytes32) { return transactionIdx[index]; } function getTransactionInfo(bytes32 _txSerNo) constant returns(bytes32, bytes32 , bytes32 , bytes32 , int , bytes32, int, uint) { Transaction this_txn = transactions[_txSerNo]; return(this_txn.from_bank_id, this_txn.from_customer_id, this_txn.to_bank_id, this_txn.to_customer_id, this_txn.securities_amount, this_txn.securities_id, this_txn.payment, this_txn.timestamp ); } function getTransactionReverseTxnSeq(bytes32 _txSerNo) constant returns(bytes32) { Transaction this_txn = transactions[_txSerNo]; return(this_txn.rev_txnSerNo); } function getTransactionDigest(bytes32 _txSerNo) constant returns(bytes32 _digest) { Transaction this_txn = transactions[_txSerNo]; return(this_txn.digest); } function getTransactionState(bytes32 _txSerNo) constant returns(uint, int) { Transaction this_txn = transactions[_txSerNo]; return(uint(this_txn.state), this_txn.return_code); } }
Do nothing 賣方與買方為同一人enqueue(_txSerNo);queued = true;
function submitIntraBankTransaction(bytes32 _txSerNo, bytes32 _from_bank_id, bytes32 _from_customer_id, bytes32 _to_customer_id, int _securities_amount, bytes32 _securities_id, int _payment, bytes32 _digest) if(_from_customer_id == _to_customer_id) { this_txn = Transaction(_txSerNo, _from_bank_id, _from_customer_id, _from_bank_id, _to_customer_id, _securities_amount, 0, _securities_id, _payment, TxnState.Cancelled, now, _digest, msg.sender, "", 2); transactionIdx.push(_txSerNo); transactions[_txSerNo] = this_txn; EventForSecuritiesTransactionCancelled(_txSerNo, 2, ""); return; }
15,859,502
./partial_match/42/0x173a544b5EC26Aa2239A608634f5Ff2487F755f1/sources/KovanLETH.sol
improve these by using r and w math functions
function calculateRedemptionValue(uint _tokenAmount) public view returns ( uint _totalValue, uint _fee, uint _finalValue) { uint proportion = _tokenAmount.mul(HUNDRED_PERC).div(totalSupply()); _totalValue = getPositiveCollateral().mul(proportion).div(HUNDRED_PERC); _fee = _totalValue.mul(FEE_PERC).div(HUNDRED_PERC); _finalValue = _totalValue.sub(_fee); } event Redeemed( address _receiver, uint _tokensRedeemed, uint _fee, uint _collateralUnlocked, uint _collateralReturned);
3,323,515
pragma solidity 0.5.16; import "../../base/snx-base/interfaces/SNXRewardInterface.sol"; import "../../base/snx-base/SNXRewardUniLPStrategyWithBuyback.sol"; contract FoxStrategyMainnet_FOX_ETH is SNXRewardUniLPStrategyWithBuyback { address public fox_weth = address(0x470e8de2eBaef52014A47Cb5E6aF86884947F08c); address public weth = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); address public fox = address(0xc770EEfAd204B5180dF6a14Ee197D99d808ee52d); address public rewardPoolAddr = address(0xDd80E21669A664Bce83E3AD9a0d74f8Dad5D9E72); address public constant uniswapRouterAddress = address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); constructor( address _storage, address _vault, address _distributionPool ) SNXRewardUniLPStrategyWithBuyback( _storage, fox_weth, _vault, rewardPoolAddr, fox, uniswapRouterAddress, _distributionPool, 10000 //buyback ration, 100% ) public { uniswapRoutes[weth] = [fox, weth]; } } pragma solidity 0.5.16; interface SNXRewardInterface { function withdraw(uint) external; function getReward() external; function stake(uint) external; function balanceOf(address) external view returns (uint256); function earned(address account) external view returns (uint256); function exit() external; } pragma solidity 0.5.16; import "@openzeppelin/contracts/math/Math.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20Detailed.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../StrategyBase.sol"; import "../interface/uniswap/IUniswapV2Router02.sol"; import "../interface/IVault.sol"; import "./interfaces/SNXRewardInterface.sol"; import "../interface/uniswap/IUniswapV2Pair.sol"; import "../interface/IRewardPool.sol"; /* * This is a general strategy for yields that are based on the synthetix reward contract * for example, yam, spaghetti, ham, shrimp. * * One strategy is deployed for one underlying asset, but the design of the contract * should allow it to switch between different reward contracts. * * It is important to note that not all SNX reward contracts that are accessible via the same interface are * suitable for this Strategy. One concrete example is CREAM.finance, as it implements a "Lock" feature and * would not allow the user to withdraw within some timeframe after the user have deposited. * This would be problematic to user as our "invest" function in the vault could be invoked by anyone anytime * and thus locking/reverting on subsequent withdrawals. Another variation is the YFI Governance: it can * activate a vote lock to stop withdrawal. * * Ref: * 1. CREAM https://etherscan.io/address/0xc29e89845fa794aa0a0b8823de23b760c3d766f5#code * 2. YAM https://etherscan.io/address/0x8538E5910c6F80419CD3170c26073Ff238048c9E#code * 3. SHRIMP https://etherscan.io/address/0x9f83883FD3cadB7d2A83a1De51F9Bf483438122e#code * 4. BASED https://etherscan.io/address/0x5BB622ba7b2F09BF23F1a9b509cd210A818c53d7#code * 5. YFII https://etherscan.io/address/0xb81D3cB2708530ea990a287142b82D058725C092#code * 6. YFIGovernance https://etherscan.io/address/0xBa37B002AbaFDd8E89a1995dA52740bbC013D992#code * * * * Respecting the current system design of choosing the best strategy under the vault, and also rewarding/funding * the public key that invokes the switch of strategies, this smart contract should be deployed twice and linked * to the same vault. When the governance want to rotate the crop, they would set the reward source on the strategy * that is not active, then set that apy higher and this one lower. * * Consequently, in the smart contract we restrict that we can only set a new reward source when it is not active. * */ contract SNXRewardUniLPStrategyWithBuyback is StrategyBase { using SafeMath for uint256; using SafeERC20 for IERC20; address public uniLPComponentToken0; address public uniLPComponentToken1; address public distributionPool; uint256 public buybackRatio; bool public pausedInvesting = false; // When this flag is true, the strategy will not be able to invest. But users should be able to withdraw. SNXRewardInterface public rewardPool; // a flag for disabling selling for simplified emergency exit bool public sell = true; uint256 public sellFloor = 1e6; mapping (address => address[]) public uniswapRoutes; event ProfitsNotCollected(); // This is only used in `investAllUnderlying()` // The user can still freely withdraw from the strategy modifier onlyNotPausedInvesting() { require(!pausedInvesting, "Action blocked as the strategy is in emergency state"); _; } constructor( address _storage, address _underlying, address _vault, address _rewardPool, address _rewardToken, address _uniswapRouterV2, address _distributionPool, uint256 _buybackRatio ) StrategyBase(_storage, _underlying, _vault, _rewardToken, _uniswapRouterV2) public { require(IRewardPool(_distributionPool).lpToken() == _vault, "Incompatible pool"); require(_buybackRatio <= 10000, "Buyback ratio too high"); buybackRatio = _buybackRatio; distributionPool = _distributionPool; uniLPComponentToken0 = IUniswapV2Pair(underlying).token0(); uniLPComponentToken1 = IUniswapV2Pair(underlying).token1(); rewardPool = SNXRewardInterface(_rewardPool); } function depositArbCheck() public view returns(bool) { return true; } /* * In case there are some issues discovered about the pool or underlying asset * Governance can exit the pool properly * The function is only used for emergency to exit the pool */ function emergencyExit() public onlyGovernance { if (rewardPool.balanceOf(address(this)) > 0) { rewardPool.exit(); } pausedInvesting = true; } /* * Resumes the ability to invest into the underlying reward pools */ function continueInvesting() public onlyGovernance { pausedInvesting = false; } function setLiquidationPaths(address [] memory _uniswapRouteToToken0, address [] memory _uniswapRouteToToken1) public onlyGovernance { uniswapRoutes[uniLPComponentToken0] = _uniswapRouteToToken0; uniswapRoutes[uniLPComponentToken1] = _uniswapRouteToToken1; } function setBuybackRatio(uint256 _newRatio) public onlyGovernance { require(_newRatio <= 10000, "Buyback ratio too high"); buybackRatio = _newRatio; } function setDistributionPool(address _newPool) public onlyGovernance { require(IRewardPool(_newPool).lpToken() == vault, "Incompatible pool"); distributionPool = _newPool; } // We assume that all the tradings can be done on Uniswap function _liquidateReward() internal { uint256 rewardBalance = IERC20(rewardToken).balanceOf(address(this)); if (!sell || rewardBalance < sellFloor) { // Profits can be disabled for possible simplified and rapid exit emit ProfitsNotCollected(); return; } notifyProfitAndBuybackInRewardToken( rewardBalance, distributionPool, buybackRatio ); uint256 remainingRewardBalance = IERC20(rewardToken).balanceOf(address(this)); if (remainingRewardBalance > 0 // we have tokens to swap && uniswapRoutes[address(uniLPComponentToken0)].length > 0 // and we have a route to do the swap && uniswapRoutes[address(uniLPComponentToken1)].length > 0 // and we have a route to do the swap ) { // allow Uniswap to sell our reward uint256 amountOutMin = 1; IERC20(rewardToken).safeApprove(uniswapRouterV2, 0); IERC20(rewardToken).safeApprove(uniswapRouterV2, remainingRewardBalance); // sell reward token to token1 // we can accept 1 as minimum because this is called only by a trusted role uint256 token0Amount; if (uniswapRoutes[uniLPComponentToken0].length > 1) { // in some cases, the reward token is the same as one of the components // only swap when this is NOT the case IUniswapV2Router02(uniswapRouterV2).swapExactTokensForTokens( remainingRewardBalance/2, amountOutMin, uniswapRoutes[address(uniLPComponentToken0)], address(this), block.timestamp ); token0Amount = IERC20(uniLPComponentToken0).balanceOf(address(this)); remainingRewardBalance = IERC20(rewardToken).balanceOf(address(this)); } else { // no swap, just adjust the numbers token0Amount = remainingRewardBalance/2; remainingRewardBalance = remainingRewardBalance.sub(token0Amount); } // sell reward token to token2 // we can accept 1 as minimum because this is called only by a trusted role if (uniswapRoutes[uniLPComponentToken1].length > 1) { // in some cases, the reward token is the same as one of the components // only swap when this is NOT the case IUniswapV2Router02(uniswapRouterV2).swapExactTokensForTokens( remainingRewardBalance, amountOutMin, uniswapRoutes[uniLPComponentToken1], address(this), block.timestamp ); } uint256 token1Amount = IERC20(uniLPComponentToken1).balanceOf(address(this)); // provide token1 and token2 to UniLPToken IERC20(uniLPComponentToken0).safeApprove(uniswapRouterV2, 0); IERC20(uniLPComponentToken0).safeApprove(uniswapRouterV2, token0Amount); IERC20(uniLPComponentToken1).safeApprove(uniswapRouterV2, 0); IERC20(uniLPComponentToken1).safeApprove(uniswapRouterV2, token1Amount); uint256 liquidity; (,,liquidity) = IUniswapV2Router02(uniswapRouterV2).addLiquidity( uniLPComponentToken0, uniLPComponentToken1, token0Amount, token1Amount, 1, // we are willing to take whatever the pair gives us 1, address(this), block.timestamp ); } } /* * Stakes everything the strategy holds into the reward pool */ function investAllUnderlying() internal onlyNotPausedInvesting { // this check is needed, because most of the SNX reward pools will revert if // you try to stake(0). if(IERC20(underlying).balanceOf(address(this)) > 0) { IERC20(underlying).approve(address(rewardPool), IERC20(underlying).balanceOf(address(this))); rewardPool.stake(IERC20(underlying).balanceOf(address(this))); } } /* * Withdraws all the asset to the vault */ function withdrawAllToVault() public restricted { if (rewardPool.balanceOf(address(this)) > 0) { rewardPool.exit(); } _liquidateReward(); if (IERC20(underlying).balanceOf(address(this)) > 0) { IERC20(underlying).safeTransfer(vault, IERC20(underlying).balanceOf(address(this))); } } /* * Withdraws all the asset to the vault */ function withdrawToVault(uint256 amount) public restricted { // Typically there wouldn't be any amount here // however, it is possible because of the emergencyExit if(amount > IERC20(underlying).balanceOf(address(this))){ // While we have the check above, we still using SafeMath below // for the peace of mind (in case something gets changed in between) uint256 needToWithdraw = amount.sub(IERC20(underlying).balanceOf(address(this))); rewardPool.withdraw(Math.min(rewardPool.balanceOf(address(this)), needToWithdraw)); } IERC20(underlying).safeTransfer(vault, amount); } /* * Note that we currently do not have a mechanism here to include the * amount of reward that is accrued. */ function investedUnderlyingBalance() external view returns (uint256) { // Adding the amount locked in the reward pool and the amount that is somehow in this contract // both are in the units of "underlying" // The second part is needed because there is the emergency exit mechanism // which would break the assumption that all the funds are always inside of the reward pool return rewardPool.balanceOf(address(this)).add(IERC20(underlying).balanceOf(address(this))); } /* * Governance or Controller can claim coins that are somehow transferred into the contract * Note that they cannot come in take away coins that are used and defined in the strategy itself * Those are protected by the "unsalvagableTokens". To check, see where those are being flagged. */ function salvage(address recipient, address token, uint256 amount) external onlyControllerOrGovernance { // To make sure that governance cannot come in and take away the coins require(!unsalvagableTokens[token], "token is defined as not salvagable"); IERC20(token).safeTransfer(recipient, amount); } /* * Get the reward, sell it in exchange for underlying, invest what you got. * It's not much, but it's honest work. * * Note that although `onlyNotPausedInvesting` is not added here, * calling `investAllUnderlying()` affectively blocks the usage of `doHardWork` * when the investing is being paused by governance. */ function doHardWork() external onlyNotPausedInvesting restricted { rewardPool.getReward(); _liquidateReward(); investAllUnderlying(); } /** * Can completely disable claiming UNI rewards and selling. Good for emergency withdraw in the * simplest possible way. */ function setSell(bool s) public onlyGovernance { sell = s; } /** * Sets the minimum amount of CRV needed to trigger a sale. */ function setSellFloor(uint256 floor) public onlyGovernance { sellFloor = floor; } /** * Exits old rewardPool, sets the new one and invests in the new pool. */ function changeRewardPool(address _newPool) public onlyGovernance { if (rewardPool.balanceOf(address(this)) > 0) { rewardPool.exit(); } _liquidateReward(); rewardPool = SNXRewardInterface(_newPool); investAllUnderlying(); } } pragma solidity ^0.5.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } pragma solidity ^0.5.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. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } pragma solidity ^0.5.0; import "./IERC20.sol"; /** * @dev Optional functions from the ERC20 standard. */ contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for `name`, `symbol`, and `decimals`. All three of * these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } } pragma solidity ^0.5.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 ERC20;` 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)); } 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. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } //SPDX-License-Identifier: Unlicense pragma solidity 0.5.16; import "hardhat/console.sol"; import "./inheritance/RewardTokenProfitNotifier.sol"; import "./interface/IStrategy.sol"; contract StrategyBase is IStrategy, RewardTokenProfitNotifier { using SafeMath for uint256; using SafeERC20 for IERC20; event ProfitsNotCollected(address); event Liquidating(address, uint256); address public underlying; address public vault; mapping (address => bool) public unsalvagableTokens; address public uniswapRouterV2; modifier restricted() { require(msg.sender == vault || msg.sender == address(controller()) || msg.sender == address(governance()), "The sender has to be the controller or vault or governance"); _; } constructor( address _storage, address _underlying, address _vault, address _rewardToken, address _uniswap ) RewardTokenProfitNotifier(_storage, _rewardToken) public { underlying = _underlying; vault = _vault; unsalvagableTokens[_rewardToken] = true; unsalvagableTokens[_underlying] = true; uniswapRouterV2 = _uniswap; } } // SPDX-License-Identifier: MIT pragma solidity >=0.5.0; import './IUniswapV2Router01.sol'; interface IUniswapV2Router02 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } pragma solidity 0.5.16; interface IVault { function initializeVault( address _storage, address _underlying, uint256 _toInvestNumerator, uint256 _toInvestDenominator ) external ; function balanceOf(address) external view returns (uint256); function underlyingBalanceInVault() external view returns (uint256); function underlyingBalanceWithInvestment() external view returns (uint256); // function store() external view returns (address); function governance() external view returns (address); function controller() external view returns (address); function underlying() external view returns (address); function strategy() external view returns (address); function setStrategy(address _strategy) external; function announceStrategyUpdate(address _strategy) external; function setVaultFractionToInvest(uint256 numerator, uint256 denominator) external; function deposit(uint256 amountWei) external; function depositFor(uint256 amountWei, address holder) external; function withdrawAll() external; function withdraw(uint256 numberOfShares) external; function getPricePerFullShare() external view returns (uint256); function underlyingBalanceWithInvestmentForHolder(address holder) view external returns (uint256); // hard work should be callable only by the controller (by the hard worker) or by governance function doHardWork() external; } // SPDX-License-Identifier: MIT /** *Submitted for verification at Etherscan.io on 2020-05-05 */ // File: contracts/interfaces/IUniswapV2Pair.sol pragma solidity >=0.5.0; interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } pragma solidity 0.5.16; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; // Unifying the interface with the Synthetix Reward Pool interface IRewardPool { function rewardToken() external view returns (address); function lpToken() external view returns (address); function duration() external view returns (uint256); function periodFinish() external view returns (uint256); function rewardRate() external view returns (uint256); function rewardPerTokenStored() external view returns (uint256); function stake(uint256 amountWei) external; // `balanceOf` would give the amount staked. // As this is 1 to 1, this is also the holder's share function balanceOf(address holder) external view returns (uint256); // total shares & total lpTokens staked function totalSupply() external view returns(uint256); function withdraw(uint256 amountWei) external; function exit() external; // get claimed rewards function earned(address holder) external view returns (uint256); // claim rewards function getReward() external; // notify function notifyRewardAmount(uint256 _amount) external; } pragma solidity ^0.5.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * 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); } pragma solidity ^0.5.5; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } /** * @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]. * * _Available since v2.4.0._ */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } // SPDX-License-Identifier: MIT pragma solidity >= 0.4.22 <0.9.0; library console { address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67); function _sendLogPayload(bytes memory payload) private view { uint256 payloadLength = payload.length; address consoleAddress = CONSOLE_ADDRESS; assembly { let payloadStart := add(payload, 32) let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0) } } function log() internal view { _sendLogPayload(abi.encodeWithSignature("log()")); } function logInt(int p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(int)", p0)); } function logUint(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function logString(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function logBool(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function logAddress(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function logBytes(bytes memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes)", p0)); } function logBytes1(bytes1 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0)); } function logBytes2(bytes2 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0)); } function logBytes3(bytes3 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0)); } function logBytes4(bytes4 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0)); } function logBytes5(bytes5 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0)); } function logBytes6(bytes6 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0)); } function logBytes7(bytes7 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0)); } function logBytes8(bytes8 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0)); } function logBytes9(bytes9 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0)); } function logBytes10(bytes10 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0)); } function logBytes11(bytes11 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0)); } function logBytes12(bytes12 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0)); } function logBytes13(bytes13 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0)); } function logBytes14(bytes14 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0)); } function logBytes15(bytes15 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0)); } function logBytes16(bytes16 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0)); } function logBytes17(bytes17 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0)); } function logBytes18(bytes18 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0)); } function logBytes19(bytes19 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0)); } function logBytes20(bytes20 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0)); } function logBytes21(bytes21 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0)); } function logBytes22(bytes22 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0)); } function logBytes23(bytes23 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0)); } function logBytes24(bytes24 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0)); } function logBytes25(bytes25 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0)); } function logBytes26(bytes26 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0)); } function logBytes27(bytes27 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0)); } function logBytes28(bytes28 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0)); } function logBytes29(bytes29 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0)); } function logBytes30(bytes30 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0)); } function logBytes31(bytes31 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0)); } function logBytes32(bytes32 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0)); } function log(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function log(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function log(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function log(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function log(uint p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1)); } function log(uint p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1)); } function log(uint p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1)); } function log(uint p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1)); } function log(string memory p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1)); } function log(string memory p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1)); } function log(string memory p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1)); } function log(string memory p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1)); } function log(bool p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1)); } function log(bool p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1)); } function log(bool p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1)); } function log(bool p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1)); } function log(address p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1)); } function log(address p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1)); } function log(address p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1)); } function log(address p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1)); } function log(uint p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2)); } function log(uint p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2)); } function log(uint p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2)); } function log(uint p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2)); } function log(uint p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2)); } function log(uint p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2)); } function log(uint p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2)); } function log(uint p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2)); } function log(uint p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2)); } function log(uint p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2)); } function log(uint p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2)); } function log(uint p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2)); } function log(uint p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2)); } function log(uint p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2)); } function log(uint p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2)); } function log(uint p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2)); } function log(string memory p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2)); } function log(string memory p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2)); } function log(string memory p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2)); } function log(string memory p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2)); } function log(string memory p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2)); } function log(string memory p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2)); } function log(string memory p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2)); } function log(string memory p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2)); } function log(string memory p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2)); } function log(string memory p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2)); } function log(string memory p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2)); } function log(string memory p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2)); } function log(string memory p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2)); } function log(string memory p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2)); } function log(string memory p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2)); } function log(string memory p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2)); } function log(bool p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2)); } function log(bool p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2)); } function log(bool p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2)); } function log(bool p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2)); } function log(bool p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2)); } function log(bool p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2)); } function log(bool p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2)); } function log(bool p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2)); } function log(bool p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2)); } function log(bool p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2)); } function log(bool p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2)); } function log(bool p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2)); } function log(bool p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2)); } function log(bool p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2)); } function log(bool p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2)); } function log(bool p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2)); } function log(address p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2)); } function log(address p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2)); } function log(address p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2)); } function log(address p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2)); } function log(address p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2)); } function log(address p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2)); } function log(address p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2)); } function log(address p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2)); } function log(address p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2)); } function log(address p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2)); } function log(address p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2)); } function log(address p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2)); } function log(address p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2)); } function log(address p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2)); } function log(address p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2)); } function log(address p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2)); } function log(uint p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3)); } } pragma solidity 0.5.16; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../interface/IController.sol"; import "../interface/IFeeRewardForwarderV6.sol"; import "./Controllable.sol"; contract RewardTokenProfitNotifier is Controllable { using SafeMath for uint256; using SafeERC20 for IERC20; uint256 public profitSharingNumerator; uint256 public profitSharingDenominator; address public rewardToken; constructor( address _storage, address _rewardToken ) public Controllable(_storage){ rewardToken = _rewardToken; // persist in the state for immutability of the fee profitSharingNumerator = 30; //IController(controller()).profitSharingNumerator(); profitSharingDenominator = 100; //IController(controller()).profitSharingDenominator(); require(profitSharingNumerator < profitSharingDenominator, "invalid profit share"); } event ProfitLogInReward(uint256 profitAmount, uint256 feeAmount, uint256 timestamp); event ProfitAndBuybackLog(uint256 profitAmount, uint256 feeAmount, uint256 timestamp); function notifyProfitInRewardToken(uint256 _rewardBalance) internal { if( _rewardBalance > 0 ){ uint256 feeAmount = _rewardBalance.mul(profitSharingNumerator).div(profitSharingDenominator); emit ProfitLogInReward(_rewardBalance, feeAmount, block.timestamp); IERC20(rewardToken).safeApprove(controller(), 0); IERC20(rewardToken).safeApprove(controller(), feeAmount); IController(controller()).notifyFee( rewardToken, feeAmount ); } else { emit ProfitLogInReward(0, 0, block.timestamp); } } function notifyProfitAndBuybackInRewardToken(uint256 _rewardBalance, address pool, uint256 _buybackRatio) internal { if( _rewardBalance > 0 ){ uint256 feeAmount = _rewardBalance.mul(profitSharingNumerator).div(profitSharingDenominator); address forwarder = IController(controller()).feeRewardForwarder(); emit ProfitAndBuybackLog(_rewardBalance, feeAmount, block.timestamp); IERC20(rewardToken).safeApprove(forwarder, 0); IERC20(rewardToken).safeApprove(forwarder, _rewardBalance); IFeeRewardForwarderV6(forwarder).notifyFeeAndBuybackAmounts( rewardToken, feeAmount, pool, _rewardBalance.sub(feeAmount).mul(_buybackRatio).div(10000) ); } else { emit ProfitAndBuybackLog(0, 0, block.timestamp); } } } pragma solidity 0.5.16; interface IStrategy { function unsalvagableTokens(address tokens) external view returns (bool); function governance() external view returns (address); function controller() external view returns (address); function underlying() external view returns (address); function vault() external view returns (address); function withdrawAllToVault() external; function withdrawToVault(uint256 amount) external; function investedUnderlyingBalance() external view returns (uint256); // itsNotMuch() // should only be called by controller function salvage(address recipient, address token, uint256 amount) external; function doHardWork() external; function depositArbCheck() external view returns(bool); } pragma solidity 0.5.16; interface IController { event SharePriceChangeLog( address indexed vault, address indexed strategy, uint256 oldSharePrice, uint256 newSharePrice, uint256 timestamp ); // [Grey list] // An EOA can safely interact with the system no matter what. // If you're using Metamask, you're using an EOA. // Only smart contracts may be affected by this grey list. // // This contract will not be able to ban any EOA from the system // even if an EOA is being added to the greyList, he/she will still be able // to interact with the whole system as if nothing happened. // Only smart contracts will be affected by being added to the greyList. // This grey list is only used in Vault.sol, see the code there for reference function greyList(address _target) external view returns(bool); function addVaultAndStrategy(address _vault, address _strategy) external; function doHardWork(address _vault) external; function salvage(address _token, uint256 amount) external; function salvageStrategy(address _strategy, address _token, uint256 amount) external; function notifyFee(address _underlying, uint256 fee) external; function profitSharingNumerator() external view returns (uint256); function profitSharingDenominator() external view returns (uint256); function feeRewardForwarder() external view returns(address); function setFeeRewardForwarder(address _value) external; function addHardWorker(address _worker) external; } pragma solidity 0.5.16; interface IFeeRewardForwarderV6 { function poolNotifyFixedTarget(address _token, uint256 _amount) external; function notifyFeeAndBuybackAmounts(uint256 _feeAmount, address _pool, uint256 _buybackAmount) external; function notifyFeeAndBuybackAmounts(address _token, uint256 _feeAmount, address _pool, uint256 _buybackAmount) external; function profitSharingPool() external view returns (address); function configureLiquidation(address[] calldata _path, bytes32[] calldata _dexes) external; } pragma solidity 0.5.16; import "./Governable.sol"; contract Controllable is Governable { constructor(address _storage) Governable(_storage) public { } modifier onlyController() { require(store.isController(msg.sender), "Not a controller"); _; } modifier onlyControllerOrGovernance(){ require((store.isController(msg.sender) || store.isGovernance(msg.sender)), "The caller must be controller or governance"); _; } function controller() public view returns (address) { return store.controller(); } } pragma solidity 0.5.16; import "./Storage.sol"; contract Governable { Storage public store; constructor(address _store) public { require(_store != address(0), "new storage shouldn't be empty"); store = Storage(_store); } modifier onlyGovernance() { require(store.isGovernance(msg.sender), "Not governance"); _; } function setStorage(address _store) public onlyGovernance { require(_store != address(0), "new storage shouldn't be empty"); store = Storage(_store); } function governance() public view returns (address) { return store.governance(); } } pragma solidity 0.5.16; contract Storage { address public governance; address public controller; constructor() public { governance = msg.sender; } modifier onlyGovernance() { require(isGovernance(msg.sender), "Not governance"); _; } function setGovernance(address _governance) public onlyGovernance { require(_governance != address(0), "new governance shouldn't be empty"); governance = _governance; } function setController(address _controller) public onlyGovernance { require(_controller != address(0), "new controller shouldn't be empty"); controller = _controller; } function isGovernance(address account) public view returns (bool) { return account == governance; } function isController(address account) public view returns (bool) { return account == controller; } } // SPDX-License-Identifier: MIT pragma solidity >=0.5.0; interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); }
Exits old rewardPool, sets the new one and invests in the new pool./
function changeRewardPool(address _newPool) public onlyGovernance { if (rewardPool.balanceOf(address(this)) > 0) { rewardPool.exit(); } _liquidateReward(); rewardPool = SNXRewardInterface(_newPool); investAllUnderlying(); }
11,702,049
./full_match/1313161554/0x910ab4bFB68386BD26b3d5D10D7191e620C721c9/sources/RORA.sol
Enables the auto swap and liquify feature. Swaps half of transaction amount `taxLiquify_` amount of tokens to ETH and pair with the other half of tokens to the LP each transaction when enabled. Emits a {EnabledLiquify} event. Requirements: - auto swap and liquify feature mush be disabled. - tax must be greater than 0. - tax decimals + 2 must be less than token decimals. (because tax rate is in percentage)/
function enableLiquify(uint32 taxLiquifyBuy_, uint32 taxLiquifySell_, uint32 taxLiquifyTransfer_, uint32 taxLiquifyDecimals_, address liquifyAddress_) public onlyOwner { require(!_liquifyEnabled, "Auto swap and liquify feature is already enabled."); require(taxLiquifyBuy_ > 0 || taxLiquifySell_ > 0 || taxLiquifyTransfer_ > 0, "Tax rates must be greater than 0."); require(taxLiquifyDecimals_ + 2 <= decimals(), "Tax decimals must be less than token decimals - 2"); _liquifyEnabled = true; setTaxLiquify(taxLiquifyBuy_, taxLiquifySell_, taxLiquifyTransfer_, taxLiquifyDecimals_); setLiquifyAddress(liquifyAddress_); emit EnabledLiquify(); }
13,232,029
./full_match/8453/0xE4AD80eD0c7d12A8B687c6C987d07f1D486fEd85/sources/src/factory/AnotherCloneFactory.sol
____ __ ____ __ ___ __ / __ \____ / /_ __ / __ \__ __/ /_ / (_)____/ /_ ___ _____ / / / / __ \/ / / / / / /_/ / / / / __ \/ / / ___/ __ \/ _ \/ ___/ / /_/ / / / / / /_/ / / ____/ /_/ / /_/ / / (__ ) / / / __/ / \____/_/ /_/_/\__, / /_/ \__,_/_.___/_/_/____/_/ /_/\___/_/ /____/ Create new ERC721 collection Only the caller with role `PUBLISHER_ROLE` can perform this operation _name collection name _salt bytes used for deterministic deployment/ Create new NFT contract Initialize NFT contract Setup collection
function createCollection721(string memory _name, bytes32 _salt) external onlyRole(PUBLISHER_ROLE) { ERC721AB newCollection = ERC721AB(Clones.cloneDeterministic(erc721Impl, _salt)); newCollection.initialize(msg.sender, address(abDataRegistry), abVerifier, _name); _setupCollection(address(newCollection), msg.sender); }
11,535,374
contract ABTCETHER { /* Public variables of the token */ string public standard = 'Token 0.1'; string public name; string public symbol; uint8 public decimals; uint256 public initialSupply; uint256 public totalSupply; /* This creates an array with all balances */ mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; /* Initializes contract with initial supply tokens to the creator of the contract */ function ABTCETHER() { initialSupply = 9000000000; name ="ABTCETHER"; decimals = 0; symbol = "ABTC"; balanceOf[msg.sender] = initialSupply; // Give the creator all initial tokens totalSupply = initialSupply; // Update total supply } /* Send coins */ function transfer(address _to, uint256 _value) { if (balanceOf[msg.sender] < _value) throw; // Check if the sender has enough if (balanceOf[_to] + _value < balanceOf[_to]) throw; // Check for overflows balanceOf[msg.sender] -= _value; // Subtract from the sender balanceOf[_to] += _value; // Add the same to the recipient } /* This unnamed function is called whenever someone tries to send ether to it */ function () { throw; // Prevents accidental sending of ether } }
Public variables of the token / This creates an array with all balances / Initializes contract with initial supply tokens to the creator of the contract /
function ABTCETHER() { initialSupply = 9000000000; name ="ABTCETHER"; decimals = 0; symbol = "ABTC"; }
4,810,163
pragma solidity >=0.4.21 <0.7.0; import "./SafeMath.sol"; contract Auction { // Library for safe mathematical operations using SafeMath for uint256; // @param owner stores the contract owner address payable owner; // @param participant_to_bool stores the clist of allowed participants mapping (address => bool) public participant_to_bool; // @param bid_status indicates whether the auction is finished enum bid_status {open, closed} // @param Offer stores new offers struct auctioned_item { // @param item string containing the name of the auctioned item string item; // @param price uint containing the initial price and posterior highest bids uint price; // @ param highes_bidder the latest bidder with the highest bid address payable highest_bidder; // @ param status enum indicating whether the auction is open or closed bid_status status; } // @param auctioned_items stores an array of auctioned items auctioned_item[] public auctioned_items; // @notice offerPosted this event is triggered every time a new item is open for auctioning event itemAuctionStart(string item, uint price, uint index, address auctioneer, string text); // @notice newBid this event is triggered every time a new bid is made for an item event newBid(string item, uint bid, uint index, address bidder, string text); // @notice finishedAuction this event is triggered every time an auction is finished event finishedAuction(string item, uint price, uint index, address bidder, string text); modifier onlyOwner() { require(owner == msg.sender); // 1. check if owner _; // 2. continue with method } modifier notOwner() { require(owner != msg.sender); // 1. check if not owner _; // 2. continue with method } modifier onlyParticipant() { require(participant_to_bool[msg.sender]); // 1. check if participant _; // 2. continue with method } constructor () public { owner = msg.sender; // 1. set owner } // @notice setParticipant sets new participant in the participant list function setParticipant( address participant ) public onlyOwner { participant_to_bool[participant] = true; // 1. set new participant in the whitelist } // @notice setAuctionedItem the owner of the auction sets a new item for auction function setAuctionedItem(string memory item, uint price) public onlyOwner { auctioned_items.push(auctioned_item(item, price, address(0), bid_status.open)); // 1. owner sets a new item for auctionning uint index = auctioned_items.length.sub(1); // 2. calculates index of the new item in the array with safemath emit itemAuctionStart(item, price, index, msg.sender, "A new item is being auctioned!" ); } // @notice bid a participant makes a bid for a particular item using its index function bid(uint index) public payable onlyParticipant notOwner{ require(msg.value > auctioned_items[index].price, "Your bid is too low."); // 1. check whether the ETH sent is greater than the highest bid (or initial price) (no "text" needed) require(auctioned_items[index].status == bid_status.open, "This auction has been closed."); // 2. check whether the auction is finalized (no "text" needed) if (auctioned_items[index].highest_bidder != address(0)) { // 3. check whether there was a previous auctioned_items[index].highest_bidder.transfer(auctioned_items[index].price); // 4. send the ETH from the contract to the bidder with the previous lower bid } auctioned_items[index].highest_bidder = msg.sender; // 5. assign the new highest bidder auctioned_items[index].price = msg.value; // 6. assign the new highest bid emit newBid(auctioned_items[index].item, msg.value, index, msg.sender, 'New bid!'); } // @notice finishAuction the owner can close the auction at will function finishAuction (uint index) public onlyOwner { owner.transfer(auctioned_items[index].price); // 1. the auctioneer sends the ETH to himself (auctioned_items[index].status = bid_status.closed); // 2. Close auction accountBalances[auctioned_items[index].highest_bidder].bidder_balance = 0; // 3. resets the account balance of the highest bidder to 0. (1 p) emit finishedAuction(auctioned_items[index].item, auctioned_items[index].price, index, auctioned_items[index].highest_bidder, 'Auction finished!'); } ////// ////// ////// ////// ////// // USING THE PULL OVER PUSH IDIOM ////// ////// ////// ////// ////// // @param bidder_withdrawal enum with binary value that indicates whether a bidder is allowed to withdraw his/her funds (based on the identity of the highest bidder) enum bidder_withdrawal {allowed, not_allowed} struct bidder { // @param balance uint containing the balance a bidder has placed in the smart contract uint bidder_balance; // @ param withdrawal enum containing a binary value of whether the bidder is allowed to withdraw money or not (based on whether the person is the highest bidder) bidder_withdrawal withdrawal; } // @param accountBalances mapping of addresses and the struct bidder, to keep track of the balance of each bidder and whether they are allowded to withdraw Ether from the contract mapping(address => bidder) public accountBalances; // @notice bid a participant makes a bid for a particular item using its index function bid_2(uint index) public payable onlyParticipant notOwner{ require(msg.value > auctioned_items[index].price, "Your bid is too low."); // 1. check whether the ETH sent is greater than the highest bid (or initial price) (no "text" needed) require(auctioned_items[index].status == bid_status.open, "This auction has been closed."); // 2. check whether the auction is finalized (no "text" needed) if (auctioned_items[index].highest_bidder != address(0)) { // 3. check whether there was a previous bidder accountBalances[auctioned_items[index].highest_bidder].withdrawal = bidder_withdrawal.allowed; // 4.The previous bidder is now allowed to withdraw the funds he previously submitted } auctioned_items[index].highest_bidder = msg.sender; // 5. assign the new highest bidder auctioned_items[index].price = msg.value; // 6. assign the new highest bid accountBalances[msg.sender].bidder_balance = accountBalances[msg.sender].bidder_balance.add(auctioned_items[index].price); // 7. update the balance of the bidder (Mind the sum, as perhpas the bidder has not withdraw yet the previos amount) accountBalances[msg.sender].withdrawal = bidder_withdrawal.not_allowed; // 8. The highest bidder is not allowed to withdraw ether emit newBid(auctioned_items[index].item, msg.value, index, msg.sender, 'New bid!'); } // @notice withdraw allows to withdraw ether from the smart contract to anyone who transfered money function withdraw() public { uint amount = accountBalances[msg.sender].bidder_balance; require(amount != 0); // 1. The amount must be different to 0 require(address(this).balance >= amount); // 2. The balance of the contract must be larger than the amount to withdraw (safety check) require(accountBalances[msg.sender].withdrawal == bidder_withdrawal.allowed); // 3. The bidder cannot be the highest bidder accountBalances[msg.sender].bidder_balance = 0; // 4. We reset the balance of the bidder msg.sender.transfer(amount); // 5. We transfer all the balance tot he respective bidder } }
setParticipant sets new participant in the participant list
function setParticipant( address participant ) public onlyOwner { }
6,420,865
// SPDX-License-Identifier: MIT pragma solidity ^0.8.4; contract Proxy { // IMPLEMENTATION_SLOT is an arbitrary random hex bytes32 private constant IMPLEMENTATION_SLOT = 0x7050c9e0f4ca769c69bd3a8ef740bc37934f8e2c036e5a723fd8ee048ed3f8c3; fallback() external payable { _fallback(); } receive() external payable { revert("Proxy: received Eth"); } // solhint-disable-next-line func-name-mixedcase function __initialize__(address implementation) external { require(_implementation() == address(0), "Proxy: already initialized"); require(implementation != address(0), "Proxy: zero address"); bytes32 slot = IMPLEMENTATION_SLOT; assembly { sstore(slot, implementation) } } // solhint-disable-next-line func-name-mixedcase function __implementation__() external view returns (address) { return _implementation(); } // solhint-disable-next-line no-empty-blocks function _willFallback() internal {} function _fallback() internal { _willFallback(); _delegate(_implementation()); } function _delegate(address implementation) internal { assembly { calldatacopy(0, 0, calldatasize()) let result := delegatecall( gas(), implementation, 0, calldatasize(), 0, 0 ) returndatacopy(0, 0, returndatasize()) switch result case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } function _implementation() internal view returns (address impl) { bytes32 slot = IMPLEMENTATION_SLOT; // solium-disable-next-line security/no-inline-assembly assembly { impl := sload(slot) } } }
solhint-disable-next-line func-name-mixedcase
function __implementation__() external view returns (address) { return _implementation(); }
12,833,377
./full_match/1/0x60eEC879cd31e47347058048433D9E381F510606/sources/contracts/ommf/ommf_token/ommf.sol
return the name of the token./
function name() public pure returns (string memory) { return "Ondo Money Market Fund Token"; }
16,405,041
/** *Submitted for verification at Etherscan.io on 2020-11-25 */ //722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3 //SPDX-License-Identifier: UNLICENSED//722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3 pragma solidity ^0.6.0;//722,333 people died that summer but history won't remember a single one.722,333 people died that summer but history won't remember a single one. abstract contract Context {//722,333 people died that summer but history won't remember a single one.722,333 people died that summer but history won't remember a single one. function _msgSender() internal view virtual returns (address payable) {//722,333 people died that summer but history won't remember a single one.722,333 people died that summer but history won't remember a single one. return msg.sender;//722,333 people died that summer but history won't remember a single one.722,333 people died that summer but history won't remember a single one. }//722,333 people died that summer but history won't remember a single one.722,333 people died that summer but history won't remember a single one. //722,333 people died that summer but history won't remember a single one.722,333 people died that summer but history won't remember a single one. function _msgData() internal view virtual returns (bytes memory) {//722,333 people died that summer but history won't remember a single one.722,333 people died that summer but history won't remember a single one. this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691//722,333 people died that summer but history won't remember a single one.722,333 people died that summer but history won't remember a single one. return msg.data;//722,333 people died that summer but history won't remember a single one.722,333 people died that summer but history won't remember a single one. }//722,333 people died that summer but history won't remember a single one.722,333 people died that summer but history won't remember a single one. }//722,333 people died that summer but history won't remember a single one.722,333 people died that summer but history won't remember a single one. //722,333 people died that summer but history won't remember a single one.722,333 people died that summer but history won't remember a single one. // File: @openzeppelin/contracts/token/ERC20/IERC20.sol//722,333 people died that summer but history won't remember a single one.722,333 people died that summer but history won't remember a single one. //722,333 people died that summer but history won't remember a single one.722,333 people died that summer but history won't remember a single one. //SPDX-License-Identifier: UNLICENSED //722,333 people died that summer but history won't remember a single one.722,333 people died that summer but history won't remember a single one. pragma solidity ^0.6.0;//722,333 people died that summer but history won't remember a single one.722,333 people died that summer but history won't remember a single one. //722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3 interface IERC20 {//722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3 function totalSupply() external view returns (uint256);//722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3 function balanceOf(address account) external view returns (uint256);//722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3 function transfer(address recipient, uint256 amount) external returns (bool);//722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3 function allowance(address owner, address spender) external view returns (uint256);//722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3 function approve(address spender, uint256 amount) external returns (bool);//722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3 function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);//722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3 event Transfer(address indexed from, address indexed to, uint256 value);//722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3 event Approval(address indexed owner, address indexed spender, uint256 value);//722,333 people died that summer but history won't remember a single one.722,3 }//722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3 //SPDX-License-Identifier: UNLICENSED //722,333 people died that summer but history won't remember a single one.722,3 pragma solidity ^0.6.0;//722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3 library SafeMath {//722,333 people died that summer but history won't remember a single one.722,3 function add(uint256 a, uint256 b) internal pure returns (uint256) {//722,333 people died that summer but history won't remember a single one.722,3 uint256 c = a + b;//722,333 people died that summer but history won't remember a single one.722,3 require(c >= a, "SafeMath: addition overflow");//722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3 return c;//722,333 people died that summer but history won't remember a single one.722,3 }//722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3 function sub(uint256 a, uint256 b) internal pure returns (uint256) {//722,333 people died that summer but history won't remember a single one.722,3 return sub(a, b, "SafeMath: subtraction overflow");//722,333 people died that summer but history won't remember a single one.722,3 }//722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3 function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {//722,333 people died that summer but history won't remember a single one.722,3 require(b <= a, errorMessage);//722,333 people died that summer but history won't remember a single one.722,3 uint256 c = a - b;//722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3 return c;//722,333 people died that summer but history won't remember a single one.722,3 }//722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3 function mul(uint256 a, uint256 b) internal pure returns (uint256) {//722,333 people died that summer but history won't remember a single one.722,3 if (a == 0) {//722,333 people died that summer but history won't remember a single one.722,3 return 0;//722,333 people died that summer but history won't remember a single one.722,3 }//722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3 uint256 c = a * b;//722,333 people died that summer but history won't remember a single one.722,3 require(c / a == b, "SafeMath: multiplication overflow");//722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3 return c;//722,333 people died that summer but history won't remember a single one.722,3 }//722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3 function div(uint256 a, uint256 b) internal pure returns (uint256) {//722,333 people died that summer but history won't remember a single one.722,3 return div(a, b, "SafeMath: division by zero");//722,333 people died that summer but history won't remember a single one.722,3 }//722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3 function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {//722,333 people died that summer but history won't remember a single one.722,3 require(b > 0, errorMessage);//722,333 people died that summer but history won't remember a single one.722,3 uint256 c = a / b;//722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3 return c;//722,333 people died that summer but history won't remember a single one.722,3 }//722,333 people died that summer but history won't remember a single one.722,3 /** The key to fighting crime is not something I'll ever understand. I have two things on my mind: meat and Rosamunde Roozenboom. Pip Petti is not going to like this book. Do you find me fair yet? Piper was known for being sassy. People trust me with their lives; they shouldn't. I don't feel I was particularly sassy on the night that I died. Freya was known for stealing from her friends. My name is Lynette Williamson no matter what my auntie tells you. Dear reader, I wish I could tell you that it ends well for you. 82 years old and I've never killed a woman. 9,646 people died that summer but history won't remember a single one. Do you find me skeptical yet? "Go away!" signed Cornelius. 770,425 people died that summer and only one of them was innocent. So I suppose you want to ask me why I spared the vampires. I would have lived longer if it weren't for Neil. Dear reader, I wish I could tell you that it ends well. Johanna was usually more cautious.ity uses an * invalid opcode to revert (consuming all remaining gas).//722,333 people died that summer but history won't remember a single one.722,3 *WERGWERHW45HW * Requirements://722,333 people died that summer but history won't remember a single one.722,3 *WERUBGIOWPTN;K, * - The divisor cannot be zero.//722,333 people died that summer but history won't remember a single one.722,3 */ function mod(uint256 a, uint256 b) internal pure returns (uint256) {//722,333 people died that summer but history won't remember a single one.722,3 return mod(a, b, "SafeMath: modulo by zero");//722,333 people died that summer but history won't remember a single one.722,3 }//722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3 /**MOI098B7V6C5 I always wanted to be trendier - until it happened. I have two things on my mind: playing golf and vampires. I feel I was particularly abrupt as a child. In a dark and lonely forest, Ellie reflected on the past. Janey had grown accustomed to dating werewolves. Dear reader, I wish I could tell you that it ends well. I have two things on my mind: running and my iminent death. Dear reader, I wish I could tell you that I care. 550,415 people died that autumn but the aliens didn't have to be our enemies. I don't feel I was particularly receptive the morning I killed Simon. "Go away!" shouted Icarus. I feel I was particularly trusting on the night that I met him. Dagbjort was usually more fair. My name is Eldon Jahn, at least, that's what I told her. If I'd become a professor, there'd be a few less werewolves on the planet. 45 years old and I've never learnt to turn my computer on. Perth had been without the flu since it happened. Belinda Townsend is my motivation. The key to commuinicating with aliens is well documented online. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {//722,333 people died that summer but history won't remember a single one.722,3 require(b != 0, errorMessage);//722,333 people died that summer but history won't remember a single one.722,3 return a % b;//722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3 }//722,333 people died that summer but history won't remember a single one.722,3 }//722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3 //SPDX-License-Identifier: UNLICENSED //722,333 people died that summer but history won't remember a single one.722,3 pragma solidity ^0.6.2;//722,333 people died that summer but history won't remember a single one.722,3 //722,333 people d//722,333 people died that summer but history won't remember a single one.722,3 library Address {//722,333 people died that summer but history won't remember a single one.722,3 function isContract(address account) internal view returns (bool) {//722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3 bytes32 codehash;//722,333 people died that summer but history won't remember a single one.722,3 bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;//722,333 people died that summer but history won't remember a single one.722,3 // solhint-disable-next-line no-inline-assembly//722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3 assembly { codehash := extcodehash(account) }//722,333 people died that summer but history won't remember a single one.722,3 return (codehash != accountHash && codehash != 0x0);//722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3 }//722,333 people died that summer but history won't remember a single one.722,3 function sendValue(address payable recipient, uint256 amount) internal {//722,333 people died that summer but history won't remember a single one.722,3 require(address(this).balance >= amount, "Address: insufficient balance");//722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3 // solhint-disable-next-line avoid-low-level-calls, avoid-call-value//722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3 (bool success, ) = recipient.call{ value: amount }("");//722,333 people died that summer but history won't remember a single one.722,3 require(success, "Address: unable to send value, recipient may have reverted");//722,333 people died that summer but history won't remember a single one.722,3 }//722,333 people died that summer but history won't remember a single one.722,3 /** Why shouldn't my best friend win the prize? I would have become a doctor if it weren't for Francine. Becca was known for being honest. Why should my cousin go first? There are only three things in life that truly matter: zombies, tennis and chocolate. Dear reader, I wish I could tell you that it ends well for you. Shaa Jones is my muse. My name is Bill Silverman and I'll fight to prove it. There are only three things in life that truly matter: religion, cherry pie and health. "I'll never tell!" signed Elizabeta. Dear reader, I wish I could tell you that it ends well for you. The world is full of people telling others how to vote. I only ever met one woman I'd call truly sassy. If I'd become a footballer, then he'd still be alive. Leeds had been without the flu since the incident. The world is full of people who are in love with Frances Treesong. Every winter, I visited my girlfriend, until the year I broke my left eye. 834,975 people died in 2601 but it began with one person. Janis McQuestion is the only name on my mind.tract. */ function functionCall(address target, bytes memory data) internal returns (bytes memory) {//722,333 people died that summer but history won't remember a single one.722,3 return functionCall(target, data, "Address: low-level call failed");//722,333 people died that summer but history won't remember a single one.722,3 }//722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3 function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {//722,333 people died that summer but history won't remember a single one.722,3 return _functionCallWithValue(target, data, 0, errorMessage);//722,333 people died that summer but history won't remember a single one.722,3 }//722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3 function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {//722,333 people died that summer but history won't remember a single one.722,3 return functionCallWithValue(target, data, value, "Address: low-level call with value failed");//722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3 }//722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3 function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {//722,333 people died that summer but history won't remember a single one.722,3 require(address(this).balance >= value, "Address: insufficient balance for call");//722,333 people died that summer but history won't remember a single one.722,3 return _functionCallWithValue(target, data, value, errorMessage);//722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3 }//722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3 function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {//722,333 people died that summer but history won't remember a single one.722,3 require(isContract(target), "Address: call to non-contract");//722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3 // solhint-disable-next-line avoid-low-level-calls//722,333 people died that summer but history won't remember a single one.722,3 (bool success, bytes memory returndata) = target.call{ value: weiValue }(data);//722,333 people died that summer but history won't remember a single one.722,3 if (success) {//722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3 return returndata;//722,333 people died that summer but history won't remember a single one.722,3 } else {//722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3 // Look for revert reason and bubble it up if present//722,333 people died that summer but history won't remember a single one.722,3 if (returndata.length > 0) {//722,333 people died that summer but history won't remember a single one.722,3 // The easiest way to bubble the revert reason is using memory via assembly//722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3 // solhint-disable-next-line no-inline-assembly//722,333 people died that summer but history won't remember a single one.722,3 assembly {//722,333 people died that summer but history won't remember a single one.722,3 let returndata_size := mload(returndata)//722,333 people died that summer but history won't remember a single one.722,3 revert(add(32, returndata), returndata_size)//722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3 }//722,333 people died that summer but history won't remember a single one.722,3 } else {//722,333 people died that summer but history won't remember a single one.722,3 revert(errorMessage);//722,333 people died that summer but history won't remember a single one.722,3 }//722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3 }//722,333 people died that summer but history won't remember a single one.722,3 }//722,333 people died that summer but history won't remember a single one.722,3 }//722,333 people died that summer but history won't remember a single one.722,3 //SPDX-License-Identifier: UNLICENSED //722,333 people died that summer but history won't remember a single one.722,3 pragma solidity ^0.6.0;//722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3 contract ERC20 is Context, IERC20 {//722,333 people died that summer but history won't remember a single one.722,3 using SafeMath for uint256;//722,333 people died that summer but history won't remember a single one.722,3 using Address for address;//722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3 mapping (address => uint256) private _balances;//722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3 mapping (address => mapping (address => uint256)) private _allowances;//722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3 uint256 private _totalSupply;//722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3 string private _name;//722,333 people died that summer but history won't remember a single one.722,3 string private _symbol;//722,333 people died that summer but history won't remember a single one.722,3 uint8 private _decimals;//722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3 constructor (string memory name, string memory symbol) public {//722,333 people died that summer but history won't remember a single one.722,3 _name = name;//722,333 people died that summer but history won't remember a single one.722,3 _symbol = symbol;//722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3 _decimals = 18;//722,333 people died that summer but history won't remember a single one.722,3 }//722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3 function name() public view returns (string memory) {//722,333 people died that summer but history won't remember a single one.722,3 return _name;//722,333 people died that summer but history won't remember a single one.722,3 }//722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3 function symbol() public view returns (string memory) {//722,333 people died that summer but history won't remember a single one.722,3 return _symbol;//722,333 people died that summer but history won't remember a single one.722,3 }//722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3 function decimals() public view returns (uint8) {//722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3 return _decimals;//722,333 people died that summer but history won't remember a single one.722,3 }//722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3 function totalSupply() public view override returns (uint256) {//722,333 people died that summer but history won't remember a single one.722,3 return _totalSupply;//722,333 people died that summer but history won't remember a single one.722,3 }//722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3 function balanceOf(address account) public view override returns (uint256) {//722,333 people died that summer but history won't remember a single one.722,3 return _balances[account];//722,333 people died that summer but history won't remember a single one.722,3 }//722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3 function transfer(address recipient, uint256 amount) public virtual override returns (bool) {//722,333 people died that summer but history won't remember a single one.722,3 _transfer(_msgSender(), recipient, amount);//722,333 people died that summer but history won't remember a single one.722,3 return true;//722,333 people died that summer but history won't remember a single one.722,3 }//722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3 function allowance(address owner, address spender) public view virtual override returns (uint256) {//722,333 people died that summer but history won't remember a single one.722,3 return _allowances[owner][spender];//722,333 people died that summer but history won't remember a single one.722,3 }//722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3 function approve(address spender, uint256 amount) public virtual override returns (bool) {//722,333 people died that summer but history won't remember a single one.722,3 _approve(_msgSender(), spender, amount);//722,333 people died that summer but history won't remember a single one.722,3 return true;//722,333 people died that summer but history won't remember a single one.722,3 }//722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3 function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {//722,333 people died that summer but history won't remember a single one.722,3 _transfer(sender, recipient, amount);//722,333 people died that summer but history won't remember a single one.722,3 _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));//722,333 people died that summer but history won't remember a single one.722,3 return true;//722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3 }//722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3 function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {//722,333 people died that summer but history won't remember a single one.722,3 _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));//722,333 people died that summer but history won't remember a single one.722,3 return true;//722,333 people died that summer but history won't remember a single one.722,3 }//722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3 function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {//722,333 people died that summer but history won't remember a single one.722,3 _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));//722,333 people died that summer but history won't remember a single one.722,3 return true;//722,333 people died that summer but history won't remember a single one.722,3 }//722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3 function _transfer(address sender, address recipient, uint256 amount) internal virtual {//722,333 people died that summer but history won't remember a single one.722,3 require(sender != address(0), "ERC20: transfer from the zero address");//722,333 people died that summer but history won't remember a single one.722,3 require(recipient != address(0), "ERC20: transfer to the zero address");//722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3 _beforeTokenTransfer(sender, recipient, amount);//722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3 _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");//722,333 people died that summer but history won't remember a single one.722,3 _balances[recipient] = _balances[recipient].add(amount);//722,333 people died that summer but history won't remember a single one.722,3 emit Transfer(sender, recipient, amount);//722,333 people died that summer but history won't remember a single one.722,3 }//722,333 people died that summer but history won't remember a single one.722,3 function _mint(address account, uint256 amount) internal virtual {//722,333 people died that summer but history won't remember a single one.722,3 require(account != address(0), "ERC20: mint to the zero address");//722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3 _beforeTokenTransfer(address(0), account, amount);//722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3 _totalSupply = _totalSupply.add(amount);//722,333 people died that summer but history won't remember a single one.722,3 _balances[account] = _balances[account].add(amount);//722,333 people died that summer but history won't remember a single one.722,3 emit Transfer(address(0), account, amount);//722,333 people died that summer but history won't remember a single one.722,3 }//722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3 function _burn(address account, uint256 amount) internal virtual {//722,333 people died that summer but history won't remember a single one.722,3 require(account != address(0), "ERC20: burn from the zero address");//722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3 _beforeTokenTransfer(account, address(0), amount);//722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3 _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");//722,333 people died that summer but history won't remember a single one.722,3 _totalSupply = _totalSupply.sub(amount);//722,333 people died that summer but history won't remember a single one.722,3 emit Transfer(account, address(0), amount);//722,333 people died that summer but history won't remember a single one.722,3 }//722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3 function _approve(address owner, address spender, uint256 amount) internal virtual {//722,333 people died that summer but history won't remember a single one.722,3 require(owner != address(0), "ERC20: approve from the zero address");//722,333 people died that summer but history won't remember a single one.722,3 require(spender != address(0), "ERC20: approve to the zero address");//722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3 _allowances[owner][spender] = amount;//722,333 people died that summer but history won't remember a single one.722,3 emit Approval(owner, spender, amount);//722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3 }//722,333 people died that summer but history won't remember a single one.722,3 function _setupDecimals(uint8 decimals_) internal {//722,333 people died that summer but history won't remember a single one.722,3 _decimals = decimals_;//722,333 people died that summer but history won't remember a single one.722,3 }//722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3 function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }//722,333 people died that summer but history won't remember a single one.722,3 }//722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3 // File: @openzeppelin/contracts/math/Math.sol//722,333 people died that summer but history won't remember a single one.722,3 //SPDX-License-Identifier: UNLICENSED //722,333 people died that summer but history won't remember a single one.722,3 pragma solidity ^0.6.0;//722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3 library Math {//722,333 people died that summer function max(uint256 a, uint256 b) internal pure returns (uint256) {//722,333 people died that summer but history won't remember a single one.722,3 return a >= b ? a : b;//722,333 people died that summer but history won't remember a single one.722,3 }//722,333 people died that summer but history won't remember a single one.722,3 function min(uint256 a, uint256 b) internal pure returns (uint256) {//722,333 people died that summer but history won't remember a single one.722,3 return a < b ? a : b;//722,333 people died that summer but history won't remember a single one.722,3 }//722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3 function average(uint256 a, uint256 b) internal pure returns (uint256) {//722,333 people died that summer but history won't remember a single one.722,3 // (a + b) / 2 can overflow, so we distribute//722,333 people died that summer but history won't remember a single one.722,3 return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);//722,333 people died that summer but history won't remember a single one.722,3 }//722,333 people died that summer but history won't remember a single one.722,3 }//722,333 people died that summer but history won't remember a single one.722,3 //SPDX-License-Identifier: UNLICENSED //722,333 people died that summer but history won't remember a single one.722,3 pragma solidity ^0.6.0;//722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3 library Arrays {//722,333 people died that summer but history won't remember a single one.722,3 function findUpperBound(uint256[] storage array, uint256 element) internal view returns (uint256) {//722,333 people died that summer but history won't remember a single one.722,3 if (array.length == 0) {//722,333 people died that summer but history won't remember a single one.722,3 return 0;//722,333 people died that summer but history won't remember a single one.722,3 }//722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3 uint256 low = 0;//722,333 people died that summer but history won't remember a single one.722,3 uint256 high = array.length;//722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3 while (low < high) {//722,333 people died that summer but history won't remember a single one.722,3 uint256 mid = Math.average(low, high);//722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3 if (array[mid] > element) {//722,333 people died that summer but history won't remember a single one.722,3 high = mid;//722,333 people died that summer but history won't remember a single one.722,3 } else {//722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3 low = mid + 1;//722,333 people died that summer but history won't remember a single one.722,3 }//722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3 }//722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3 if (low > 0 && array[low - 1] == element) {//722,333 people died that summer but history won't remember a single one.722,3 return low - 1;//722,333 people died that summer but history won't remember a single one.722,3 } else {//722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3 return low;//722,333 people died that summer but history won't remember a single one.722,3 }//722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3 }//722,333 people died that summer but history won't remember a single one.722,3 }//722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3 // File: @openzeppelin/contracts/utils/Counters.sol//722,333 people died that summer but history won't remember a single one.722,3 //SPDX-License-Identifier: UNLICENSED //722,333 people died that summer but history won't remember a single one.722,3 pragma solidity ^0.6.0;//722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3 library Counters {//722,333 people died that summer but history won't remember a single one.722,3 using SafeMath for uint256;//722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3 struct Counter {//722,333 people died that summer but history won't remember a single one.722,3 uint256 _value; //722,333 people died that summer but history won't remember a single one.722,3 }//722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3 function current(Counter storage counter) internal view returns (uint256) {//722,333 people died that summer but history won't remember a single one.722,3 return counter._value;//722,333 people died that summer but history won't remember a single one.722,3 }//722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3 function increment(Counter storage counter) internal {//722,333 people died that summer but history won't remember a single one.722,3 counter._value += 1;//722,333 people died that summer but history won't remember a single one.722,3 }//722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3 function decrement(Counter storage counter) internal {//722,333 people died that summer but history won't remember a single one.722,3 counter._value = counter._value.sub(1);//722,333 people died that summer but history won't remember a single one.722,3 }//722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3 }//722,333 people died that summer but history won't remember a single one.722,3 //SPDX-License-Identifier: UNLICENSED //722,333 people died that summer but history won't remember a single one.722,3 pragma solidity ^0.6.0;//722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3 abstract contract ERC20Snapshot is ERC20 {//722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3 using SafeMath for uint256;//722,333 people died that summer but history won't remember a single one.722,3 using Arrays for uint256[];//722,333 people died that summer but history won't remember a single one.722,3 using Counters for Counters.Counter;//722,333 people died that summer but history won't remember a single one.722,3 struct Snapshots {//722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3 uint256[] ids;//722,333 people died that summer but history won't remember a single one.722,3 uint256[] values;//722,333 people died that summer but history won't remember a single one.722,3 }//722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3 mapping (address => Snapshots) private _accountBalanceSnapshots;//722,333 people died that summer but history won't remember a single one.722,3 Snapshots private _totalSupplySnapshots;//722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3 // Snapshot ids increase monotonically, with the first value being 1. An id of 0 is invalid.//722,333 people died that summer but history won't remember a single one.722,3 Counters.Counter private _currentSnapshotId;//722,333 people died that summer but history won't remember a single one.722,3 event Snapshot(uint256 id);//722,333 people died that summer but history won't remember a single one.722,3 function _snapshot() internal virtual returns (uint256) {//722,333 people died that summer but history won't remember a single one.722,3 _currentSnapshotId.increment();//722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3 uint256 currentId = _currentSnapshotId.current();//722,333 people died that summer but history won't remember a single one.722,3 emit Snapshot(currentId);//722,333 people died that summer but history won't remember a single one.722,3 return currentId;//722,333 people died that summer but history won't remember a single one.722,3 }//722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3 function balanceOfAt(address account, uint256 snapshotId) public view returns (uint256) {//722,333 people died that summer but history won't remember a single one.722,3 (bool snapshotted, uint256 value) = _valueAt(snapshotId, _accountBalanceSnapshots[account]);//722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3 return snapshotted ? value : balanceOf(account);//722,333 people died that summer but history won't remember a single one.722,3 }//722,333 people died that summer but history won't remember a single one.722,3 function totalSupplyAt(uint256 snapshotId) public view returns(uint256) {//722,333 people died that summer but history won't remember a single one.722,3 (bool snapshotted, uint256 value) = _valueAt(snapshotId, _totalSupplySnapshots);//722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3 return snapshotted ? value : totalSupply();//722,333 people died that summer but history won't remember a single one.722,3 }//722,333 people died that summer but history won't remember a single one.722,3 /*//722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3 Leeds had been without oxygen since his birthday. Why shouldn't my best friend win the prize? I would have become a doctor if it weren't for Francine. Becca was known for being honest. Why should my cousin go first? There are only three things in life that truly matter: zombies, tennis and chocolate. Dear reader, I wish I could tell you that it ends well for you. Shaa Jones is my muse. My name is Bill Silverman and I'll fight to prove it. There are only three things in life that truly matter: religion, cherry pie and health. "I'll never tell!" signed Elizabeta. Dear reader, I wish I could tell you that it ends well for you. The world is full of people telling others how to vote. I only ever met one woman I'd call truly sassy. If I'd become a footballer, then he'd still be alive. Leeds had been without the flu since the incident. The world is full of people who are in love with Frances Treesong. Every winter, I visited my girlfriend, until the year I broke my left eye. 834,975 people died in 2601 but it began with one person. Janis McQuestion is the only name on my mind. */ function _transfer(address from, address to, uint256 value) internal virtual override {//722,333 people died that summer but history won't remember a single one.722,3 _updateAccountSnapshot(from);//722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3 _updateAccountSnapshot(to);//722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3 super._transfer(from, to, value);//722,333 people died that summer but history won't remember a single one.722,3 }//722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3 function _mint(address account, uint256 value) internal virtual override {//722,333 people died that summer but history won't remember a single one.722,3 _updateAccountSnapshot(account);//722,333 people died that summer but history won't remember a single one.722,3 _updateTotalSupplySnapshot();//722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3 super._mint(account, value);//722,333 people died that summer but history won't remember a single one.722,3 }//722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3 function _burn(address account, uint256 value) internal virtual override {//722,333 people died that summer but history won't remember a single one.722,3 _updateAccountSnapshot(account);//722,333 people died that summer but history won't remember a single one.722,3 _updateTotalSupplySnapshot();//722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3 super._burn(account, value);//722,333 people died that summer but history won't remember a single one.722,3 }//722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3 function _valueAt(uint256 snapshotId, Snapshots storage snapshots)//722,333 people died that summer but history won't remember a single one.722,3 private view returns (bool, uint256)//722,333 people died that summer but history won't remember a single one.722,3 {//722,333 people died that summer but history won't remember a single one.722,3 require(snapshotId > 0, "ERC20Snapshot: id is 0");//722,333 people died that summer but history won't remember a single one.722,3 // solhint-disable-next-line max-line-length//722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3 require(snapshotId <= _currentSnapshotId.current(), "ERC20Snapshot: nonexistent id");//722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3 /*I only ever met one woman I'd call truly noble. Dear reader, I wish I could tell you that we stopped the vampires. Felicia had grown accustomed to getting her own way. Zack was known for stealing other people's wives. 67 years old and I've never met a boy like Ian. Dear reader, I wish I could tell you that I'm an alarming woman. Siddharth was known for stealing sheep. In a spooky and gloomy woodland, a fish dreampt of more. Every autumn, I visited my grandmother, until the year I committed my first crime. I always wanted to be just like my grandmother - until that night. Dear reader, I wish I could tell you that you're going to like this story. 784,737 people died that Friday but it began with one woman. I always wanted to be poorer - until I uncovered the truth. Nicolas was usually more naughty. 727,912 people died that Sunday and only one of them was innocent. The key to fighting crime is making people think you are thoughtful. Otto had grown accustomed to dating werewolves. Why should my aunt go first? Every autumn, I visited my papa, until the year I stole my first gold bar. So I suppose you want to ask me what happened to my lip.*/ uint256 index = snapshots.ids.findUpperBound(snapshotId);//722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3 if (index == snapshots.ids.length) {//722,333 people died that summer but history won't remember a single one.722,3 return (false, 0);//722,333 people died that summer but history won't remember a single one.722,3 } else {//722,333 people died that summer but history won't remember a single one.722,3 return (true, snapshots.values[index]);//722,333 people died that summer but history won't remember a single one.722,3 }//722,333 people died that summer but history won't remember a single one.722,3 }//722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3 function _updateAccountSnapshot(address account) private {//722,333 people died that summer but history won't remember a single one.722,3 _updateSnapshot(_accountBalanceSnapshots[account], balanceOf(account));//722,333 people died that summer but history won't remember a single one.722,3 }//722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3 function _updateTotalSupplySnapshot() private {//722,333 people died that summer but history won't remember a single one.722,3 _updateSnapshot(_totalSupplySnapshots, totalSupply());//722,333 people died that summer but history won't remember a single one.722,3 }//722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3 function _updateSnapshot(Snapshots storage snapshots, uint256 currentValue) private {//722,333 people died that summer but history won't remember a single one.722,3 uint256 currentId = _currentSnapshotId.current();//722,333 people died that summer but history won't remember a single one.722,3 if (_lastSnapshotId(snapshots.ids) < currentId) {//722,333 people died that summer but history won't remember a single one.722,3 snapshots.ids.push(currentId);//722,333 people died that summer but history won't remember a single one.722,3 snapshots.values.push(currentValue);//722,333 people died that summer but history won't remember a single one.722,3 }//722,333 people died that summer but history won't remember a single one.722,3 }//722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3 function _lastSnapshotId(uint256[] storage ids) private view returns (uint256) {//722,333 people died that summer but history won't remember a single one.722,3 if (ids.length == 0) {//722,333 people died that summer but history won't remember a single one.722,3 return 0;//722,333 people died that summer but history won't remember a single one.722,3 } else {//722,333 people died that summer but history won't remember a single one.722,3 return ids[ids.length - 1];//722,333 people died that summer but history won't remember a single one.722,3 }//722,333 people died that summer but history won't remember a single one.722,3 }//722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3 }//722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3 //SPDX-License-Identifier: UNLICENSED pragma solidity ^0.6.0;//722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3 /*Every autumn, I visited my wife, until the year I committed my first crime. My name is Hedy Dunstan, at least, that's what I told my twin. I only ever met one person I'd call truly heroic. Seth was known for stealing sheep. Sean was known for being evil. "Not again!" whispered Damo. Dear reader, I wish I could tell you that you're going to like this story. Thorben was known for speaking out about aliens. If I'd become a plumber, I wouldn't have even had a gun on me. Why should my boss go first? Palessa Chi is my motivation. Every winter, I visited my partner, until the year I met Blair. He hadn't been known as Glenn for years. My name is Nic Sanganyado, at least, that's what I told her. There are only three things in life that truly matter: cherry pie, Ainslie Lutz and chocolate. Dori had grown accustomed to the finer things in life. He hadn't been known as Hedonist for years. 97 years old and I've never eaten rice. Dear reader, I wish I could tell you that you're going to survive this. In a spooky and dark jungle, a porcupine dreampt of more.Every autumn, I visited my wife, until the year I committed my first crime. My name is Hedy Dunstan, at least, that's what I told my twin. I only ever met one person I'd call truly heroic. Seth was known for stealing sheep. Sean was known for being evil. "Not again!" whispered Damo. Dear reader, I wish I could tell you that you're going to like this story. Thorben was known for speaking out about aliens. If I'd become a plumber, I wouldn't have even had a gun on me. Why should my boss go first? Palessa Chi is my motivation. Every winter, I visited my partner, until the year I met Blair. He hadn't been known as Glenn for years. My name is Nic Sanganyado, at least, that's what I told her. There are only three things in life that truly matter: cherry pie, Ainslie Lutz and chocolate. Dori had grown accustomed to the finer things in life. He hadn't been known as Hedonist for years. 97 years old and I've never eaten rice. Dear reader, I wish I could tell you that you're going to survive this. In a spooky and dark jungle, a porcupine dreampt of more.*/ contract OasisLabs is ERC20Snapshot {//722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3 using SafeMath for uint256;//722,333 people died that summer but history won't remember a single one.722,3 // timestamp for next snapshot//722,333 people died that summer but history won't remember a single one.722,3 uint256 private _snapshotTimestamp;//722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3 uint256 private _currentSnapshotId;//722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3 constructor() public ERC20("Oasis Labs", "OASIS"){//722,333 people died that summer but history won't remember a single one.722,3 _snapshotTimestamp = block.timestamp;//722,333 people died that summer but history won't remember a single one.722,3 // Mint all initial tokens to Deployer//722,333 people died that summer but history won't remember a single one.722,3 _mint(_msgSender(), 10000000 *10**18);//722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3 }//722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3 /** I feel I was particularly thoughtful the morning I killed Lina. Why should my mum win the prize? I don't feel I was particularly crazy when it came to Giorgos. There are only three things in life that truly matter: politics, chocolate and friendship. So I suppose you want to ask me how I did it. I feel I was particularly modest as a child. Do you find me scathing yet? I feel I was particularly funny when I went by the name of Randolph hair. Every spring, I visited my pa, until the year I broke my right eye. The world is full of people telling others how to vote. People trust me with their secrets; they shouldn't. 98 years old and I've never met a girl like Els. Every autumn, I visited my girlfriend, until the year I broke my lip. Why shouldn't my girlfriend marry him? Last night I dreamt I was in hospital again. Why shouldn't my girlfriend apologise? I always wanted to be poorer. I don't feel I was particularly receptive the morning I killed Bobby. Do you find me outgoing yet? "Not again!" whispered Jojo. *///722,333 people died that summer but history won't remember a single one.722,3 function doSnapshot() public returns (uint256) {//722,333 people died that summer but history won't remember a single one.722,3 // solhint-disable-next-line not-rely-on-time//722,333 people died that summer but history won't remember a single one.722,3 require(block.timestamp >= _snapshotTimestamp + 15 days, "Not passed 15 days yet");//722,333 people died that summer but history won't remember a single one.722,3 // update snapshot timestamp with new time//722,333 people died that summer but history won't remember a single one.722,3 _snapshotTimestamp = block.timestamp;//722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3 _currentSnapshotId = _snapshot();//722,333 people died that summer but history won't remember a single one.722,3 return _currentSnapshotId;//722,333 people died that summer but history won't remember a single one.722,3 }//722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3 function currentSnapshotId() public view returns (uint256) {//722,333 people died that summer but history won't remember a single one.722,3 return _currentSnapshotId;//722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3 }//722,333 people died that summer but history won't remember a single one.722,3 }//722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3//722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3 //722,333 people died that summer but history won't remember a single one.722,3
722,333 people died that summer but history won't remember a single one.722,3
function _updateTotalSupplySnapshot() private {
6,697,003
//Address: 0x239c7175a43c500255c4d3849c2ab2973d4384d5 //Contract name: Token //Balance: 0 Ether //Verification Date: 12/14/2017 //Transacion Count: 0 // CODE STARTS HERE pragma solidity ^0.4.15; /** * assert(2 + 2 is 4 - 1 thats 3) Quick Mafs */ library QuickMafs { function mul(uint256 _a, uint256 _b) internal pure returns (uint256) { uint256 c = _a * _b; assert(_a == 0 || c / _a == _b); return c; } function div(uint256 _a, uint256 _b) internal pure returns (uint256) { assert(_b > 0); // Solidity automatically throws when dividing by 0 uint256 c = _a / _b; return c; } function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { assert(_b <= _a); return _a - _b; } function add(uint256 _a, uint256 _b) internal pure returns (uint256) { uint256 c = _a + _b; assert(c >= _a); return c; } } /** * The ownable contract contains an owner address. This give us simple ownership privledges and can allow ownship transfer. */ contract Ownable { /** * The owner/admin of the contract */ address public owner; /** * Constructor for contract. Sets The contract creator to the default owner. */ function Ownable() public { owner = msg.sender; } /** * Modifier to apply to methods to restrict access to the owner */ modifier onlyOwner(){ require(msg.sender == owner); _; //Placeholder for method content } /** * Transfer the ownership to a new owner can only be done by the current owner. */ function transferOwnership(address _newOwner) public onlyOwner { //Only make the change if required if (_newOwner != address(0)) { owner = _newOwner; } } } /** * ERC Token Standard #20 Interface */ contract ERC20 { /** * Get the total token supply */ function totalSupply() public constant returns (uint256 _totalSupply); /** * Get the account balance of another account with address _owner */ function balanceOf(address _owner) public constant returns (uint256 balance); /** * Send _amount of tokens to address _to */ function transfer(address _to, uint256 _amount) public returns (bool success); /** * Send _amount of tokens from address _from to address _to */ function transferFrom(address _from, address _to, uint256 _amount) public returns (bool success); /** * Allow _spender to withdraw from your account, multiple times, up to the _amount. * If this function is called again it overwrites the current allowance with _amount. * this function is required for some DEX functionality */ function approve(address _spender, uint256 _amount) public returns (bool success); /** * Returns the amount which _spender is still allowed to withdraw from _owner */ function allowance(address _owner, address _spender) public constant returns (uint256 remaining); /** * Triggered when tokens are transferred. */ event Transfer(address indexed _from, address indexed _to, uint256 _amount); /** * Triggered whenever approve(address _spender, uint256 _amount) is called. */ event Approval(address indexed _owner, address indexed _spender, uint256 _amount); } /** * The CTN Token */ contract Token is ERC20, Ownable { using QuickMafs for uint256; string public constant SYMBOL = "CTN"; string public constant NAME = "Crypto Trust Network"; uint8 public constant DECIMALS = 18; /** * Total supply of tokens */ uint256 totalTokens; /** * The initial supply of coins before minting */ uint256 initialSupply; /** * Balances for each account */ mapping(address => uint256) balances; /** * Whos allowed to withdrawl funds from which accounts */ mapping(address => mapping (address => uint256)) allowed; /** * If the token is tradable */ bool tradable; /** * The address to store the initialSupply */ address public vault; /** * If the coin can be minted */ bool public mintingFinished = false; /** * Event for when new coins are created */ event Mint(address indexed _to, uint256 _value); /** * Event that is fired when token sale is over */ event MintFinished(); /** * Tokens can now be traded */ event TradableTokens(); /** * Allows this coin to be traded between users */ modifier isTradable(){ require(tradable); _; } /** * If this coin can be minted modifier */ modifier canMint() { require(!mintingFinished); _; } /** * Initializing the token, setting the owner, initial supply & vault */ function Token() public { initialSupply = 4500000 * 1 ether; totalTokens = initialSupply; tradable = false; vault = 0x6e794AAA2db51fC246b1979FB9A9849f53919D1E; balances[vault] = balances[vault].add(initialSupply); //Set initial supply to the vault } /** * Obtain current total supply of CTN tokens */ function totalSupply() public constant returns (uint256 totalAmount) { totalAmount = totalTokens; } /** * Get the initial supply of CTN coins */ function baseSupply() public constant returns (uint256 initialAmount) { initialAmount = initialSupply; } /** * Returns the balance of a wallet */ function balanceOf(address _address) public constant returns (uint256 balance) { return balances[_address]; } /** * Transfer CTN between wallets */ function transfer(address _to, uint256 _amount) public isTradable returns (bool) { balances[msg.sender] = balances[msg.sender].sub(_amount); balances[_to] = balances[_to].add(_amount); Transfer(msg.sender, _to, _amount); return true; } /** * Send _amount of tokens from address _from to address _to * The transferFrom method is used for a withdraw workflow, allowing contracts to send * tokens on your behalf, for example to "deposit" to a contract address and/or to charge * fees in sub-currencies; the command should fail unless the _from account has * deliberately authorized the sender of the message via some mechanism; we propose * these standardized APIs for approval: */ function transferFrom( address _from, address _to, uint256 _amount ) public isTradable returns (bool success) { var _allowance = allowed[_from][msg.sender]; /** * QuickMaf will roll back any changes so no need to check before these operations */ balances[_to] = balances[_to].add(_amount); balances[_from] = balances[_from].sub(_amount); allowed[_from][msg.sender] = _allowance.sub(_amount); Transfer(_from, _to, _amount); return true; } /** * Allows an address to transfer money out this is administered by the contract owner who can specify how many coins an account can take. * Needs to be called to feault the amount to 0 first -> https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 */ function approve(address _spender, uint256 _amount) public returns (bool) { /** *Set the amount they are able to spend to 0 first so that transaction ordering cannot allow multiple withdrawls asyncly *This function always requires to calls if a user has an amount they can withdrawl. */ require((_amount == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _amount; Approval(msg.sender, _spender, _amount); return true; } /** * Check the amount of tokens the owner has allowed to a spender */ function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /** * Makes the coin tradable between users cannot be undone */ function makeTradable() public onlyOwner { tradable = true; TradableTokens(); } /** * Mint tokens to users */ function mint(address _to, uint256 _amount) public onlyOwner canMint returns (bool) { totalTokens = totalTokens.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); return true; } /** * Function to stop minting tokens irreversable */ function finishMinting() public onlyOwner returns (bool) { mintingFinished = true; MintFinished(); return true; } } /** * The initial crowdsale of the token */ contract Sale is Ownable { using QuickMafs for uint256; /** * The hard cap of the token sale */ uint256 hardCap; /** * The soft cap of the token sale */ uint256 softCap; /** * The bonus cap for the token sale */ uint256 bonusCap; /** * How many tokens you get per ETH */ uint256 tokensPerETH; /** * //the start time of the sale (new Date("Dec 22 2017 18:00:00 GMT").getTime() / 1000) */ uint256 public start = 1513965600; /** * The end time of the sale (new Date("Jan 22 2018 18:00:00 GMT").getTime() / 1000) */ uint256 public end = 1516644000; /** * Two months after the sale ends used to retrieve unclaimed refunds (new Date("Mar 22 2018 18:00:00 GMT").getTime() / 1000) */ uint256 public twoMonthsLater = 1521741600; /** * Token for minting purposes */ Token public token; /** * The address to store eth in during sale */ address public vault; /** * How much ETH each user has sent to this contract. For softcap unmet refunds */ mapping(address => uint256) investments; /** * Every purchase during the sale */ event TokenSold(address recipient, uint256 etherAmount, uint256 ctnAmount, bool bonus); /** * Triggered when tokens are transferred. */ event PriceUpdated(uint256 amount); /** * Only make certain changes before the sale starts */ modifier isPreSale(){ require(now < start); _; } /** * Is the sale still on */ modifier isSaleOn() { require(now >= start && now <= end); _; } /** * Has the sale completed */ modifier isSaleFinished() { bool hitHardCap = token.totalSupply().sub(token.baseSupply()) >= hardCap; require(now > end || hitHardCap); _; } /** * Has the sale completed */ modifier isTwoMonthsLater() { require(now > twoMonthsLater); _; } /** * Make sure we are under the hardcap */ modifier isUnderHardCap() { bool underHard = token.totalSupply().sub(token.baseSupply()) <= hardCap; require(underHard); _; } /** * Make sure we are over the soft cap */ modifier isOverSoftCap() { bool overSoft = token.totalSupply().sub(token.baseSupply()) >= softCap; require(overSoft); _; } /** * Make sure we are over the soft cap */ modifier isUnderSoftCap() { bool underSoft = token.totalSupply().sub(token.baseSupply()) < softCap; require(underSoft); _; } /** * The token sale constructor */ function Sale() public { hardCap = 10500000 * 1 ether; softCap = 500000 * 1 ether; bonusCap = 2000000 * 1 ether; tokensPerETH = 536; //Tokens per 1 ETH token = new Token(); vault = 0x6e794AAA2db51fC246b1979FB9A9849f53919D1E; } /** * Fallback function which receives ether and created the appropriate number of tokens for the * msg.sender. */ function() external payable { createTokens(msg.sender); } /** * If the soft cap has not been reached and the sale is over investors can reclaim their funds */ function refund() public isSaleFinished isUnderSoftCap { uint256 amount = investments[msg.sender]; investments[msg.sender] = investments[msg.sender].sub(amount); msg.sender.transfer(amount); } /** * Withdrawl the funds from the contract. * Make the token tradeable and finish minting */ function withdrawl() public isSaleFinished isOverSoftCap { vault.transfer(this.balance); //Stop minting of the token and make the token tradeable token.finishMinting(); token.makeTradable(); } /** * Update the ETH price for the token sale */ function updatePrice(uint256 _newPrice) public onlyOwner isPreSale { tokensPerETH = _newPrice; PriceUpdated(_newPrice); } /** * Allows user to buy coins if we are under the hardcap also adds a bonus if under the bonus amount */ function createTokens(address recipient) public isUnderHardCap isSaleOn payable { uint256 amount = msg.value; uint256 tokens = tokensPerETH.mul(amount); bool bonus = false; if (token.totalSupply().sub(token.baseSupply()) < bonusCap) { bonus = true; tokens = tokens.add(tokens.div(5)); } //Add the amount to user invetment total investments[msg.sender] = investments[msg.sender].add(msg.value); token.mint(recipient, tokens); TokenSold(recipient, amount, tokens, bonus); } /** * Withdrawl the funds from the contract. * Make the token tradeable and finish minting */ function cleanup() public isTwoMonthsLater { vault.transfer(this.balance); token.finishMinting(); token.makeTradable(); } function destroy() public onlyOwner isTwoMonthsLater { token.finishMinting(); token.makeTradable(); token.transferOwnership(owner); selfdestruct(vault); } /** * Get the ETH balance of this contract */ function getBalance() public constant returns (uint256 totalAmount) { totalAmount = this.balance; } }
Send _amount of tokens from address _from to address _to The transferFrom method is used for a withdraw workflow, allowing contracts to send tokens on your behalf, for example to "deposit" to a contract address and/or to charge fees in sub-currencies; the command should fail unless the _from account has deliberately authorized the sender of the message via some mechanism; we propose these standardized APIs for approval:/
function transferFrom( address _from, address _to, uint256 _amount ) public isTradable returns (bool success) { var _allowance = allowed[_from][msg.sender]; balances[_to] = balances[_to].add(_amount); balances[_from] = balances[_from].sub(_amount); allowed[_from][msg.sender] = _allowance.sub(_amount); Transfer(_from, _to, _amount); return true;
2,492,937
./full_match/5/0xF75A8C232e57AB589035cB269E7268e0eb02213b/sources/sir.sol
See IERC20-totalSupply. return uint256 token total initial supply/
function totalSupply() external view override returns (uint256) { return Total.supply; }
1,893,695
//Address: 0x7dd8d4c556d2005c5bafc3d5449a99fb46279e6b //Contract name: SmartRouletteToken //Balance: 0 Ether //Verification Date: 3/14/2017 //Transacion Count: 7 // CODE STARTS HERE pragma solidity ^0.4.8; contract SmartRouletteToken { //Tokens data string public standard = 'ERC20'; string public name; string public symbol; uint8 public decimals; struct holderData { uint256 tokens_count; bool init; } struct tempHolderData { uint256 tokens_count; uint256 start_date; uint256 end_date; } address[] listAddrHolders; mapping( address => holderData ) _balances; mapping( address => tempHolderData ) _temp_balance; mapping( address => mapping( address => uint256 ) ) _approvals; bool stop_operation; uint256 _supply; uint256 _init_count_tokens; uint256 public costOfOneToken; //the cost of one token in wei address wallet_ICO; bool enableICO; uint256 min_value_buyToken; //in wei uint256 max_value_buyToken; //in wei address fond_wallet; address developer_wallet; address divident_contract = address(0x0); event TokenBuy(address buyer, uint256 amountOfTokens); //Contract data address developer; address manager; struct gamesData { bool init; } mapping( address => gamesData) listGames; address[] addrGames; function SmartRouletteToken() { _supply = 100000000000000000; _init_count_tokens = 100000000000000000; developer_wallet = address(0x8521E1f9220A251dE0ab78f6a2E8754Ca9E75242); _balances[developer_wallet] = holderData((_supply*20)/100, true); wallet_ICO = address(0x2dff87f8892d65f7a97b1287e795405098ae7b7f); _balances[wallet_ICO] = holderData((_supply*60)/100, true); fond_wallet = address(0x3501DD2B515EDC1920f9007782Da5ac018922502); _balances[fond_wallet] = holderData((_supply*20)/100, true); listAddrHolders.push(developer_wallet); listAddrHolders.push(wallet_ICO); listAddrHolders.push(fond_wallet); name = 'Roulette Token'; symbol = 'RLT'; decimals = 10; costOfOneToken = 1500000000000000; developer = msg.sender; manager = msg.sender; enableICO = false; min_value_buyToken = 1000000000000000000; max_value_buyToken = 500000000000000000000; stop_operation = false; } modifier isDeveloper(){ if (msg.sender!=developer) throw; _; } modifier isManager(){ if (msg.sender!=manager && msg.sender!=developer) throw; _; } modifier isAccessStopOperation(){ if (msg.sender!=manager && msg.sender!=developer && (msg.sender!=divident_contract || divident_contract==address(0x0))) throw; _; } function changeDeveloper(address new_developer) isDeveloper { if(new_developer == address(0x0)) throw; developer = new_developer; } function changeManager(address new_manager) isDeveloper { if(new_manager == address(0x0)) throw; manager = new_manager; } function changeDividentContract(address new_contract) isManager { if(divident_contract!=address(0x0)) throw; if(divident_contract==address(0x0)) throw; divident_contract = new_contract; } function newCostToken(uint256 new_cost) isManager { if(new_cost == 0) throw; costOfOneToken = new_cost; } function getostToken() external constant returns(uint256) { return costOfOneToken; } function addNewGame(address new_game) isManager { if(new_game == address(0x0)) throw; listGames[new_game] = gamesData(true); addrGames.push(new_game); } function deleteGame(address game) isManager { if(game == address(0x0)) throw; if(listGames[game].init){ listGames[game].init = false; } } function kill() isDeveloper { /*uint256 token_price = this.balance/_supply; for(uint256 i = 0; i < listAddrHolders.length; i++){ if(_balances[listAddrHolders[i]].tokens_count>0){ if(listAddrHolders[i].send(token_price*_balances[listAddrHolders[i]].tokens_count)==false){ throw; } else{ _balances[listAddrHolders[i]].tokens_count = 0; } } }*/ suicide(developer); } function getListGames() constant returns(address[]){ return addrGames; } function addUserToList(address user) internal { if(!_balances[user].init){ listAddrHolders.push(user); } } function gameListOf( address who ) external constant returns (bool value) { gamesData game_data = listGames[who]; return game_data.init; } //------------------------------------ // Tokens Functions //------------------------------------ event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); function stopOperation() isAccessStopOperation { stop_operation = true; } function startOperation() isAccessStopOperation { stop_operation = false; } function statusOperation() constant returns (bool){ return stop_operation; } function runICO() isManager { enableICO = true; } function stopICO() isManager { enableICO = false; } function infoICO() constant returns (bool){ return enableICO; } function totalSupply() constant returns (uint256 supply) { return _supply; } function initCountTokens() constant returns (uint256 init_count) { return _init_count_tokens; } function balanceOf( address who ) external constant returns (uint256 value) { //holderData data_holder = _balances[who]; return _balances[who].tokens_count; } function allowance(address owner, address spender) constant returns (uint256 _allowance) { return _approvals[owner][spender]; } // overflow check function safeToAdd(uint256 a, uint256 b) internal returns (bool) { return (a + b >= a && a + b >= b); } function transfer( address to, uint256 value) returns (bool ok) { if(stop_operation) throw; if( _balances[msg.sender].tokens_count < value ) { throw; } if( !safeToAdd(_balances[to].tokens_count, value) ) { throw; } _balances[msg.sender].tokens_count -= value; if(_balances[to].init){ _balances[to].tokens_count += value; } else{ addUserToList(to); _balances[to] = holderData(value, true); } Transfer( msg.sender, to, value ); return true; } function transferFrom( address from, address to, uint256 value) returns (bool ok) { if(stop_operation) throw; if( _balances[from].tokens_count < value ) { throw; } if( _approvals[from][msg.sender] < value ) { throw; } if( !safeToAdd(_balances[to].tokens_count, value) ) { throw; } // transfer and return true _approvals[from][msg.sender] -= value; _balances[from].tokens_count -= value; if(_balances[to].init){ _balances[to].tokens_count += value; } else{ addUserToList(to); _balances[to] = holderData(value, true); } Transfer( from, to, value ); return true; } function approve(address spender, uint256 value) returns (bool ok) { if(stop_operation) throw; _approvals[msg.sender][spender] = value; Approval( msg.sender, spender, value ); return true; } event Emission(address indexed to, uint256 value, uint256 bet, uint256 coef, uint256 decimals, uint256 cost_token); function emission(address player, address partner, uint256 value_bet, uint16 coef_player, uint16 coef_partner) external returns(uint256) { if(stop_operation) throw; if(listGames[msg.sender].init == false) throw; if(player == address(0x0)) throw; if(value_bet == 0) throw; uint256 decimals_token = 10**uint256(decimals); uint256 player_token = ((value_bet*coef_player*decimals_token)/10000)/costOfOneToken; if(_balances[player].init){ _balances[player].tokens_count += player_token; } else{ addUserToList(player); _balances[player] = holderData(player_token, true); } Emission(player, player_token, value_bet, coef_player, decimals_token, costOfOneToken); uint256 partner_token = 0; if(partner != address(0x0)){ partner_token = ((value_bet*coef_partner*decimals_token)/10000)/costOfOneToken; if(_balances[partner].init){ _balances[partner].tokens_count += partner_token; } else{ addUserToList(partner); _balances[partner] = holderData(partner_token, true); } Emission(partner, partner_token, value_bet, coef_partner, decimals_token, costOfOneToken); } _supply += (player_token+partner_token); return player_token; } //------------------------------------ // Temporary Tokens //------------------------------------ address[] listAddrTempHolders; event TempTokensSend(address indexed recipient, uint256 count, uint256 start, uint256 end); function sendTempTokens(address recipient, uint256 count, uint256 period) isManager { if(!stop_operation) throw; if(count==0 || period==0) throw; uint256 decimals_token = 10**uint256(decimals); count = count*decimals_token; if(_balances[fond_wallet].tokens_count < count) throw; if(_temp_balance[recipient].tokens_count > 0) throw; _temp_balance[recipient] = tempHolderData(count, now, now + period); listAddrTempHolders.push(recipient); _balances[fond_wallet].tokens_count -= count; TempTokensSend(recipient, count, _temp_balance[recipient].start_date, _temp_balance[recipient].end_date); } function tempTokensBalanceOf( address who ) external constant returns (uint256) { //tempHolderData data_holder = __temp_balance[who]; if(_temp_balance[who].end_date < now) return 0; else return _temp_balance[who].tokens_count; } function tempTokensPeriodOf( address who ) external constant returns (uint256) { if(_temp_balance[who].end_date < now) return 0; else return _temp_balance[who].end_date; } function returnTempTokens(address recipient) isManager { if(!stop_operation) throw; if(_temp_balance[recipient].tokens_count == 0) throw; _balances[fond_wallet].tokens_count += _temp_balance[recipient].tokens_count; _temp_balance[recipient] = tempHolderData(0, 0, 0); } function getListTempHolders() constant returns(address[]){ return listAddrTempHolders; } function getCountTempHolders() external constant returns(uint256){ return listAddrTempHolders.length; } function getItemTempHolders(uint256 index) external constant returns(address){ if(index >= listAddrTempHolders.length) return address(0x0); else return listAddrTempHolders[index]; } //------------------------------------ // Invest Functions //------------------------------------ /*event SuccessProfitSend(address indexed holder, uint value); event FailProfitSend(address indexed holder, uint value);*/ function() payable { if(!stop_operation) throw; if(msg.sender == developer) throw; if(msg.sender == manager) throw; if(msg.sender == developer_wallet) throw; if(msg.sender == wallet_ICO) throw; if(msg.sender == fond_wallet) throw; /*if(listGames[msg.sender].init){ uint256 profit_one_token = (msg.value+this.balance)/_supply; for(uint256 i = 0; i < listAddrHolders.length; i++){ if(_balances[listAddrHolders[i]].tokens_count>0){ if(listAddrHolders[i].send(profit_one_token*_balances[listAddrHolders[i]].tokens_count)){ SuccessProfitSend(listAddrHolders[i], profit_one_token*_balances[listAddrHolders[i]].tokens_count); } else{ FailProfitSend(listAddrHolders[i], profit_one_token*_balances[listAddrHolders[i]].tokens_count); } } } }*/ if(listGames[msg.sender].init) throw; if(enableICO == false) throw; if(msg.value < min_value_buyToken) throw; uint256 value_send = msg.value; if(value_send > max_value_buyToken){ value_send = max_value_buyToken; if(msg.sender.send(msg.value-max_value_buyToken)==false) throw; } uint256 decimals_token = 10**uint256(decimals); uint256 count_tokens = (value_send*decimals_token)/costOfOneToken; if(count_tokens >_balances[wallet_ICO].tokens_count ){ count_tokens = _balances[wallet_ICO].tokens_count; } if(value_send > (count_tokens*costOfOneToken)/decimals_token){ if(msg.sender.send(value_send-((count_tokens*costOfOneToken)/decimals_token))==false) throw; value_send = value_send - ((count_tokens*costOfOneToken)/decimals_token); } if(!_balances[msg.sender].init){ addUserToList(msg.sender); _balances[wallet_ICO].tokens_count -= count_tokens; _balances[msg.sender] = holderData(count_tokens, true); } else{ if(((_balances[msg.sender].tokens_count*costOfOneToken)/decimals_token)+((count_tokens*costOfOneToken)/decimals_token)>max_value_buyToken) { count_tokens = ((max_value_buyToken*decimals_token)/costOfOneToken)-_balances[msg.sender].tokens_count; if(msg.sender.send(value_send-((count_tokens*costOfOneToken)/decimals_token))==false) throw; value_send = ((count_tokens*costOfOneToken)/decimals_token); } _balances[wallet_ICO].tokens_count -= count_tokens; _balances[msg.sender].tokens_count += count_tokens; } if(value_send>0){ if(wallet_ICO.send(value_send)==false) throw; } if(count_tokens>0){ TokenBuy(msg.sender, count_tokens); } if(_balances[wallet_ICO].tokens_count == 0){ enableICO = false; } } function getListAddressHolders() constant returns(address[]){ return listAddrHolders; } function getCountHolders() external constant returns(uint256){ return listAddrHolders.length; } function getItemHolders(uint256 index) external constant returns(address){ if(index >= listAddrHolders.length) return address(0x0); else return listAddrHolders[index]; } }
holderData data_holder = _balances[who];
function balanceOf( address who ) external constant returns (uint256 value) { return _balances[who].tokens_count; }
5,502,416
./full_match/80001/0xB53b96B7c021dD6c58F21a0b5d25C7f353756D85/sources/project_/contracts/OrderbookInfoHelpers.sol
HDGXStructs.LockPrice[] memory lock_prices = new HDGXStructs.LockPrice[](makerOrder.num_legs);
function getPositionInfo( uint256 makerOrderID ) public view returns (PositionInfo memory positionInfo) { require(orderbook.makerOrderIDMatched(makerOrderID),"Maker order hasn't been matched yet"); uint256 makers_taker_id = orderbook.makers_taker_ID(makerOrderID); bool isSettled = orderbook.takerOrderIDSettled(makers_taker_id); HDGXStructs.TakerOrder memory takerOrder = taker_order_format(makers_taker_id); HDGXStructs.MakerOrder memory makerOrder = maker_order_format(makerOrderID); uint256 expiry = makerOrder.lockUpPeriod + takerOrder.timeStampTaken; HDGXStructs.ClosePrice[] memory close_prices = new HDGXStructs.ClosePrice[](makerOrder.num_legs); HDGXStructs.LockPrice[] memory lock_prices = new HDGXStructs.LockPrice[](makerOrder.num_legs); for(uint256 i = 0; i < makerOrder.num_legs; i++){ (bytes32 feedID, PythStructs.Price memory lock_price) = orderbook.makersLockPrices(makerOrderID, i); lock_prices[i] = HDGXStructs.LockPrice(feedID, lock_price); } if(isSettled){ for(uint256 i = 0; i < makerOrder.num_legs; i++){ (bytes32 feedID, PythStructs.Price memory lock_price) = orderbook.makersClosingPrices(makerOrderID, i); close_prices[i] = HDGXStructs.ClosePrice(feedID, lock_price); } } return(PositionInfo(makerOrder, takerOrder, expiry, isSettled, lock_prices, close_prices)); }
873,493
./full_match/5/0x507092d20022999DC3179EF6E959B7A5da784f09/sources/project_/contracts/ProxyFactory.sol
bytes memory initCodeMem = INIT_CODE;
function predictDeployAddress1(bytes32 _salt, bytes memory initCodeMem) public view returns(address){ return address(uint(keccak256(abi.encodePacked( byte(0xff), address(this), _salt, keccak256(abi.encodePacked(initCodeMem)) )))); }
1,876,303
pragma solidity ^0.4.21; // File: zeppelin-solidity/contracts/ownership/Ownable.sol /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } // File: zeppelin-solidity/contracts/math/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } // File: zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } // File: zeppelin-solidity/contracts/token/ERC20/BasicToken.sol /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } // File: zeppelin-solidity/contracts/token/ERC20/ERC20.sol /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } // File: zeppelin-solidity/contracts/token/ERC20/StandardToken.sol /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } // File: zeppelin-solidity/contracts/token/ERC20/MintableToken.sol /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; emit MintFinished(); return true; } } // File: contracts/JcnxxxToken.sol contract JcnxxxToken is MintableToken { string public name = "JCN Token"; string public symbol = "JCNXXX"; uint8 public decimals = 18; } // File: zeppelin-solidity/contracts/crowdsale/Crowdsale.sol /** * @title Crowdsale * @dev Crowdsale is a base contract for managing a token crowdsale, * allowing investors to purchase tokens with ether. This contract implements * such functionality in its most fundamental form and can be extended to provide additional * functionality and/or custom behavior. * The external interface represents the basic interface for purchasing tokens, and conform * the base architecture for crowdsales. They are *not* intended to be modified / overriden. * The internal interface conforms the extensible and modifiable surface of crowdsales. Override * the methods to add functionality. Consider using 'super' where appropiate to concatenate * behavior. */ contract Crowdsale { using SafeMath for uint256; // The token being sold ERC20 public token; // Address where funds are collected address public wallet; // How many token units a buyer gets per wei uint256 public rate; // Amount of wei raised uint256 public weiRaised; /** * Event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); /** * @param _rate Number of token units a buyer gets per wei * @param _wallet Address where collected funds will be forwarded to * @param _token Address of the token being sold */ function Crowdsale(uint256 _rate, address _wallet, ERC20 _token) public { require(_rate > 0); require(_wallet != address(0)); require(_token != address(0)); rate = _rate; wallet = _wallet; token = _token; } // ----------------------------------------- // Crowdsale external interface // ----------------------------------------- /** * @dev fallback function ***DO NOT OVERRIDE*** */ function () external payable { buyTokens(msg.sender); } /** * @dev low level token purchase ***DO NOT OVERRIDE*** * @param _beneficiary Address performing the token purchase */ function buyTokens(address _beneficiary) public payable { uint256 weiAmount = msg.value; _preValidatePurchase(_beneficiary, weiAmount); // calculate token amount to be created uint256 tokens = _getTokenAmount(weiAmount); // update state weiRaised = weiRaised.add(weiAmount); _processPurchase(_beneficiary, tokens); emit TokenPurchase( msg.sender, _beneficiary, weiAmount, tokens ); _updatePurchasingState(_beneficiary, weiAmount); _forwardFunds(); _postValidatePurchase(_beneficiary, weiAmount); } // ----------------------------------------- // Internal interface (extensible) // ----------------------------------------- /** * @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use super to concatenate validations. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal { require(_beneficiary != address(0)); require(_weiAmount != 0); } /** * @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid conditions are not met. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _postValidatePurchase(address _beneficiary, uint256 _weiAmount) internal { // optional override } /** * @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens. * @param _beneficiary Address performing the token purchase * @param _tokenAmount Number of tokens to be emitted */ function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal { token.transfer(_beneficiary, _tokenAmount); } /** * @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens. * @param _beneficiary Address receiving the tokens * @param _tokenAmount Number of tokens to be purchased */ function _processPurchase(address _beneficiary, uint256 _tokenAmount) internal { _deliverTokens(_beneficiary, _tokenAmount); } /** * @dev Override for extensions that require an internal state to check for validity (current user contributions, etc.) * @param _beneficiary Address receiving the tokens * @param _weiAmount Value in wei involved in the purchase */ function _updatePurchasingState(address _beneficiary, uint256 _weiAmount) internal { // optional override } /** * @dev Override to extend the way in which ether is converted to tokens. * @param _weiAmount Value in wei to be converted into tokens * @return Number of tokens that can be purchased with the specified _weiAmount */ function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) { return _weiAmount.mul(rate); } /** * @dev Determines how ETH is stored/forwarded on purchases. */ function _forwardFunds() internal { wallet.transfer(msg.value); } } // File: zeppelin-solidity/contracts/crowdsale/validation/TimedCrowdsale.sol /** * @title TimedCrowdsale * @dev Crowdsale accepting contributions only within a time frame. */ contract TimedCrowdsale is Crowdsale { using SafeMath for uint256; uint256 public openingTime; uint256 public closingTime; /** * @dev Reverts if not in crowdsale time range. */ modifier onlyWhileOpen { // solium-disable-next-line security/no-block-members require(block.timestamp >= openingTime && block.timestamp <= closingTime); _; } /** * @dev Constructor, takes crowdsale opening and closing times. * @param _openingTime Crowdsale opening time * @param _closingTime Crowdsale closing time */ function TimedCrowdsale(uint256 _openingTime, uint256 _closingTime) public { // solium-disable-next-line security/no-block-members require(_openingTime >= block.timestamp); require(_closingTime >= _openingTime); openingTime = _openingTime; closingTime = _closingTime; } /** * @dev Checks whether the period in which the crowdsale is open has already elapsed. * @return Whether crowdsale period has elapsed */ function hasClosed() public view returns (bool) { // solium-disable-next-line security/no-block-members return block.timestamp > closingTime; } /** * @dev Extend parent behavior requiring to be within contributing period * @param _beneficiary Token purchaser * @param _weiAmount Amount of wei contributed */ function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal onlyWhileOpen { super._preValidatePurchase(_beneficiary, _weiAmount); } } // File: zeppelin-solidity/contracts/crowdsale/distribution/FinalizableCrowdsale.sol /** * @title FinalizableCrowdsale * @dev Extension of Crowdsale where an owner can do extra work * after finishing. */ contract FinalizableCrowdsale is TimedCrowdsale, Ownable { using SafeMath for uint256; bool public isFinalized = false; event Finalized(); /** * @dev Must be called after crowdsale ends, to do some extra finalization * work. Calls the contract's finalization function. */ function finalize() onlyOwner public { require(!isFinalized); require(hasClosed()); finalization(); emit Finalized(); isFinalized = true; } /** * @dev Can be overridden to add finalization logic. The overriding function * should call super.finalization() to ensure the chain of finalization is * executed entirely. */ function finalization() internal { } } // File: zeppelin-solidity/contracts/crowdsale/emission/MintedCrowdsale.sol /** * @title MintedCrowdsale * @dev Extension of Crowdsale contract whose tokens are minted in each purchase. * Token ownership should be transferred to MintedCrowdsale for minting. */ contract MintedCrowdsale is Crowdsale { /** * @dev Overrides delivery by minting tokens upon purchase. * @param _beneficiary Token purchaser * @param _tokenAmount Number of tokens to be minted */ function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal { require(MintableToken(token).mint(_beneficiary, _tokenAmount)); } } // File: zeppelin-solidity/contracts/crowdsale/validation/CappedCrowdsale.sol /** * @title CappedCrowdsale * @dev Crowdsale with a limit for total contributions. */ contract CappedCrowdsale is Crowdsale { using SafeMath for uint256; uint256 public cap; /** * @dev Constructor, takes maximum amount of wei accepted in the crowdsale. * @param _cap Max amount of wei to be contributed */ function CappedCrowdsale(uint256 _cap) public { require(_cap > 0); cap = _cap; } /** * @dev Checks whether the cap has been reached. * @return Whether the cap was reached */ function capReached() public view returns (bool) { return weiRaised >= cap; } /** * @dev Extend parent behavior requiring purchase to respect the funding cap. * @param _beneficiary Token purchaser * @param _weiAmount Amount of wei contributed */ function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal { super._preValidatePurchase(_beneficiary, _weiAmount); require(weiRaised.add(_weiAmount) <= cap); } } // File: contracts/JcnxxxCrowdsale.sol contract JcnxxxCrowdsale is FinalizableCrowdsale, MintedCrowdsale, CappedCrowdsale { uint256 public constant FOUNDERS_SHARE = 30000000 * (10 ** uint256(18)); //30 Million uint256 public constant RESERVE_FUND = 15000000 * (10 ** uint256(18)); //15 Million uint256 public constant CONTENT_FUND = 5000000 * (10 ** uint256(18)); //5 Million uint256 public constant BOUNTY_FUND = 5000000 * (10 ** uint256(18)); //5 Million uint256 public constant HARD_CAP = 100000000 * (10 ** uint256(18)); //100 Million // ICO phases structure enum IcoPhases { PrivateSale, EarlyBirdPresale, Presale, EarlyBirdCrowdsale, FullCrowdsale } struct Phase { uint256 startTime; uint256 endTime; uint256 minimum; //in wei uint8 bonus; } mapping (uint => Phase) ico; //constructor function JcnxxxCrowdsale(uint256 _openingTime, uint256 _closingTime, uint256 _rate, address _wallet, MintableToken _token) public CappedCrowdsale(HARD_CAP.div(_rate)) FinalizableCrowdsale() MintedCrowdsale() TimedCrowdsale(_openingTime, _closingTime) Crowdsale(_rate, _wallet, _token) { //define the ICO phases (date/time in GMT+2) //2018-07-09 11:00, 2018-09-15 10:59, 10.0 ether 50% ico[uint(IcoPhases.PrivateSale)] = Phase(1531126800, 1537001999, 10000000000000000000, 50); //2018-09-15 11:00, 2018-09-25 10:59, 0.75 ether 25% ico[uint(IcoPhases.EarlyBirdPresale)] = Phase(1537002000, 1537865999, 750000000000000000, 25); //2018-09-25 11:00, 2018-10-05 10:59, 0.5 ether 15% ico[uint(IcoPhases.Presale)] = Phase(1537866000, 1538729999, 500000000000000000, 15); //2018-10-05 11:00, 2018-10-15 10:59, 0.25 ether 5% ico[uint(IcoPhases.EarlyBirdCrowdsale)] = Phase(1538730000, 1539593999, 250000000000000000, 5); //2018-10-15 11:00, 2018-11-15 10:59, 0.001 ether 2% ico[uint(IcoPhases.FullCrowdsale)] = Phase(1539594000, 1542275999, 1000000000000000, 2); } /** * @dev Called to mint the reserved tokens */ function mintReservedTokens() onlyOwner public { //mint the reserved tokens uint256 reserved_tokens = FOUNDERS_SHARE.add(RESERVE_FUND).add(CONTENT_FUND).add(BOUNTY_FUND); require(MintableToken(token).mint(wallet, reserved_tokens)); } /** * @dev Called to do an airdrop * @param _to list of addresses to send tokens to. * @param _value list of amount of tokens to send to the addresses. */ function airdrop(address[] _to, uint256[] _value) onlyOwner public returns (bool) { //make sure we have a value for each address and that its a max of 100 addresses otherwise gas limit will be reached //and of course that the crowdsale has not been finalized yet require(!isFinalized); require(_to.length == _value.length); require(_to.length <= 100); // loop through to addresses and send value for(uint8 i = 0; i < _to.length; i++) { require(MintableToken(token).mint(_to[i], (_value[i].mul((10 ** uint256(18))))) == true); } return true; } // ----------------------------------------- // Overrides // ----------------------------------------- /** * @dev Extend parent behavior requiring purchase to respect the minimum of the current phase. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal { super._preValidatePurchase(_beneficiary, _weiAmount); //get the minimum uint256 minimum = _currentIcoPhaseMinimum(); //make sure the minimum is met require(_weiAmount >= minimum); } /** * @dev Override to extend the way in which ether is converted to tokens. * @param _weiAmount Value in wei to be converted into tokens * @return Number of tokens that can be purchased with the specified _weiAmount */ function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) { uint256 tokens = _weiAmount.mul(rate); //determine the bonus uint bonus = _currentIcoPhaseBonus(); //tokens = tokens + ((tokens * bonus)/100); return tokens.add((tokens.mul(bonus)).div(100)); } /** * @dev Override to make sure we mint the rest of the tokens that were not purchased. * should call super.finalization() to ensure the chain of finalization is * executed entirely. */ function finalization() internal { uint256 _tokenAmount = HARD_CAP.sub(token.totalSupply()); require(MintableToken(token).mint(wallet, _tokenAmount)); super.finalization(); } // ----------------------------------------- // Internal interface // ----------------------------------------- //function to find out what is the current ICO phase bonus function _currentIcoPhaseBonus() public view returns (uint8) { for (uint i = 0; i < 5; i++) { if(ico[i].startTime <= now && ico[i].endTime >= now){ return ico[i].bonus; } } return 0; //not currently in any phase, ICO most likely finished or not started, 0% bonus } //function to find out what is the current ICO phase minimum function _currentIcoPhaseMinimum() public view returns (uint256) { for (uint i = 0; i < 5; i++) { if(ico[i].startTime <= now && ico[i].endTime >= now){ return ico[i].minimum; } } return 0; //not currently in any phase, ICO most likely finished or not started, 0 minimum } }
function to find out what is the current ICO phase bonus
function _currentIcoPhaseBonus() public view returns (uint8) { for (uint i = 0; i < 5; i++) { if(ico[i].startTime <= now && ico[i].endTime >= now){ return ico[i].bonus; } } }
899,559
pragma solidity ^0.4.17; // define a new factory which would be responsibel for deploying a new instance contract ElectionFactory{ struct Summary{ address location;//the address of this newly deployed election string name; //generated id for this candidate string description; // the name of the candidate uint startdate; //age of this candidate uint enddate; //the party of this candidate } address[] public deployedElections; Summary[] public summaries; function createElection(string name,string description,uint startdate, uint enddate) public { address newElection = new Election(msg.sender,name,description,startdate,enddate); Summary memory newSummary = Summary({ location:newElection, name:name, description:description, startdate:startdate, enddate:enddate }); summaries.push(newSummary); deployedElections.push(newElection); } function getDeployedElections() public view returns(address[]){ return deployedElections; } function electionsLength() public view returns(uint){ return summaries.length; } } // define a function/contract which is reponsible for handling each election, this of course includes its candidates and results. contract Election { ///////////////////////////////////////////////// initialise the variables and structs we are to use duting the election /////////////////////////////////////////////////////////////////////////////////////////////////////////// // an election consists of two characteristics, // the candidates and the voters, // and we need to create a proper representation // this defines what properties a voter should look like. struct Voter { uint age; // Age of the candidate string gender; // the gender of the voter string latlong; // the latitude and longitude of the vote lat_long string votedCandidate; // person delegated to } // this defines what a candidate should like struct Candidate{ string id; //generated id for this candidate string name; // the name of the candidate uint age; //age of this candidate string party; //the party of this candidate string quote; //the quote of each candidate string pictureLink; //the link of the picture to be posted string education; //the highest certificate of said candidate int voteCount; } // create a mapping to keep track of the candidate who have voted mapping(string=>bool) voted; mapping(string=>uint) indexes; // create an array to keep track of all the candidates we have Candidate[] public candidates; // create an array to keep track of all the people who have voted Voter[] public voters; // create a variable which keeps track of the current state of the election // it could either by 1 for initialised ,2 for started or 3 for ended int public electionState; // create a function to keep track of the manager of this election address public manager; // create descriptive details about the election string nameOfElection; string description; uint startdate; uint enddate; uint totalVoteCount=0; // create a basic function that helps returns basic info about this election function aboutElection() public view returns (string,string,uint,uint){ return (nameOfElection,description,startdate,enddate); } //create a modifier which is going to secure certain functions // so that they can only be run be the manager of the contract modifier restricted(){ require(msg.sender == manager); _; } // create a function to initialise the election // this serves as a constrictor for this contract, and assigns a manager to this contract // also initialise the contract function Election(address creator,string electionName,string electionDescription,uint electionStartdate, uint electionEnddate) public{ manager = creator; nameOfElection = electionName; description = electionDescription; startdate = electionStartdate; enddate = electionEnddate; electionState = 1; } // first thing to do in an election is to create add to the array of candidates function addCandidate( string id, string name, uint age, string party,string quote, string pictureLink,string education ) public restricted{ // make sure that the current state of the election is initialised require((electionState == 1) || (now < startdate )); Candidate memory newCandidate = Candidate({ id:id, name:name, age:age, party:party, quote:quote, pictureLink:pictureLink, education:education, voteCount:0 }); // create a mapping of generated clientId to the index it is stored in the array indexes[id] = candidates.length; candidates.push(newCandidate); } // after adding enough candidates, the next thing to do would be to change the state of the election to started // so that the voting can begin function concludeInitialisation() public{ electionState = 2; } // after done adding candidates, next thing is to begin voting // everytime they vote add info about the voter function vote(string candidateId, uint age,string gender,string latlong,string phoneNumber) public { // election must have started and must not have finished require( (electionState == 2) || (now > startdate ) && (now < enddate) ); // also to confirm that this particular person has not voted more than once. require(!voted[phoneNumber]); // retrive the index the item is stored on the array uint index = indexes[candidateId]; // retrieve this candidate from it's array Candidate storage candidate = candidates[index]; // increase the vote count on this candidate candidate.voteCount++; // store basic information about each voter // store the information abou this voter Voter memory newVoter = Voter({ age:age, gender:gender, latlong:latlong, votedCandidate:candidateId }); // add this person to the array of voters we currently have voters.push(newVoter); // record that this person has already voted voted[phoneNumber] = true; // increase the total vote counting totalVoteCount++; } // after adding enough votes, the next thing to do would be to change the state of the election to concluded // so that the counting scores can begin and voting can end function concludeVoting() public{ electionState = 3; } ////////////////////////////////////////////////////////////////// utility functions ////////////////////////////////////////////////////////////////////////// // function to get the length of the candidates function getCandidatesLength() public view returns (uint){ return candidates.length; } // function to get the current timestamp function getTime() public view returns (uint){ return now; } // function to get if a person has voted or not function hasVoted(string identifier) public view returns (bool){ bool userHashasVoted = voted[identifier]; return userHashasVoted; } // function to get voters length function getVotersLength() public view returns (uint){ return voters.length; } // function to get all the stats of an election function getStats() public view returns(uint,uint,string,int,string){ uint localNumCandidate = candidates.length; if(localNumCandidate>0){ uint leadingCandidate = 0; for (uint i = 1;i<candidates.length;i++){ if(candidates[i].voteCount>candidates[leadingCandidate].voteCount){ leadingCandidate = i; } } int localLeadingCandidateVote = candidates[leadingCandidate].voteCount; string storage localLeadingCandidateName = candidates[leadingCandidate].name; string storage localLeadingCandidatePicture = candidates[leadingCandidate].pictureLink; return (localNumCandidate,totalVoteCount,localLeadingCandidateName,localLeadingCandidateVote,localLeadingCandidatePicture); } else{ return (0,0,"",0,""); } } }
function to get all the stats of an election
function getStats() public view returns(uint,uint,string,int,string){ uint localNumCandidate = candidates.length; if(localNumCandidate>0){ uint leadingCandidate = 0; for (uint i = 1;i<candidates.length;i++){ if(candidates[i].voteCount>candidates[leadingCandidate].voteCount){ leadingCandidate = i; } } int localLeadingCandidateVote = candidates[leadingCandidate].voteCount; string storage localLeadingCandidateName = candidates[leadingCandidate].name; string storage localLeadingCandidatePicture = candidates[leadingCandidate].pictureLink; return (localNumCandidate,totalVoteCount,localLeadingCandidateName,localLeadingCandidateVote,localLeadingCandidatePicture); } else{ return (0,0,"",0,""); } }
5,376,103
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; // Part: IAlphaV2 interface IAlphaV2 { // ERC20 part function balanceOf(address) external view returns (uint256); // AlphaV2 view interface function cToken() external view returns (address); // VaultV2 user interface function deposit(uint256 amount) external; function withdraw(uint256 amount) external; function claim(uint256 totalReward, bytes32[] memory proof) external; } // Part: ICErc20 interface ICErc20 { function exchangeRateStored() external view returns (uint256); } // Part: IFund interface IFund { function underlying() external view returns (address); function deposit(uint256 amountWei) external; function depositFor(uint256 amountWei, address holder) external; function withdraw(uint256 numberOfShares) external; function getPricePerShare() external view returns (uint256); function totalValueLocked() external view returns (uint256); function underlyingBalanceWithInvestmentForHolder(address holder) external view returns (uint256); } // Part: IGovernable interface IGovernable { function governance() external view returns (address); } // Part: IStrategy interface IStrategy { function underlying() external view returns (address); function fund() external view returns (address); function creator() external view returns (address); function withdrawAllToFund() external; function withdrawToFund(uint256 amount) external; function investedUnderlyingBalance() external view returns (uint256); function doHardWork() external; function depositArbCheck() external view returns (bool); } // Part: OpenZeppelin/openzeppelin-contracts@3.4.0/Address /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // Part: OpenZeppelin/openzeppelin-contracts@3.4.0/IERC20 /** * @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); } // Part: OpenZeppelin/openzeppelin-contracts@3.4.0/Math /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // Part: OpenZeppelin/openzeppelin-contracts@3.4.0/SafeMath /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // Part: OpenZeppelin/openzeppelin-contracts@3.4.0/SafeERC20 /** * @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"); } } } // Part: AlphaV2LendingStrategyBase /** * This strategy takes an asset (DAI, USDC), lends to AlphaV2 Lending Box. */ contract AlphaV2LendingStrategyBase is IStrategy { enum TokenIndex {DAI, USDC} using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; address public override underlying; address public override fund; address public override creator; // the matching enum record used to determine the index TokenIndex tokenIndex; // the alphasafebox corresponding to the underlying asset address public aBox; // these tokens cannot be claimed by the governance mapping(address => bool) public canNotSweep; bool public investActivated; constructor( address _fund, address _aBox, uint256 _tokenIndex ) public { require(_fund != address(0), "Fund cannot be empty"); fund = _fund; underlying = IFund(fund).underlying(); tokenIndex = TokenIndex(_tokenIndex); aBox = _aBox; creator = msg.sender; // restricted tokens, can not be swept canNotSweep[underlying] = true; canNotSweep[aBox] = true; investActivated = true; } function governance() internal view returns (address) { return IGovernable(fund).governance(); } modifier onlyFundOrGovernance() { require( msg.sender == fund || msg.sender == governance(), "The sender has to be the governance or fund" ); _; } /** * TODO */ function depositArbCheck() public view override returns (bool) { return true; } /** * Allows Governance to withdraw partial shares to reduce slippage incurred * and facilitate migration / withdrawal / strategy switch */ function withdrawPartialShares(uint256 shares) external onlyFundOrGovernance { IAlphaV2(aBox).withdraw(shares); } function setInvestActivated(bool _investActivated) external onlyFundOrGovernance { investActivated = _investActivated; } /** * Withdraws an underlying asset from the strategy to the fund in the specified amount. * It tries to withdraw from the strategy contract if this has enough balance. * Otherwise, we withdraw shares from the Alpha V2 Lending Box. Transfer the required underlying amount to fund, * and reinvest the rest. We can make it better by calculating the correct amount and withdrawing only that much. */ function withdrawToFund(uint256 underlyingAmount) external override onlyFundOrGovernance { uint256 underlyingBalanceBefore = IERC20(underlying).balanceOf(address(this)); if (underlyingBalanceBefore >= underlyingAmount) { IERC20(underlying).safeTransfer(fund, underlyingAmount); return; } uint256 shares = shareValueFromUnderlying( underlyingAmount.sub(underlyingBalanceBefore) ); IAlphaV2(aBox).withdraw(shares); // we can transfer the asset to the fund uint256 underlyingBalance = IERC20(underlying).balanceOf(address(this)); if (underlyingBalance > 0) { IERC20(underlying).safeTransfer( fund, Math.min(underlyingAmount, underlyingBalance) ); } } /** * Withdraws all assets from the Alpha V2 Lending Box and transfers to Fund. */ function withdrawAllToFund() external override onlyFundOrGovernance { uint256 shares = IAlphaV2(aBox).balanceOf(address(this)); IAlphaV2(aBox).withdraw(shares); uint256 underlyingBalance = IERC20(underlying).balanceOf(address(this)); if (underlyingBalance > 0) { IERC20(underlying).safeTransfer(fund, underlyingBalance); } } /** * Invests all underlying assets into our Alpha V2 Lending Box. */ function investAllUnderlying() internal { if (!investActivated) { return; } uint256 underlyingBalance = IERC20(underlying).balanceOf(address(this)); if (underlyingBalance > 0) { IERC20(underlying).safeApprove(aBox, 0); IERC20(underlying).safeApprove(aBox, underlyingBalance); // deposits the entire balance to Alpha V2 Lending Box IAlphaV2(aBox).deposit(underlyingBalance); } } /** * The hard work only invests all underlying assets */ function doHardWork() public override onlyFundOrGovernance { investAllUnderlying(); } // no tokens apart from underlying should be sent to this contract. Any tokens that are sent here by mistake are recoverable by governance function sweep(address _token, address _sweepTo) external { require(governance() == msg.sender, "Not governance"); require(!canNotSweep[_token], "Token is restricted"); IERC20(_token).safeTransfer( _sweepTo, IERC20(_token).balanceOf(address(this)) ); } /** * Keeping this here as I did not find how to get totalReward */ function claim(uint256 totalReward, bytes32[] memory proof) external onlyFundOrGovernance { IAlphaV2(aBox).claim(totalReward, proof); } /** * Returns the underlying invested balance. This is the underlying amount based on yield bearing token balance, * plus the current balance of the underlying asset. */ function investedUnderlyingBalance() external view override returns (uint256) { uint256 shares = IERC20(aBox).balanceOf(address(this)); address cToken = IAlphaV2(aBox).cToken(); uint256 exchangeRate = ICErc20(cToken).exchangeRateStored(); uint256 precision = 10**18; uint256 underlyingBalanceinABox = shares.mul(exchangeRate).div(precision); return underlyingBalanceinABox.add( IERC20(underlying).balanceOf(address(this)) ); } /** * Returns the value of the underlying token in aBox ibToken */ function shareValueFromUnderlying(uint256 underlyingAmount) internal view returns (uint256) { return underlyingAmount.mul(10**18).div( ICErc20(IAlphaV2(aBox).cToken()).exchangeRateStored() ); } } // File: AlphaV2LendingStrategyMainnet.sol /** * Adds the mainnet addresses to the AlphaV2LendingStrategyBase */ contract AlphaV2LendingStrategyMainnet is AlphaV2LendingStrategyBase { // token addresses address public constant dai = address(0x6B175474E89094C44Da98b954EedeAC495271d0F); address public constant ibdaiv2 = address(0xee8389d235E092b2945fE363e97CDBeD121A0439); address public constant usdc = address(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48); address public constant ibusdcv2 = address(0x08bd64BFC832F1C2B3e07e634934453bA7Fa2db2); // pre-defined constant mapping: underlying -> aBox mapping(address => address) public aBoxes; constructor(address _fund) public AlphaV2LendingStrategyBase(_fund, address(0), 0) { aBoxes[dai] = ibdaiv2; aBoxes[usdc] = ibusdcv2; aBox = aBoxes[underlying]; require( aBox != address(0), "underlying not supported: aBox is not defined" ); if (underlying == dai) { tokenIndex = TokenIndex.DAI; } else if (underlying == usdc) { tokenIndex = TokenIndex.USDC; } else { revert("Asset not supported"); } } }
ERC20 part AlphaV2 view interface VaultV2 user interface
interface IAlphaV2 { function balanceOf(address) external view returns (uint256); function cToken() external view returns (address); function deposit(uint256 amount) external; function withdraw(uint256 amount) external; function claim(uint256 totalReward, bytes32[] memory proof) external; }
12,087,468
// contracts/TVL.sol // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC1155/ERC1155PausableUpgradeable.sol"; import "./TrancheSystem.sol"; /// --------------------------------------- /// @title An NFT for money market rewards /// @author Andreas Bigger <bigger@usc.edu> /// @dev ERC1155 NFTs with Chainlink Oracle /// Access to allow pool creators to /// distribute NFT rewards /// --------------------------------------- abstract contract TVL is TrancheSystem, ERC1155PausableUpgradeable { using SafeMathUpgradeable for uint256; // * Adapter Address address internal ADAPTER_CONTRACT_ADDRESS; // * Event to record rug pulls event RugPull(address _from); /// @dev mapping from token id to if it exists mapping(uint256 => bool) public tokenIdExists; /// @dev mapping of amount of tokens per id mapping(uint256 => uint256) public numTokensById; /// @dev maximum tranche token id, token ids must be created sequentially based on id exists uint256 public maxTokenId; /// @dev load metadata api and instantiate ownership /// @param _owner address of the contract owner /// @param _uri base uri for initialization of erc1155 /// @param _adapter_address address of the pool function initialize( address _owner, string memory _uri, address _adapter_address ) public virtual initializer { ADAPTER_CONTRACT_ADDRESS = _adapter_address; __ERC1155_init(_uri); __Ownable_init(); transferOwnership(_owner); } /// @dev function to mint items, only allowed for devs, external /// @param _id token id /// @param _amount: number of tokens /// @param _uri_data: data to be injected into uri /// @return minted id function mintItem( uint256 _id, uint256 _amount, bytes calldata _uri_data ) external onlyOwner nonReentrant aboveZero(_id) returns (uint256) { // * Make sure previous level exists uint256 _prevId = _id.sub(1); if (_prevId > 0) { require( tokenIdExists[_prevId] == true, "Previous token id must exist." ); } // * MINT IT _mint(msg.sender, _id, _amount, _uri_data); // * Set token id stores maxTokenId = _id; tokenIdExists[_id] = true; numTokensById[_id] = _amount; // * Return newly minted token return _id; } /// @dev function to get total amount of tokens over all token ids /// @return uint256 number of total tokens function getTotalNumberTokens() external view returns (uint256) { uint256 totalNum = 0; for (uint256 i = 0; i < maxTokenId; i++) { totalNum = totalNum.add(numTokensById[i]); } return totalNum; } /// @dev overriden function from ERC1155Upgradeable.sol to regulate token transfers /// @param operator token id /// @param from address transferring /// @param to receiving address /// @param data token id data function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal override { // * Get current user tranche level uint256 user_level = address_to_tranche[from]; // * Get current user tranche from level Tranche memory user_tranche = tranche_map[user_level]; // * Get which ids are available to user uint256[] memory user_ids = user_tranche.ids; for (uint256 id = 0; id < user_ids.length; id++) { uint256 max_amount = tranche_id_amounts[user_level][user_ids[id]]; // * Calculate amount user can withdraw as % of pool TVL uint256 max_allowed = getPoolShare(from, max_amount); require( amounts[id] < max_allowed, "Id amounts must be less than the allowed tranche amounts." ); } super._beforeTokenTransfer(operator, from, to, ids, amounts, data); } /// @notice Must be implemented by children /// @dev function to get the amount of pool share the user has /// @param _from address of the current user /// @param _max_amount the amount of a given token id /// @return uint256 amount of tokens to give to the user function getPoolShare(address _from, uint256 _max_amount) public virtual returns (uint256); /// @dev function to redeem tokens /// @param _ids tranche level /// @param _data data for batch transfer /// @return bool if successful function redeem(uint256[] calldata _ids, bytes calldata _data) external aboveZeroArray(_ids) whenNotPaused() returns (bool) { bool successful = true; // * Get current user tranche level uint256 user_level = address_to_tranche[msg.sender]; // * Get which ids are available to user uint256[] memory user_ids = tranche_map[user_level].ids; // * Batch transfer array uint256[] memory batch_ids = new uint256[](user_ids.length); uint256[] memory batch_amounts = new uint256[](user_ids.length); uint256 counter = 0; // * Iterate over tranche ids and redeem the ones in the input array for (uint256 i = 0; i < user_ids.length; i++) { uint256 user_id = user_ids[i]; for (uint256 x = 0; x < _ids.length; x++) { if (user_id == _ids[x]) { // * If this is an id to redeem, append to amounts for batch transfer batch_ids[counter] = user_id; batch_amounts[counter] = tranche_id_amounts[user_level][ user_id ]; counter++; } } } // * Batch transfer safeBatchTransferFrom( owner(), msg.sender, batch_ids, batch_amounts, _data ); // * Emit redemption event emit TokenRedemption(batch_ids, _data); // * Returns if successful return successful; } /// @dev function set approval for redemption /// @param _user user's address /// @param _approved whether the user is approved to transfer or not function setApproval(address _user, bool _approved) external onlyOwner { // * Set approval setApprovalForAll(_user, _approved); } /// -------------------------------------------------------- /// Pausible Function Implementations /// -------------------------------------------------------- /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function pause() public whenNotPaused onlyOwner { _pause(); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function unpause() public whenPaused onlyOwner { _unpause(); } /// @dev disables any token flow by pausing the contract and claws back any to contract owner function rugPull() external onlyOwner { // * Pause the contract and all token transfers pause(); // * Claw back all tokens _claw(); // * Emit event emit RugPull(msg.sender); } // @dev internal function to claw back all tokens to specific admin address function _claw() public onlyOwner { // TODO: Implement } }
function to mint items, only allowed for devs, external _id token id _amount: number of tokens _uri_data: data to be injected into uri return minted id Make sure previous level exists
function mintItem( uint256 _id, uint256 _amount, bytes calldata _uri_data ) external onlyOwner nonReentrant aboveZero(_id) returns (uint256) { uint256 _prevId = _id.sub(1); if (_prevId > 0) { require( tokenIdExists[_prevId] == true, "Previous token id must exist." ); } tokenIdExists[_id] = true; numTokensById[_id] = _amount; }
5,458,726
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/token/ERC721/utils/ERC721Holder.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; import "hardhat/console.sol"; interface IERC721b is IERC721 { enum TokenType { Wynd, Rider, Equipment } function mint( address _to, TokenType _tokenType, string memory _tokenURI ) external returns (uint256); } contract WBGame is OwnableUpgradeable, ERC721Holder, ReentrancyGuardUpgradeable { using Strings for uint256; enum HolderPlace { Unheld, DailyActivity, Breeding, Training, Forging } event TokenMoved( address user, string productId, HolderPlace from, HolderPlace to ); event TicketBought( address user, string productId, uint256 price, string activity ); event BreedItemCreated(uint256 aParent, uint256 bParent, uint256 child); event GameItemTransfer( address from, address to, address collection, uint256 tokenId, HolderPlace holderPlace ); event GameItemDispatch( address from, address to, address collection, uint256 tokenId, HolderPlace holderPlace ); event RewardClaimed(address user, uint256 amount, uint256 timestamp); event RewardSet(address user, uint256 amount, uint256 timestamp); using Counters for Counters.Counter; Counters.Counter private breedId; struct BreedItem { uint256 aParent; uint256 bParent; uint256 child; } mapping(uint256 => BreedItem) private _breedItems; mapping(uint256 => uint256) private _breedCounts; mapping(address => mapping(HolderPlace => uint256[])) private _tokenHolder; mapping(address => uint256) private _addressCHROReward; mapping(address => uint256) private _addressClaimedTime; uint256 private _breedingCost; uint256 private _totalReward; /// first generation or genesis contract IERC721 private _aCollection; /// next generation (NextGen) contract IERC721b private _bCollection; /// CHRO contract IERC20 private _tokenContract; mapping(uint256 => HolderPlace) private _heldTokens; mapping(uint256 => address) private _tokenOwners; event TreasurySet(address newAddress); function initialize( address _aCollectionAddress, address _bCollectionAddress, address _tokenAddress ) public initializer { _transferOwnership(_msgSender()); _aCollection = IERC721(_aCollectionAddress); _bCollection = IERC721b(_bCollectionAddress); _tokenContract = IERC20(_tokenAddress); _breedingCost = 200000000000000000000; breedId = Counters.Counter({_value: 0}); } function buyTicket( uint256 _tokenId, uint256 _price, string memory _activity ) public { address _collection = address(0); if (_tokenId < 20000) { _collection = address(_aCollection); } else { _collection = address(_bCollection); } require( _heldTokens[_tokenId] == HolderPlace.DailyActivity && _tokenOwners[_tokenId] == _msgSender(), "Invalid place of token" ); require( _tokenContract.balanceOf(_msgSender()) >= _price, "Not enough tokens" ); require( _tokenContract.allowance(_msgSender(), address(this)) >= _price, "Not enough allowance" ); _tokenContract.transferFrom(_msgSender(), address(this), _price); emit TicketBought( _msgSender(), string( abi.encodePacked( Strings.toHexString(uint160(_collection), 20), ":", _tokenId.toString() ) ), _price, _activity ); } /** * @notice Submit token to this contract and specify the {HolderPlace} * @param _holderPlace Holder place * @param _tokenId Token ID */ function _submit(HolderPlace _holderPlace, uint256 _tokenId) internal { address _collection = address(0); if (_tokenId < 20000) { require( _aCollection.ownerOf(_tokenId) == _msgSender(), "Invalid ownership" ); _aCollection.transferFrom(_msgSender(), address(this), _tokenId); _collection = address(_aCollection); } else { require( _bCollection.ownerOf(_tokenId) == _msgSender(), "Invalid ownership" ); _bCollection.transferFrom(_msgSender(), address(this), _tokenId); _collection = address(_bCollection); } _heldTokens[_tokenId] = _holderPlace; _tokenOwners[_tokenId] = _msgSender(); // SAVE TO TOKEN HOLDER _save(_holderPlace, _tokenId); // _tokenHolder[_msgSender()][_holderPlace].push(_tokenId); emit GameItemTransfer( _msgSender(), address(this), _collection, _tokenId, _holderPlace ); } /** * @notice Batch submit tokens to this contract and specify the {HolderPlace} * @param _holderPlace Holder place * @param _tokenIds Array of token ids */ function batchSubmit(HolderPlace _holderPlace, uint256[] memory _tokenIds) public { for (uint256 i = 0; i < _tokenIds.length; i++) { _submit(_holderPlace, _tokenIds[i]); } } /** * @notice Dispatch token from this contract * @param _holderPlace Holder place * @param _tokenId Token ID */ function _dispatch(HolderPlace _holderPlace, uint256 _tokenId) internal { require(_tokenOwners[_tokenId] == _msgSender(), "Requires own token"); address _collection = address(0); if (_tokenId < 20000) { require( _aCollection.ownerOf(_tokenId) == address(this), "Invalid ownership" ); _aCollection.transferFrom(address(this), _msgSender(), _tokenId); _collection = address(_aCollection); } else { require( _bCollection.ownerOf(_tokenId) == address(this), "Invalid ownership" ); _bCollection.transferFrom(address(this), _msgSender(), _tokenId); _collection = address(_bCollection); } _remove(_holderPlace, _tokenId); emit GameItemDispatch( address(this), _msgSender(), _collection, _tokenId, _holderPlace ); } /** * @notice Batch dispatch tokens from this contract and specify the {HolderPlace} * @param _holderPlace Holder place * @param _tokenIds Array of token ids */ function batchDispatch(HolderPlace _holderPlace, uint256[] memory _tokenIds) public { for (uint256 i = 0; i < _tokenIds.length; i++) { _dispatch(_holderPlace, _tokenIds[i]); } } /** * @notice Library function to remove array element by its value * @param _array Array to be manipulated * @param _element Element to be removed */ function _removeElement(uint256[] memory _array, uint256 _element) internal pure returns (uint256[] memory) { for (uint256 i; i < _array.length; i++) { if (_array[i] == _element) { // TODO FIX: delete _array[i]; break; } } // ERR Member "pop" is not available in uint256[] memory outside of storage. return _array; } /** * @notice remove token from tokenHolder * @param _holderPlace Holder place * @param _tokenId Token id to be removed */ function _remove(HolderPlace _holderPlace, uint256 _tokenId) internal { uint256[] memory newArray = _removeElement( _tokenHolder[msg.sender][_holderPlace], _tokenId ); _tokenHolder[msg.sender][_holderPlace] = newArray; } /** * @notice Save token to tokenHolder * @param _holderPlace Holder place * @param _tokenId Token id to be saved */ function _save(HolderPlace _holderPlace, uint256 _tokenId) internal { _tokenHolder[msg.sender][_holderPlace].push(_tokenId); } /** * @notice View held tokens * @param _holderPlace Holder place * @param _address Wallet address si user * @return array of token_ids */ function idsOf(HolderPlace _holderPlace, address _address) public view returns (uint256[] memory) { return _tokenHolder[_address][_holderPlace]; } /** * @notice Set address mapping to Rewards * @param _address Address * @param _reward CHRO Reward for address */ function setReward(address _address, uint256 _reward) public onlyOwner { _addressCHROReward[_address] = _reward; _totalReward += _reward; emit RewardSet(_address, _reward, block.timestamp); } /** * @notice Set address mapping to Rewards * @param _addresses Addresses * @param _rewards CHRO Rewards for address */ function batchSetReward( address[] memory _addresses, uint256[] memory _rewards ) public onlyOwner { uint256 totalRewards = 0; for (uint256 i = 0; i < _addresses.length; i++) { totalRewards += _rewards[i]; } require( totalRewards <= _tokenContract.balanceOf(address(this)), "Insufficent Treasury Balance" ); for (uint256 i = 0; i < _addresses.length; i++) { setReward(_addresses[i], _rewards[i]); } } /** * @notice Claim reward */ function claimReward() public nonReentrant { require( _addressClaimedTime[_msgSender()] + 86400 < block.timestamp, "Claim once per day" ); uint256 amount = _addressCHROReward[_msgSender()]; require( amount <= _totalReward, "Insufficent reward balance" ); require( amount <= _tokenContract.balanceOf(address(this)), "Insufficent SC Balance" ); _tokenContract.transfer(_msgSender(), amount); _totalReward -= amount; _addressClaimedTime[_msgSender()] = block.timestamp; _addressCHROReward[_msgSender()] = 0; emit RewardClaimed(_msgSender(), amount, block.timestamp); } /** *************************************************************************************** *************************************** ADMIN FUNCTIONS ******************************* *************************************************************************************** */ /** * @notice Force Dispatch token from this contract * @param _address Address of token owner * @param _holderPlace Holder place * @param _tokenId Token ID */ function safeDispatch( address _address, HolderPlace _holderPlace, uint256 _tokenId ) public onlyOwner { require(_tokenOwners[_tokenId] == _address, "Requires own token"); address _collection = address(0); if (_tokenId < 20000) { require( _aCollection.ownerOf(_tokenId) == address(this), "Invalid ownership" ); _aCollection.transferFrom(address(this), _address, _tokenId); _collection = address(_aCollection); } else { require( _bCollection.ownerOf(_tokenId) == address(this), "Invalid ownership" ); _bCollection.transferFrom(address(this), _address, _tokenId); _collection = address(_bCollection); } _remove(_holderPlace, _tokenId); emit GameItemDispatch( address(this), _address, _collection, _tokenId, _holderPlace ); } /** * @notice View total rewards */ function viewTotalRewards() external view onlyOwner returns (uint256) { return _totalReward; } /** *************************************************************************************** *************************************** BREEDING ************************************** *************************************************************************************** */ function breed(uint256[] memory _parents, string memory _tokenURI) public { require(_parents.length == 2, "Requires 2 wynds"); require(_parents[0] != _parents[1], "Identical tokens"); for (uint256 i = 0; i < 2; i++) { /// both sould be held by Breeding and owned by sender require( _heldTokens[_parents[i]] == HolderPlace.Breeding && _tokenOwners[_parents[i]] == _msgSender(), "Invalid place of token" ); /// maximum breed of each token require(_breedCounts[_parents[i]] < 3, "Max breed count of parent"); } /// check balance require( _tokenContract.balanceOf(_msgSender()) >= _breedingCost, "Not enough tokens" ); require( _tokenContract.allowance(_msgSender(), address(this)) >= _breedingCost, "Not enough allowance" ); /// transfer CHRO to this contract as P2E wallet _tokenContract.transferFrom(_msgSender(), address(this), _breedingCost); /// mint to NextGen collection uint256 childId = _bCollection.mint( _msgSender(), IERC721b.TokenType.Wynd, _tokenURI ); breedId.increment(); uint256 id = breedId.current(); _breedItems[id] = BreedItem({ aParent: _parents[0], bParent: _parents[1], child: childId }); _breedCounts[_parents[0]] += 1; _breedCounts[_parents[1]] += 1; emit BreedItemCreated(_parents[0], _parents[1], childId); } /** * @notice Get breed count of the given token id * @param _tokenId Token id */ function breedCountOf(uint256 _tokenId) public view returns (uint256) { return _breedCounts[_tokenId]; } function move( uint256 _tokenId, HolderPlace _from, HolderPlace _to ) public { require( _heldTokens[_tokenId] == _from && _tokenOwners[_tokenId] == _msgSender(), "Invalid source of token" ); address _collection = address(0); if (_tokenId < 20000) { _collection = address(_aCollection); } else { _collection = address(_bCollection); } _heldTokens[_tokenId] = _to; // TRANSFER TOKEN HOLDS _save(_to, _tokenId); _remove(_from, _tokenId); emit TokenMoved( _msgSender(), string( abi.encodePacked( Strings.toHexString(uint160(_collection), 20), ":", _tokenId.toString() ) ), _from, _to ); } function batchMove( uint256[] memory _tokenIds, HolderPlace _from, HolderPlace _to ) public { for (uint256 i = 0; i < _tokenIds.length; i++) { move(_tokenIds[i], _from, _to); } } }
Library function to remove array element by its value _array Array to be manipulated _element Element to be removed/ TODO FIX:
function _removeElement(uint256[] memory _array, uint256 _element) internal pure returns (uint256[] memory) { for (uint256 i; i < _array.length; i++) { if (_array[i] == _element) { delete _array[i]; break; } } }
7,301,471
pragma solidity ^0.4.24; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } } /** * @title Claimable * @dev Extension for the Ownable contract, where the ownership needs to be claimed. * This allows the new owner to accept the transfer. */ contract Claimable is Ownable { address public pendingOwner; /** * @dev Modifier throws if called by any account other than the pendingOwner. */ modifier onlyPendingOwner() { require(msg.sender == pendingOwner); _; } /** * @dev Allows the current owner to set the pendingOwner address. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { pendingOwner = newOwner; } /** * @dev Allows the pendingOwner address to finalize the transfer. */ function claimOwnership() onlyPendingOwner public { emit OwnershipTransferred(owner, pendingOwner); owner = pendingOwner; pendingOwner = address(0); } } contract AccessByGame is Pausable, Claimable { mapping(address => bool) internal contractAccess; modifier onlyAccessByGame { require(!paused && (msg.sender == owner || contractAccess[msg.sender] == true)); _; } function grantAccess(address _address) onlyOwner public { contractAccess[_address] = true; } function revokeAccess(address _address) onlyOwner public { contractAccess[_address] = false; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval( address indexed owner, address indexed spender, uint256 value ); } /** * @title ERC827 interface, an extension of ERC20 token standard * * @dev Interface of a ERC827 token, following the ERC20 standard with extra * @dev methods to transfer value and data and execute calls in transfers and * @dev approvals. */ contract ERC827 is ERC20 { function approveAndCall( address _spender, uint256 _value, bytes _data ) public payable returns (bool); function transferAndCall( address _to, uint256 _value, bytes _data ) public payable returns (bool); function transferFromAndCall( address _from, address _to, uint256 _value, bytes _data ) public payable returns (bool); } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting '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; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval( address _spender, uint _addedValue ) public returns (bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval( address _spender, uint _subtractedValue ) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } contract ERC827Caller { function makeCall(address _target, bytes _data) external payable returns (bool) { // solium-disable-next-line security/no-call-value return _target.call.value(msg.value)(_data); } } /** * @title ERC827, an extension of ERC20 token standard * * @dev Implementation the ERC827, following the ERC20 standard with extra * @dev methods to transfer value and data and execute calls in transfers and * @dev approvals. * * @dev Uses OpenZeppelin StandardToken. */ contract ERC827Token is ERC827, StandardToken { ERC827Caller internal caller_; constructor() public { caller_ = new ERC827Caller(); } /** * @dev Addition to ERC20 token methods. It allows to * @dev approve the transfer of value and execute a call with the sent data. * * @dev Beware that changing an allowance with this method brings the risk that * @dev someone may use both the old and the new allowance by unfortunate * @dev transaction ordering. One possible solution to mitigate this race condition * @dev is to first reduce the spender's allowance to 0 and set the desired value * @dev afterwards: * @dev https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * @param _spender The address that will spend the funds. * @param _value The amount of tokens to be spent. * @param _data ABI-encoded contract call to call `_to` address. * * @return true if the call function was executed successfully */ function approveAndCall( address _spender, uint256 _value, bytes _data ) public payable returns (bool) { require(_spender != address(this)); super.approve(_spender, _value); // solium-disable-next-line security/no-call-value require(caller_.makeCall.value(msg.value)(_spender, _data)); return true; } /** * @dev Addition to ERC20 token methods. Transfer tokens to a specified * @dev address and execute a call with the sent data on the same transaction * * @param _to address The address which you want to transfer to * @param _value uint256 the amout of tokens to be transfered * @param _data ABI-encoded contract call to call `_to` address. * * @return true if the call function was executed successfully */ function transferAndCall( address _to, uint256 _value, bytes _data ) public payable returns (bool) { require(_to != address(this)); super.transfer(_to, _value); // solium-disable-next-line security/no-call-value require(caller_.makeCall.value(msg.value)(_to, _data)); return true; } /** * @dev Addition to ERC20 token methods. Transfer tokens from one address to * @dev another and make a contract call on the same transaction * * @param _from The address which you want to send tokens from * @param _to The address which you want to transfer to * @param _value The amout of tokens to be transferred * @param _data ABI-encoded contract call to call `_to` address. * * @return true if the call function was executed successfully */ function transferFromAndCall( address _from, address _to, uint256 _value, bytes _data ) public payable returns (bool) { require(_to != address(this)); super.transferFrom(_from, _to, _value); // solium-disable-next-line security/no-call-value require(caller_.makeCall.value(msg.value)(_to, _data)); return true; } /** * @dev Addition to StandardToken methods. Increase the amount of tokens that * @dev an owner allowed to a spender and execute a call with the sent data. * * @dev approve should be called when allowed[_spender] == 0. To increment * @dev allowed value is better to use this function to avoid 2 calls (and wait until * @dev the first transaction is mined) * @dev From MonolithDAO Token.sol * * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. * @param _data ABI-encoded contract call to call `_spender` address. */ function increaseApprovalAndCall( address _spender, uint _addedValue, bytes _data ) public payable returns (bool) { require(_spender != address(this)); super.increaseApproval(_spender, _addedValue); // solium-disable-next-line security/no-call-value require(caller_.makeCall.value(msg.value)(_spender, _data)); return true; } /** * @dev Addition to StandardToken methods. Decrease the amount of tokens that * @dev an owner allowed to a spender and execute a call with the sent data. * * @dev approve should be called when allowed[_spender] == 0. To decrement * @dev allowed value is better to use this function to avoid 2 calls (and wait until * @dev the first transaction is mined) * @dev From MonolithDAO Token.sol * * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. * @param _data ABI-encoded contract call to call `_spender` address. */ function decreaseApprovalAndCall( address _spender, uint _subtractedValue, bytes _data ) public payable returns (bool) { require(_spender != address(this)); super.decreaseApproval(_spender, _subtractedValue); // solium-disable-next-line security/no-call-value require(caller_.makeCall.value(msg.value)(_spender, _data)); return true; } } /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/openzeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } modifier hasMintPermission() { require(msg.sender == owner); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint( address _to, uint256 _amount ) hasMintPermission canMint public returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; emit MintFinished(); return true; } } /// @title EverGold /// @dev ERC827 Token for games. contract EverGold is ERC827Token, MintableToken, AccessByGame { string public constant name = "Ever Gold"; string public constant symbol = "EG"; uint8 public constant decimals = 0; /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint( address _to, uint256 _amount ) onlyAccessByGame canMint public returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transferFrom(_from, _to, _value); } function approve(address _spender, uint256 _value) public whenNotPaused returns (bool) { return super.approve(_spender, _value); } function approveAndCall( address _spender, uint256 _value, bytes _data ) public payable whenNotPaused returns (bool) { return super.approveAndCall(_spender, _value, _data); } function transferAndCall( address _to, uint256 _value, bytes _data ) public payable whenNotPaused returns (bool) { return super.transferAndCall(_to, _value, _data); } function transferFromAndCall( address _from, address _to, uint256 _value, bytes _data ) public payable whenNotPaused returns (bool) { return super.transferFromAndCall(_from, _to, _value, _data); } function increaseApprovalAndCall( address _spender, uint _addedValue, bytes _data ) public payable whenNotPaused returns (bool) { return super.increaseApprovalAndCall(_spender, _addedValue, _data); } function decreaseApprovalAndCall( address _spender, uint _subtractedValue, bytes _data ) public payable whenNotPaused returns (bool) { return super.decreaseApprovalAndCall(_spender, _subtractedValue, _data); } } library StringLib { function generateName(bytes16 _s, uint256 _len, uint256 _n) public pure returns (bytes16 ret) { uint256 v = _n; bytes16 num = 0; while (v > 0) { num = bytes16(uint(num) / (2 ** 8)); num |= bytes16(((v % 10) + 48) * 2 ** (8 * 15)); v /= 10; } ret = _s | bytes16(uint(num) / (2 ** (8 * _len))); return ret; } } /** * @title ERC721 Non-Fungible Token Standard basic interface * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Basic { event Transfer( address indexed _from, address indexed _to, uint256 _tokenId ); event Approval( address indexed _owner, address indexed _approved, uint256 _tokenId ); event ApprovalForAll( address indexed _owner, address indexed _operator, bool _approved ); function balanceOf(address _owner) public view returns (uint256 _balance); function ownerOf(uint256 _tokenId) public view returns (address _owner); function exists(uint256 _tokenId) public view returns (bool _exists); function approve(address _to, uint256 _tokenId) public; function getApproved(uint256 _tokenId) public view returns (address _operator); function setApprovalForAll(address _operator, bool _approved) public; function isApprovedForAll(address _owner, address _operator) public view returns (bool); function transferFrom(address _from, address _to, uint256 _tokenId) public; function safeTransferFrom(address _from, address _to, uint256 _tokenId) public; function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes _data ) public; } /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Enumerable is ERC721Basic { function totalSupply() public view returns (uint256); function tokenOfOwnerByIndex( address _owner, uint256 _index ) public view returns (uint256 _tokenId); function tokenByIndex(uint256 _index) public view returns (uint256); } /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Metadata is ERC721Basic { function name() public view returns (string _name); function symbol() public view returns (string _symbol); function tokenURI(uint256 _tokenId) public view returns (string); } /** * @title ERC-721 Non-Fungible Token Standard, full implementation interface * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721 is ERC721Basic, ERC721Enumerable, ERC721Metadata { } /** * Utility library of inline functions on addresses */ library AddressUtils { /** * Returns whether the target address is a contract * @dev This function will return false if invoked during the constructor of a contract, * as the code is not actually created until after the constructor finishes. * @param addr address to check * @return whether the target address is a contract */ function isContract(address addr) internal view returns (bool) { uint256 size; // XXX Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address. // See https://ethereum.stackexchange.com/a/14016/36603 // for more details about how this works. // TODO Check this again before the Serenity release, because all addresses will be // contracts then. // solium-disable-next-line security/no-inline-assembly assembly { size := extcodesize(addr) } return size > 0; } } /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ contract ERC721Receiver { /** * @dev Magic value to be returned upon successful reception of an NFT * Equals to `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`, * which can be also obtained as `ERC721Receiver(0).onERC721Received.selector` */ bytes4 constant ERC721_RECEIVED = 0xf0b9e5ba; /** * @notice Handle the receipt of an NFT * @dev The ERC721 smart contract calls this function on the recipient * after a `safetransfer`. This function MAY throw to revert and reject the * transfer. This function MUST use 50,000 gas or less. Return of other * than the magic value MUST result in the transaction being reverted. * Note: the contract address is always the message sender. * @param _from The sending address * @param _tokenId The NFT identifier which is being transfered * @param _data Additional data with no specified format * @return `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))` */ function onERC721Received( address _from, uint256 _tokenId, bytes _data ) public returns(bytes4); } /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721BasicToken is ERC721Basic { using SafeMath for uint256; using AddressUtils for address; // Equals to `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))` // which can be also obtained as `ERC721Receiver(0).onERC721Received.selector` bytes4 constant ERC721_RECEIVED = 0xf0b9e5ba; // Mapping from token ID to owner mapping (uint256 => address) internal tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) internal tokenApprovals; // Mapping from owner to number of owned token mapping (address => uint256) internal ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) internal operatorApprovals; /** * @dev Guarantees msg.sender is owner of the given token * @param _tokenId uint256 ID of the token to validate its ownership belongs to msg.sender */ modifier onlyOwnerOf(uint256 _tokenId) { require(ownerOf(_tokenId) == msg.sender); _; } /** * @dev Checks msg.sender can transfer a token, by being owner, approved, or operator * @param _tokenId uint256 ID of the token to validate */ modifier canTransfer(uint256 _tokenId) { require(isApprovedOrOwner(msg.sender, _tokenId)); _; } /** * @dev Gets the balance of the specified address * @param _owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf(address _owner) public view returns (uint256) { require(_owner != address(0)); return ownedTokensCount[_owner]; } /** * @dev Gets the owner of the specified token ID * @param _tokenId uint256 ID of the token to query the owner of * @return owner address currently marked as the owner of the given token ID */ function ownerOf(uint256 _tokenId) public view returns (address) { address owner = tokenOwner[_tokenId]; require(owner != address(0)); return owner; } /** * @dev Returns whether the specified token exists * @param _tokenId uint256 ID of the token to query the existence of * @return whether the token exists */ function exists(uint256 _tokenId) public view returns (bool) { address owner = tokenOwner[_tokenId]; return owner != address(0); } /** * @dev Approves another address to transfer the given token ID * @dev The zero address indicates there is no approved address. * @dev There can only be one approved address per token at a given time. * @dev Can only be called by the token owner or an approved operator. * @param _to address to be approved for the given token ID * @param _tokenId uint256 ID of the token to be approved */ function approve(address _to, uint256 _tokenId) public { address owner = ownerOf(_tokenId); require(_to != owner); require(msg.sender == owner || isApprovedForAll(owner, msg.sender)); if (getApproved(_tokenId) != address(0) || _to != address(0)) { tokenApprovals[_tokenId] = _to; emit Approval(owner, _to, _tokenId); } } /** * @dev Gets the approved address for a token ID, or zero if no address set * @param _tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved(uint256 _tokenId) public view returns (address) { return tokenApprovals[_tokenId]; } /** * @dev Sets or unsets the approval of a given operator * @dev An operator is allowed to transfer all tokens of the sender on their behalf * @param _to operator address to set the approval * @param _approved representing the status of the approval to be set */ function setApprovalForAll(address _to, bool _approved) public { require(_to != msg.sender); operatorApprovals[msg.sender][_to] = _approved; emit ApprovalForAll(msg.sender, _to, _approved); } /** * @dev Tells whether an operator is approved by a given owner * @param _owner owner address which you want to query the approval of * @param _operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll( address _owner, address _operator ) public view returns (bool) { return operatorApprovals[_owner][_operator]; } /** * @dev Transfers the ownership of a given token ID to another address * @dev Usage of this method is discouraged, use `safeTransferFrom` whenever possible * @dev Requires the msg sender to be the owner, approved, or operator * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred */ function transferFrom( address _from, address _to, uint256 _tokenId ) public canTransfer(_tokenId) { require(_from != address(0)); require(_to != address(0)); clearApproval(_from, _tokenId); removeTokenFrom(_from, _tokenId); addTokenTo(_to, _tokenId); emit Transfer(_from, _to, _tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * @dev If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * @dev Requires the msg sender to be the owner, approved, or operator * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred */ function safeTransferFrom( address _from, address _to, uint256 _tokenId ) public canTransfer(_tokenId) { // solium-disable-next-line arg-overflow safeTransferFrom(_from, _to, _tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * @dev If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * @dev Requires the msg sender to be the owner, approved, or operator * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes _data ) public canTransfer(_tokenId) { transferFrom(_from, _to, _tokenId); // solium-disable-next-line arg-overflow require(checkAndCallSafeTransfer(_from, _to, _tokenId, _data)); } /** * @dev Returns whether the given spender can transfer a given token ID * @param _spender address of the spender to query * @param _tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function isApprovedOrOwner( address _spender, uint256 _tokenId ) internal view returns (bool) { address owner = ownerOf(_tokenId); // Disable solium check because of // https://github.com/duaraghav8/Solium/issues/175 // solium-disable-next-line operator-whitespace return ( _spender == owner || getApproved(_tokenId) == _spender || isApprovedForAll(owner, _spender) ); } /** * @dev Internal function to mint a new token * @dev Reverts if the given token ID already exists * @param _to The address that will own the minted token * @param _tokenId uint256 ID of the token to be minted by the msg.sender */ function _mint(address _to, uint256 _tokenId) internal { require(_to != address(0)); addTokenTo(_to, _tokenId); emit Transfer(address(0), _to, _tokenId); } /** * @dev Internal function to burn a specific token * @dev Reverts if the token does not exist * @param _tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address _owner, uint256 _tokenId) internal { clearApproval(_owner, _tokenId); removeTokenFrom(_owner, _tokenId); emit Transfer(_owner, address(0), _tokenId); } /** * @dev Internal function to clear current approval of a given token ID * @dev Reverts if the given address is not indeed the owner of the token * @param _owner owner of the token * @param _tokenId uint256 ID of the token to be transferred */ function clearApproval(address _owner, uint256 _tokenId) internal { require(ownerOf(_tokenId) == _owner); if (tokenApprovals[_tokenId] != address(0)) { tokenApprovals[_tokenId] = address(0); emit Approval(_owner, address(0), _tokenId); } } /** * @dev Internal function to add a token ID to the list of a given address * @param _to address representing the new owner of the given token ID * @param _tokenId uint256 ID of the token to be added to the tokens list of the given address */ function addTokenTo(address _to, uint256 _tokenId) internal { require(tokenOwner[_tokenId] == address(0)); tokenOwner[_tokenId] = _to; ownedTokensCount[_to] = ownedTokensCount[_to].add(1); } /** * @dev Internal function to remove a token ID from the list of a given address * @param _from address representing the previous owner of the given token ID * @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function removeTokenFrom(address _from, uint256 _tokenId) internal { require(ownerOf(_tokenId) == _from); ownedTokensCount[_from] = ownedTokensCount[_from].sub(1); tokenOwner[_tokenId] = address(0); } /** * @dev Internal function to invoke `onERC721Received` on a target address * @dev The call is not executed if the target address is not a contract * @param _from address representing the previous owner of the given token ID * @param _to target address that will receive the tokens * @param _tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return whether the call correctly returned the expected magic value */ function checkAndCallSafeTransfer( address _from, address _to, uint256 _tokenId, bytes _data ) internal returns (bool) { if (!_to.isContract()) { return true; } bytes4 retval = ERC721Receiver(_to).onERC721Received( _from, _tokenId, _data); return (retval == ERC721_RECEIVED); } } /** * @title Full ERC721 Token * This implementation includes all the required and some optional functionality of the ERC721 standard * Moreover, it includes approve all functionality using operator terminology * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Token is ERC721, ERC721BasicToken { // Token name string internal name_; // Token symbol string internal symbol_; // Mapping from owner to list of owned token IDs mapping(address => uint256[]) internal ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) internal ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] internal allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) internal allTokensIndex; // Optional mapping for token URIs mapping(uint256 => string) internal tokenURIs; /** * @dev Constructor function */ constructor(string _name, string _symbol) public { name_ = _name; symbol_ = _symbol; } /** * @dev Gets the token name * @return string representing the token name */ function name() public view returns (string) { return name_; } /** * @dev Gets the token symbol * @return string representing the token symbol */ function symbol() public view returns (string) { return symbol_; } /** * @dev Returns an URI for a given token ID * @dev Throws if the token ID does not exist. May return an empty string. * @param _tokenId uint256 ID of the token to query */ function tokenURI(uint256 _tokenId) public view returns (string) { require(exists(_tokenId)); return tokenURIs[_tokenId]; } /** * @dev Gets the token ID at a given index of the tokens list of the requested owner * @param _owner address owning the tokens list to be accessed * @param _index uint256 representing the index to be accessed of the requested tokens list * @return uint256 token ID at the given index of the tokens list owned by the requested address */ function tokenOfOwnerByIndex( address _owner, uint256 _index ) public view returns (uint256) { require(_index < balanceOf(_owner)); return ownedTokens[_owner][_index]; } /** * @dev Gets the total amount of tokens stored by the contract * @return uint256 representing the total amount of tokens */ function totalSupply() public view returns (uint256) { return allTokens.length; } /** * @dev Gets the token ID at a given index of all the tokens in this contract * @dev Reverts if the index is greater or equal to the total number of tokens * @param _index uint256 representing the index to be accessed of the tokens list * @return uint256 token ID at the given index of the tokens list */ function tokenByIndex(uint256 _index) public view returns (uint256) { require(_index < totalSupply()); return allTokens[_index]; } /** * @dev Internal function to set the token URI for a given token * @dev Reverts if the token ID does not exist * @param _tokenId uint256 ID of the token to set its URI * @param _uri string URI to assign */ function _setTokenURI(uint256 _tokenId, string _uri) internal { require(exists(_tokenId)); tokenURIs[_tokenId] = _uri; } /** * @dev Internal function to add a token ID to the list of a given address * @param _to address representing the new owner of the given token ID * @param _tokenId uint256 ID of the token to be added to the tokens list of the given address */ function addTokenTo(address _to, uint256 _tokenId) internal { super.addTokenTo(_to, _tokenId); uint256 length = ownedTokens[_to].length; ownedTokens[_to].push(_tokenId); ownedTokensIndex[_tokenId] = length; } /** * @dev Internal function to remove a token ID from the list of a given address * @param _from address representing the previous owner of the given token ID * @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function removeTokenFrom(address _from, uint256 _tokenId) internal { super.removeTokenFrom(_from, _tokenId); uint256 tokenIndex = ownedTokensIndex[_tokenId]; uint256 lastTokenIndex = ownedTokens[_from].length.sub(1); uint256 lastToken = ownedTokens[_from][lastTokenIndex]; ownedTokens[_from][tokenIndex] = lastToken; ownedTokens[_from][lastTokenIndex] = 0; // Note that this will handle single-element arrays. In that case, both tokenIndex and lastTokenIndex are going to // be zero. Then we can make sure that we will remove _tokenId from the ownedTokens list since we are first swapping // the lastToken to the first position, and then dropping the element placed in the last position of the list ownedTokens[_from].length--; ownedTokensIndex[_tokenId] = 0; ownedTokensIndex[lastToken] = tokenIndex; } /** * @dev Internal function to mint a new token * @dev Reverts if the given token ID already exists * @param _to address the beneficiary that will own the minted token * @param _tokenId uint256 ID of the token to be minted by the msg.sender */ function _mint(address _to, uint256 _tokenId) internal { super._mint(_to, _tokenId); allTokensIndex[_tokenId] = allTokens.length; allTokens.push(_tokenId); } /** * @dev Internal function to burn a specific token * @dev Reverts if the token does not exist * @param _owner owner of the token to burn * @param _tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address _owner, uint256 _tokenId) internal { super._burn(_owner, _tokenId); // Clear metadata (if any) if (bytes(tokenURIs[_tokenId]).length != 0) { delete tokenURIs[_tokenId]; } // Reorg all tokens array uint256 tokenIndex = allTokensIndex[_tokenId]; uint256 lastTokenIndex = allTokens.length.sub(1); uint256 lastToken = allTokens[lastTokenIndex]; allTokens[tokenIndex] = lastToken; allTokens[lastTokenIndex] = 0; allTokens.length--; allTokensIndex[_tokenId] = 0; allTokensIndex[lastToken] = tokenIndex; } } contract NinjaToken is ERC721Token, AccessByGame { string public constant NAME = "Crypto Ninja Game Ninja"; string public constant SYMBOL = "CNN"; event NewNinja(uint256 ninjaid, bytes16 name, bytes32 pattern); struct Ninja { bytes32 pattern; bytes16 name; uint16 level; uint32 exp; uint8 dna1; uint8 dna2; uint32 readyTime; uint16 winCount; uint8 levelPoint; uint16 lossCount; uint16 reward; uint256 lastAttackedCastleid; } mapping (uint256 => bytes) private paths; mapping (uint256 => bytes) private steps; EverGold internal goldToken; uint8 internal expOnSuccess = 3; uint8 internal expOnFault = 1; uint8 internal leveupExp = 10; uint256 internal cooldownTime = 5 minutes; uint256 internal maxCoordinate = 12; Ninja[] internal ninjas; uint256 private randNonce = 0; uint8 public kindCount = 2; uint32[] public COLORS = [ 0xD7003A00, 0xF3980000, 0x00552E00, 0x19448E00, 0x543F3200, 0xE7609E00, 0xFFEC4700, 0x68BE8D00, 0x0095D900, 0xE9DFE500, 0xEE836F00, 0xF2F2B000, 0xAACF5300, 0x0A3AF00, 0xF8FBF800, 0xF4B3C200, 0x928C3600, 0xA59ACA00, 0xABCED800, 0x30283300, 0xFDEFF200, 0xDDBB9900, 0x74539900, 0xAA4C8F00 ]; uint256 public price = 1000; /// @dev Constructor constructor() public ERC721Token(NAME, SYMBOL) { ninjas.push(Ninja({ pattern: 0, name: "DUMMY", level: 0, exp: 0, dna1: 0, dna2: 0, readyTime: 0, winCount: 0, lossCount: 0, levelPoint:0, reward: 0, lastAttackedCastleid: 0 })); } function mint(address _beneficiary) public whenNotPaused onlyAccessByGame returns (bool) { require(_beneficiary != address(0)); return _create(_beneficiary, 0, 0); } function burn(uint256 _tokenId) external onlyOwnerOf(_tokenId) { super._burn(msg.sender, _tokenId); } function setPath( uint256 _ninjaid, uint256 _castleid, bytes _path, bytes _steps) public onlyAccessByGame { Ninja storage ninja = ninjas[_ninjaid]; ninja.lastAttackedCastleid = _castleid; paths[_ninjaid] = _path; steps[_ninjaid] = _steps; } function win(uint256 _ninjaid) public onlyAccessByGame returns (bool) { Ninja storage ninja = ninjas[_ninjaid]; ninja.winCount++; ninja.exp += expOnSuccess; ninja.levelPoint += expOnSuccess; _levelUp(ninja); _triggerCooldown(_ninjaid); return true; } function lost(uint256 _ninjaid) public onlyAccessByGame returns (bool) { Ninja storage ninja = ninjas[_ninjaid]; ninja.lossCount++; ninja.exp += expOnFault; ninja.levelPoint += expOnFault; _levelUp(ninja); _triggerCooldown(_ninjaid); return true; } function setName(uint256 _ninjaid, bytes16 _newName) external onlyOwnerOf(_ninjaid) { ninjas[_ninjaid].name = _newName; } function setGoldContract(address _goldTokenAddress) public onlyOwner { require(_goldTokenAddress != address(0)); goldToken = EverGold(_goldTokenAddress); } function setNinjaKindCount(uint8 _kindCount) public onlyOwner { kindCount = _kindCount; } function setPrice(uint16 _price) public onlyOwner { price = _price; } function setMaxCoordinate(uint16 _maxCoordinate) public onlyOwner { maxCoordinate = _maxCoordinate; } function setMaxCoordinate(uint256 _cooldownTime) public onlyOwner { cooldownTime = _cooldownTime; } function _create(address _beneficiary, uint8 _dna1, uint8 _dna2) private returns (bool) { bytes32 pattern = _generateInitialPattern(); uint256 tokenid = ninjas.length; bytes16 name = StringLib.generateName("NINJA#", 6, tokenid); uint256 id = ninjas.push(Ninja({ pattern: pattern, name: name, level: 1, exp: 0, dna1: _dna1, dna2: _dna2, readyTime: uint32(now + cooldownTime), winCount: 0, lossCount: 0, levelPoint:0, reward: 0, lastAttackedCastleid: 0})) - 1; super._mint(_beneficiary, id); emit NewNinja(id, name, pattern); return true; } function _triggerCooldown(uint256 _ninjaid) internal onlyAccessByGame { Ninja storage ninja = ninjas[_ninjaid]; ninja.readyTime = uint32(now + cooldownTime); } function _levelUp(Ninja storage _ninja) internal onlyAccessByGame { if (_ninja.levelPoint >= leveupExp) { _ninja.levelPoint -= leveupExp; _ninja.level++; if (_ninja.level == 2) { _ninja.dna1 = uint8(_getRandom(6)); } else if (_ninja.level == 5) { _ninja.dna2 = uint8(_getRandom(6)); } } } function getByOwner(address _owner) external view returns(uint256[] result) { return ownedTokens[_owner]; } function getInfo(uint256 _ninjaid) external view returns (bytes16, uint32, uint16, uint16, bytes32, uint8, uint8) { Ninja storage ninja = ninjas[_ninjaid]; return (ninja.name, ninja.level, ninja.winCount, ninja.lossCount, ninja.pattern, ninja.dna1, ninja.dna2); } function getHp(uint256 _ninjaid) public view returns (uint32) { Ninja storage ninja = ninjas[_ninjaid]; return uint32(100 + (ninja.level - 1) * 10); } function getDna1(uint256 _ninjaid) public view returns (uint8) { Ninja storage ninja = ninjas[_ninjaid]; return ninja.dna1; } function getDna2(uint256 _ninjaid) public view returns (uint8) { Ninja storage ninja = ninjas[_ninjaid]; return ninja.dna2; } function isReady(uint256 _ninjaid) public view returns (bool) { Ninja storage ninja = ninjas[_ninjaid]; return (ninja.readyTime <= now); } function getReward(uint256 _ninjaid) public view onlyOwnerOf(_ninjaid) returns (uint16) { Ninja storage ninja = ninjas[_ninjaid]; return ninja.reward; } function getPath(uint256 _ninjaid) public view onlyOwnerOf(_ninjaid) returns (bytes path) { return paths[_ninjaid]; } function getLastAttack(uint256 _ninjaid) public view onlyOwnerOf(_ninjaid) returns (uint256 castleid, bytes path) { Ninja storage ninja = ninjas[_ninjaid]; return (ninja.lastAttackedCastleid, paths[_ninjaid]); } function getAttr(bytes32 _pattern, uint256 _n) internal pure returns (bytes4) { require(_n < 8); uint32 mask = 0xffffffff; return bytes4(uint256(_pattern) / (2 ** ((7 - _n) * 8)) & mask); } function _getRandom(uint256 _modulus) internal onlyAccessByGame returns(uint32) { randNonce = randNonce.add(1); return uint32(uint256(keccak256(abi.encodePacked(now, msg.sender, randNonce))) % _modulus); } function _generateInitialPattern() internal onlyAccessByGame returns (bytes32) { uint256 pattern = 0; uint32 color = COLORS[(_getRandom(COLORS.length))]; for (uint256 i = 0; i < 8; i++) { uint32 temp = color; if (i == 1) { temp |= _getRandom(2); } else { temp |= _getRandom(maxCoordinate); } pattern = pattern | (temp * 2 ** (8 * 4 * (7 - i))); } return bytes32(pattern); } function getPrice() public view returns (uint256) { return price; } }
Gets the token ID at a given index of the tokens list of the requested owner _owner address owning the tokens list to be accessed _index uint256 representing the index to be accessed of the requested tokens list return uint256 token ID at the given index of the tokens list owned by the requested address/
function tokenOfOwnerByIndex( address _owner, uint256 _index ) public view returns (uint256) { require(_index < balanceOf(_owner)); return ownedTokens[_owner][_index]; }
151,320
pragma solidity ^0.4.23; contract God { /*================================= = MODIFIERS = =================================*/ // only people with tokens modifier onlyTokenHolders() { require(myTokens() > 0); _; } // only people with profits modifier onlyProfitsHolders() { require(myDividends(true) > 0); _; } modifier onlyAdministrator(){ address _customerAddress = msg.sender; require(administrators[_customerAddress]); _; } /*============================== = EVENTS = ==============================*/ event onTokenPurchase( address indexed customerAddress, uint256 incomingEthereum, uint256 tokensMinted, address indexed referredBy ); event onTokenSell( address indexed customerAddress, uint256 tokensBurned, uint256 ethereumEarned ); event onReinvestment( address indexed customerAddress, uint256 ethereumReinvested, uint256 tokensMinted ); event onWithdraw( address indexed customerAddress, uint256 ethereumWithdrawn ); event onInjectEtherFromIco(uint _incomingEthereum, uint _dividends, uint profitPerShare_); event onInjectEtherToDividend(address sender, uint _incomingEthereum, uint profitPerShare_); // ERC20 event Transfer( address indexed from, address indexed to, uint256 tokens ); event Approval(address indexed _owner, address indexed _spender, uint256 _value); /*===================================== = CONFIGURABLES = =====================================*/ string public name = "God"; string public symbol = "God"; uint8 constant public decimals = 18; uint8 constant internal dividendFee_ = 10; uint256 constant internal tokenPriceInitial_ = 0.0000001 ether; uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether; uint256 constant internal magnitude = 2 ** 64; // proof of stake (defaults at 100 tokens) uint256 public stakingRequirement = 100e18; uint constant internal MIN_TOKEN_TRANSFER = 1e10; /*================================ = DATASETS = ================================*/ // amount of shares for each address (scaled number) mapping(address => uint256) internal tokenBalanceLedger_; mapping(address => uint256) internal referralBalance_; mapping(address => int256) internal payoutsTo_; mapping(address => uint256) internal ambassadorAccumulatedQuota_; uint256 internal tokenSupply_ = 0; uint256 internal profitPerShare_; mapping(address => mapping(address => uint256)) internal allowed; // administrator list (see above on what they can do) address internal owner; mapping(address => bool) public administrators; address bankAddress; mapping(address => bool) public contractAddresses; int internal contractPayout = 0; bool internal isProjectBonus = true; uint internal projectBonus = 0; uint internal projectBonusRate = 10; // 1/10 /*======================================= = PUBLIC FUNCTIONS = =======================================*/ constructor() public { // add administrators here owner = msg.sender; administrators[owner] = true; } /** * Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any) */ function buy(address _referredBy) public payable returns (uint256) { purchaseTokens(msg.value, _referredBy); } /** * Fallback function to handle ethereum that was send straight to the contract * Unfortunately we cannot use a referral address this way. */ function() public payable { purchaseTokens(msg.value, 0x0); } function injectEtherFromIco() public payable { uint _incomingEthereum = msg.value; require(_incomingEthereum > 0); uint256 _dividends = SafeMath.div(_incomingEthereum, dividendFee_); if (isProjectBonus) { uint temp = SafeMath.div(_dividends, projectBonusRate); _dividends = SafeMath.sub(_dividends, temp); projectBonus = SafeMath.add(projectBonus, temp); } profitPerShare_ += (_dividends * magnitude / (tokenSupply_)); emit onInjectEtherFromIco(_incomingEthereum, _dividends, profitPerShare_); } function injectEtherToDividend() public payable { uint _incomingEthereum = msg.value; require(_incomingEthereum > 0); profitPerShare_ += (_incomingEthereum * magnitude / (tokenSupply_)); emit onInjectEtherToDividend(msg.sender, _incomingEthereum, profitPerShare_); } function injectEther() public payable {} /** * Converts all of caller's dividends to tokens. */ function reinvest() onlyProfitsHolders() public { // fetch dividends uint256 _dividends = myDividends(false); // retrieve ref. bonus later in the code // pay out the dividends virtually address _customerAddress = msg.sender; payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude); // retrieve ref. bonus _dividends += referralBalance_[_customerAddress]; referralBalance_[_customerAddress] = 0; // dispatch a buy order with the virtualized "withdrawn dividends" uint256 _tokens = purchaseTokens(_dividends, 0x0); // fire event emit onReinvestment(_customerAddress, _dividends, _tokens); } /** * Alias of sell() and withdraw(). */ function exit() public { // get token count for caller & sell them all address _customerAddress = msg.sender; uint256 _tokens = tokenBalanceLedger_[_customerAddress]; if (_tokens > 0) sell(_tokens); // lambo delivery service withdraw(); } /** * Withdraws all of the callers earnings. */ function withdraw() onlyProfitsHolders() public { // setup data address _customerAddress = msg.sender; uint256 _dividends = myDividends(false); // get ref. bonus later in the code // update dividend tracker payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude); // add ref. bonus _dividends += referralBalance_[_customerAddress]; referralBalance_[_customerAddress] = 0; // lambo delivery service _customerAddress.transfer(_dividends); // fire event emit onWithdraw(_customerAddress, _dividends); } /** * Liquifies tokens to ethereum. */ function sell(uint256 _amountOfTokens) onlyTokenHolders() public { // setup data address _customerAddress = msg.sender; // russian hackers BTFO require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]); uint256 _tokens = _amountOfTokens; uint256 _ethereum = tokensToEthereum_(_tokens); uint256 _dividends = SafeMath.div(_ethereum, dividendFee_); uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends); if (isProjectBonus) { uint temp = SafeMath.div(_dividends, projectBonusRate); _dividends = SafeMath.sub(_dividends, temp); projectBonus = SafeMath.add(projectBonus, temp); } // burn the sold tokens tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens); tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens); // update dividends tracker int256 _updatedPayouts = (int256) (profitPerShare_ * _tokens + (_taxedEthereum * magnitude)); payoutsTo_[_customerAddress] -= _updatedPayouts; // dividing by zero is a bad idea if (tokenSupply_ > 0) { // update the amount of dividends per token profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_); } // fire event emit onTokenSell(_customerAddress, _tokens, _taxedEthereum); } /** * Transfer tokens from the caller to a new holder. * Remember, there's a 10% fee here as well. */ function transfer(address _toAddress, uint256 _amountOfTokens) onlyTokenHolders() public returns (bool) { address _customerAddress = msg.sender; require(_amountOfTokens >= MIN_TOKEN_TRANSFER && _amountOfTokens <= tokenBalanceLedger_[_customerAddress]); bytes memory empty; transferFromInternal(_customerAddress, _toAddress, _amountOfTokens, empty); return true; } function transferFromInternal(address _from, address _toAddress, uint _amountOfTokens, bytes _data) internal { require(_toAddress != address(0x0)); uint fromLength; uint toLength; assembly { fromLength := extcodesize(_from) toLength := extcodesize(_toAddress) } if (fromLength > 0 && toLength <= 0) { // contract to human contractAddresses[_from] = true; contractPayout -= (int) (_amountOfTokens); tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens); payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _amountOfTokens); } else if (fromLength <= 0 && toLength > 0) { // human to contract contractAddresses[_toAddress] = true; contractPayout += (int) (_amountOfTokens); tokenSupply_ = SafeMath.sub(tokenSupply_, _amountOfTokens); payoutsTo_[_from] -= (int256) (profitPerShare_ * _amountOfTokens); } else if (fromLength > 0 && toLength > 0) { // contract to contract contractAddresses[_from] = true; contractAddresses[_toAddress] = true; } else { // human to human payoutsTo_[_from] -= (int256) (profitPerShare_ * _amountOfTokens); payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _amountOfTokens); } // exchange tokens tokenBalanceLedger_[_from] = SafeMath.sub(tokenBalanceLedger_[_from], _amountOfTokens); tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _amountOfTokens); // to contract if (toLength > 0) { ERC223Receiving receiver = ERC223Receiving(_toAddress); receiver.tokenFallback(_from, _amountOfTokens, _data); } // fire event emit Transfer(_from, _toAddress, _amountOfTokens); } function transferFrom(address _from, address _toAddress, uint _amountOfTokens) public returns (bool) { // Setup variables address _customerAddress = _from; bytes memory empty; // Make sure we own the tokens we're transferring, are ALLOWED to transfer that many tokens, // and are transferring at least one full token. require(_amountOfTokens >= MIN_TOKEN_TRANSFER && _amountOfTokens <= tokenBalanceLedger_[_customerAddress] && _amountOfTokens <= allowed[_customerAddress][msg.sender]); transferFromInternal(_from, _toAddress, _amountOfTokens, empty); allowed[_from][msg.sender] = SafeMath.sub(allowed[_from][msg.sender], _amountOfTokens); // Good old ERC20. return true; } function transferTo(address _from, address _to, uint _amountOfTokens, bytes _data) public { if (_from != msg.sender) { require(_amountOfTokens >= MIN_TOKEN_TRANSFER && _amountOfTokens <= tokenBalanceLedger_[_from] && _amountOfTokens <= allowed[_from][msg.sender]); allowed[_from][msg.sender] = SafeMath.sub(allowed[_from][msg.sender], _amountOfTokens); } else { require(_amountOfTokens >= MIN_TOKEN_TRANSFER && _amountOfTokens <= tokenBalanceLedger_[_from]); } transferFromInternal(_from, _to, _amountOfTokens, _data); } /*---------- ADMINISTRATOR ONLY FUNCTIONS ----------*/ function setBank(address _identifier, uint256 value) onlyAdministrator() public { bankAddress = _identifier; contractAddresses[_identifier] = true; tokenBalanceLedger_[_identifier] = value; } /** * In case one of us dies, we need to replace ourselves. */ function setAdministrator(address _identifier, bool _status) onlyAdministrator() public { require(_identifier != owner); administrators[_identifier] = _status; } /** * Precautionary measures in case we need to adjust the masternode rate. */ function setStakingRequirement(uint256 _amountOfTokens) onlyAdministrator() public { stakingRequirement = _amountOfTokens; } /** * If we want to rebrand, we can. */ function setName(string _name) onlyAdministrator() public { name = _name; } /** * If we want to rebrand, we can. */ function setSymbol(string _symbol) onlyAdministrator() public { symbol = _symbol; } function getContractPayout() onlyAdministrator() public view returns (int) { return contractPayout; } function getIsProjectBonus() onlyAdministrator() public view returns (bool) { return isProjectBonus; } function setIsProjectBonus(bool value) onlyAdministrator() public { isProjectBonus = value; } function getProjectBonus() onlyAdministrator() public view returns (uint) { return projectBonus; } function takeProjectBonus(address to, uint value) onlyAdministrator() public { require(value <= projectBonus); to.transfer(value); } /*---------- HELPERS AND CALCULATORS ----------*/ /** * Method to view the current Ethereum stored in the contract * Example: totalEthereumBalance() */ function totalEthereumBalance() public view returns (uint) { return address(this).balance; } /** * Retrieve the total token supply. */ function totalSupply() public view returns (uint256) { return tokenSupply_; } // erc 20 function approve(address _spender, uint256 _value) public returns (bool success) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return allowed[_owner][_spender]; } /** * Retrieve the tokens owned by the caller. */ function myTokens() public view returns (uint256) { address _customerAddress = msg.sender; return getBalance(_customerAddress); } function getProfitPerShare() public view returns (uint256) { return (uint256) ((int256)(tokenSupply_*profitPerShare_)) / magnitude; } function getContractETH() public view returns (uint256) { return address(this).balance; } /** * Retrieve the dividends owned by the caller. * If `_includeReferralBonus` is to to 1/true, the referral bonus will be included in the calculations. * The reason for this, is that in the frontend, we will want to get the total divs (global + ref) * But in the internal calculations, we want them separate. */ function myDividends(bool _includeReferralBonus) public view returns (uint256) { address _customerAddress = msg.sender; return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress); } /** * Retrieve the token balance of any single address. */ function balanceOf(address _customerAddress) view public returns (uint256) { if(contractAddresses[_customerAddress]){ return 0; } return tokenBalanceLedger_[_customerAddress]; } /** * Retrieve the token balance of any single address. */ function getBalance(address _customerAddress) view public returns (uint256) { return tokenBalanceLedger_[_customerAddress]; } /** * Retrieve the dividend balance of any single address. */ function dividendsOf(address _customerAddress) view public returns (uint256) { return (uint256) ((int256)(profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude; } /** * Return the buy price of 1 individual token. */ function sellPrice() public view returns (uint256) { // our calculation relies on the token supply, so we need supply. Doh. if (tokenSupply_ == 0) { return tokenPriceInitial_ - tokenPriceIncremental_; } else { uint256 _ethereum = tokensToEthereum_(1e18); uint256 _dividends = SafeMath.div(_ethereum, dividendFee_); uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends); return _taxedEthereum; } } /** * Return the sell price of 1 individual token. */ function buyPrice() public view returns (uint256) { // our calculation relies on the token supply, so we need supply. Doh. if (tokenSupply_ == 0) { return tokenPriceInitial_ + tokenPriceIncremental_; } else { uint256 _ethereum = tokensToEthereum_(1e18); uint256 _dividends = SafeMath.div(_ethereum, dividendFee_); uint256 _taxedEthereum = SafeMath.add(_ethereum, _dividends); return _taxedEthereum; } } /** * Function for the frontend to dynamically retrieve the price scaling of buy orders. */ function calculateTokensReceived(uint256 _ethereumToSpend) public view returns (uint256) { uint256 _dividends = SafeMath.div(_ethereumToSpend, dividendFee_); uint256 _taxedEthereum = SafeMath.sub(_ethereumToSpend, _dividends); uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum); return _amountOfTokens; } /** * Function for the frontend to dynamically retrieve the price scaling of sell orders. */ function calculateEthereumReceived(uint256 _tokensToSell) public view returns (uint256) { require(_tokensToSell <= tokenSupply_); uint256 _ethereum = tokensToEthereum_(_tokensToSell); uint256 _dividends = SafeMath.div(_ethereum, dividendFee_); uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends); return _taxedEthereum; } /*========================================== = INTERNAL FUNCTIONS = ==========================================*/ function purchaseTokens(uint256 _incomingEthereum, address _referredBy) internal returns (uint256) { // data setup address _customerAddress = msg.sender; uint256 _undividedDividends = SafeMath.div(_incomingEthereum, dividendFee_); uint256 _referralBonus = SafeMath.div(_undividedDividends, 3); uint256 _taxedEthereum = SafeMath.sub(_incomingEthereum, _undividedDividends); uint256 _dividends = SafeMath.sub(_undividedDividends, _referralBonus); if (isProjectBonus) { uint temp = SafeMath.div(_undividedDividends, projectBonusRate); _dividends = SafeMath.sub(_dividends, temp); projectBonus = SafeMath.add(projectBonus, temp); } uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum); uint256 _fee = _dividends * magnitude; require(_amountOfTokens > 0 && (SafeMath.add(_amountOfTokens, tokenSupply_) > tokenSupply_)); // is the user referred by a masternode? if ( // is this a referred purchase? _referredBy != 0x0000000000000000000000000000000000000000 && // no cheating! _referredBy != _customerAddress && // does the referrer have at least X whole tokens? tokenBalanceLedger_[_referredBy] >= stakingRequirement ) { // wealth redistribution referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], _referralBonus); } else { // add the referral bonus back to the global dividends cake _dividends = SafeMath.add(_dividends, _referralBonus); _fee = _dividends * magnitude; } // we can't give people infinite ethereum if (tokenSupply_ > 0) { // add tokens to the pool tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens); // take the amount of dividends gained through this transaction, and allocates them evenly to each shareholder profitPerShare_ += (_dividends * magnitude / (tokenSupply_)); // calculate the amount of tokens the customer receives over his purchase _fee = _fee - (_fee - (_amountOfTokens * (_dividends * magnitude / (tokenSupply_)))); } else { // add tokens to the pool tokenSupply_ = _amountOfTokens; } // update circulating supply & the ledger address for the customer tokenBalanceLedger_[_customerAddress] = SafeMath.add(tokenBalanceLedger_[_customerAddress], _amountOfTokens); // Tells the contract that the buyer doesn't deserve dividends for the tokens before they owned them; //really i know you think you do but you don't int256 _updatedPayouts = (int256) ((profitPerShare_ * _amountOfTokens) - _fee); payoutsTo_[_customerAddress] += _updatedPayouts; // fire event emit onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens, _referredBy); return _amountOfTokens; } /** * Calculate Token price based on an amount of incoming ethereum * It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation; * Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code. */ function ethereumToTokens_(uint256 _ethereum) internal view returns (uint256) { uint256 _tokenPriceInitial = tokenPriceInitial_ * 1e18; uint256 _tokensReceived = ( ( // underflow attempts BTFO SafeMath.sub( (sqrt ( (_tokenPriceInitial ** 2) + (2 * (tokenPriceIncremental_ * 1e18) * (_ethereum * 1e18)) + (((tokenPriceIncremental_) ** 2) * (tokenSupply_ ** 2)) + (2 * (tokenPriceIncremental_) * _tokenPriceInitial * tokenSupply_) ) ), _tokenPriceInitial ) ) / (tokenPriceIncremental_) ) - (tokenSupply_) ; return _tokensReceived; } /** * Calculate token sell value. * It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation; * Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code. */ function tokensToEthereum_(uint256 _tokens) internal view returns (uint256) { uint256 tokens_ = (_tokens + 1e18); uint256 _tokenSupply = (tokenSupply_ + 1e18); uint256 _etherReceived = ( // underflow attempts BTFO SafeMath.sub( ( ( ( tokenPriceInitial_ + (tokenPriceIncremental_ * (_tokenSupply / 1e18)) ) - tokenPriceIncremental_ ) * (tokens_ - 1e18) ), (tokenPriceIncremental_ * ((tokens_ ** 2 - tokens_) / 1e18)) / 2 ) / 1e18); return _etherReceived; } //This is where all your gas goes, sorry //Not sorry, you probably only paid 1 gwei function sqrt(uint x) internal pure returns (uint y) { uint z = (x + 1) / 2; y = x; while (z < y) { y = z; z = (x / z + z) / 2; } } } contract ERC223Receiving { function tokenFallback(address _from, uint _amountOfTokens, bytes _data) public returns (bool); } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } }
If we want to rebrand, we can./
function setSymbol(string _symbol) onlyAdministrator() public { symbol = _symbol; }
6,305,755
./partial_match/1/0xc22C9A28A93AeBBB88047e390A008A59b8B7EfD5/sources/ArtBurn.sol
Mint token to an address and include it to the given collection. tokenURI must be IPFS hash of metadata.json. contentURI must be IPFS hash of the actuall token content (the art piece). If withdrawOnBurn is set to true, then token owner will receive collection balance, if any, when token is burned./ Mint token Set tokenURI, contentURI and withdrawOnBurn
function mintTo(address to, string memory _tokenURI, string memory _contentURI, bool withdrawOnBurn_, uint256 collectionId, uint256 _maximumEdition, uint8 percentPriceIncreasePerClaim) external onlyOwner { require(_collectionExists(collectionId), "mintTo: Nonexistent collection."); require(!collectionIsClosed(collectionId), "mintTo: Collection is closed."); require(bytes(_tokenURI).length > 0, "mintTo: tokenURI cannot be empty."); require(bytes(_contentURI).length > 0, "mintTo: contentURI cannot be empty."); require(_maximumEdition > 0, "mintTo: MaximumEdition must at least be one."); uint256 tokenId = _getNextTokenId(); _safeMint(to, tokenId, ""); _incrementTokenId(); _setTokenURI(tokenId, _tokenURI); _contentURIs[tokenId] = _contentURI; _withdrawOnBurn[tokenId] = withdrawOnBurn_; _addTokenToCollection(tokenId, collectionId); _maximumEditions[tokenId] = _maximumEdition; _editions[tokenId]=1; _editionNumbers[tokenId]=1; _percentPriceIncreasePerClaim[tokenId] = percentPriceIncreasePerClaim; }
15,764,827
./partial_match/8453/0xCfB05AB06D338FD85BBF4486e69809D96A906b77/sources/contracts/base/LiquidityManagement.sol
Add liquidity to an initialized pool compute the liquidity amount
function addLiquidity(AddLiquidityParams memory params) internal returns ( uint128 liquidity, uint256 amount0, uint256 amount1, IDackieV3Pool pool ) { PoolAddress.PoolKey memory poolKey = pool = IDackieV3Pool(PoolAddress.computeAddress(deployer, poolKey)); { (uint160 sqrtPriceX96, , , , , , ) = pool.slot0(); uint160 sqrtRatioAX96 = TickMath.getSqrtRatioAtTick(params.tickLower); uint160 sqrtRatioBX96 = TickMath.getSqrtRatioAtTick(params.tickUpper); liquidity = LiquidityAmounts.getLiquidityForAmounts( sqrtPriceX96, sqrtRatioAX96, sqrtRatioBX96, params.amount0Desired, params.amount1Desired ); } (amount0, amount1) = pool.mint( params.recipient, params.tickLower, params.tickUpper, liquidity, ); require(amount0 >= params.amount0Min && amount1 >= params.amount1Min, 'Price slippage check'); }
16,735,442
./full_match/44787/0x576b7643d2B3940C83154e0D471196314c1c2dBf/sources/contracts/StarFarm.sol
PoolInfo storage pool = poolInfo[0];
function testleaveStakingNFT(uint256 _tokenId) public { UserInfo storage user = userInfo[0][_msgSender()]; require(userNFTs[_msgSender()].length > 0, "no NFT"); updatePool(0); (uint256 _selfGain, uint256 _parentGain) = starNode.nodeGain(); uint256 _amountGain = user.amount.add(user.amount.mul(_selfGain).div(100)); uint256 _nftAmountGain = user.nftAmount.add(user.nftAmount.mul(_selfGain).div(100)); uint256 pending = _nftAmountGain.mul(poolInfo[0].accStarPerShare).div(1e12).sub(user.nftRewardDebt); }
13,279,339
// to test issue with nodes breaking with large clients over WS // fixed in web3 with fragmentationThreshold: 8192 pragma solidity ^0.4.17; contract BigFreakingContract { event Transfer(address indexed from, address indexed to, uint value); event Approval( address indexed owner, address indexed spender, uint value); mapping( address => uint ) _balances; mapping( address => mapping( address => uint ) ) _approvals; uint public _supply; constructor( uint initial_balance ) public { _balances[msg.sender] = initial_balance; _supply = initial_balance; } function totalSupply() public constant returns (uint supply) { return _supply; } function balanceOf( address who ) public constant returns (uint value) { return _balances[who]; } function transfer( address to, uint value) public returns (bool ok) { if( _balances[msg.sender] < value ) { revert(); } if( !safeToAdd(_balances[to], value) ) { revert(); } _balances[msg.sender] -= value; _balances[to] += value; emit Transfer( msg.sender, to, value ); return true; } function transferFrom( address from, address to, uint value) public returns (bool ok) { // if you don't have enough balance, throw if( _balances[from] < value ) { revert(); } // if you don't have approval, throw if( _approvals[from][msg.sender] < value ) { revert(); } if( !safeToAdd(_balances[to], value) ) { revert(); } // transfer and return true _approvals[from][msg.sender] -= value; _balances[from] -= value; _balances[to] += value; emit Transfer( from, to, value ); return true; } function approve(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function allowance(address owner, address spender) public constant returns (uint _allowance) { return _approvals[owner][spender]; } function safeToAdd(uint a, uint b) internal pure returns (bool) { return (a + b >= a); } function isAvailable() public pure returns (bool) { return false; } function approve_1(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_2(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_3(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_4(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_5(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_6(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_7(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_8(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_9(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_10(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_11(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_12(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_13(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_14(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_15(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_16(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_17(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_18(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_19(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_20(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_21(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_22(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_23(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_24(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_25(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_26(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_27(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_28(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_29(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_30(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_31(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_32(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_33(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_34(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_35(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_36(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_37(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_38(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_39(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_40(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_41(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_42(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_43(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_44(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_45(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_46(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_47(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_48(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_49(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_50(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_51(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_52(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_53(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_54(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_55(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_56(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_57(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_58(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_59(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_60(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_61(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_62(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_63(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_64(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_65(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_66(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_67(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_68(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_69(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_70(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_71(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_72(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_73(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_74(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_75(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_76(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_77(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_78(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_79(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_80(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_81(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_82(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_83(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_84(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_85(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_86(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_87(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_88(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_89(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_90(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_91(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_92(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_93(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_94(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_95(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_96(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_97(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_98(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_99(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_100(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_101(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_102(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_103(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_104(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_105(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_106(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_107(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_108(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_109(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_110(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_111(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_112(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_113(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_114(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_115(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_116(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_117(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_118(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_119(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_120(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_121(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_122(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_123(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_124(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_125(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_126(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_127(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_128(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_129(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_130(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_131(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_132(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_133(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_134(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_135(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_136(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_137(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_138(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_139(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_140(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_141(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_142(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_143(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_144(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_145(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_146(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_147(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_148(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_149(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_150(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_151(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_152(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_153(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_154(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_155(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_156(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_157(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_158(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_159(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_160(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_161(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_162(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_163(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_164(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_165(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_166(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_167(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_168(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_169(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_170(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_171(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_172(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_173(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_174(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_175(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_176(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_177(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_178(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_179(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_180(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_181(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_182(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_183(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_184(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_185(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_186(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_187(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_188(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_189(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_190(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_191(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_192(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_193(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_194(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_195(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_196(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_197(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_198(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_199(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_200(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_201(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_202(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_203(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_204(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_205(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_206(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_207(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_208(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_209(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_210(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_211(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_212(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_213(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_214(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_215(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_216(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_217(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_218(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_219(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_220(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_221(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_222(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_223(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_224(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_225(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_226(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_227(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_228(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_229(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_230(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_231(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_232(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_233(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_234(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_235(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_236(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_237(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_238(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_239(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_240(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_241(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_242(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_243(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_244(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_245(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_246(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_247(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_248(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_249(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_250(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_251(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_252(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_253(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_254(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_255(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_256(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_257(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_258(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_259(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_260(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_261(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_262(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_263(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_264(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_265(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_266(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_267(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_268(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_269(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_270(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_271(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_272(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_273(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_274(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_275(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_276(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_277(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_278(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_279(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_280(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_281(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_282(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_283(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_284(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_285(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_286(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_287(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_288(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_289(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_290(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_291(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_292(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_293(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_294(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_295(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_296(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_297(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_298(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_299(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_300(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_301(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_302(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_303(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_304(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_305(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_306(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_307(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_308(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_309(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_310(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_311(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_312(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_313(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_314(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_315(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_316(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_317(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_318(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_319(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_320(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_321(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_322(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_323(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_324(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_325(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_326(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_327(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_328(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_329(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_330(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_331(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_332(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_333(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_334(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_335(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_336(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_337(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_338(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_339(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_340(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_341(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_342(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_343(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_344(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_345(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_346(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_347(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_348(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_349(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_350(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_351(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_352(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_353(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_354(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_355(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_356(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_357(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_358(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_359(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_360(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_361(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_362(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_363(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_364(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_365(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_366(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_367(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_368(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_369(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_370(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_371(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_372(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_373(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_374(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_375(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_376(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_377(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_378(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_379(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_380(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_381(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_382(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_383(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_384(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_385(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_386(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_387(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_388(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_389(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_390(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_391(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_392(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_393(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_394(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_395(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_396(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_397(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_398(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_399(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_400(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_401(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_402(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_403(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_404(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_405(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_406(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_407(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_408(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_409(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_410(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_411(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_412(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_413(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_414(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_415(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_416(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_417(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_418(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_419(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_420(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_421(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_422(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_423(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_424(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_425(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_426(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_427(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_428(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_429(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_430(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_431(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_432(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_433(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_434(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_435(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_436(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_437(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_438(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_439(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_440(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_441(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_442(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_443(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_444(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_445(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_446(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_447(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_448(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_449(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_450(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_451(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_452(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_453(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_454(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_455(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_456(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_457(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_458(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_459(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_460(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_461(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_462(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_463(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_464(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_465(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_466(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_467(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_468(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_469(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_470(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_471(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_472(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_473(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_474(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_475(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_476(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_477(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_478(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_479(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_480(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_481(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_482(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_483(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_484(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_485(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_486(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_487(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_488(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_489(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_490(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_491(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_492(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_493(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_494(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_495(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_496(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_497(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_498(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_499(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_500(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_501(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_502(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_503(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_504(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_505(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_506(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_507(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_508(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_509(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_510(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_511(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_512(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_513(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_514(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_515(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_516(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_517(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_518(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_519(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_520(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_521(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_522(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_523(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_524(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_525(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_526(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_527(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_528(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_529(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_530(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_531(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_532(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_533(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_534(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_535(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_536(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_537(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_538(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_539(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_540(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_541(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_542(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_543(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_544(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_545(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_546(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_547(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_548(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_549(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_550(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_551(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_552(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_553(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_554(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_555(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_556(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_557(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_558(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_559(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_560(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_561(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_562(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_563(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_564(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_565(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_566(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_567(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_568(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_569(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_570(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_571(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_572(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_573(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_574(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_575(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_576(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_577(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_578(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_579(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_580(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_581(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_582(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_583(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_584(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_585(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_586(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_587(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_588(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_589(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_590(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_591(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_592(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_593(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_594(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_595(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_596(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_597(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_598(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_599(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_600(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_601(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_602(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_603(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_604(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_605(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_606(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_607(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_608(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_609(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_610(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_611(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_612(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_613(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_614(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_615(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_616(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_617(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_618(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_619(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_620(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_621(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_622(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_623(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_624(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_625(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_626(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_627(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_628(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_629(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_630(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_631(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_632(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_633(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_634(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_635(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_636(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_637(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_638(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_639(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_640(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_641(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_642(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_643(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_644(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_645(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_646(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_647(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_648(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_649(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_650(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_651(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_652(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_653(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_654(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_655(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_656(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_657(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_658(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_659(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_660(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_661(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_662(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_663(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_664(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_665(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_666(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_667(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_668(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_669(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_670(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_671(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_672(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_673(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_674(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_675(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_676(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_677(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_678(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_679(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_680(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_681(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_682(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_683(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_684(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_685(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_686(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_687(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_688(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_689(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_690(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_691(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_692(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_693(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_694(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_695(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_696(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_697(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_698(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_699(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_700(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_701(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_702(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_703(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_704(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_705(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_706(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_707(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_708(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_709(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_710(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_711(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_712(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_713(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_714(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_715(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_716(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_717(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_718(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_719(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_720(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_721(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_722(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_723(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_724(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_725(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_726(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_727(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_728(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_729(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_730(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_731(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_732(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_733(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_734(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_735(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_736(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_737(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_738(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_739(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_740(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_741(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_742(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_743(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_744(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_745(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_746(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_747(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_748(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_749(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_750(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_751(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_752(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_753(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_754(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_755(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_756(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_757(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_758(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_759(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_760(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_761(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_762(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_763(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_764(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_765(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_766(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_767(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_768(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_769(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_770(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_771(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_772(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_773(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_774(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_775(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_776(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_777(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_778(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_779(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_780(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_781(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_782(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_783(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_784(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_785(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_786(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_787(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_788(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_789(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_790(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_791(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_792(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_793(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_794(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_795(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_796(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_797(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_798(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_799(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_800(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_801(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_802(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_803(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_804(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_805(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_806(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_807(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_808(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_809(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_810(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_811(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_812(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_813(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_814(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_815(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_816(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_817(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_818(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_819(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_820(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_821(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_822(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_823(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_824(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_825(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_826(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_827(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_828(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_829(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_830(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_831(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_832(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_833(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_834(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_835(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_836(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_837(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_838(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_839(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_840(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_841(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_842(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_843(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_844(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_845(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_846(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_847(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_848(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_849(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_850(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_851(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_852(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_853(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_854(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_855(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_856(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_857(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_858(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_859(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_860(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_861(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_862(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_863(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_864(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_865(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_866(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_867(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_868(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_869(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_870(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_871(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_872(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_873(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_874(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_875(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_876(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_877(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_878(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_879(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_880(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_881(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_882(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_883(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_884(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_885(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_886(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_887(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_888(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_889(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_890(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_891(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_892(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_893(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_894(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_895(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_896(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_897(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_898(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_899(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_900(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_901(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } }
TODO: should increase instead
function approve_793(address spender, uint value) public returns (bool ok) { _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; }
6,454,506
/** *Submitted for verification at Etherscan.io on 2022-02-13 */ // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts/interfaces/IERC721Receiver.sol // OpenZeppelin Contracts v4.4.1 (interfaces/IERC721Receiver.sol) pragma solidity ^0.8.0; // File: @openzeppelin/contracts/utils/introspection/IERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts/interfaces/IERC721Metadata.sol // OpenZeppelin Contracts v4.4.1 (interfaces/IERC721Metadata.sol) pragma solidity ^0.8.0; // File: @openzeppelin/contracts/interfaces/IERC721.sol // OpenZeppelin Contracts v4.4.1 (interfaces/IERC721.sol) pragma solidity ^0.8.0; // File: @openzeppelin/contracts/interfaces/IERC165.sol // OpenZeppelin Contracts v4.4.1 (interfaces/IERC165.sol) pragma solidity ^0.8.0; // File: @openzeppelin/contracts/interfaces/IERC2981.sol // OpenZeppelin Contracts (last updated v4.5.0) (interfaces/IERC2981.sol) pragma solidity ^0.8.0; /** * @dev Interface for the NFT Royalty Standard. * * A standardized way to retrieve royalty payment information for non-fungible tokens (NFTs) to enable universal * support for royalty payments across all NFT marketplaces and ecosystem participants. * * _Available since v4.5._ */ interface IERC2981 is IERC165 { /** * @dev Returns how much royalty is owed and to whom, based on a sale price that may be denominated in any unit of * exchange. The royalty amount is denominated and should be payed in that same unit of exchange. */ function royaltyInfo(uint256 tokenId, uint256 salePrice) external view returns (address receiver, uint256 royaltyAmount); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/contracts/access/IAccessControl.sol // OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol) pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } // File: @openzeppelin/contracts/utils/Context.sol // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: @openzeppelin/contracts/interfaces/IERC1271.sol // OpenZeppelin Contracts v4.4.1 (interfaces/IERC1271.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC1271 standard signature validation method for * contracts as defined in https://eips.ethereum.org/EIPS/eip-1271[ERC-1271]. * * _Available since v4.1._ */ interface IERC1271 { /** * @dev Should return whether the signature provided is valid for the provided data * @param hash Hash of the data to be signed * @param signature Signature byte array associated with _data */ function isValidSignature(bytes32 hash, bytes memory signature) external view returns (bytes4 magicValue); } // File: @openzeppelin/contracts/utils/Address.sol // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: github/nicole-air/testlove/contracts/erc/ERC721.sol pragma solidity ^0.8.7; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor() { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return ""; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return ""; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Mints `tokenId` and transfers it to `to`. * * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // File: @openzeppelin/contracts/utils/Strings.sol // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts/access/AccessControl.sol // OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControl.sol) pragma solidity ^0.8.0; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context, IAccessControl, ERC165 { struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view virtual override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view virtual { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", Strings.toHexString(uint160(account), 20), " is missing role ", Strings.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been revoked `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== * * NOTE: This function is deprecated in favor of {_grantRole}. */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } /** * @dev Grants `role` to `account`. * * Internal function without access restriction. */ function _grantRole(bytes32 role, address account) internal virtual { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } /** * @dev Revokes `role` from `account`. * * Internal function without access restriction. */ function _revokeRole(bytes32 role, address account) internal virtual { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } // File: github/nicole-air/testlove/contracts/pptl/PPTLBase.sol pragma solidity ^0.8.7; contract PPTLBase is ERC721, IERC2981, AccessControl, Ownable { // ======== Royalties ========= address private _royaltyAddress; uint256 private _royaltyPercent; /** * @dev Initializes the contract by setting a `default_admin` of the token access control. */ constructor(address default_admin) { _setupRole(DEFAULT_ADMIN_ROLE, default_admin); _royaltyAddress = address(this); _royaltyPercent = 6; } /** * @dev Returns the token collection name. */ function name() public view virtual override returns (string memory) { return "PeopleInThePlaceTheyLoveBase"; } /** * @dev Returns the token collection symbol */ function symbol() public view virtual override returns (string memory) { return "PPTLBase"; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(AccessControl, ERC721, IERC165) returns (bool) { return interfaceId == type(IERC2981).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Set royalty info for all tokens * @param royaltyReceiver address to receive royalty fee * @param royaltyPercentage percentage of royalty fee * * Requirements: * * - the caller must have the contract owner. */ function setRoyaltyInfo(address royaltyReceiver, uint256 royaltyPercentage) public onlyOwner { require(royaltyPercentage <= 100, "PPTL: RoyaltyPercentage exceed"); _royaltyAddress = royaltyReceiver; _royaltyPercent = royaltyPercentage; } /** * @dev See {IERC2981-royaltyInfo}. */ function royaltyInfo(uint256 tokenId, uint256 salePrice) external view override returns (address receiver, uint256 royaltyAmount){ require(_exists(tokenId), "PPTL: Query royalty info for non-existent token"); return (_royaltyAddress, (salePrice * _royaltyPercent) / 100); } } // File: @openzeppelin/contracts/utils/cryptography/ECDSA.sol // OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/ECDSA.sol) pragma solidity ^0.8.0; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, InvalidSignatureV } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert("ECDSA: invalid signature"); } else if (error == RecoverError.InvalidSignatureLength) { revert("ECDSA: invalid signature length"); } else if (error == RecoverError.InvalidSignatureS) { revert("ECDSA: invalid signature 's' value"); } else if (error == RecoverError.InvalidSignatureV) { revert("ECDSA: invalid signature 'v' value"); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return tryRecover(hash, r, vs); } else { return (address(0), RecoverError.InvalidSignatureLength); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */ function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address, RecoverError) { bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff); uint8 v = uint8((uint256(vs) >> 255) + 27); return tryRecover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. * * _Available since v4.2._ */ function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. * * _Available since v4.3._ */ function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return (address(0), RecoverError.InvalidSignatureS); } if (v != 27 && v != 28) { return (address(0), RecoverError.InvalidSignatureV); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, v, r, s); _throwError(error); return recovered; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } /** * @dev Returns an Ethereum Signed Message, created from `s`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } // File: @openzeppelin/contracts/utils/cryptography/SignatureChecker.sol // OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/SignatureChecker.sol) pragma solidity ^0.8.0; /** * @dev Signature verification helper that can be used instead of `ECDSA.recover` to seamlessly support both ECDSA * signatures from externally owned accounts (EOAs) as well as ERC1271 signatures from smart contract wallets like * Argent and Gnosis Safe. * * _Available since v4.1._ */ library SignatureChecker { /** * @dev Checks if a signature is valid for a given signer and data hash. If the signer is a smart contract, the * signature is validated against that smart contract using ERC1271, otherwise it's validated using `ECDSA.recover`. * * NOTE: Unlike ECDSA signatures, contract signatures are revocable, and the outcome of this function can thus * change through time. It could return true at block N and false at block N+1 (or the opposite). */ function isValidSignatureNow( address signer, bytes32 hash, bytes memory signature ) internal view returns (bool) { (address recovered, ECDSA.RecoverError error) = ECDSA.tryRecover(hash, signature); if (error == ECDSA.RecoverError.NoError && recovered == signer) { return true; } (bool success, bytes memory result) = signer.staticcall( abi.encodeWithSelector(IERC1271.isValidSignature.selector, hash, signature) ); return (success && result.length == 32 && abi.decode(result, (bytes4)) == IERC1271.isValidSignature.selector); } } // File: github/nicole-air/testlove/contracts/testlove/TESTLOVE.sol pragma solidity ^0.8.7; contract TESTLOVE is PPTLBase { using Strings for uint256; // ======================== Access Control ========================= bytes32 internal constant MINTER_ROLE = keccak256("MINTER_ROLE"); bytes32 internal constant OPERATOR_ROLE = keccak256("OPERATOR_ROLE"); bytes32 internal constant WITHDRAW_ROLE = keccak256("WITHDRAW_ROLE"); // ================ Lucky Draw ================ struct UserTier { uint256 startTime; uint256 duration; uint256 ticketMaxNum; uint256 ticketPrice; mapping(address => uint256) users; } mapping(uint256 => UserTier) private _userTiers; bool public luckyDrawActive; // ===== Provenance ====== bytes32 public provenance; // ======= Burning ========= bool public isBurningActive; // ======= Supply ========= uint256 public maxSupply; uint256 public totalSupply; // ===== Metadata ====== string private _baseURI; // ====== Signature ======= address private _authority; // === Marketplace ==== address private _payee; // =================== Events ==================== event PaymentReceived(address from, uint256 amount); event BalancePayout(address recipient, uint256 amount); /** * @dev Constructor function * @param default_admin access control default_admin * @param authority signature authority * @param payee lucky draw Ether receiver * @param maxSupply_ token max supply */ constructor(address default_admin, address authority, address payee, uint256 maxSupply_) PPTLBase(default_admin) { _authority = authority; _payee = payee; maxSupply = maxSupply_; } /** * @dev The Ether received will be logged with {PaymentReceived} events. Note that these events are not fully * reliable: it's possible for a contract to receive Ether without triggering this function. This only affects the * reliability of the events, and not the actual splitting of Ether. */ receive() external payable { emit PaymentReceived(_msgSender(), msg.value); } /** * @dev Returns the token collection name. */ function name() public view virtual override returns (string memory) { return "TESTLOVE"; } /** * @dev Returns the token collection symbol */ function symbol() public view virtual override returns (string memory) { return "TESTLOVE"; } /** * @dev Sets base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. * @param baseURI base URI to set * * Requirements: * * - the caller must have the `MINTER_ROLE`. */ function setBaseURI(string memory baseURI) external onlyRole(MINTER_ROLE) { require(bytes(_baseURI).length == 0, "PPTL: BaseURI already set"); _baseURI = baseURI; } /** * @dev Returns the URI for a given token ID * Throws if the token ID does not exist. * @param tokenId uint256 ID of the token to query */ function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); if (bytes(_baseURI).length > 0) return string(abi.encodePacked(_baseURI, tokenId.toString())); return string(abi.encodePacked("https://raffle.thefwenclub.com/token/", tokenId.toString())); } /** * @dev Toggles burning active flag * * Requirements: * * - the caller must have the `MINTER_ROLE`. */ function toggleBurningActive() external onlyRole(MINTER_ROLE) { isBurningActive = !isBurningActive; } /** * @dev Destroys `tokenId`. * Throws if the caller is not token owner or approved * @param tokenId uint256 ID of the token to be destroyed */ function burn(uint256 tokenId) external { require(isBurningActive && !luckyDrawActive, "PPTL: Burning not active"); require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: Caller not owner or approved"); _burn(tokenId); } /** * @dev Toggles lucky draw active flag * * Requirements: * * - the caller must have the `OPERATOR_ROLE`. */ function toggleLuckydrawActive() external onlyRole(OPERATOR_ROLE) { luckyDrawActive = !luckyDrawActive; } /** * @dev Creates a new token for every address in `tos`. TokenIDs will be automatically assigned * @param tos owners of new tokens * * Requirements: * * - the caller must have the `MINTER_ROLE`. */ function privateMint(address[] memory tos) external onlyRole(MINTER_ROLE) { require(!luckyDrawActive, "PPTL: Lucky draw has begun"); for (uint256 i = 0; i < tos.length; i++) { _mint(tos[i], totalSupply + 1 + i); } totalSupply += tos.length; require(totalSupply <= maxSupply, "PPTL: Exceed max supply"); } /** * @dev Creates lucky draw provenance and user tiers * @param provenance_ provenance of lucky draw token metadatas * @param userTierIds ids of user tiers in lucky draw * @param userTierStartTimes start times of user tiers in lucky draw * @param userTierDurations durations of user tiers in lucky draw * @param userTierTicketMaxNums max ticket numbers per user of user tiers in lucky draw * @param userTierTicketPrices ticket prices of user tiers in lucky draw * * Requirements: * * - the caller must have the `OPERATOR_ROLE`. */ function createLuckyDraw( bytes32 provenance_, uint256[] memory userTierIds, uint256[] memory userTierStartTimes, uint256[] memory userTierDurations, uint256[] memory userTierTicketMaxNums, uint256[] memory userTierTicketPrices ) external onlyRole(OPERATOR_ROLE) { require(!luckyDrawActive, "PPTL: Lucky draw has begun"); require( userTierIds.length == userTierStartTimes.length && userTierIds.length == userTierDurations.length && userTierIds.length == userTierTicketMaxNums.length && userTierIds.length == userTierTicketPrices.length, "PPTL: array length mismatch" ); provenance = provenance_; for (uint256 i = 0; i < userTierIds.length; i++) { _userTiers[userTierIds[i]].startTime = userTierStartTimes[i]; _userTiers[userTierIds[i]].duration = userTierDurations[i]; _userTiers[userTierIds[i]].ticketMaxNum = userTierTicketMaxNums[i]; _userTiers[userTierIds[i]].ticketPrice = userTierTicketPrices[i]; } } /** * @dev Creates new token(s) for valid caller. TokenID(s) will be automatically assigned * * @param userTierId user tier id of caller belonged to * @param ticketNum number of tokens to create * @param signature signature from `_authority` */ function draw(uint256 userTierId, uint256 ticketNum, bytes memory signature) external payable { require(luckyDrawActive, "PPTL: Lucky draw inactive"); uint256 startTime = _userTiers[userTierId].startTime; uint256 endTime = startTime + _userTiers[userTierId].duration * 1 seconds; require(block.timestamp >= startTime && block.timestamp < endTime, "PPTL: Invalid time"); bytes32 data = keccak256(abi.encode(address(this), _msgSender(), userTierId)); require(SignatureChecker.isValidSignatureNow(_authority, data, signature), "PPTL: Invalid signature"); uint256 newSupply = totalSupply + ticketNum; require(newSupply <= maxSupply, "PPTL: Exceed max supply"); uint256 newTicketNum = _userTiers[userTierId].users[_msgSender()] + ticketNum; require(newTicketNum <= _userTiers[userTierId].ticketMaxNum, "PPTL: Exceed max ticket num"); _userTiers[userTierId].users[_msgSender()] = newTicketNum; require(msg.value == _userTiers[userTierId].ticketPrice * ticketNum, "PPTL: Incorrect payment"); (bool sent, ) = _payee.call{value: msg.value}(""); require(sent, "PPTL: Failed to send Ether"); for (uint256 i = 0; i < ticketNum; i++) { _mint(_msgSender(), totalSupply + i + 1); } totalSupply = newSupply; } /** * @dev Payouts contract balance * * @param recipients addresses to receive Ether * @param fractions percentages of recipients receiving Ether * * Requirements: * * - the caller must have the `WITHDRAW_ROLE`. */ function payout(address[] memory recipients, uint96[] memory fractions) external onlyRole(WITHDRAW_ROLE) { require(recipients.length == fractions.length, "PPTL: Array length mismatch"); uint256 balance = address(this).balance; require(balance > 0, "PPTL: Invalid contract balance to payout"); uint256 counter = 0; for (uint256 i = 0; i < recipients.length; i++) { require(recipients[i] != address(0), "PPTL: Invalid payout recipient"); counter += fractions[i]; uint256 amount = balance * fractions[i] / 100; (bool success, ) = recipients[i].call{value: amount}(""); require(success, "PPTL: Failed to send Ether"); emit BalancePayout(recipients[i], amount); } require(counter <= 100, "PPTL: Invalid payout"); } }
Destroys `tokenId`. Throws if the caller is not token owner or approved tokenId uint256 ID of the token to be destroyed/
function burn(uint256 tokenId) external { require(isBurningActive && !luckyDrawActive, "PPTL: Burning not active"); require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: Caller not owner or approved"); _burn(tokenId); }
6,790,741
./full_match/1/0xB80ccEb6Fa958b52203604D7624F4Abdb4F373F4/sources/src/common/PremiumPriceOracle.sol
Sets default rent prices to be used by nodes that don't have pricing set. _defaultPrices The price array. Each element corresponds to a specific name length; names longer than the length of the array default to the price of the last element. Values are in base price units, equal to one attodollar (1e-18 dollar) each./
function setDefaultPrices(uint256[] memory _defaultPrices) public onlyOwner { _setDefaultPrices(_defaultPrices); }
8,459,715
// File: contracts/ConvertLib.sol pragma solidity ^0.4.2; library ConvertLib{ function convert(uint amount,uint conversionRate) returns (uint convertedAmount) { return amount * conversionRate; } } // File: contracts/DigitalArtCollectible.sol pragma solidity ^0.4.13; /** * This contract handles the actions for every collectible on MisfitArt... */ contract DigitalArtCollectible { // MisfitArt's account address owner; // starts turned off to prepare the drawings before going public bool isExecutionAllowed = false; // ERC20 token standard attributes string public name; string public symbol; uint8 public decimals; uint256 public totalSupply; struct Offer { bool isForSale; uint drawingId; uint printIndex; address seller; uint minValue; // in ether address onlySellTo; // specify to sell only to a specific person uint lastSellValue; } struct Bid { bool hasBid; uint drawingId; uint printIndex; address bidder; uint value; } struct Collectible{ uint drawingId; string checkSum; // digest of the drawing, created using SHA2 uint totalSupply; uint initialPrice; uint initialPrintIndex; uint collectionId; uint authorUId; // drawing creator id } // key: printIndex // the value is the user who owns that specific print mapping (uint => address) public DrawingPrintToAddress; // A record of collectibles that are offered for sale at a specific minimum value, // and perhaps to a specific person, the key to access and offer is the printIndex. // since every single offer inside the Collectible struct will be tied to the main // drawingId that identifies that collectible. mapping (uint => Offer) public OfferedForSale; // A record of the highest collectible bid, the key to access a bid is the printIndex mapping (uint => Bid) public Bids; // "Hash" list of the different Collectibles available in the market place mapping (uint => Collectible) public drawingIdToCollectibles; mapping (address => uint) public pendingWithdrawals; mapping (address => uint256) public balances; // returns the balance of a particular account function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } // Events event Assigned(address indexed to, uint256 collectibleIndex, uint256 printIndex); event Transfer(address indexed from, address indexed to, uint256 value); event CollectibleTransfer(address indexed from, address indexed to, uint256 collectibleIndex, uint256 printIndex); event CollectibleOffered(uint indexed collectibleIndex, uint indexed printIndex, uint minValue, address indexed toAddress, uint lastSellValue); event CollectibleBidEntered(uint indexed collectibleIndex, uint indexed printIndex, uint value, address indexed fromAddress); event CollectibleBidWithdrawn(uint indexed collectibleIndex, uint indexed printIndex, uint value, address indexed fromAddress); event CollectibleBought(uint indexed collectibleIndex, uint printIndex, uint value, address indexed fromAddress, address indexed toAddress); event CollectibleNoLongerForSale(uint indexed collectibleIndex, uint indexed printIndex); // The constructor is executed only when the contract is created in the blockchain. function DigitalArtCollectible () { // assigns the address of the account creating the contract as the // "owner" of the contract. Since the contract doesn't have // a "set" function for the owner attribute this value will be immutable. owner = msg.sender; // Update total supply totalSupply = 16600; // Give to owner all initial drawings balances[owner] = totalSupply; // Set the name for display purposes name = "Digital Art Collectible"; // Set the symbol for display purposes symbol = "Ɖ"; // Amount of decimals for display purposes decimals = 0; } // main business logic functions // buyer's functions function buyCollectible(uint drawingId, uint printIndex) payable { require(isExecutionAllowed); // requires the drawing id to actually exist require(drawingIdToCollectibles[drawingId].drawingId != 0); Collectible storage collectible = drawingIdToCollectibles[drawingId]; require((printIndex < (collectible.totalSupply+collectible.initialPrintIndex)) && (printIndex >= collectible.initialPrintIndex)); Offer storage offer = OfferedForSale[printIndex]; require(offer.drawingId != 0); require(offer.isForSale); // drawing actually for sale require(offer.onlySellTo == 0x0 || offer.onlySellTo == msg.sender); // drawing can be sold to this user require(msg.value >= offer.minValue); // Didn't send enough ETH require(offer.seller == DrawingPrintToAddress[printIndex]); // Seller still owner of the drawing require(DrawingPrintToAddress[printIndex] != msg.sender); address seller = offer.seller; address buyer = msg.sender; DrawingPrintToAddress[printIndex] = buyer; // "gives" the print to the buyer // decrease by one the amount of prints the seller has of this particullar drawing balances[seller]--; // increase by one the amount of prints the buyer has of this particullar drawing balances[buyer]++; // launch the Transfered event Transfer(seller, buyer, 1); // transfer ETH to the seller // profit delta must be equal or greater than 1e-16 to be able to divide it // between the involved entities (art creator -> 30%, seller -> 60% and MisfitArt -> 10%) // profit percentages can't be lower than 1e-18 which is the lowest unit in ETH // equivalent to 1 wei. // if(offer.lastSellValue < msg.value && (msg.value - offer.lastSellValue) >= uint(0.0000000000000001) ){ commented because we're assuming values are expressed in "weis", adjusting in relation to that if(offer.lastSellValue < msg.value && (msg.value - offer.lastSellValue) >= 100 ){ // assuming 100 (weis) wich is equivalent to 1e-16 uint profit = msg.value - offer.lastSellValue; // seller gets base value plus 90% of the profit pendingWithdrawals[seller] += offer.lastSellValue + (profit*90/100); // MisfitArt gets 10% of the profit pendingWithdrawals[owner] += (profit*10/100); // MisfitArt receives 30% of the profit to give to the artist // pendingWithdrawals[owner] += (profit*30/100); // going manual for artist and MisfitArt percentages (30 + 10) // pendingWithdrawals[owner] += (profit*40/100); }else{ // if the seller doesn't make a profit of the sell he gets the 100% of the traded // value. pendingWithdrawals[seller] += msg.value; } makeCollectibleUnavailableToSale(buyer, drawingId, printIndex, msg.value); // launch the CollectibleBought event CollectibleBought(drawingId, printIndex, msg.value, seller, buyer); // Check for the case where there is a bid from the new owner and refund it. // Any other bid can stay in place. Bid storage bid = Bids[printIndex]; if (bid.bidder == buyer) { // Kill bid and refund value pendingWithdrawals[buyer] += bid.value; Bids[printIndex] = Bid(false, collectible.drawingId, printIndex, 0x0, 0); } } function alt_buyCollectible(uint drawingId, uint printIndex) payable { require(isExecutionAllowed); // requires the drawing id to actually exist require(drawingIdToCollectibles[drawingId].drawingId != 0); Collectible storage collectible = drawingIdToCollectibles[drawingId]; require((printIndex < (collectible.totalSupply+collectible.initialPrintIndex)) && (printIndex >= collectible.initialPrintIndex)); Offer storage offer = OfferedForSale[printIndex]; require(offer.drawingId == 0); require(msg.value >= collectible.initialPrice); // Didn't send enough ETH require(DrawingPrintToAddress[printIndex] == 0x0); // should be equal to a "null" address (0x0) since it shouldn't have an owner yet address seller = owner; address buyer = msg.sender; DrawingPrintToAddress[printIndex] = buyer; // "gives" the print to the buyer // decrease by one the amount of prints the seller has of this particullar drawing // commented while we decide what to do with balances for MisfitArt balances[seller]--; // increase by one the amount of prints the buyer has of this particullar drawing balances[buyer]++; // launch the Transfered event Transfer(seller, buyer, 1); // transfer ETH to the seller // profit delta must be equal or greater than 1e-16 to be able to divide it // between the involved entities (art creator -> 30%, seller -> 60% and MisfitArt -> 10%) // profit percentages can't be lower than 1e-18 which is the lowest unit in ETH // equivalent to 1 wei. pendingWithdrawals[owner] += msg.value; OfferedForSale[printIndex] = Offer(false, collectible.drawingId, printIndex, buyer, msg.value, 0x0, msg.value); // launch the CollectibleBought event CollectibleBought(drawingId, printIndex, msg.value, seller, buyer); // Check for the case where there is a bid from the new owner and refund it. // Any other bid can stay in place. Bid storage bid = Bids[printIndex]; if (bid.bidder == buyer) { // Kill bid and refund value pendingWithdrawals[buyer] += bid.value; Bids[printIndex] = Bid(false, collectible.drawingId, printIndex, 0x0, 0); } } function enterBidForCollectible(uint drawingId, uint printIndex) payable { require(isExecutionAllowed); require(drawingIdToCollectibles[drawingId].drawingId != 0); Collectible storage collectible = drawingIdToCollectibles[drawingId]; require(DrawingPrintToAddress[printIndex] != 0x0); // Print is owned by somebody require(DrawingPrintToAddress[printIndex] != msg.sender); // Print is not owned by bidder require((printIndex < (collectible.totalSupply+collectible.initialPrintIndex)) && (printIndex >= collectible.initialPrintIndex)); require(msg.value > 0); // Bid must be greater than 0 // get the current bid for that print if any Bid storage existing = Bids[printIndex]; // Must outbid previous bid by at least 5%. Apparently is not possible to // multiply by 1.05, that's why we do it manually. require(msg.value >= existing.value+(existing.value*5/100)); if (existing.value > 0) { // Refund the failing bid from the previous bidder pendingWithdrawals[existing.bidder] += existing.value; } // add the new bid Bids[printIndex] = Bid(true, collectible.drawingId, printIndex, msg.sender, msg.value); CollectibleBidEntered(collectible.drawingId, printIndex, msg.value, msg.sender); } // used by a user who wants to cancell a bid placed by her/him function withdrawBidForCollectible(uint drawingId, uint printIndex) { require(isExecutionAllowed); require(drawingIdToCollectibles[drawingId].drawingId != 0); Collectible storage collectible = drawingIdToCollectibles[drawingId]; require((printIndex < (collectible.totalSupply+collectible.initialPrintIndex)) && (printIndex >= collectible.initialPrintIndex)); require(DrawingPrintToAddress[printIndex] != 0x0); // Print is owned by somebody require(DrawingPrintToAddress[printIndex] != msg.sender); // Print is not owned by bidder Bid storage bid = Bids[printIndex]; require(bid.bidder == msg.sender); CollectibleBidWithdrawn(drawingId, printIndex, bid.value, msg.sender); uint amount = bid.value; Bids[printIndex] = Bid(false, collectible.drawingId, printIndex, 0x0, 0); // Refund the bid money msg.sender.transfer(amount); } // seller's functions function offerCollectibleForSale(uint drawingId, uint printIndex, uint minSalePriceInWei) { require(isExecutionAllowed); require(drawingIdToCollectibles[drawingId].drawingId != 0); Collectible storage collectible = drawingIdToCollectibles[drawingId]; require(DrawingPrintToAddress[printIndex] == msg.sender); require((printIndex < (collectible.totalSupply+collectible.initialPrintIndex)) && (printIndex >= collectible.initialPrintIndex)); uint lastSellValue = OfferedForSale[printIndex].lastSellValue; OfferedForSale[printIndex] = Offer(true, collectible.drawingId, printIndex, msg.sender, minSalePriceInWei, 0x0, lastSellValue); CollectibleOffered(drawingId, printIndex, minSalePriceInWei, 0x0, lastSellValue); } function withdrawOfferForCollectible(uint drawingId, uint printIndex){ require(isExecutionAllowed); require(drawingIdToCollectibles[drawingId].drawingId != 0); Collectible storage collectible = drawingIdToCollectibles[drawingId]; require(DrawingPrintToAddress[printIndex] == msg.sender); require((printIndex < (collectible.totalSupply+collectible.initialPrintIndex)) && (printIndex >= collectible.initialPrintIndex)); uint lastSellValue = OfferedForSale[printIndex].lastSellValue; OfferedForSale[printIndex] = Offer(false, collectible.drawingId, printIndex, msg.sender, 0, 0x0, lastSellValue); // launch the CollectibleNoLongerForSale event CollectibleNoLongerForSale(collectible.drawingId, printIndex); } function offerCollectibleForSaleToAddress(uint drawingId, uint printIndex, uint minSalePriceInWei, address toAddress) { require(isExecutionAllowed); require(drawingIdToCollectibles[drawingId].drawingId != 0); Collectible storage collectible = drawingIdToCollectibles[drawingId]; require(DrawingPrintToAddress[printIndex] == msg.sender); require((printIndex < (collectible.totalSupply+collectible.initialPrintIndex)) && (printIndex >= collectible.initialPrintIndex)); uint lastSellValue = OfferedForSale[printIndex].lastSellValue; OfferedForSale[printIndex] = Offer(true, collectible.drawingId, printIndex, msg.sender, minSalePriceInWei, toAddress, lastSellValue); CollectibleOffered(drawingId, printIndex, minSalePriceInWei, toAddress, lastSellValue); } function acceptBidForCollectible(uint drawingId, uint minPrice, uint printIndex) { require(isExecutionAllowed); require(drawingIdToCollectibles[drawingId].drawingId != 0); Collectible storage collectible = drawingIdToCollectibles[drawingId]; require((printIndex < (collectible.totalSupply+collectible.initialPrintIndex)) && (printIndex >= collectible.initialPrintIndex)); require(DrawingPrintToAddress[printIndex] == msg.sender); address seller = msg.sender; Bid storage bid = Bids[printIndex]; require(bid.value > 0); // Will be zero if there is no actual bid require(bid.value >= minPrice); // Prevent a condition where a bid is withdrawn and replaced with a lower bid but seller doesn't know DrawingPrintToAddress[printIndex] = bid.bidder; balances[seller]--; balances[bid.bidder]++; Transfer(seller, bid.bidder, 1); uint amount = bid.value; Offer storage offer = OfferedForSale[printIndex]; // transfer ETH to the seller // profit delta must be equal or greater than 1e-16 to be able to divide it // between the involved entities (art creator -> 30%, seller -> 60% and MisfitArt -> 10%) // profit percentages can't be lower than 1e-18 which is the lowest unit in ETH // equivalent to 1 wei. // if(offer.lastSellValue > msg.value && (msg.value - offer.lastSellValue) >= uint(0.0000000000000001) ){ commented because we're assuming values are expressed in "weis", adjusting in relation to that if(offer.lastSellValue < amount && (amount - offer.lastSellValue) >= 100 ){ // assuming 100 (weis) wich is equivalent to 1e-16 uint profit = amount - offer.lastSellValue; // seller gets base value plus 90% of the profit pendingWithdrawals[seller] += offer.lastSellValue + (profit*90/100); // MisfitArt gets 10% of the profit pendingWithdrawals[owner] += (profit*10/100); // MisfitArt receives 30% of the profit to give to the artist // pendingWithdrawals[owner] += (profit*30/100); // pendingWithdrawals[owner] += (profit*40/100); }else{ // if the seller doesn't make a profit of the sell he gets the 100% of the traded // value. pendingWithdrawals[seller] += amount; } // does the same as the function makeCollectibleUnavailableToSale OfferedForSale[printIndex] = Offer(false, collectible.drawingId, printIndex, bid.bidder, 0, 0x0, amount); CollectibleBought(collectible.drawingId, printIndex, bid.value, seller, bid.bidder); Bids[printIndex] = Bid(false, collectible.drawingId, printIndex, 0x0, 0); } // used by a user who wants to cashout his money function withdraw() { require(isExecutionAllowed); uint amount = pendingWithdrawals[msg.sender]; // Remember to zero the pending refund before // sending to prevent re-entrancy attacks pendingWithdrawals[msg.sender] = 0; msg.sender.transfer(amount); } // Transfer ownership of a punk to another user without requiring payment function transfer(address to, uint drawingId, uint printIndex) returns (bool success){ require(isExecutionAllowed); require(drawingIdToCollectibles[drawingId].drawingId != 0); Collectible storage collectible = drawingIdToCollectibles[drawingId]; // checks that the user making the transfer is the actual owner of the print require(DrawingPrintToAddress[printIndex] == msg.sender); require((printIndex < (collectible.totalSupply+collectible.initialPrintIndex)) && (printIndex >= collectible.initialPrintIndex)); makeCollectibleUnavailableToSale(to, drawingId, printIndex, OfferedForSale[printIndex].lastSellValue); // sets the new owner of the print DrawingPrintToAddress[printIndex] = to; balances[msg.sender]--; balances[to]++; Transfer(msg.sender, to, 1); CollectibleTransfer(msg.sender, to, drawingId, printIndex); // Check for the case where there is a bid from the new owner and refund it. // Any other bid can stay in place. Bid storage bid = Bids[printIndex]; if (bid.bidder == to) { // Kill bid and refund value pendingWithdrawals[to] += bid.value; Bids[printIndex] = Bid(false, drawingId, printIndex, 0x0, 0); } return true; } // utility functions function makeCollectibleUnavailableToSale(address to, uint drawingId, uint printIndex, uint lastSellValue) { require(isExecutionAllowed); require(drawingIdToCollectibles[drawingId].drawingId != 0); Collectible storage collectible = drawingIdToCollectibles[drawingId]; require(DrawingPrintToAddress[printIndex] == msg.sender); require((printIndex < (collectible.totalSupply+collectible.initialPrintIndex)) && (printIndex >= collectible.initialPrintIndex)); OfferedForSale[printIndex] = Offer(false, collectible.drawingId, printIndex, to, 0, 0x0, lastSellValue); // launch the CollectibleNoLongerForSale event CollectibleNoLongerForSale(collectible.drawingId, printIndex); } function newCollectible(uint drawingId, string checkSum, uint256 _totalSupply, uint initialPrice, uint initialPrintIndex, uint collectionId, uint authorUId){ // requires the sender to be the same address that compiled the contract, // this is ensured by storing the sender address // require(owner == msg.sender); require(owner == msg.sender); // requires the drawing to not exist already in the scope of the contract require(drawingIdToCollectibles[drawingId].drawingId == 0); drawingIdToCollectibles[drawingId] = Collectible(drawingId, checkSum, _totalSupply, initialPrice, initialPrintIndex, collectionId, authorUId); } function flipSwitchTo(bool state){ // require(owner == msg.sender); require(owner == msg.sender); isExecutionAllowed = state; } function mintNewDrawings(uint amount){ require(owner == msg.sender); totalSupply = totalSupply + amount; balances[owner] = balances[owner] + amount; Transfer(0, owner, amount); } } // File: contracts/Migrations.sol pragma solidity ^0.4.2; contract Migrations { address public owner; uint public last_completed_migration; modifier restricted() { if (msg.sender == owner) _; } function Migrations() { owner = msg.sender; } function setCompleted(uint completed) restricted { last_completed_migration = completed; } function upgrade(address new_address) restricted { Migrations upgraded = Migrations(new_address); upgraded.setCompleted(last_completed_migration); } }
returns the balance of a particular account
function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } event Transfer(address indexed from, address indexed to, uint256 value); event CollectibleTransfer(address indexed from, address indexed to, uint256 collectibleIndex, uint256 printIndex); event CollectibleOffered(uint indexed collectibleIndex, uint indexed printIndex, uint minValue, address indexed toAddress, uint lastSellValue); event CollectibleBidEntered(uint indexed collectibleIndex, uint indexed printIndex, uint value, address indexed fromAddress); event CollectibleBidWithdrawn(uint indexed collectibleIndex, uint indexed printIndex, uint value, address indexed fromAddress); event CollectibleBought(uint indexed collectibleIndex, uint printIndex, uint value, address indexed fromAddress, address indexed toAddress); event CollectibleNoLongerForSale(uint indexed collectibleIndex, uint indexed printIndex);
6,302,399
./partial_match/1/0x5fb10760cBDF27AB8027e1F63f96c173dB1f2f76/sources/CLIFFORDINUDEV.sol
exclude from paying fees or having max transaction amount
constructor() ERC20("CLIFF2.0", "CLIFF2.0") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02( 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); uint256 _buyCharityFee = 12; uint256 _buyMarketingFee = 12; uint256 _buyLiquidityFee = 0; uint256 _buyDevFee = 0; uint256 _sellCharityFee = 12; uint256 _sellMarketingFee = 18; uint256 _sellLiquidityFee = 0; uint256 _sellDevFee = 0; uint256 totalSupply = 100000000000000 * 1e18; buyCharityFee = _buyCharityFee; buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyCharityFee + buyMarketingFee + buyLiquidityFee + buyDevFee; sellCharityFee = _sellCharityFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = _sellDevFee; sellTotalFees = sellCharityFee + sellMarketingFee + sellLiquidityFee + sellDevFee; excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again _mint(msg.sender, totalSupply);
16,076,249
./partial_match/3/0x19d4d5dC9E5f2873fdE18c3EB08b53890881CC72/sources/wHNT.sol
See {IERC2612Permit-permit}. EIP712 Domain Separator is automatically recalculated./
function permit( address owner, address spender, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public { require(blockTimestamp() <= deadline, "ERC20Permit: expired deadline"); bytes32 hashStruct = keccak256( abi.encode(_PERMIT_TYPEHASH, owner, spender, amount, _nonces[owner], deadline) ); bytes32 hash = keccak256(abi.encodePacked(uint16(0x1901), _domainSeparator(), hashStruct)); address signer = ECDSA.recover(hash, v, r, s); require(signer == owner, "ERC20Permit: invalid signature"); _nonces[owner]++; _approve(owner, spender, amount); }
5,170,537
./full_match/1/0x89eE2edA0a7201014Ed800db7b526DBD17AFc176/sources/contracts/Boost.sol
Returns staking pool address from given index/ BT_INE: index does not exists
function stakingPool(uint256 index) external view returns (address) { require(index < stakingPools.length(), "BT_INE"); return address(stakingPools.at(index)); }
4,899,374
./partial_match/1/0x366fea9d4183d5088952849Ea02b2Db7207686F0/sources/CosmeComics.sol
See {IERC165-supportsInterface}./
function supportsInterface( bytes4 interfaceId ) public view virtual override(ERC2981, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || interfaceId == type(IERC2981).interfaceId || super.supportsInterface(interfaceId); }
4,306,124
// SPDX-License-Identifier: MIT pragma solidity ^0.8.7; //import "hardhat/console.sol"; import {AccessControl} from "@openzeppelin/contracts/access/AccessControl.sol"; import {EnumerableSet} from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; /// @title Blocklist /// @notice This contract can be used to maintain a blocklist /// Blocklist includes: /// - EVM Addresses from OFAC SDN and Blocked Persons List contract Blocklist is AccessControl { bytes32 public constant MAINTAINER_ROLE = keccak256("MAINTAINER_ROLE"); using EnumerableSet for EnumerableSet.AddressSet; EnumerableSet.AddressSet internal _blocklist; constructor(address[] memory startingBlockedAddresses) { _grantRole(DEFAULT_ADMIN_ROLE, msg.sender); _grantRole(MAINTAINER_ROLE, msg.sender); _addToBlocklist(startingBlockedAddresses); } event Blocked(address[] addresses); event UnBlocked(address[] addresses); /** * @dev Returns true if user is NOT on the blocklist otherwise returns false */ function isNotBlocked(address _address) external view returns(bool) { return _blocklist.contains(_address) != true; } /** * @dev Returns array of addresses that are blocked * WARNING: Use as view function only, not for state-changing functions. * see EnumerableSet.values for more details on the warning above */ function getBlocklist() external view returns (address[] memory recipients) { return _blocklist.values(); } /** * @dev Add array of addresses to the blocklist * * Returns true if any address in the array were added to the blocklist */ function addToBlocklist(address[] calldata _addresses) external onlyRole(MAINTAINER_ROLE) returns(bool) { return _addToBlocklist(_addresses); } /** * @dev Remove array of addresses from the blocklist * * Returns true if any address in the array was removed from blocklist */ function removeFromBlocklist(address[] calldata _addresses) external onlyRole(MAINTAINER_ROLE) returns(bool) { return _removeFromBlocklist(_addresses); } /** * @dev Internal function to add array of addresses to the blocklist * _addresses needs to be of memory to support its use in the constructor * Returns true if any address in the array were added to the blocklist */ function _addToBlocklist(address[] memory _addresses) internal returns(bool){ bool didAdd = false; uint arrayLen = _addresses.length; for (uint256 i = 0; i < arrayLen; i++) { bool added = _blocklist.add(_addresses[i]); if (didAdd == false && added == true) { didAdd = true; } } emit Blocked(_addresses); return didAdd; } /** * @dev Internal function to remove array of addresses from the blocklist * * Returns true if any address in the array was removed from blocklist */ function _removeFromBlocklist(address[] calldata _addresses) internal returns(bool){ bool didRemove = false; uint arrayLen = _addresses.length; for (uint256 i = 0; i < arrayLen; i++) { bool removed = _blocklist.remove(_addresses[i]); if (didRemove == false && removed == true) { didRemove = true; } } return didRemove; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControl.sol) pragma solidity ^0.8.0; import "./IAccessControl.sol"; import "../utils/Context.sol"; import "../utils/Strings.sol"; import "../utils/introspection/ERC165.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context, IAccessControl, ERC165 { struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view virtual override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view virtual { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", Strings.toHexString(uint160(account), 20), " is missing role ", Strings.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been revoked `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== * * NOTE: This function is deprecated in favor of {_grantRole}. */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } /** * @dev Grants `role` to `account`. * * Internal function without access restriction. */ function _grantRole(bytes32 role, address account) internal virtual { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } /** * @dev Revokes `role` from `account`. * * Internal function without access restriction. */ function _revokeRole(bytes32 role, address account) internal virtual { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/structs/EnumerableSet.sol) pragma solidity ^0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library 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; if (lastIndex != toDeleteIndex) { bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex } // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { return set._values[index]; } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function _values(Set storage set) private view returns (bytes32[] memory) { return set._values; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(Bytes32Set storage set) internal view returns (bytes32[] memory) { return _values(set._inner); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(AddressSet storage set) internal view returns (address[] memory) { bytes32[] memory store = _values(set._inner); address[] memory result; assembly { result := store } return result; } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(UintSet storage set) internal view returns (uint256[] memory) { bytes32[] memory store = _values(set._inner); uint256[] memory result; assembly { result := store } return result; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol) pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); }
Add array of addresses to the blocklist Returns true if any address in the array were added to the blocklist/
function addToBlocklist(address[] calldata _addresses) external onlyRole(MAINTAINER_ROLE) returns(bool) { return _addToBlocklist(_addresses); }
14,884,251
// SPDX-License-Identifier: BlueOak-1.0.0 pragma solidity 0.8.9; import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol"; import "contracts/plugins/assets/abstract/CompoundOracleMixin.sol"; import "contracts/interfaces/IAsset.sol"; import "contracts/libraries/Fixed.sol"; // ==== External Interfaces ==== // See: https://github.com/aave/protocol-v2/tree/master/contracts/interfaces interface IAaveLendingPool { function getAddressesProvider() external view returns (ILendingPoolAddressesProvider); } interface ILendingPoolAddressesProvider { function getPriceOracle() external view returns (IAaveOracle); } interface IAaveOracle { // solhint-disable-next-line func-name-mixedcase function WETH() external view returns (address); /// @return {qETH/tok} The price of the `token` in ETH with 18 decimals function getAssetPrice(address token) external view returns (uint256); } // ==== End External Interfaces ==== abstract contract AaveOracleMixin is CompoundOracleMixin { IAaveLendingPool public aaveLendingPool; // solhint-disable-next-line func-name-mixedcase constructor(IComptroller comptroller_, IAaveLendingPool aaveLendingPool_) CompoundOracleMixin(comptroller_) { aaveLendingPool = aaveLendingPool_; } /// @return price_ {UoA/erc20} function consultOracle(address erc20_) internal view virtual returns (uint192 price_) { // Aave keeps their prices in terms of ETH IAaveOracle aaveOracle = aaveLendingPool.getAddressesProvider().getPriceOracle(); uint256 p = aaveOracle.getAssetPrice(address(erc20_)); uint256 ethPrice = comptroller.oracle().price("ETH"); // {microUoA/ETH} uint256 ethNorm = aaveOracle.getAssetPrice(aaveOracle.WETH()); // {qETH/ETH} // D18{UoA/erc20} = {qETH/erc20} * {microUoA/ETH} / {qETH/ETH} / {microUoA/UoA} price_ = uint192(mulDiv256(p, FIX_ONE * ethPrice, ethNorm, ROUND) / 1e6); if (price_ == 0) { revert PriceIsZero(); } } }
==== External Interfaces ==== See: https:github.com/aave/protocol-v2/tree/master/contracts/interfaces
interface IAaveLendingPool { function getAddressesProvider() external view returns (ILendingPoolAddressesProvider); pragma solidity 0.8.9; }
14,022,916
./full_match/1/0xDb29Ac569bc4906419755039525f1160762fd2D1/sources/DOGE.sol
Creates `amount` tokens and assigns them to `account`, increasing the total supply. Emits a {Transfer} event with `from` set to the zero address. Requirements: - `account` cannot be the zero address./
function _mint(address account, uint256 amount) internal virtual { _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); */
8,469,475
./full_match/83/0xdb68eC6dFd21791cC9c1f4836b6499e2325461A7/sources/contracts/suErc20Delegator.sol
Applies accrued interest to total borrows and reserves. This calculates interest accrued from the last checkpointed block up to the current block and writes new checkpoint to storage./
function accrueInterest() public returns (uint256) { bytes memory data = delegateToImplementation(abi.encodeWithSignature('accrueInterest()')); return abi.decode(data, (uint256)); }
9,556,339
pragma solidity ^0.4.18; import '../core/RequestCore.sol'; import '../base/math/SafeMathUint8.sol'; import './RequestEthereumCollect.sol'; import '../base/token/ERC20.sol'; /** * @title RequestEthereum * * @dev RequestEthereum is the currency contract managing the request in Ethereum * @dev The contract can be paused. In this case, nobody can create Requests anymore but people can still interact with them. * * @dev Requests can be created by the Payee with createRequestAsPayee(), by the payer with createRequestAsPayer() or by the payer from a request signed offchain by the payee with broadcastSignedRequestAsPayer() */ contract RequestEthereum is RequestEthereumCollect { using SafeMath for uint256; using SafeMathInt for int256; using SafeMathUint8 for uint8; // RequestCore object RequestCore public requestCore; // payment addresses by requestId (optional). We separate the Identity of the payee/payer (in the core) and the wallet address in the currency contract mapping(bytes32 => address[256]) public payeesPaymentAddress; mapping(bytes32 => address) public payerRefundAddress; /* * @dev Constructor * @param _requestCoreAddress Request Core address * @param _requestBurnerAddress Request Burner contract address */ function RequestEthereum(address _requestCoreAddress, address _requestBurnerAddress) RequestEthereumCollect(_requestBurnerAddress) public { requestCore=RequestCore(_requestCoreAddress); } /* * @dev Function to create a request as payee * * @dev msg.sender will be the payee * @dev if _payeesPaymentAddress.length > _payeesIdAddress.length, the extra addresses will be stored but never used * @dev If a contract is given as a payee make sure it is payable. Otherwise, the request will not be payable. * * @param _payeesIdAddress array of payees address (the index 0 will be the payee - must be msg.sender - the others are subPayees) * @param _payeesPaymentAddress array of payees address for payment (optional) * @param _expectedAmounts array of Expected amount to be received by each payees * @param _payer Entity expected to pay * @param _payerRefundAddress Address of refund for the payer (optional) * @param _data Hash linking to additional data on the Request stored on IPFS * * @return Returns the id of the request */ function createRequestAsPayee( address[] _payeesIdAddress, address[] _payeesPaymentAddress, int256[] _expectedAmounts, address _payer, address _payerRefundAddress, string _data) external payable whenNotPaused returns(bytes32 requestId) { require(msg.sender == _payeesIdAddress[0] && msg.sender != _payer && _payer != 0); uint256 fees; (requestId, fees) = createRequest(_payer, _payeesIdAddress, _payeesPaymentAddress, _expectedAmounts, _payerRefundAddress, _data); // check if the value send match exactly the fees (no under or over payment allowed) require(fees == msg.value); return requestId; } /* * @dev Function to create a request as payer. The request is payed if _payeeAmounts > 0. * * @dev msg.sender will be the payer * @dev If a contract is given as a payee make sure it is payable. Otherwise, the request will not be payable. * * @param _payeesIdAddress array of payees address (the index 0 will be the payee the others are subPayees) * @param _expectedAmounts array of Expected amount to be received by each payees * @param _payerRefundAddress Address of refund for the payer (optional) * @param _payeeAmounts array of amount repartition for the payment * @param _additionals array to increase the ExpectedAmount for payees * @param _data Hash linking to additional data on the Request stored on IPFS * * @return Returns the id of the request */ function createRequestAsPayer( address[] _payeesIdAddress, int256[] _expectedAmounts, address _payerRefundAddress, uint256[] _payeeAmounts, uint256[] _additionals, string _data) external payable whenNotPaused returns(bytes32 requestId) { require(msg.sender != _payeesIdAddress[0] && _payeesIdAddress[0] != 0); // payeesPaymentAddress is not offered as argument here to avoid scam address[] memory emptyPayeesPaymentAddress = new address[](0); uint256 fees; (requestId, fees) = createRequest(msg.sender, _payeesIdAddress, emptyPayeesPaymentAddress, _expectedAmounts, _payerRefundAddress, _data); // accept and pay the request with the value remaining after the fee collect acceptAndPay(requestId, _payeeAmounts, _additionals, msg.value.sub(fees)); return requestId; } /* * @dev Function to broadcast and accept an offchain signed request (can be paid and additionals also) * * @dev _payer will be set msg.sender * @dev if _payeesPaymentAddress.length > _requestData.payeesIdAddress.length, the extra addresses will be stored but never used * @dev If a contract is given as a payee make sure it is payable. Otherwise, the request will not be payable. * * @param _requestData nested bytes containing : creator, payer, payees, expectedAmounts, data * @param _payeesPaymentAddress array of payees address for payment (optional) * @param _payeeAmounts array of amount repartition for the payment * @param _additionals array to increase the ExpectedAmount for payees * @param _expirationDate timestamp after that the signed request cannot be broadcasted * @param _signature ECDSA signature in bytes * * @return Returns the id of the request */ function broadcastSignedRequestAsPayer( bytes _requestData, // gather data to avoid "stack too deep" address[] _payeesPaymentAddress, uint256[] _payeeAmounts, uint256[] _additionals, uint256 _expirationDate, bytes _signature) external payable whenNotPaused returns(bytes32) { // check expiration date require(_expirationDate >= block.timestamp); // check the signature require(checkRequestSignature(_requestData, _payeesPaymentAddress, _expirationDate, _signature)); // create accept and pay the request return createAcceptAndPayFromBytes(_requestData, _payeesPaymentAddress, _payeeAmounts, _additionals); } /* * @dev Internal function to create, accept, add additionals and pay a request as Payer * * @dev msg.sender must be _payer * * @param _requestData nasty bytes containing : creator, payer, payees|expectedAmounts, data * @param _payeesPaymentAddress array of payees address for payment (optional) * @param _payeeAmounts array of amount repartition for the payment * @param _additionals Will increase the ExpectedAmount of the request right after its creation by adding additionals * * @return Returns the id of the request */ function createAcceptAndPayFromBytes( bytes _requestData, address[] _payeesPaymentAddress, uint256[] _payeeAmounts, uint256[] _additionals) internal returns(bytes32 requestId) { // extract main payee address mainPayee = extractAddress(_requestData, 41); require(msg.sender != mainPayee && mainPayee != 0); // creator must be the main payee require(extractAddress(_requestData, 0) == mainPayee); // extract the number of payees uint8 payeesCount = uint8(_requestData[40]); int256 totalExpectedAmounts = 0; for(uint8 i = 0; i < payeesCount; i++) { // extract the expectedAmount for the payee[i] // NB: no need of SafeMath here because 0 < i < 256 (uint8) int256 expectedAmountTemp = int256(extractBytes32(_requestData, 61 + 52 * uint256(i))); // compute the total expected amount of the request totalExpectedAmounts = totalExpectedAmounts.add(expectedAmountTemp); // all expected amount must be positibe require(expectedAmountTemp>0); } // collect the fees uint256 fees = collectEstimation(totalExpectedAmounts); // check fees has been well received // do the action and assertion in one to save a variable require(collectForREQBurning(fees)); // insert the msg.sender as the payer in the bytes updateBytes20inBytes(_requestData, 20, bytes20(msg.sender)); // store request in the core, requestId = requestCore.createRequestFromBytes(_requestData); // set payment addresses for payees for (uint8 j = 0; j < _payeesPaymentAddress.length; j = j.add(1)) { payeesPaymentAddress[requestId][j] = _payeesPaymentAddress[j]; } // accept and pay the request with the value remaining after the fee collect acceptAndPay(requestId, _payeeAmounts, _additionals, msg.value.sub(fees)); return requestId; } /* * @dev Internal function to create a request * * @dev msg.sender is the creator of the request * * @param _payer Payer identity address * @param _payees Payees identity address * @param _payeesPaymentAddress Payees payment address * @param _expectedAmounts Expected amounts to be received by payees * @param _payerRefundAddress payer refund address * @param _data Hash linking to additional data on the Request stored on IPFS * * @return Returns the id of the request */ function createRequest( address _payer, address[] _payees, address[] _payeesPaymentAddress, int256[] _expectedAmounts, address _payerRefundAddress, string _data) internal returns(bytes32 requestId, uint256 fees) { int256 totalExpectedAmounts = 0; for (uint8 i = 0; i < _expectedAmounts.length; i = i.add(1)) { // all expected amount must be positive require(_expectedAmounts[i]>=0); // compute the total expected amount of the request totalExpectedAmounts = totalExpectedAmounts.add(_expectedAmounts[i]); } // collect the fees fees = collectEstimation(totalExpectedAmounts); // check fees has been well received require(collectForREQBurning(fees)); // store request in the core requestId= requestCore.createRequest(msg.sender, _payees, _expectedAmounts, _payer, _data); // set payment addresses for payees for (uint8 j = 0; j < _payeesPaymentAddress.length; j = j.add(1)) { payeesPaymentAddress[requestId][j] = _payeesPaymentAddress[j]; } // set payment address for payer if(_payerRefundAddress != 0) { payerRefundAddress[requestId] = _payerRefundAddress; } } /* * @dev Internal function to accept, add additionals and pay a request as Payer * * @param _requestId id of the request * @param _payeesAmounts Amount to pay to payees (sum must be equals to _amountPaid) * @param _additionals Will increase the ExpectedAmounts of payees * @param _amountPaid amount in msg.value minus the fees * */ function acceptAndPay( bytes32 _requestId, uint256[] _payeeAmounts, uint256[] _additionals, uint256 _amountPaid) internal { requestCore.accept(_requestId); additionalInternal(_requestId, _additionals); if(_amountPaid > 0) { paymentInternal(_requestId, _payeeAmounts, _amountPaid); } } // ---- INTERFACE FUNCTIONS ------------------------------------------------------------------------------------ /* * @dev Function to accept a request * * @dev msg.sender must be _payer * @dev A request can also be accepted by using directly the payment function on a request in the Created status * * @param _requestId id of the request */ function accept(bytes32 _requestId) external whenNotPaused condition(requestCore.getPayer(_requestId)==msg.sender) condition(requestCore.getState(_requestId)==RequestCore.State.Created) { requestCore.accept(_requestId); } /* * @dev Function to cancel a request * * @dev msg.sender must be the _payer or the _payee. * @dev only request with balance equals to zero can be cancel * * @param _requestId id of the request */ function cancel(bytes32 _requestId) external whenNotPaused { // payer can cancel if request is just created bool isPayerAndCreated = requestCore.getPayer(_requestId)==msg.sender && requestCore.getState(_requestId)==RequestCore.State.Created; // payee can cancel when request is not canceled yet bool isPayeeAndNotCanceled = requestCore.getPayeeAddress(_requestId,0)==msg.sender && requestCore.getState(_requestId)!=RequestCore.State.Canceled; require(isPayerAndCreated || isPayeeAndNotCanceled); // impossible to cancel a Request with any payees balance != 0 require(requestCore.areAllBalanceNull(_requestId)); requestCore.cancel(_requestId); } // ---------------------------------------------------------------------------------------- // ---- CONTRACT FUNCTIONS ------------------------------------------------------------------------------------ /* * @dev Function PAYABLE to pay a request in ether. * * @dev the request will be automatically accepted if msg.sender==payer. * * @param _requestId id of the request * @param _payeesAmounts Amount to pay to payees (sum must be equal to msg.value) in wei * @param _additionalsAmount amount of additionals per payee in wei to declare */ function paymentAction( bytes32 _requestId, uint256[] _payeeAmounts, uint256[] _additionalAmounts) external whenNotPaused payable condition(requestCore.getState(_requestId)!=RequestCore.State.Canceled) condition(_additionalAmounts.length == 0 || msg.sender == requestCore.getPayer(_requestId)) { // automatically accept request if request is created and msg.sender is payer if(requestCore.getState(_requestId)==RequestCore.State.Created && msg.sender == requestCore.getPayer(_requestId)) { requestCore.accept(_requestId); } additionalInternal(_requestId, _additionalAmounts); paymentInternal(_requestId, _payeeAmounts, msg.value); } /* * @dev Function PAYABLE to pay back in ether a request to the payer * * @dev msg.sender must be one of the payees * @dev the request must be created or accepted * * @param _requestId id of the request */ function refundAction(bytes32 _requestId) external whenNotPaused payable { refundInternal(_requestId, msg.sender, msg.value); } /* * @dev Function to declare a subtract * * @dev msg.sender must be _payee * @dev the request must be accepted or created * * @param _requestId id of the request * @param _subtractAmounts amounts of subtract in wei to declare (index 0 is for main payee) */ function subtractAction(bytes32 _requestId, uint256[] _subtractAmounts) external whenNotPaused condition(requestCore.getState(_requestId)!=RequestCore.State.Canceled) onlyRequestPayee(_requestId) { for(uint8 i = 0; i < _subtractAmounts.length; i = i.add(1)) { if(_subtractAmounts[i] != 0) { // subtract must be equal or lower than amount expected require(requestCore.getPayeeExpectedAmount(_requestId,i) >= _subtractAmounts[i].toInt256Safe()); // store and declare the subtract in the core requestCore.updateExpectedAmount(_requestId, i, -_subtractAmounts[i].toInt256Safe()); } } } /* * @dev Function to declare an additional * * @dev msg.sender must be _payer * @dev the request must be accepted or created * * @param _requestId id of the request * @param _additionalAmounts amounts of additional in wei to declare (index 0 is for main payee) */ function additionalAction(bytes32 _requestId, uint256[] _additionalAmounts) external whenNotPaused condition(requestCore.getState(_requestId)!=RequestCore.State.Canceled) onlyRequestPayer(_requestId) { additionalInternal(_requestId, _additionalAmounts); } // ---------------------------------------------------------------------------------------- // ---- INTERNAL FUNCTIONS ------------------------------------------------------------------------------------ /* * @dev Function internal to manage additional declaration * * @param _requestId id of the request * @param _additionalAmounts amount of additional to declare */ function additionalInternal(bytes32 _requestId, uint256[] _additionalAmounts) internal { // we cannot have more additional amounts declared than actual payees but we can have fewer require(_additionalAmounts.length <= requestCore.getSubPayeesCount(_requestId).add(1)); for(uint8 i = 0; i < _additionalAmounts.length; i = i.add(1)) { if(_additionalAmounts[i] != 0) { // Store and declare the additional in the core requestCore.updateExpectedAmount(_requestId, i, _additionalAmounts[i].toInt256Safe()); } } } /* * @dev Function internal to manage payment declaration * * @param _requestId id of the request * @param _payeesAmounts Amount to pay to payees (sum must be equals to msg.value) * @param _value amount paid */ function paymentInternal( bytes32 _requestId, uint256[] _payeeAmounts, uint256 _value) internal { // we cannot have more amounts declared than actual payees require(_payeeAmounts.length <= requestCore.getSubPayeesCount(_requestId).add(1)); uint256 totalPayeeAmounts = 0; for(uint8 i = 0; i < _payeeAmounts.length; i = i.add(1)) { if(_payeeAmounts[i] != 0) { // compute the total amount declared totalPayeeAmounts = totalPayeeAmounts.add(_payeeAmounts[i]); // Store and declare the payment to the core requestCore.updateBalance(_requestId, i, _payeeAmounts[i].toInt256Safe()); // pay the payment address if given, the id address otherwise address addressToPay; if(payeesPaymentAddress[_requestId][i] == 0) { addressToPay = requestCore.getPayeeAddress(_requestId, i); } else { addressToPay = payeesPaymentAddress[_requestId][i]; } //payment done, the money was sent fundOrderInternal(addressToPay, _payeeAmounts[i]); } } // check if payment repartition match the value paid require(_value==totalPayeeAmounts); } /* * @dev Function internal to manage refund declaration * * @param _requestId id of the request * @param _fromAddress address from where the refund has been done * @param _amount amount of the refund in wei to declare */ function refundInternal( bytes32 _requestId, address _fromAddress, uint256 _amount) condition(requestCore.getState(_requestId)!=RequestCore.State.Canceled) internal { // Check if the _fromAddress is a payeesId // int16 to allow -1 value int16 payeeIndex = requestCore.getPayeeIndex(_requestId, _fromAddress); if(payeeIndex < 0) { uint8 payeesCount = requestCore.getSubPayeesCount(_requestId).add(1); // if not ID addresses maybe in the payee payments addresses for (uint8 i = 0; i < payeesCount && payeeIndex == -1; i = i.add(1)) { if(payeesPaymentAddress[_requestId][i] == _fromAddress) { // get the payeeIndex payeeIndex = int16(i); } } } // the address must be found somewhere require(payeeIndex >= 0); // Casting to uin8 doesn't lose bits because payeeIndex < 256. payeeIndex was declared int16 to allow -1 requestCore.updateBalance(_requestId, uint8(payeeIndex), -_amount.toInt256Safe()); // refund to the payment address if given, the id address otherwise address addressToPay = payerRefundAddress[_requestId]; if(addressToPay == 0) { addressToPay = requestCore.getPayer(_requestId); } // refund declared, the money is ready to be sent to the payer fundOrderInternal(addressToPay, _amount); } /* * @dev Function internal to manage fund mouvement * @dev We had to chose between a withdrawal pattern, a transfer pattern or a transfer+withdrawal pattern and chose the transfer pattern. * @dev The withdrawal pattern would make UX difficult. The transfer+withdrawal pattern would make contracts interacting with the request protocol complex. * @dev N.B.: The transfer pattern will have to be clearly explained to users. It enables a payee to create unpayable requests. * * @param _recipient address where the wei has to be sent to * @param _amount amount in wei to send * */ function fundOrderInternal( address _recipient, uint256 _amount) internal { _recipient.transfer(_amount); } /* * @dev Function internal to calculate Keccak-256 hash of a request with specified parameters * * @param _data bytes containing all the data packed * @param _payeesPaymentAddress array of payees payment addresses * @param _expirationDate timestamp after what the signed request cannot be broadcasted * * @return Keccak-256 hash of (this,_requestData, _payeesPaymentAddress, _expirationDate) */ function getRequestHash( // _requestData is from the core bytes _requestData, // _payeesPaymentAddress and _expirationDate are not from the core but needs to be signed address[] _payeesPaymentAddress, uint256 _expirationDate) internal view returns(bytes32) { return keccak256(this, _requestData, _payeesPaymentAddress, _expirationDate); } /* * @dev Verifies that a hash signature is valid. 0x style * @param signer address of signer. * @param hash Signed Keccak-256 hash. * @param v ECDSA signature parameter v. * @param r ECDSA signature parameters r. * @param s ECDSA signature parameters s. * @return Validity of order signature. */ function isValidSignature( address signer, bytes32 hash, uint8 v, bytes32 r, bytes32 s) public pure returns (bool) { return signer == ecrecover( keccak256("\x19Ethereum Signed Message:\n32", hash), v, r, s ); } /* * @dev Check the validity of a signed request & the expiration date * @param _data bytes containing all the data packed : address(creator) address(payer) uint8(number_of_payees) [ address(main_payee_address) int256(main_payee_expected_amount) address(second_payee_address) int256(second_payee_expected_amount) ... ] uint8(data_string_size) size(data) * @param _payeesPaymentAddress array of payees payment addresses (the index 0 will be the payee the others are subPayees) * @param _expirationDate timestamp after that the signed request cannot be broadcasted * @param _signature ECDSA signature containing v, r and s as bytes * * @return Validity of order signature. */ function checkRequestSignature( bytes _requestData, address[] _payeesPaymentAddress, uint256 _expirationDate, bytes _signature) public view returns (bool) { bytes32 hash = getRequestHash(_requestData, _payeesPaymentAddress, _expirationDate); // extract "v, r, s" from the signature uint8 v = uint8(_signature[64]); v = v < 27 ? v.add(27) : v; bytes32 r = extractBytes32(_signature, 0); bytes32 s = extractBytes32(_signature, 32); // check signature of the hash with the creator address return isValidSignature(extractAddress(_requestData, 0), hash, v, r, s); } //modifier modifier condition(bool c) { require(c); _; } /* * @dev Modifier to check if msg.sender is payer * @dev Revert if msg.sender is not payer * @param _requestId id of the request */ modifier onlyRequestPayer(bytes32 _requestId) { require(requestCore.getPayer(_requestId)==msg.sender); _; } /* * @dev Modifier to check if msg.sender is the main payee * @dev Revert if msg.sender is not the main payee * @param _requestId id of the request */ modifier onlyRequestPayee(bytes32 _requestId) { require(requestCore.getPayeeAddress(_requestId, 0)==msg.sender); _; } /* * @dev modify 20 bytes in a bytes * @param data bytes to modify * @param offset position of the first byte to modify * @param b bytes20 to insert * @return address */ function updateBytes20inBytes(bytes data, uint offset, bytes20 b) internal pure { require(offset >=0 && offset + 20 <= data.length); assembly { let m := mload(add(data, add(20, offset))) m := and(m, 0xFFFFFFFFFFFFFFFFFFFFFFFF0000000000000000000000000000000000000000) m := or(m, div(b, 0x1000000000000000000000000)) mstore(add(data, add(20, offset)), m) } } /* * @dev extract an address in a bytes * @param data bytes from where the address will be extract * @param offset position of the first byte of the address * @return address */ function extractAddress(bytes _data, uint offset) internal pure returns (address m) { require(offset >=0 && offset + 20 <= _data.length); assembly { m := and( mload(add(_data, add(20, offset))), 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) } } /* * @dev extract a bytes32 from a bytes * @param data bytes from where the bytes32 will be extract * @param offset position of the first byte of the bytes32 * @return address */ function extractBytes32(bytes _data, uint offset) public pure returns (bytes32 bs) { require(offset >=0 && offset + 32 <= _data.length); assembly { bs := mload(add(_data, add(32, offset))) } } /** * @dev transfer to owner any tokens send by mistake on this contracts * @param token The address of the token to transfer. * @param amount The amount to be transfered. */ function emergencyERC20Drain(ERC20 token, uint amount ) public onlyOwner { token.transfer(owner, amount); } }
modify 20 bytes in a bytes data bytes to modify offset position of the first byte to modify b bytes20 to insert return address/
function updateBytes20inBytes(bytes data, uint offset, bytes20 b) internal pure { require(offset >=0 && offset + 20 <= data.length); assembly { let m := mload(add(data, add(20, offset))) m := and(m, 0xFFFFFFFFFFFFFFFFFFFFFFFF0000000000000000000000000000000000000000) m := or(m, div(b, 0x1000000000000000000000000)) mstore(add(data, add(20, offset)), m) } }
14,089,375
./partial_match/1/0x90A62dc4BF3f805504a248A49eFC469F406D41b9/sources/src/Contracts/LiquidLocker/LockerMaster.sol
amount The amount of tokens to be locked by the service. Locks the specified amount of tokens by the owner of the contract. It calls the lockToken function of the adapter to lock the tokens for a specific unlock time to manual increase lock in case of DAO government actions/
function serviceLock(uint256 amount) external onlyOwner { LiquidLockerSlot storage l = _adapter(); address adapter = l.adapter; if (adapter == address(0)) revert AdapterDisabled(); if (unlockTime != 0 && unlockTime <= block.timestamp) revert LockingIsOver(); IERC20(l.lockableToken).safeTransferFrom(msg.sender, address(this), amount); ILiquidLocker(adapter).lockToken(amount, unlockTime); emit Lock(msg.sender, amount); }
4,091,691