Unnamed: 0
int64
0
7.36k
comments
stringlengths
3
35.2k
code_string
stringlengths
1
527k
code
stringlengths
1
527k
__index_level_0__
int64
0
88.6k
9
// Throws if called by any account other than the blacklister/
modifier onlyBlacklister() { require(msg.sender == blacklister); _; }
modifier onlyBlacklister() { require(msg.sender == blacklister); _; }
61,084
192
// ERC1155TradableERC1155Tradable - ERC1155 contract that whitelists an operator address, has create and mint functionality, and supports useful standards from OpenZeppelin, /
contract ERC1155Tradable is ERC1155, ERC1155MintBurn, ERC1155Metadata, Ownable { //address proxyRegistryAddress; uint256 private totalTokenAssets = 10000; uint256 private totalReserve = 336; uint256 public _currentTokenID = 0; uint256 public _customizedTokenId = 9000; // uint256 private _maxTokenPerUser = 1000; uint256 private _maxTokenPerMint = 2; uint256 public sold = 0; uint256 private reserved = 0; // uint256 private presalesMaxToken = 3; uint256 private preSalesPrice1 = 0.07 ether; uint256 private preSalesPrice2 = 0.088 ether; uint256 private publicSalesPrice = 0.088 ether; uint256 private preSalesMaxSupply3 = 9000; address private signerAddress = 0x22A19Fd9F3a29Fe8260F88C46dB04941Fa0615C9; uint16 public salesStage = 3; //1-presales1 , 2-presales2 , 3-public address payable public companyWallet = 0xE369C3f00d8dc97Be4B58a7ede901E48c4767bD2; //test mapping(uint256 => uint256) private _presalesPrice; mapping(address => uint256) public presales1minted; // To check how many tokens an address has minted during presales mapping(address => uint256) public presales2minted; // To check how many tokens an address has minted during presales mapping(address => uint256) public minted; // To check how many tokens an address has minted mapping (uint256 => address) public creators; mapping (uint256 => uint256) public tokenSupply; mapping(uint256 => string) public rawdata; event TokenMinted(uint indexed _tokenid, address indexed _userAddress, string indexed _rawData); // Contract name string public name; // Contract symbol string public symbol; /** * @dev Require msg.sender to be the creator of the token id */ modifier creatorOnly(uint256 _id) { require(creators[_id] == msg.sender, "ERC1155Tradable#creatorOnly: ONLY_CREATOR_ALLOWED"); _; } /** * @dev Require msg.sender to own more than 0 of the token id */ modifier ownersOnly(uint256 _id) { require(balances[msg.sender][_id] > 0, "ERC1155Tradable#ownersOnly: ONLY_OWNERS_ALLOWED"); _; } constructor( string memory _name, string memory _symbol //address _proxyRegistryAddress ) public { name = _name; symbol = _symbol; //proxyRegistryAddress = _proxyRegistryAddress; } using Strings for string; // // Function to receive Ether. msg.data must be empty // receive() external payable {} // // Fallback function is called when msg.data is not empty // fallback() external payable {} function uri( uint256 _id ) public view returns (string memory) { require(_exists(_id), "ERC721Tradable#uri: NONEXISTENT_TOKEN"); return Strings.strConcat( baseMetadataURI, Strings.uint2str(_id) ); } /** * @dev Returns the total quantity for a token ID * @param _id uint256 ID of the token to query * @return amount of token in existence */ function totalSupply( uint256 _id ) public view returns (uint256) { return tokenSupply[_id]; } /** * @dev Will update the base URL of token's URI * @param _newBaseMetadataURI New base URL of token's URI */ function setBaseMetadataURI( string memory _newBaseMetadataURI ) public onlyOwner { _setBaseMetadataURI(_newBaseMetadataURI); } /** * @dev Creates a new token type and assigns _initialSupply to an address * NOTE: remove onlyOwner if you want third parties to create new tokens on your contract (which may change your IDs) * @param _initialOwner address of the first owner of the token * @param _initialSupply amount to supply the first owner * @param _uri Optional URI for this token type * @param _data Data to pass if receiver is contract * @return The newly created token ID */ function reserve( //When start this mint 336 first address _initialOwner, uint256 _initialSupply, string calldata _uri, bytes calldata _data ) external onlyOwner returns (uint256) { require(reserved + _initialSupply <= totalReserve, "Reserve Empty"); sold += _initialSupply; for (uint256 i = 0; i < _initialSupply; i++) { reserved++; uint256 _id = reserved; if (bytes(_uri).length > 0) { emit URI(_uri, _id); } creators[_id] = msg.sender; _mint(_initialOwner, _id, 1, _data); tokenSupply[_id] = 1; } return 0; } function toBytes(address a) public pure returns (bytes memory b){ assembly { let m := mload(0x40) a := and(a, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) mstore(add(m, 20), xor(0x140000000000000000000000000000000000000000, a)) mstore(0x40, add(m, 52)) b := m } } function addressToString(address _addr) internal pure returns(string memory) { bytes32 value = bytes32(uint256(_addr)); bytes memory alphabet = "0123456789abcdef"; bytes memory str = new bytes(42); str[0] = "0"; str[1] = "x"; for (uint i = 0; i < 20; i++) { str[2+i*2] = alphabet[uint(uint8(value[i + 12] >> 4))]; str[3+i*2] = alphabet[uint(uint8(value[i + 12] & 0x0f))]; } return string(str); } function toAsciiString(address x) internal pure returns (string memory) { bytes memory s = new bytes(40); for (uint i = 0; i < 20; i++) { bytes1 b = bytes1(uint8(uint(uint160(x)) / (2**(8*(19 - i))))); bytes1 hi = bytes1(uint8(b) / 16); bytes1 lo = bytes1(uint8(b) - 16 * uint8(hi)); s[2*i] = char(hi); s[2*i+1] = char(lo); } return string(s); } function char( bytes1 b ) internal pure returns (bytes1 c) { if (uint8(b) < 10) return bytes1(uint8(b) + 0x30); else return bytes1(uint8(b) + 0x57); } function bytes32ToString(bytes32 _bytes32) public pure returns (string memory) { uint8 i = 0; bytes memory bytesArray = new bytes(64); for (i = 0; i < bytesArray.length; i++) { uint8 _f = uint8(_bytes32[i/2] & 0x0f); uint8 _l = uint8(_bytes32[i/2] >> 4); bytesArray[i] = toByte(_f); i = i + 1; bytesArray[i] = toByte(_l); } return string(bytesArray); } function stringToBytes32(string memory source) public pure returns (bytes32 result) { bytes memory tempEmptyStringTest = bytes(source); if (tempEmptyStringTest.length == 0) { return 0x0; } assembly { result := mload(add(source, 32)) } } function splitSignature(bytes memory sig) public pure returns (uint8, bytes32, bytes32) { require(sig.length == 65); bytes32 r; bytes32 s; uint8 v; assembly { // first 32 bytes, after the length prefix r := mload(add(sig, 32)) // second 32 bytes s := mload(add(sig, 64)) // final byte (first byte of the next 32 bytes) v := byte(0, mload(add(sig, 96))) } return (v, r, s); } function recoverSigner(bytes32 message, bytes memory sig) public pure returns (address) { uint8 v; bytes32 r; bytes32 s; (v, r, s) = splitSignature(sig); return ecrecover(message, v, r, s); } function isValidData(string memory _word, bytes memory sig) public view returns(bool){ bytes32 message = keccak256(abi.encodePacked(_word)); return (recoverSigner(message, sig) == signerAddress); } function toByte(uint8 _uint8) public pure returns (byte) { if(_uint8 < 10) { return byte(_uint8 + 48); } else { return byte(_uint8 + 87); } } function withdraw() public onlyOwner { require(companyWallet != address(0), "Please Set Company Wallet Address"); uint256 balance = address(this).balance; companyWallet.transfer(balance); } function presales( address _initialOwner, uint256 _initialSupply, bytes calldata _sig, bytes calldata _data ) external payable returns (uint256) { require(salesStage == 1 || salesStage == 2, "Presales is closed"); if(salesStage == 1){ require(sold + _initialSupply <= preSalesMaxSupply3, "Max Token reached for Sales Stage 1"); require(_initialSupply * preSalesPrice1 == msg.value, "Invalid Fund"); }else if(salesStage == 2){ require(sold + _initialSupply <= preSalesMaxSupply3, "Max Token reached for Sales Stage 2"); require(_initialSupply * preSalesPrice2 == msg.value, "Invalid Fund"); } require(isValidData(addressToString(msg.sender), _sig), addressToString(msg.sender)); sold += _initialSupply; if(salesStage == 1){ presales1minted[_initialOwner] += _initialSupply; }else if(salesStage == 2){ presales2minted[_initialOwner] += _initialSupply; } minted[_initialOwner] += _initialSupply; for (uint256 i = 0; i < _initialSupply; i++) { uint256 _id = _getNextTokenID() + totalReserve; _incrementTokenTypeId(); creators[_id] = msg.sender; _mint(_initialOwner, _id, 1, _data); tokenSupply[_id] = 1; emit TokenMinted(_id, _initialOwner, ""); } return 0; } function publicsales( address _initialOwner, uint256 _initialSupply, string calldata _uri, bytes calldata _data ) external payable returns (uint256) { require(salesStage == 3 , "Public Sales Is Closed"); require(sold + _initialSupply <= preSalesMaxSupply3, "Max Token reached for Sales Stage 3"); require(_initialSupply * publicSalesPrice == msg.value , "Invalid Fund"); sold += _initialSupply; minted[_initialOwner] += _initialSupply; for (uint256 i = 0; i < _initialSupply; i++) { uint256 _id = _getNextTokenID() + totalReserve; _incrementTokenTypeId(); if (bytes(_uri).length > 0) { emit URI(_uri, _id); } creators[_id] = msg.sender; _mint(_initialOwner, _id, 1, _data); tokenSupply[_id] = 1; emit TokenMinted(_id, _initialOwner, ""); } return 0; } function CustomizedSales( address _initialOwner, uint256 _initialSupply, string calldata _rawdata, bytes calldata _sig, bytes calldata _data, uint price ) external payable returns (uint256) { string memory data = Strings.strConcat(_rawdata, _uint2str(price)); require(isValidData(data, _sig), "Invalid Signature"); uint temp_id = _getNextCustomizedTokenID(); require(temp_id + _initialSupply -1 <= totalTokenAssets, "Max Token Minted"); require(msg.value == price, "Invalid fund"); for (uint256 i = 0; i < _initialSupply; i++) { uint256 _id = _getNextCustomizedTokenID(); _incrementCustomizedTokenTypeId(); creators[_id] = msg.sender; _mint(_initialOwner, _id, 1, _data); tokenSupply[_id] = 1; rawdata[_id] = _rawdata; emit TokenMinted(_id, _initialOwner, _rawdata); } return 0; } function setSalesStage( uint16 stage ) public onlyOwner { salesStage = stage; } function setCompanyWallet( address payable newWallet ) public onlyOwner { companyWallet = newWallet; } function ownerMint( address _initialOwner, uint256 _initialSupply, string calldata _uri, bytes calldata _data ) external onlyOwner returns (uint256) { require(sold + _initialSupply <= preSalesMaxSupply3, "Max Token Minted"); sold += _initialSupply; for (uint256 i = 0; i < _initialSupply; i++) { uint256 _id = _getNextTokenID() + totalReserve; _incrementTokenTypeId(); //uint256 _id = reserved; if (bytes(_uri).length > 0) { emit URI(_uri, _id); } creators[_id] = msg.sender; _mint(_initialOwner, _id, 1, _data); tokenSupply[_id] = 1; } return 0; } function walletbalance( ) public view returns (uint256) { return address(this).balance; } /** * @dev Mint tokens for each id in _ids * @param _to The address to mint tokens to * @param _ids Array of ids to mint * @param _quantities Array of amounts of tokens to mint per id * @param _data Data to pass if receiver is contract */ function batchMint( address _to, uint256[] memory _ids, uint256[] memory _quantities, bytes memory _data ) public { for (uint256 i = 0; i < _ids.length; i++) { uint256 _id = _ids[i]; require(creators[_id] == msg.sender, "ERC1155Tradable#batchMint: ONLY_CREATOR_ALLOWED"); uint256 quantity = _quantities[i]; tokenSupply[_id] = tokenSupply[_id].add(quantity); } _batchMint(_to, _ids, _quantities, _data); } function setPrice(uint _sale1, uint _sale2, uint _salepublic) external onlyOwner{ preSalesPrice1 = _sale1; preSalesPrice2 = _sale2; publicSalesPrice = _salepublic; } /** * @dev Change the creator address for given tokens * @param _to Address of the new creator * @param _ids Array of Token IDs to change creator */ function setCreator( address _to, uint256[] memory _ids ) public { require(_to != address(0), "ERC1155Tradable#setCreator: INVALID_ADDRESS."); for (uint256 i = 0; i < _ids.length; i++) { uint256 id = _ids[i]; _setCreator(_to, id); } } /** * @dev Change the creator address for given token * @param _to Address of the new creator * @param _id Token IDs to change creator of */ function _setCreator(address _to, uint256 _id) internal creatorOnly(_id) { creators[_id] = _to; } /** * @dev Returns whether the specified token exists by checking to see if it has a creator * @param _id uint256 ID of the token to query the existence of * @return bool whether the token exists */ function _exists( uint256 _id ) internal view returns (bool) { return creators[_id] != address(0); } /** * @dev calculates the next token ID based on value of _currentTokenID * @return uint256 for the next token ID */ function _getNextTokenID() private view returns (uint256) { return _currentTokenID.add(1); } /** * @dev calculates the next token ID based on value of _customizedTokenId * @return uint256 for the next token ID */ function _getNextCustomizedTokenID() private view returns (uint256) { return _customizedTokenId.add(1); } /** * @dev increments the value of _currentTokenID */ function _incrementTokenTypeId() private { _currentTokenID++; } /** * @dev increments the value of _customizedTokenId */ function _incrementCustomizedTokenTypeId() private { _customizedTokenId++; } }
contract ERC1155Tradable is ERC1155, ERC1155MintBurn, ERC1155Metadata, Ownable { //address proxyRegistryAddress; uint256 private totalTokenAssets = 10000; uint256 private totalReserve = 336; uint256 public _currentTokenID = 0; uint256 public _customizedTokenId = 9000; // uint256 private _maxTokenPerUser = 1000; uint256 private _maxTokenPerMint = 2; uint256 public sold = 0; uint256 private reserved = 0; // uint256 private presalesMaxToken = 3; uint256 private preSalesPrice1 = 0.07 ether; uint256 private preSalesPrice2 = 0.088 ether; uint256 private publicSalesPrice = 0.088 ether; uint256 private preSalesMaxSupply3 = 9000; address private signerAddress = 0x22A19Fd9F3a29Fe8260F88C46dB04941Fa0615C9; uint16 public salesStage = 3; //1-presales1 , 2-presales2 , 3-public address payable public companyWallet = 0xE369C3f00d8dc97Be4B58a7ede901E48c4767bD2; //test mapping(uint256 => uint256) private _presalesPrice; mapping(address => uint256) public presales1minted; // To check how many tokens an address has minted during presales mapping(address => uint256) public presales2minted; // To check how many tokens an address has minted during presales mapping(address => uint256) public minted; // To check how many tokens an address has minted mapping (uint256 => address) public creators; mapping (uint256 => uint256) public tokenSupply; mapping(uint256 => string) public rawdata; event TokenMinted(uint indexed _tokenid, address indexed _userAddress, string indexed _rawData); // Contract name string public name; // Contract symbol string public symbol; /** * @dev Require msg.sender to be the creator of the token id */ modifier creatorOnly(uint256 _id) { require(creators[_id] == msg.sender, "ERC1155Tradable#creatorOnly: ONLY_CREATOR_ALLOWED"); _; } /** * @dev Require msg.sender to own more than 0 of the token id */ modifier ownersOnly(uint256 _id) { require(balances[msg.sender][_id] > 0, "ERC1155Tradable#ownersOnly: ONLY_OWNERS_ALLOWED"); _; } constructor( string memory _name, string memory _symbol //address _proxyRegistryAddress ) public { name = _name; symbol = _symbol; //proxyRegistryAddress = _proxyRegistryAddress; } using Strings for string; // // Function to receive Ether. msg.data must be empty // receive() external payable {} // // Fallback function is called when msg.data is not empty // fallback() external payable {} function uri( uint256 _id ) public view returns (string memory) { require(_exists(_id), "ERC721Tradable#uri: NONEXISTENT_TOKEN"); return Strings.strConcat( baseMetadataURI, Strings.uint2str(_id) ); } /** * @dev Returns the total quantity for a token ID * @param _id uint256 ID of the token to query * @return amount of token in existence */ function totalSupply( uint256 _id ) public view returns (uint256) { return tokenSupply[_id]; } /** * @dev Will update the base URL of token's URI * @param _newBaseMetadataURI New base URL of token's URI */ function setBaseMetadataURI( string memory _newBaseMetadataURI ) public onlyOwner { _setBaseMetadataURI(_newBaseMetadataURI); } /** * @dev Creates a new token type and assigns _initialSupply to an address * NOTE: remove onlyOwner if you want third parties to create new tokens on your contract (which may change your IDs) * @param _initialOwner address of the first owner of the token * @param _initialSupply amount to supply the first owner * @param _uri Optional URI for this token type * @param _data Data to pass if receiver is contract * @return The newly created token ID */ function reserve( //When start this mint 336 first address _initialOwner, uint256 _initialSupply, string calldata _uri, bytes calldata _data ) external onlyOwner returns (uint256) { require(reserved + _initialSupply <= totalReserve, "Reserve Empty"); sold += _initialSupply; for (uint256 i = 0; i < _initialSupply; i++) { reserved++; uint256 _id = reserved; if (bytes(_uri).length > 0) { emit URI(_uri, _id); } creators[_id] = msg.sender; _mint(_initialOwner, _id, 1, _data); tokenSupply[_id] = 1; } return 0; } function toBytes(address a) public pure returns (bytes memory b){ assembly { let m := mload(0x40) a := and(a, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) mstore(add(m, 20), xor(0x140000000000000000000000000000000000000000, a)) mstore(0x40, add(m, 52)) b := m } } function addressToString(address _addr) internal pure returns(string memory) { bytes32 value = bytes32(uint256(_addr)); bytes memory alphabet = "0123456789abcdef"; bytes memory str = new bytes(42); str[0] = "0"; str[1] = "x"; for (uint i = 0; i < 20; i++) { str[2+i*2] = alphabet[uint(uint8(value[i + 12] >> 4))]; str[3+i*2] = alphabet[uint(uint8(value[i + 12] & 0x0f))]; } return string(str); } function toAsciiString(address x) internal pure returns (string memory) { bytes memory s = new bytes(40); for (uint i = 0; i < 20; i++) { bytes1 b = bytes1(uint8(uint(uint160(x)) / (2**(8*(19 - i))))); bytes1 hi = bytes1(uint8(b) / 16); bytes1 lo = bytes1(uint8(b) - 16 * uint8(hi)); s[2*i] = char(hi); s[2*i+1] = char(lo); } return string(s); } function char( bytes1 b ) internal pure returns (bytes1 c) { if (uint8(b) < 10) return bytes1(uint8(b) + 0x30); else return bytes1(uint8(b) + 0x57); } function bytes32ToString(bytes32 _bytes32) public pure returns (string memory) { uint8 i = 0; bytes memory bytesArray = new bytes(64); for (i = 0; i < bytesArray.length; i++) { uint8 _f = uint8(_bytes32[i/2] & 0x0f); uint8 _l = uint8(_bytes32[i/2] >> 4); bytesArray[i] = toByte(_f); i = i + 1; bytesArray[i] = toByte(_l); } return string(bytesArray); } function stringToBytes32(string memory source) public pure returns (bytes32 result) { bytes memory tempEmptyStringTest = bytes(source); if (tempEmptyStringTest.length == 0) { return 0x0; } assembly { result := mload(add(source, 32)) } } function splitSignature(bytes memory sig) public pure returns (uint8, bytes32, bytes32) { require(sig.length == 65); bytes32 r; bytes32 s; uint8 v; assembly { // first 32 bytes, after the length prefix r := mload(add(sig, 32)) // second 32 bytes s := mload(add(sig, 64)) // final byte (first byte of the next 32 bytes) v := byte(0, mload(add(sig, 96))) } return (v, r, s); } function recoverSigner(bytes32 message, bytes memory sig) public pure returns (address) { uint8 v; bytes32 r; bytes32 s; (v, r, s) = splitSignature(sig); return ecrecover(message, v, r, s); } function isValidData(string memory _word, bytes memory sig) public view returns(bool){ bytes32 message = keccak256(abi.encodePacked(_word)); return (recoverSigner(message, sig) == signerAddress); } function toByte(uint8 _uint8) public pure returns (byte) { if(_uint8 < 10) { return byte(_uint8 + 48); } else { return byte(_uint8 + 87); } } function withdraw() public onlyOwner { require(companyWallet != address(0), "Please Set Company Wallet Address"); uint256 balance = address(this).balance; companyWallet.transfer(balance); } function presales( address _initialOwner, uint256 _initialSupply, bytes calldata _sig, bytes calldata _data ) external payable returns (uint256) { require(salesStage == 1 || salesStage == 2, "Presales is closed"); if(salesStage == 1){ require(sold + _initialSupply <= preSalesMaxSupply3, "Max Token reached for Sales Stage 1"); require(_initialSupply * preSalesPrice1 == msg.value, "Invalid Fund"); }else if(salesStage == 2){ require(sold + _initialSupply <= preSalesMaxSupply3, "Max Token reached for Sales Stage 2"); require(_initialSupply * preSalesPrice2 == msg.value, "Invalid Fund"); } require(isValidData(addressToString(msg.sender), _sig), addressToString(msg.sender)); sold += _initialSupply; if(salesStage == 1){ presales1minted[_initialOwner] += _initialSupply; }else if(salesStage == 2){ presales2minted[_initialOwner] += _initialSupply; } minted[_initialOwner] += _initialSupply; for (uint256 i = 0; i < _initialSupply; i++) { uint256 _id = _getNextTokenID() + totalReserve; _incrementTokenTypeId(); creators[_id] = msg.sender; _mint(_initialOwner, _id, 1, _data); tokenSupply[_id] = 1; emit TokenMinted(_id, _initialOwner, ""); } return 0; } function publicsales( address _initialOwner, uint256 _initialSupply, string calldata _uri, bytes calldata _data ) external payable returns (uint256) { require(salesStage == 3 , "Public Sales Is Closed"); require(sold + _initialSupply <= preSalesMaxSupply3, "Max Token reached for Sales Stage 3"); require(_initialSupply * publicSalesPrice == msg.value , "Invalid Fund"); sold += _initialSupply; minted[_initialOwner] += _initialSupply; for (uint256 i = 0; i < _initialSupply; i++) { uint256 _id = _getNextTokenID() + totalReserve; _incrementTokenTypeId(); if (bytes(_uri).length > 0) { emit URI(_uri, _id); } creators[_id] = msg.sender; _mint(_initialOwner, _id, 1, _data); tokenSupply[_id] = 1; emit TokenMinted(_id, _initialOwner, ""); } return 0; } function CustomizedSales( address _initialOwner, uint256 _initialSupply, string calldata _rawdata, bytes calldata _sig, bytes calldata _data, uint price ) external payable returns (uint256) { string memory data = Strings.strConcat(_rawdata, _uint2str(price)); require(isValidData(data, _sig), "Invalid Signature"); uint temp_id = _getNextCustomizedTokenID(); require(temp_id + _initialSupply -1 <= totalTokenAssets, "Max Token Minted"); require(msg.value == price, "Invalid fund"); for (uint256 i = 0; i < _initialSupply; i++) { uint256 _id = _getNextCustomizedTokenID(); _incrementCustomizedTokenTypeId(); creators[_id] = msg.sender; _mint(_initialOwner, _id, 1, _data); tokenSupply[_id] = 1; rawdata[_id] = _rawdata; emit TokenMinted(_id, _initialOwner, _rawdata); } return 0; } function setSalesStage( uint16 stage ) public onlyOwner { salesStage = stage; } function setCompanyWallet( address payable newWallet ) public onlyOwner { companyWallet = newWallet; } function ownerMint( address _initialOwner, uint256 _initialSupply, string calldata _uri, bytes calldata _data ) external onlyOwner returns (uint256) { require(sold + _initialSupply <= preSalesMaxSupply3, "Max Token Minted"); sold += _initialSupply; for (uint256 i = 0; i < _initialSupply; i++) { uint256 _id = _getNextTokenID() + totalReserve; _incrementTokenTypeId(); //uint256 _id = reserved; if (bytes(_uri).length > 0) { emit URI(_uri, _id); } creators[_id] = msg.sender; _mint(_initialOwner, _id, 1, _data); tokenSupply[_id] = 1; } return 0; } function walletbalance( ) public view returns (uint256) { return address(this).balance; } /** * @dev Mint tokens for each id in _ids * @param _to The address to mint tokens to * @param _ids Array of ids to mint * @param _quantities Array of amounts of tokens to mint per id * @param _data Data to pass if receiver is contract */ function batchMint( address _to, uint256[] memory _ids, uint256[] memory _quantities, bytes memory _data ) public { for (uint256 i = 0; i < _ids.length; i++) { uint256 _id = _ids[i]; require(creators[_id] == msg.sender, "ERC1155Tradable#batchMint: ONLY_CREATOR_ALLOWED"); uint256 quantity = _quantities[i]; tokenSupply[_id] = tokenSupply[_id].add(quantity); } _batchMint(_to, _ids, _quantities, _data); } function setPrice(uint _sale1, uint _sale2, uint _salepublic) external onlyOwner{ preSalesPrice1 = _sale1; preSalesPrice2 = _sale2; publicSalesPrice = _salepublic; } /** * @dev Change the creator address for given tokens * @param _to Address of the new creator * @param _ids Array of Token IDs to change creator */ function setCreator( address _to, uint256[] memory _ids ) public { require(_to != address(0), "ERC1155Tradable#setCreator: INVALID_ADDRESS."); for (uint256 i = 0; i < _ids.length; i++) { uint256 id = _ids[i]; _setCreator(_to, id); } } /** * @dev Change the creator address for given token * @param _to Address of the new creator * @param _id Token IDs to change creator of */ function _setCreator(address _to, uint256 _id) internal creatorOnly(_id) { creators[_id] = _to; } /** * @dev Returns whether the specified token exists by checking to see if it has a creator * @param _id uint256 ID of the token to query the existence of * @return bool whether the token exists */ function _exists( uint256 _id ) internal view returns (bool) { return creators[_id] != address(0); } /** * @dev calculates the next token ID based on value of _currentTokenID * @return uint256 for the next token ID */ function _getNextTokenID() private view returns (uint256) { return _currentTokenID.add(1); } /** * @dev calculates the next token ID based on value of _customizedTokenId * @return uint256 for the next token ID */ function _getNextCustomizedTokenID() private view returns (uint256) { return _customizedTokenId.add(1); } /** * @dev increments the value of _currentTokenID */ function _incrementTokenTypeId() private { _currentTokenID++; } /** * @dev increments the value of _customizedTokenId */ function _incrementCustomizedTokenTypeId() private { _customizedTokenId++; } }
51,825
151
// we're getting this info from the aToken, because some of assets can be not compliant with ETC20Detailed
reserveData.symbol = IERC20Detailed(reserveData.aTokenAddress).symbol(); reserveData.name = ''; ( reserveData.baseLTVasCollateral, reserveData.reserveLiquidationThreshold, reserveData.reserveLiquidationBonus, reserveData.decimals, reserveData.reserveFactor ) = baseData.configuration.getParamsMemory();
reserveData.symbol = IERC20Detailed(reserveData.aTokenAddress).symbol(); reserveData.name = ''; ( reserveData.baseLTVasCollateral, reserveData.reserveLiquidationThreshold, reserveData.reserveLiquidationBonus, reserveData.decimals, reserveData.reserveFactor ) = baseData.configuration.getParamsMemory();
23,580
13
// Housing Stores history of resident check-ins and check-outs /
contract Housing { uint256 capacity; uint servicer; // address // Model an Resident struct Resident { uint id; // address uint bedId; uint checkIn; uint duration; bool isCheckedIn; } // mapping(uint => uint) private vouchers; // address to Bed space mapping(address => bool) private beds; // mapping(uint => bool) public beds; // Store Residents // Fetch Residents mapping(uint => Resident) public residents; // Store Residents count uint public residentsCount; event checkInEvent(uint indexed _voucherId); function addResident (uint applicant, uint _durationMilliseconds) private { residentsCount ++; residents[residentsCount] = Resident( applicant, residentsCount, 169107856, // current checkin timestamp _durationMilliseconds, false ); } function reside (uint _voucherId) public { // require that current residency has not reached capacity assert(residentsCount < capacity); // require that voucher id matches that of the servicer assert(_voucherId == servicer); // require that the applicant is not already registered assert(!beds[msg.sender]); // register the new resident to the bed beds[msg.sender] = true; // update the resident bed index residents[residentsCount].isCheckedIn = true; // trigger checkin event emit checkInEvent(_voucherId); } }
contract Housing { uint256 capacity; uint servicer; // address // Model an Resident struct Resident { uint id; // address uint bedId; uint checkIn; uint duration; bool isCheckedIn; } // mapping(uint => uint) private vouchers; // address to Bed space mapping(address => bool) private beds; // mapping(uint => bool) public beds; // Store Residents // Fetch Residents mapping(uint => Resident) public residents; // Store Residents count uint public residentsCount; event checkInEvent(uint indexed _voucherId); function addResident (uint applicant, uint _durationMilliseconds) private { residentsCount ++; residents[residentsCount] = Resident( applicant, residentsCount, 169107856, // current checkin timestamp _durationMilliseconds, false ); } function reside (uint _voucherId) public { // require that current residency has not reached capacity assert(residentsCount < capacity); // require that voucher id matches that of the servicer assert(_voucherId == servicer); // require that the applicant is not already registered assert(!beds[msg.sender]); // register the new resident to the bed beds[msg.sender] = true; // update the resident bed index residents[residentsCount].isCheckedIn = true; // trigger checkin event emit checkInEvent(_voucherId); } }
8,347
7
// This function verifies if an address has the following accesses or not - Super Admin - Admins - Store Owner/
function checkAccess(address addressToVerify) view public returns(bool, bool, bool) { bool isAdmin = Utils.existInTheArray(adminUsers, addressToVerify); bool isStoreOwner = Utils.existInTheArray(storeOwners, addressToVerify); bool isSuperAdmin = false; if ( addressToVerify == superAdmin ) { isSuperAdmin = true; } return (isSuperAdmin, isAdmin, isStoreOwner); }
function checkAccess(address addressToVerify) view public returns(bool, bool, bool) { bool isAdmin = Utils.existInTheArray(adminUsers, addressToVerify); bool isStoreOwner = Utils.existInTheArray(storeOwners, addressToVerify); bool isSuperAdmin = false; if ( addressToVerify == superAdmin ) { isSuperAdmin = true; } return (isSuperAdmin, isAdmin, isStoreOwner); }
49,526
52
// return address the address of currently active (latest) version of me (the app contract)
function currentLogic() public view returns (address) { return GluonView(gluon).current(id); }
function currentLogic() public view returns (address) { return GluonView(gluon).current(id); }
815
8
// Functions with this modifer cannot be reentered. The mutex will be locked/before function execution and unlocked after.
modifier nonReentrant() { // Ensure mutex is unlocked require( !locked, "REENTRANCY_ILLEGAL" ); // Lock mutex before function call locked = true; // Perform function call _; // Unlock mutex after function call locked = false; }
modifier nonReentrant() { // Ensure mutex is unlocked require( !locked, "REENTRANCY_ILLEGAL" ); // Lock mutex before function call locked = true; // Perform function call _; // Unlock mutex after function call locked = false; }
39,149
108
// save current booster price, since transfer is done last since getBoosterPrice() returns new boost balance, avoid re-calculation
(uint256 boosterAmount, uint256 newBoostBalance) = getBoosterPrice(msg.sender);
(uint256 boosterAmount, uint256 newBoostBalance) = getBoosterPrice(msg.sender);
41,800
15
// Handle the receipt of a NFT. The ERC721 smart contract calls this function on therecipient after a `transfer`. This function MAY throw to revert and reject the transfer. Returnof other than the magic value MUST result in the transaction being reverted.Returns `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` unless throwing. The contract address is always the message sender. A wallet/broker/auction applicationMUST implement the wallet interface if it will accept safe transfers. _operator The address which called `safeTransferFrom` function. _from The address which previously owned the token. _tokenId The NFT identifier which is being transferred. _data Additional data with no specified format.return Returns `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`. /
function onERC721Received( address _operator, address _from, uint256 _tokenId, bytes calldata _data ) external returns(bytes4);
function onERC721Received( address _operator, address _from, uint256 _tokenId, bytes calldata _data ) external returns(bytes4);
24,296
127
// Vesting contracts.
PresaleTokenVault public presaleTokenVault; TokenVesting public foundersVault; UbiatarPlayVault public ubiatarPlayVault;
PresaleTokenVault public presaleTokenVault; TokenVesting public foundersVault; UbiatarPlayVault public ubiatarPlayVault;
33,816
14
// Disable EB.mintPrint
IEulerBeats(EulerBeats).setEnabled(false);
IEulerBeats(EulerBeats).setEnabled(false);
6,960
2
// Metadata setter and locker
string private metadataTokenURI; uint256 immutable mvpMintStartDate; uint256 immutable giveAwayIndexStart; uint256 immutable mvpPassword; bool private lock;
string private metadataTokenURI; uint256 immutable mvpMintStartDate; uint256 immutable giveAwayIndexStart; uint256 immutable mvpPassword; bool private lock;
5,215
55
// remove from for sale list
for (uint j=0;j<upForSaleList.length;j++) { if (upForSaleList[j] == animalId) delete upForSaleList[j]; }
for (uint j=0;j<upForSaleList.length;j++) { if (upForSaleList[j] == animalId) delete upForSaleList[j]; }
38,456
3
// Tips for min and max if interger
int256 public maxInt = type(int256).max; int256 public minInt = type(int256).min; address public addr = 0xdC7C84966b5aaCa1174e9B5660fEC286c6c70F22; // 40 bytes max and min bytes32 public b32 = 0xdC7C84966b5aaCa1174e9B5660fEC286c6c70F22dC7C84966b5aaCa1174e9B56; // 64 bytes max and min
int256 public maxInt = type(int256).max; int256 public minInt = type(int256).min; address public addr = 0xdC7C84966b5aaCa1174e9B5660fEC286c6c70F22; // 40 bytes max and min bytes32 public b32 = 0xdC7C84966b5aaCa1174e9B5660fEC286c6c70F22dC7C84966b5aaCa1174e9B56; // 64 bytes max and min
2,460
189
// abstract contract for putting a rate limit on how fast a contract can mint FEI/Fei Protocol
abstract contract RateLimitedMinter is RateLimited { uint256 private constant MAX_FEI_LIMIT_PER_SECOND = 10_000e18; // 10000 FEI/s or ~860m FEI/day constructor( uint256 _feiLimitPerSecond, uint256 _mintingBufferCap, bool _doPartialMint ) RateLimited(MAX_FEI_LIMIT_PER_SECOND, _feiLimitPerSecond, _mintingBufferCap, _doPartialMint) {} /// @notice override the FEI minting behavior to enforce a rate limit function _mintFei(address to, uint256 amount) internal virtual override { uint256 mintAmount = _depleteBuffer(amount); super._mintFei(to, mintAmount); } }
abstract contract RateLimitedMinter is RateLimited { uint256 private constant MAX_FEI_LIMIT_PER_SECOND = 10_000e18; // 10000 FEI/s or ~860m FEI/day constructor( uint256 _feiLimitPerSecond, uint256 _mintingBufferCap, bool _doPartialMint ) RateLimited(MAX_FEI_LIMIT_PER_SECOND, _feiLimitPerSecond, _mintingBufferCap, _doPartialMint) {} /// @notice override the FEI minting behavior to enforce a rate limit function _mintFei(address to, uint256 amount) internal virtual override { uint256 mintAmount = _depleteBuffer(amount); super._mintFei(to, mintAmount); } }
42,991
155
// An admin function that lets the ecosystem's organizers withdraw the underlying token around which this DMMA wraps from this contract. This is used to withdraw deposited tokens, to be allocated to real-world assets that produce income streams and can cover interest payments. /
function withdrawUnderlying(uint underlyingAmount) external returns (bool);
function withdrawUnderlying(uint underlyingAmount) external returns (bool);
27,498
89
// Limit the quick dump possibility
uint diff = 0; uint allowed = 0; if (balances[payer] > current_supply / 100) { // for balances > 1% of total supply if (block.timestamp > ICO_START_TIME) { diff = block.timestamp - ICO_START_TIME; } else {
uint diff = 0; uint allowed = 0; if (balances[payer] > current_supply / 100) { // for balances > 1% of total supply if (block.timestamp > ICO_START_TIME) { diff = block.timestamp - ICO_START_TIME; } else {
56,580
246
// Performs a transfer in, ideally returning an explanatory error code upon failure rather than reverting. If caller has not called `checkTransferIn`, this may revert due to insufficient balance or insufficient allowance. If caller has called `checkTransferIn` successfully, this should not revert in normal conditions. /
function doTransferIn(address from, uint amount) internal returns (Error);
function doTransferIn(address from, uint amount) internal returns (Error);
23,458
61
// The number of blocks that credit will be distributed over to depositors.
uint256 creditUnlockBlocks;
uint256 creditUnlockBlocks;
15,129
48
//
contract FinalizableToken is ERC20Token, OpsManaged, Finalizable { using Math for uint256; // The constructor will assign the initial token supply to the owner (msg.sender). function FinalizableToken(string _name, string _symbol, uint8 _decimals, uint256 _totalSupply) public ERC20Token(_name, _symbol, _decimals, _totalSupply, msg.sender) OpsManaged() Finalizable() { } function transfer(address _to, uint256 _value) public returns (bool success) { validateTransfer(msg.sender, _to); return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { validateTransfer(msg.sender, _to); return super.transferFrom(_from, _to, _value); } function validateTransfer(address _sender, address _to) private view { require(_to != address(0)); // Once the token is finalized, everybody can transfer tokens. if (finalized) { return; } if (isOwner(_to)) { return; } // Before the token is finalized, only owner and ops are allowed to initiate transfers. // This allows them to move tokens while the sale is still ongoing for example. require(isOwnerOrOps(_sender)); } }
contract FinalizableToken is ERC20Token, OpsManaged, Finalizable { using Math for uint256; // The constructor will assign the initial token supply to the owner (msg.sender). function FinalizableToken(string _name, string _symbol, uint8 _decimals, uint256 _totalSupply) public ERC20Token(_name, _symbol, _decimals, _totalSupply, msg.sender) OpsManaged() Finalizable() { } function transfer(address _to, uint256 _value) public returns (bool success) { validateTransfer(msg.sender, _to); return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { validateTransfer(msg.sender, _to); return super.transferFrom(_from, _to, _value); } function validateTransfer(address _sender, address _to) private view { require(_to != address(0)); // Once the token is finalized, everybody can transfer tokens. if (finalized) { return; } if (isOwner(_to)) { return; } // Before the token is finalized, only owner and ops are allowed to initiate transfers. // This allows them to move tokens while the sale is still ongoing for example. require(isOwnerOrOps(_sender)); } }
16,207
11
// mint
function mintTokens(uint8 quantity) private { for (uint256 i = 0; i < quantity; i++) { uint256 newTokenId = totalSupply + 1; _safeMint(msg.sender, newTokenId); totalSupply++; } _nrMinted[msg.sender] += quantity; }
function mintTokens(uint8 quantity) private { for (uint256 i = 0; i < quantity; i++) { uint256 newTokenId = totalSupply + 1; _safeMint(msg.sender, newTokenId); totalSupply++; } _nrMinted[msg.sender] += quantity; }
49,577
35
// Cost of arbitration. Accessor to arbitrationPrice. _extraData Not used by this contract.return fee Amount to be paid./
function arbitrationCost(bytes memory _extraData) public view returns(uint fee) { return arbitrationPrice; }
function arbitrationCost(bytes memory _extraData) public view returns(uint fee) { return arbitrationPrice; }
51,247
0
// Stem constructor
constructor(string _name, string _symbol, uint256 initialSupply) public { name = _name; symbol = _symbol; stemMaster = msg.sender; totalSupply = initialSupply; ledger[msg.sender] = initialSupply; }
constructor(string _name, string _symbol, uint256 initialSupply) public { name = _name; symbol = _symbol; stemMaster = msg.sender; totalSupply = initialSupply; ledger[msg.sender] = initialSupply; }
10,006
1
// emitted at each SmardexPair created token0 address of the token0 token1 address of the token1 pair address of the SmardexPair created totalPair number of SmardexPair created so far /
event PairCreated(address indexed token0, address indexed token1, address pair, uint256 totalPair);
event PairCreated(address indexed token0, address indexed token1, address pair, uint256 totalPair);
45,265
3
// Used to validate if a user has been using the reserve for borrowing self The configuration object reserveIndex The index of the reserve in the bitmapreturn True if the user has been using a reserve for borrowing, false otherwise /
{ require(reserveIndex < 128, Errors.UL_INVALID_INDEX); return (self.data >> (reserveIndex * 2)) & 1 != 0; }
{ require(reserveIndex < 128, Errors.UL_INVALID_INDEX); return (self.data >> (reserveIndex * 2)) & 1 != 0; }
33,801
89
// number of tokens Per day
rewardRate = [50, 60, 75, 100, 150, 500, 0]; started = false;
rewardRate = [50, 60, 75, 100, 150, 500, 0]; started = false;
20,409
41
// Set LP token. stakingToken_ LP token address /
function setLPToken(address stakingToken_) external onlyOwner { if (stakingToken_ == address(0)) revert AddressZero(); if (stakingToken != address(0)) revert AlreadySet(); stakingToken = stakingToken_; emit LPTokenUpdated(stakingToken_); }
function setLPToken(address stakingToken_) external onlyOwner { if (stakingToken_ == address(0)) revert AddressZero(); if (stakingToken != address(0)) revert AlreadySet(); stakingToken = stakingToken_; emit LPTokenUpdated(stakingToken_); }
28,879
30
// Update the hero owner and set the new price
pokemons[_pokemonId].ownerAddress = msg.sender; pokemons[_pokemonId].currentPrice = pokemons[_pokemonId].currentPrice.mul(3).div(2); levels[_pokemonId] = levels[_pokemonId] + 1;
pokemons[_pokemonId].ownerAddress = msg.sender; pokemons[_pokemonId].currentPrice = pokemons[_pokemonId].currentPrice.mul(3).div(2); levels[_pokemonId] = levels[_pokemonId] + 1;
11,667
1,011
// Handles token deposits into Notional. If there is a transfer fee then we must/ calculate the net balance after transfer. Amounts are denominated in the destination token's/ precision.
function _deposit( Token memory token, address account, uint256 amount
function _deposit( Token memory token, address account, uint256 amount
63,437
7
// initial setup
function start() public override { Terminal.print(0, 'You need to attach future owner of the token.\nIt will be used also to pay for all transactions.'); attachMultisig(); }
function start() public override { Terminal.print(0, 'You need to attach future owner of the token.\nIt will be used also to pay for all transactions.'); attachMultisig(); }
24,400
13
// Get the base URI
function getBaseURI() external view onlyOwner returns (string memory) { return _baseTokenURI; }
function getBaseURI() external view onlyOwner returns (string memory) { return _baseTokenURI; }
53,885
84
// add the bought and remove the cashed out
nBalance = nBalance.add(nAddBalance).sub(nRmvBalance); return nBalance;
nBalance = nBalance.add(nAddBalance).sub(nRmvBalance); return nBalance;
8,622
59
// require proof that the initial exit choices are committed to an identified merkle trie.
bytes32 merkleLeaf = LibProofStack.directMerkleLeaf( args.choices[i] ); console.log("merkleLeaf"); console.logBytes32(merkleLeaf); if (!self.checkRoot(args.proofs[i], args.rootLabel, merkleLeaf)) revert Transcript_InvalidStartChoice(); self._revealChoices(
bytes32 merkleLeaf = LibProofStack.directMerkleLeaf( args.choices[i] ); console.log("merkleLeaf"); console.logBytes32(merkleLeaf); if (!self.checkRoot(args.proofs[i], args.rootLabel, merkleLeaf)) revert Transcript_InvalidStartChoice(); self._revealChoices(
11,775
217
// Add new rewards to a rewarded vault. _vaultId ID of the vault to have reward. _rewardAmount Amount of the reward token to add. /
function addRewards(uint256 _vaultId, uint256 _rewardAmount) public { require(msg.sender == governance, "not governance"); require(vaults[_vaultId] != address(0x0), "vault not exist"); require(_rewardAmount > 0, "zero amount"); address vault = vaults[_vaultId]; IERC20Mintable(rewardToken).mint(vault, _rewardAmount); // Mint 40% of tokens to governance. IERC20Mintable(rewardToken).mint(reserve, _rewardAmount.mul(2).div(5)); RewardedVault(vault).notifyRewardAmount(_rewardAmount); }
function addRewards(uint256 _vaultId, uint256 _rewardAmount) public { require(msg.sender == governance, "not governance"); require(vaults[_vaultId] != address(0x0), "vault not exist"); require(_rewardAmount > 0, "zero amount"); address vault = vaults[_vaultId]; IERC20Mintable(rewardToken).mint(vault, _rewardAmount); // Mint 40% of tokens to governance. IERC20Mintable(rewardToken).mint(reserve, _rewardAmount.mul(2).div(5)); RewardedVault(vault).notifyRewardAmount(_rewardAmount); }
45,341
5
// Redeem principal and interest on a pool token. Called by valid pools as part of their redemption flow tokenId pool token id principalRedeemed principal to redeem. This cannot exceed the token's principal amount, and the redemption cannot cause the pool's total principal redeemed to exceed the pool's total minted principal interestRedeemed interest to redeem. /
function redeem(uint256 tokenId, uint256 principalRedeemed, uint256 interestRedeemed) external;
function redeem(uint256 tokenId, uint256 principalRedeemed, uint256 interestRedeemed) external;
39,774
3
// MyFriendships A contract for managing one's friendships. /
contract MyFriendships { address public me; uint public numberOfFriends; address public latestFriend; mapping(address => bool) myFriends; /** * @dev Create a contract to keep track of my friendships. */ function MyFriendships() public { me = msg.sender; } /** * @dev Start an exciting new friendship with me. */ function becomeFriendsWithMe () public { require(msg.sender != me); // I won't be friends with myself. myFriends[msg.sender] = true; latestFriend = msg.sender; numberOfFriends++; } /** * @dev Am I friends with this address? */ function friendsWith (address addr) public view returns (bool) { return myFriends[addr]; } }
contract MyFriendships { address public me; uint public numberOfFriends; address public latestFriend; mapping(address => bool) myFriends; /** * @dev Create a contract to keep track of my friendships. */ function MyFriendships() public { me = msg.sender; } /** * @dev Start an exciting new friendship with me. */ function becomeFriendsWithMe () public { require(msg.sender != me); // I won't be friends with myself. myFriends[msg.sender] = true; latestFriend = msg.sender; numberOfFriends++; } /** * @dev Am I friends with this address? */ function friendsWith (address addr) public view returns (bool) { return myFriends[addr]; } }
4,579
255
// Infinite geometric series
uint256 leverage = uint256(1e36).div(1e18 - safeLeverageColFactor); return leverage;
uint256 leverage = uint256(1e36).div(1e18 - safeLeverageColFactor); return leverage;
75,188
39
// Interface Imports /
import { iOVM_BondManager } from "../../iOVM/verification/iOVM_BondManager.sol"; /* Contract Imports */ import { Lib_AddressResolver } from "../../libraries/resolver/Lib_AddressResolver.sol"; /** * @title mockOVM_BondManager */ contract mockOVM_BondManager is iOVM_BondManager, Lib_AddressResolver { constructor( address _libAddressManager ) Lib_AddressResolver(_libAddressManager) {} function recordGasSpent( bytes32 _preStateRoot, bytes32 _txHash, address _who, uint256 _gasSpent ) override public {} function finalize( bytes32 _preStateRoot, address _publisher, uint256 _timestamp ) override public {} function deposit() override public {} function startWithdrawal() override public {} function finalizeWithdrawal() override public {} function claim( address _who ) override public {} function isCollateralized( address _who ) override public view returns ( bool ) { // Only authenticate sequencer to submit state root batches. return _who == resolve("OVM_Proposer"); } function getGasSpent( bytes32, // _preStateRoot, address // _who ) override public pure returns ( uint256 ) { return 0; } }
import { iOVM_BondManager } from "../../iOVM/verification/iOVM_BondManager.sol"; /* Contract Imports */ import { Lib_AddressResolver } from "../../libraries/resolver/Lib_AddressResolver.sol"; /** * @title mockOVM_BondManager */ contract mockOVM_BondManager is iOVM_BondManager, Lib_AddressResolver { constructor( address _libAddressManager ) Lib_AddressResolver(_libAddressManager) {} function recordGasSpent( bytes32 _preStateRoot, bytes32 _txHash, address _who, uint256 _gasSpent ) override public {} function finalize( bytes32 _preStateRoot, address _publisher, uint256 _timestamp ) override public {} function deposit() override public {} function startWithdrawal() override public {} function finalizeWithdrawal() override public {} function claim( address _who ) override public {} function isCollateralized( address _who ) override public view returns ( bool ) { // Only authenticate sequencer to submit state root batches. return _who == resolve("OVM_Proposer"); } function getGasSpent( bytes32, // _preStateRoot, address // _who ) override public pure returns ( uint256 ) { return 0; } }
16,527
8
// Modifier to restrict access to employer-only functions
modifier onlyEmployer() { require(employers[msg.sender].ethAddress != address(0), "Only employers can call this function."); _; }
modifier onlyEmployer() { require(employers[msg.sender].ethAddress != address(0), "Only employers can call this function."); _; }
25,841
323
// Otherwise we just transfer
return super._internalTransfer(from, to, value, data);
return super._internalTransfer(from, to, value, data);
25,522
35
// Emit withdraw event
emit WithdrawEarnings(transferAmount, msg.sender);
emit WithdrawEarnings(transferAmount, msg.sender);
9,094
33
// contract addresses
address public adapterDeployer; address public assessor; address public poolAdmin; address public seniorTranche; address public juniorTranche; address public seniorOperator; address public juniorOperator; address public reserve; address public coordinator;
address public adapterDeployer; address public assessor; address public poolAdmin; address public seniorTranche; address public juniorTranche; address public seniorOperator; address public juniorOperator; address public reserve; address public coordinator;
10,651
9
// Emit an event that includes an address and a number as the main values. Example: when an award of tokens is given. _eventName The bytes32 encoded (hex) representation of the event's name in audit files. _account The account in question. _amount The amount in question. _id The unique ID that can be matched with the record in the distributed audit file, to matchany other information related to this event (e.g. a reason the action was taken). _cid The Content ID of the distributed audit file./
function emitEvent(bytes32 _eventName, address _account, uint _amount, uint _id, string calldata _cid) external onlyAdmins { emit LogEvent(_eventName, _account, _amount, _id, _cid, msg.sender); emit LogLatestAudit(_cid); }
function emitEvent(bytes32 _eventName, address _account, uint _amount, uint _id, string calldata _cid) external onlyAdmins { emit LogEvent(_eventName, _account, _amount, _id, _cid, msg.sender); emit LogLatestAudit(_cid); }
47,781
38
// Player has won the three-moon mega jackpot!
profit = SafeMath.mul(spin.tokenValue, 500); category = 1; emit ThreeMoonJackpot(target, spin.blockn);
profit = SafeMath.mul(spin.tokenValue, 500); category = 1; emit ThreeMoonJackpot(target, spin.blockn);
67,617
5
// The rICO token contract address.
address public tokenAddress;
address public tokenAddress;
8,629
20
// Returns an array of contract-level delegates for a given vault and contract vault The cold wallet who issued the delegation contract_ The address for the contract you're delegatingreturn addresses Array of contract-level delegates for a given vault and contract /
function getDelegatesForContract(address vault, address contract_) external view returns (address[] memory);
function getDelegatesForContract(address vault, address contract_) external view returns (address[] memory);
16,177
31
// Update consignment to indicate it has been marketed Emits a ConsignmentMarketed event. Reverts if consignment has already been marketed. A consignment is considered as marketed if it has a marketHandler other than Unhandled. See: {SeenTypes.MarketHandler}_consignmentId - the id of the consignment/
function marketConsignment(uint256 _consignmentId, SeenTypes.MarketHandler _marketHandler) external;
function marketConsignment(uint256 _consignmentId, SeenTypes.MarketHandler _marketHandler) external;
12,934
21
// SavingsManager
function collectInterest() external virtual returns (uint256 swapFeesGained, uint256 newSupply); function collectPlatformInterest() external virtual returns (uint256 mintAmount, uint256 newSupply);
function collectInterest() external virtual returns (uint256 swapFeesGained, uint256 newSupply); function collectPlatformInterest() external virtual returns (uint256 mintAmount, uint256 newSupply);
36,515
125
// Simple ERC20 + EIP-2612 implementation./Solady (https:github.com/vectorized/solady/blob/main/src/tokens/ERC20.sol)/Modified from Solmate (https:github.com/transmissions11/solmate/blob/main/src/tokens/ERC20.sol)/Modified from OpenZeppelin (https:github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/ERC20.sol)//Note:/ The ERC20 standard allows minting and transferring to and from the zero address,/ minting and transferring zero tokens, as well as self-approvals./ For performance, this implementation WILL NOT revert for such actions./ Please add any checks with overrides if desired.
abstract contract ERC20 { /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* CUSTOM ERRORS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev The total supply has overflowed. error TotalSupplyOverflow(); /// @dev The allowance has overflowed. error AllowanceOverflow(); /// @dev The allowance has underflowed. error AllowanceUnderflow(); /// @dev Insufficient balance. error InsufficientBalance(); /// @dev Insufficient allowance. error InsufficientAllowance(); /// @dev The permit is invalid. error InvalidPermit(); /// @dev The permit has expired. error PermitExpired(); /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* EVENTS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev Emitted when `amount` tokens is transferred from `from` to `to`. event Transfer(address indexed from, address indexed to, uint256 amount); /// @dev Emitted when `amount` tokens is approved by `owner` to be used by `spender`. event Approval(address indexed owner, address indexed spender, uint256 amount); /// @dev `keccak256(bytes("Transfer(address,address,uint256)"))`. uint256 private constant _TRANSFER_EVENT_SIGNATURE = 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef; /// @dev `keccak256(bytes("Approval(address,address,uint256)"))`. uint256 private constant _APPROVAL_EVENT_SIGNATURE = 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925; /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* STORAGE */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev The storage slot for the total supply. uint256 private constant _TOTAL_SUPPLY_SLOT = 0x05345cdf77eb68f44c; /// @dev The balance slot of `owner` is given by: /// ``` /// mstore(0x0c, _BALANCE_SLOT_SEED) /// mstore(0x00, owner) /// let balanceSlot := keccak256(0x0c, 0x20) /// ``` uint256 private constant _BALANCE_SLOT_SEED = 0x87a211a2; /// @dev The allowance slot of (`owner`, `spender`) is given by: /// ``` /// mstore(0x20, spender) /// mstore(0x0c, _ALLOWANCE_SLOT_SEED) /// mstore(0x00, owner) /// let allowanceSlot := keccak256(0x0c, 0x34) /// ``` uint256 private constant _ALLOWANCE_SLOT_SEED = 0x7f5e9f20; /// @dev The nonce slot of `owner` is given by: /// ``` /// mstore(0x0c, _NONCES_SLOT_SEED) /// mstore(0x00, owner) /// let nonceSlot := keccak256(0x0c, 0x20) /// ``` uint256 private constant _NONCES_SLOT_SEED = 0x38377508; /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* ERC20 METADATA */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev Returns the name of the token. function name() public view virtual returns (string memory); /// @dev Returns the symbol of the token. function symbol() public view virtual returns (string memory); /// @dev Returns the decimals places of the token. function decimals() public view virtual returns (uint8) { return 18; } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* ERC20 */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev Returns the amount of tokens in existence. function totalSupply() public view virtual returns (uint256 result) { /// @solidity memory-safe-assembly assembly { result := sload(_TOTAL_SUPPLY_SLOT) } } /// @dev Returns the amount of tokens owned by `owner`. function balanceOf(address owner) public view virtual returns (uint256 result) { /// @solidity memory-safe-assembly assembly { mstore(0x0c, _BALANCE_SLOT_SEED) mstore(0x00, owner) result := sload(keccak256(0x0c, 0x20)) } } /// @dev Returns the amount of tokens that `spender` can spend on behalf of `owner`. function allowance(address owner, address spender) public view virtual returns (uint256 result) { /// @solidity memory-safe-assembly assembly { mstore(0x20, spender) mstore(0x0c, _ALLOWANCE_SLOT_SEED) mstore(0x00, owner) result := sload(keccak256(0x0c, 0x34)) } } /// @dev Sets `amount` as the allowance of `spender` over the caller's tokens. /// /// Emits a {Approval} event. function approve(address spender, uint256 amount) public virtual returns (bool) { /// @solidity memory-safe-assembly assembly { // Compute the allowance slot and store the amount. mstore(0x20, spender) mstore(0x0c, _ALLOWANCE_SLOT_SEED) mstore(0x00, caller()) sstore(keccak256(0x0c, 0x34), amount) // Emit the {Approval} event. mstore(0x00, amount) log3(0x00, 0x20, _APPROVAL_EVENT_SIGNATURE, caller(), shr(96, mload(0x2c))) } return true; } /// @dev Atomically increases the allowance granted to `spender` by the caller. /// /// Emits a {Approval} event. function increaseAllowance(address spender, uint256 difference) public virtual returns (bool) { /// @solidity memory-safe-assembly assembly { // Compute the allowance slot and load its value. mstore(0x20, spender) mstore(0x0c, _ALLOWANCE_SLOT_SEED) mstore(0x00, caller()) let allowanceSlot := keccak256(0x0c, 0x34) let allowanceBefore := sload(allowanceSlot) // Add to the allowance. let allowanceAfter := add(allowanceBefore, difference) // Revert upon overflow. if lt(allowanceAfter, allowanceBefore) { mstore(0x00, 0xf9067066) // `AllowanceOverflow()`. revert(0x1c, 0x04) } // Store the updated allowance. sstore(allowanceSlot, allowanceAfter) // Emit the {Approval} event. mstore(0x00, allowanceAfter) log3(0x00, 0x20, _APPROVAL_EVENT_SIGNATURE, caller(), shr(96, mload(0x2c))) } return true; } /// @dev Atomically decreases the allowance granted to `spender` by the caller. /// /// Emits a {Approval} event. function decreaseAllowance(address spender, uint256 difference) public virtual returns (bool) { /// @solidity memory-safe-assembly assembly { // Compute the allowance slot and load its value. mstore(0x20, spender) mstore(0x0c, _ALLOWANCE_SLOT_SEED) mstore(0x00, caller()) let allowanceSlot := keccak256(0x0c, 0x34) let allowanceBefore := sload(allowanceSlot) // Revert if will underflow. if lt(allowanceBefore, difference) { mstore(0x00, 0x8301ab38) // `AllowanceUnderflow()`. revert(0x1c, 0x04) } // Subtract and store the updated allowance. let allowanceAfter := sub(allowanceBefore, difference) sstore(allowanceSlot, allowanceAfter) // Emit the {Approval} event. mstore(0x00, allowanceAfter) log3(0x00, 0x20, _APPROVAL_EVENT_SIGNATURE, caller(), shr(96, mload(0x2c))) } return true; } /// @dev Transfer `amount` tokens from the caller to `to`. /// /// Requirements: /// - `from` must at least have `amount`. /// /// Emits a {Transfer} event. function transfer(address to, uint256 amount) public virtual returns (bool) { _beforeTokenTransfer(msg.sender, to, amount); /// @solidity memory-safe-assembly assembly { // Compute the balance slot and load its value. mstore(0x0c, _BALANCE_SLOT_SEED) mstore(0x00, caller()) let fromBalanceSlot := keccak256(0x0c, 0x20) let fromBalance := sload(fromBalanceSlot) // Revert if insufficient balance. if gt(amount, fromBalance) { mstore(0x00, 0xf4d678b8) // `InsufficientBalance()`. revert(0x1c, 0x04) } // Subtract and store the updated balance. sstore(fromBalanceSlot, sub(fromBalance, amount)) // Compute the balance slot of `to`. mstore(0x00, to) let toBalanceSlot := keccak256(0x0c, 0x20) // Add and store the updated balance of `to`. // Will not overflow because the sum of all user balances // cannot exceed the maximum uint256 value. sstore(toBalanceSlot, add(sload(toBalanceSlot), amount)) // Emit the {Transfer} event. mstore(0x20, amount) log3(0x20, 0x20, _TRANSFER_EVENT_SIGNATURE, caller(), shr(96, mload(0x0c))) } _afterTokenTransfer(msg.sender, to, amount); return true; } /// @dev Transfers `amount` tokens from `from` to `to`. /// /// Note: Does not update the allowance if it is the maximum uint256 value. /// /// Requirements: /// - `from` must at least have `amount`. /// - The caller must have at least `amount` of allowance to transfer the tokens of `from`. /// /// Emits a {Transfer} event. function transferFrom(address from, address to, uint256 amount) public virtual returns (bool) { _beforeTokenTransfer(from, to, amount); /// @solidity memory-safe-assembly assembly { let from_ := shl(96, from) // Compute the allowance slot and load its value. mstore(0x20, caller()) mstore(0x0c, or(from_, _ALLOWANCE_SLOT_SEED)) let allowanceSlot := keccak256(0x0c, 0x34) let allowance_ := sload(allowanceSlot) // If the allowance is not the maximum uint256 value. if iszero(eq(allowance_, not(0))) { // Revert if the amount to be transferred exceeds the allowance. if gt(amount, allowance_) { mstore(0x00, 0x13be252b) // `InsufficientAllowance()`. revert(0x1c, 0x04) } // Subtract and store the updated allowance. sstore(allowanceSlot, sub(allowance_, amount)) } // Compute the balance slot and load its value. mstore(0x0c, or(from_, _BALANCE_SLOT_SEED)) let fromBalanceSlot := keccak256(0x0c, 0x20) let fromBalance := sload(fromBalanceSlot) // Revert if insufficient balance. if gt(amount, fromBalance) { mstore(0x00, 0xf4d678b8) // `InsufficientBalance()`. revert(0x1c, 0x04) } // Subtract and store the updated balance. sstore(fromBalanceSlot, sub(fromBalance, amount)) // Compute the balance slot of `to`. mstore(0x00, to) let toBalanceSlot := keccak256(0x0c, 0x20) // Add and store the updated balance of `to`. // Will not overflow because the sum of all user balances // cannot exceed the maximum uint256 value. sstore(toBalanceSlot, add(sload(toBalanceSlot), amount)) // Emit the {Transfer} event. mstore(0x20, amount) log3(0x20, 0x20, _TRANSFER_EVENT_SIGNATURE, shr(96, from_), shr(96, mload(0x0c))) } _afterTokenTransfer(from, to, amount); return true; } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* EIP-2612 */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev Returns the current nonce for `owner`. /// This value is used to compute the signature for EIP-2612 permit. function nonces(address owner) public view virtual returns (uint256 result) { /// @solidity memory-safe-assembly assembly { // Compute the nonce slot and load its value. mstore(0x0c, _NONCES_SLOT_SEED) mstore(0x00, owner) result := sload(keccak256(0x0c, 0x20)) } } /// @dev Sets `value` as the allowance of `spender` over the tokens of `owner`, /// authorized by a signed approval by `owner`. /// /// Emits a {Approval} event. function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public virtual { bytes32 domainSeparator = DOMAIN_SEPARATOR(); /// @solidity memory-safe-assembly assembly { // Grab the free memory pointer. let m := mload(0x40) // Revert if the block timestamp greater than `deadline`. if gt(timestamp(), deadline) { mstore(0x00, 0x1a15a3cc) // `PermitExpired()`. revert(0x1c, 0x04) } // Clean the upper 96 bits. owner := shr(96, shl(96, owner)) spender := shr(96, shl(96, spender)) // Compute the nonce slot and load its value. mstore(0x0c, _NONCES_SLOT_SEED) mstore(0x00, owner) let nonceSlot := keccak256(0x0c, 0x20) let nonceValue := sload(nonceSlot) // Increment and store the updated nonce. sstore(nonceSlot, add(nonceValue, 1)) // Prepare the inner hash. // `keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)")`. // forgefmt: disable-next-item mstore(m, 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9) mstore(add(m, 0x20), owner) mstore(add(m, 0x40), spender) mstore(add(m, 0x60), value) mstore(add(m, 0x80), nonceValue) mstore(add(m, 0xa0), deadline) // Prepare the outer hash. mstore(0, 0x1901) mstore(0x20, domainSeparator) mstore(0x40, keccak256(m, 0xc0)) // Prepare the ecrecover calldata. mstore(0, keccak256(0x1e, 0x42)) mstore(0x20, and(0xff, v)) mstore(0x40, r) mstore(0x60, s) pop(staticcall(gas(), 1, 0, 0x80, 0x20, 0x20)) // If the ecrecover fails, the returndatasize will be 0x00, // `owner` will be be checked if it equals the hash at 0x00, // which evaluates to false (i.e. 0), and we will revert. // If the ecrecover succeeds, the returndatasize will be 0x20, // `owner` will be compared against the returned address at 0x20. if iszero(eq(mload(returndatasize()), owner)) { mstore(0x00, 0xddafbaef) // `InvalidPermit()`. revert(0x1c, 0x04) } // Compute the allowance slot and store the value. // The `owner` is already at slot 0x20. mstore(0x40, or(shl(160, _ALLOWANCE_SLOT_SEED), spender)) sstore(keccak256(0x2c, 0x34), value) // Emit the {Approval} event. log3(add(m, 0x60), 0x20, _APPROVAL_EVENT_SIGNATURE, owner, spender) mstore(0x40, m) // Restore the free memory pointer. mstore(0x60, 0) // Restore the zero pointer. } } /// @dev Returns the EIP-2612 domains separator. function DOMAIN_SEPARATOR() public view virtual returns (bytes32 result) { /// @solidity memory-safe-assembly assembly { result := mload(0x40) // Grab the free memory pointer. } // We simply calculate it on-the-fly to allow for cases where the `name` may change. bytes32 nameHash = keccak256(bytes(name())); /// @solidity memory-safe-assembly assembly { let m := result // `keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)")`. // forgefmt: disable-next-item mstore(m, 0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f) mstore(add(m, 0x20), nameHash) // `keccak256("1")`. // forgefmt: disable-next-item mstore(add(m, 0x40), 0xc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6) mstore(add(m, 0x60), chainid()) mstore(add(m, 0x80), address()) result := keccak256(m, 0xa0) } } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* INTERNAL MINT FUNCTIONS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev Mints `amount` tokens to `to`, increasing the total supply. /// /// Emits a {Transfer} event. function _mint(address to, uint256 amount) internal virtual { _beforeTokenTransfer(address(0), to, amount); /// @solidity memory-safe-assembly assembly { let totalSupplyBefore := sload(_TOTAL_SUPPLY_SLOT) let totalSupplyAfter := add(totalSupplyBefore, amount) // Revert if the total supply overflows. if lt(totalSupplyAfter, totalSupplyBefore) { mstore(0x00, 0xe5cfe957) // `TotalSupplyOverflow()`. revert(0x1c, 0x04) } // Store the updated total supply. sstore(_TOTAL_SUPPLY_SLOT, totalSupplyAfter) // Compute the balance slot and load its value. mstore(0x0c, _BALANCE_SLOT_SEED) mstore(0x00, to) let toBalanceSlot := keccak256(0x0c, 0x20) // Add and store the updated balance. sstore(toBalanceSlot, add(sload(toBalanceSlot), amount)) // Emit the {Transfer} event. mstore(0x20, amount) log3(0x20, 0x20, _TRANSFER_EVENT_SIGNATURE, 0, shr(96, mload(0x0c))) } _afterTokenTransfer(address(0), to, amount); } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* INTERNAL BURN FUNCTIONS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev Burns `amount` tokens from `from`, reducing the total supply. /// /// Emits a {Transfer} event. function _burn(address from, uint256 amount) internal virtual { _beforeTokenTransfer(from, address(0), amount); /// @solidity memory-safe-assembly assembly { // Compute the balance slot and load its value. mstore(0x0c, _BALANCE_SLOT_SEED) mstore(0x00, from) let fromBalanceSlot := keccak256(0x0c, 0x20) let fromBalance := sload(fromBalanceSlot) // Revert if insufficient balance. if gt(amount, fromBalance) { mstore(0x00, 0xf4d678b8) // `InsufficientBalance()`. revert(0x1c, 0x04) } // Subtract and store the updated balance. sstore(fromBalanceSlot, sub(fromBalance, amount)) // Subtract and store the updated total supply. sstore(_TOTAL_SUPPLY_SLOT, sub(sload(_TOTAL_SUPPLY_SLOT), amount)) // Emit the {Transfer} event. mstore(0x00, amount) log3(0x00, 0x20, _TRANSFER_EVENT_SIGNATURE, shr(96, shl(96, from)), 0) } _afterTokenTransfer(from, address(0), amount); } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* INTERNAL TRANSFER FUNCTIONS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev Moves `amount` of tokens from `from` to `to`. function _transfer(address from, address to, uint256 amount) internal virtual { _beforeTokenTransfer(from, to, amount); /// @solidity memory-safe-assembly assembly { let from_ := shl(96, from) // Compute the balance slot and load its value. mstore(0x0c, or(from_, _BALANCE_SLOT_SEED)) let fromBalanceSlot := keccak256(0x0c, 0x20) let fromBalance := sload(fromBalanceSlot) // Revert if insufficient balance. if gt(amount, fromBalance) { mstore(0x00, 0xf4d678b8) // `InsufficientBalance()`. revert(0x1c, 0x04) } // Subtract and store the updated balance. sstore(fromBalanceSlot, sub(fromBalance, amount)) // Compute the balance slot of `to`. mstore(0x00, to) let toBalanceSlot := keccak256(0x0c, 0x20) // Add and store the updated balance of `to`. // Will not overflow because the sum of all user balances // cannot exceed the maximum uint256 value. sstore(toBalanceSlot, add(sload(toBalanceSlot), amount)) // Emit the {Transfer} event. mstore(0x20, amount) log3(0x20, 0x20, _TRANSFER_EVENT_SIGNATURE, shr(96, from_), shr(96, mload(0x0c))) } _afterTokenTransfer(from, to, amount); } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* INTERNAL ALLOWANCE FUNCTIONS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev Updates the allowance of `owner` for `spender` based on spent `amount`. function _spendAllowance(address owner, address spender, uint256 amount) internal virtual { /// @solidity memory-safe-assembly assembly { // Compute the allowance slot and load its value. mstore(0x20, spender) mstore(0x0c, _ALLOWANCE_SLOT_SEED) mstore(0x00, owner) let allowanceSlot := keccak256(0x0c, 0x34) let allowance_ := sload(allowanceSlot) // If the allowance is not the maximum uint256 value. if iszero(eq(allowance_, not(0))) { // Revert if the amount to be transferred exceeds the allowance. if gt(amount, allowance_) { mstore(0x00, 0x13be252b) // `InsufficientAllowance()`. revert(0x1c, 0x04) } // Subtract and store the updated allowance. sstore(allowanceSlot, sub(allowance_, amount)) } } } /// @dev Sets `amount` as the allowance of `spender` over the tokens of `owner`. /// /// Emits a {Approval} event. function _approve(address owner, address spender, uint256 amount) internal virtual { /// @solidity memory-safe-assembly assembly { let owner_ := shl(96, owner) // Compute the allowance slot and store the amount. mstore(0x20, spender) mstore(0x0c, or(owner_, _ALLOWANCE_SLOT_SEED)) sstore(keccak256(0x0c, 0x34), amount) // Emit the {Approval} event. mstore(0x00, amount) log3(0x00, 0x20, _APPROVAL_EVENT_SIGNATURE, shr(96, owner_), shr(96, mload(0x2c))) } } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* HOOKS TO OVERRIDE */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev Hook that is called before any transfer of tokens. /// This includes minting and burning. function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual {} /// @dev Hook that is called after any transfer of tokens. /// This includes minting and burning. function _afterTokenTransfer(address from, address to, uint256 amount) internal virtual {} }
abstract contract ERC20 { /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* CUSTOM ERRORS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev The total supply has overflowed. error TotalSupplyOverflow(); /// @dev The allowance has overflowed. error AllowanceOverflow(); /// @dev The allowance has underflowed. error AllowanceUnderflow(); /// @dev Insufficient balance. error InsufficientBalance(); /// @dev Insufficient allowance. error InsufficientAllowance(); /// @dev The permit is invalid. error InvalidPermit(); /// @dev The permit has expired. error PermitExpired(); /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* EVENTS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev Emitted when `amount` tokens is transferred from `from` to `to`. event Transfer(address indexed from, address indexed to, uint256 amount); /// @dev Emitted when `amount` tokens is approved by `owner` to be used by `spender`. event Approval(address indexed owner, address indexed spender, uint256 amount); /// @dev `keccak256(bytes("Transfer(address,address,uint256)"))`. uint256 private constant _TRANSFER_EVENT_SIGNATURE = 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef; /// @dev `keccak256(bytes("Approval(address,address,uint256)"))`. uint256 private constant _APPROVAL_EVENT_SIGNATURE = 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925; /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* STORAGE */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev The storage slot for the total supply. uint256 private constant _TOTAL_SUPPLY_SLOT = 0x05345cdf77eb68f44c; /// @dev The balance slot of `owner` is given by: /// ``` /// mstore(0x0c, _BALANCE_SLOT_SEED) /// mstore(0x00, owner) /// let balanceSlot := keccak256(0x0c, 0x20) /// ``` uint256 private constant _BALANCE_SLOT_SEED = 0x87a211a2; /// @dev The allowance slot of (`owner`, `spender`) is given by: /// ``` /// mstore(0x20, spender) /// mstore(0x0c, _ALLOWANCE_SLOT_SEED) /// mstore(0x00, owner) /// let allowanceSlot := keccak256(0x0c, 0x34) /// ``` uint256 private constant _ALLOWANCE_SLOT_SEED = 0x7f5e9f20; /// @dev The nonce slot of `owner` is given by: /// ``` /// mstore(0x0c, _NONCES_SLOT_SEED) /// mstore(0x00, owner) /// let nonceSlot := keccak256(0x0c, 0x20) /// ``` uint256 private constant _NONCES_SLOT_SEED = 0x38377508; /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* ERC20 METADATA */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev Returns the name of the token. function name() public view virtual returns (string memory); /// @dev Returns the symbol of the token. function symbol() public view virtual returns (string memory); /// @dev Returns the decimals places of the token. function decimals() public view virtual returns (uint8) { return 18; } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* ERC20 */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev Returns the amount of tokens in existence. function totalSupply() public view virtual returns (uint256 result) { /// @solidity memory-safe-assembly assembly { result := sload(_TOTAL_SUPPLY_SLOT) } } /// @dev Returns the amount of tokens owned by `owner`. function balanceOf(address owner) public view virtual returns (uint256 result) { /// @solidity memory-safe-assembly assembly { mstore(0x0c, _BALANCE_SLOT_SEED) mstore(0x00, owner) result := sload(keccak256(0x0c, 0x20)) } } /// @dev Returns the amount of tokens that `spender` can spend on behalf of `owner`. function allowance(address owner, address spender) public view virtual returns (uint256 result) { /// @solidity memory-safe-assembly assembly { mstore(0x20, spender) mstore(0x0c, _ALLOWANCE_SLOT_SEED) mstore(0x00, owner) result := sload(keccak256(0x0c, 0x34)) } } /// @dev Sets `amount` as the allowance of `spender` over the caller's tokens. /// /// Emits a {Approval} event. function approve(address spender, uint256 amount) public virtual returns (bool) { /// @solidity memory-safe-assembly assembly { // Compute the allowance slot and store the amount. mstore(0x20, spender) mstore(0x0c, _ALLOWANCE_SLOT_SEED) mstore(0x00, caller()) sstore(keccak256(0x0c, 0x34), amount) // Emit the {Approval} event. mstore(0x00, amount) log3(0x00, 0x20, _APPROVAL_EVENT_SIGNATURE, caller(), shr(96, mload(0x2c))) } return true; } /// @dev Atomically increases the allowance granted to `spender` by the caller. /// /// Emits a {Approval} event. function increaseAllowance(address spender, uint256 difference) public virtual returns (bool) { /// @solidity memory-safe-assembly assembly { // Compute the allowance slot and load its value. mstore(0x20, spender) mstore(0x0c, _ALLOWANCE_SLOT_SEED) mstore(0x00, caller()) let allowanceSlot := keccak256(0x0c, 0x34) let allowanceBefore := sload(allowanceSlot) // Add to the allowance. let allowanceAfter := add(allowanceBefore, difference) // Revert upon overflow. if lt(allowanceAfter, allowanceBefore) { mstore(0x00, 0xf9067066) // `AllowanceOverflow()`. revert(0x1c, 0x04) } // Store the updated allowance. sstore(allowanceSlot, allowanceAfter) // Emit the {Approval} event. mstore(0x00, allowanceAfter) log3(0x00, 0x20, _APPROVAL_EVENT_SIGNATURE, caller(), shr(96, mload(0x2c))) } return true; } /// @dev Atomically decreases the allowance granted to `spender` by the caller. /// /// Emits a {Approval} event. function decreaseAllowance(address spender, uint256 difference) public virtual returns (bool) { /// @solidity memory-safe-assembly assembly { // Compute the allowance slot and load its value. mstore(0x20, spender) mstore(0x0c, _ALLOWANCE_SLOT_SEED) mstore(0x00, caller()) let allowanceSlot := keccak256(0x0c, 0x34) let allowanceBefore := sload(allowanceSlot) // Revert if will underflow. if lt(allowanceBefore, difference) { mstore(0x00, 0x8301ab38) // `AllowanceUnderflow()`. revert(0x1c, 0x04) } // Subtract and store the updated allowance. let allowanceAfter := sub(allowanceBefore, difference) sstore(allowanceSlot, allowanceAfter) // Emit the {Approval} event. mstore(0x00, allowanceAfter) log3(0x00, 0x20, _APPROVAL_EVENT_SIGNATURE, caller(), shr(96, mload(0x2c))) } return true; } /// @dev Transfer `amount` tokens from the caller to `to`. /// /// Requirements: /// - `from` must at least have `amount`. /// /// Emits a {Transfer} event. function transfer(address to, uint256 amount) public virtual returns (bool) { _beforeTokenTransfer(msg.sender, to, amount); /// @solidity memory-safe-assembly assembly { // Compute the balance slot and load its value. mstore(0x0c, _BALANCE_SLOT_SEED) mstore(0x00, caller()) let fromBalanceSlot := keccak256(0x0c, 0x20) let fromBalance := sload(fromBalanceSlot) // Revert if insufficient balance. if gt(amount, fromBalance) { mstore(0x00, 0xf4d678b8) // `InsufficientBalance()`. revert(0x1c, 0x04) } // Subtract and store the updated balance. sstore(fromBalanceSlot, sub(fromBalance, amount)) // Compute the balance slot of `to`. mstore(0x00, to) let toBalanceSlot := keccak256(0x0c, 0x20) // Add and store the updated balance of `to`. // Will not overflow because the sum of all user balances // cannot exceed the maximum uint256 value. sstore(toBalanceSlot, add(sload(toBalanceSlot), amount)) // Emit the {Transfer} event. mstore(0x20, amount) log3(0x20, 0x20, _TRANSFER_EVENT_SIGNATURE, caller(), shr(96, mload(0x0c))) } _afterTokenTransfer(msg.sender, to, amount); return true; } /// @dev Transfers `amount` tokens from `from` to `to`. /// /// Note: Does not update the allowance if it is the maximum uint256 value. /// /// Requirements: /// - `from` must at least have `amount`. /// - The caller must have at least `amount` of allowance to transfer the tokens of `from`. /// /// Emits a {Transfer} event. function transferFrom(address from, address to, uint256 amount) public virtual returns (bool) { _beforeTokenTransfer(from, to, amount); /// @solidity memory-safe-assembly assembly { let from_ := shl(96, from) // Compute the allowance slot and load its value. mstore(0x20, caller()) mstore(0x0c, or(from_, _ALLOWANCE_SLOT_SEED)) let allowanceSlot := keccak256(0x0c, 0x34) let allowance_ := sload(allowanceSlot) // If the allowance is not the maximum uint256 value. if iszero(eq(allowance_, not(0))) { // Revert if the amount to be transferred exceeds the allowance. if gt(amount, allowance_) { mstore(0x00, 0x13be252b) // `InsufficientAllowance()`. revert(0x1c, 0x04) } // Subtract and store the updated allowance. sstore(allowanceSlot, sub(allowance_, amount)) } // Compute the balance slot and load its value. mstore(0x0c, or(from_, _BALANCE_SLOT_SEED)) let fromBalanceSlot := keccak256(0x0c, 0x20) let fromBalance := sload(fromBalanceSlot) // Revert if insufficient balance. if gt(amount, fromBalance) { mstore(0x00, 0xf4d678b8) // `InsufficientBalance()`. revert(0x1c, 0x04) } // Subtract and store the updated balance. sstore(fromBalanceSlot, sub(fromBalance, amount)) // Compute the balance slot of `to`. mstore(0x00, to) let toBalanceSlot := keccak256(0x0c, 0x20) // Add and store the updated balance of `to`. // Will not overflow because the sum of all user balances // cannot exceed the maximum uint256 value. sstore(toBalanceSlot, add(sload(toBalanceSlot), amount)) // Emit the {Transfer} event. mstore(0x20, amount) log3(0x20, 0x20, _TRANSFER_EVENT_SIGNATURE, shr(96, from_), shr(96, mload(0x0c))) } _afterTokenTransfer(from, to, amount); return true; } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* EIP-2612 */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev Returns the current nonce for `owner`. /// This value is used to compute the signature for EIP-2612 permit. function nonces(address owner) public view virtual returns (uint256 result) { /// @solidity memory-safe-assembly assembly { // Compute the nonce slot and load its value. mstore(0x0c, _NONCES_SLOT_SEED) mstore(0x00, owner) result := sload(keccak256(0x0c, 0x20)) } } /// @dev Sets `value` as the allowance of `spender` over the tokens of `owner`, /// authorized by a signed approval by `owner`. /// /// Emits a {Approval} event. function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public virtual { bytes32 domainSeparator = DOMAIN_SEPARATOR(); /// @solidity memory-safe-assembly assembly { // Grab the free memory pointer. let m := mload(0x40) // Revert if the block timestamp greater than `deadline`. if gt(timestamp(), deadline) { mstore(0x00, 0x1a15a3cc) // `PermitExpired()`. revert(0x1c, 0x04) } // Clean the upper 96 bits. owner := shr(96, shl(96, owner)) spender := shr(96, shl(96, spender)) // Compute the nonce slot and load its value. mstore(0x0c, _NONCES_SLOT_SEED) mstore(0x00, owner) let nonceSlot := keccak256(0x0c, 0x20) let nonceValue := sload(nonceSlot) // Increment and store the updated nonce. sstore(nonceSlot, add(nonceValue, 1)) // Prepare the inner hash. // `keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)")`. // forgefmt: disable-next-item mstore(m, 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9) mstore(add(m, 0x20), owner) mstore(add(m, 0x40), spender) mstore(add(m, 0x60), value) mstore(add(m, 0x80), nonceValue) mstore(add(m, 0xa0), deadline) // Prepare the outer hash. mstore(0, 0x1901) mstore(0x20, domainSeparator) mstore(0x40, keccak256(m, 0xc0)) // Prepare the ecrecover calldata. mstore(0, keccak256(0x1e, 0x42)) mstore(0x20, and(0xff, v)) mstore(0x40, r) mstore(0x60, s) pop(staticcall(gas(), 1, 0, 0x80, 0x20, 0x20)) // If the ecrecover fails, the returndatasize will be 0x00, // `owner` will be be checked if it equals the hash at 0x00, // which evaluates to false (i.e. 0), and we will revert. // If the ecrecover succeeds, the returndatasize will be 0x20, // `owner` will be compared against the returned address at 0x20. if iszero(eq(mload(returndatasize()), owner)) { mstore(0x00, 0xddafbaef) // `InvalidPermit()`. revert(0x1c, 0x04) } // Compute the allowance slot and store the value. // The `owner` is already at slot 0x20. mstore(0x40, or(shl(160, _ALLOWANCE_SLOT_SEED), spender)) sstore(keccak256(0x2c, 0x34), value) // Emit the {Approval} event. log3(add(m, 0x60), 0x20, _APPROVAL_EVENT_SIGNATURE, owner, spender) mstore(0x40, m) // Restore the free memory pointer. mstore(0x60, 0) // Restore the zero pointer. } } /// @dev Returns the EIP-2612 domains separator. function DOMAIN_SEPARATOR() public view virtual returns (bytes32 result) { /// @solidity memory-safe-assembly assembly { result := mload(0x40) // Grab the free memory pointer. } // We simply calculate it on-the-fly to allow for cases where the `name` may change. bytes32 nameHash = keccak256(bytes(name())); /// @solidity memory-safe-assembly assembly { let m := result // `keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)")`. // forgefmt: disable-next-item mstore(m, 0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f) mstore(add(m, 0x20), nameHash) // `keccak256("1")`. // forgefmt: disable-next-item mstore(add(m, 0x40), 0xc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6) mstore(add(m, 0x60), chainid()) mstore(add(m, 0x80), address()) result := keccak256(m, 0xa0) } } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* INTERNAL MINT FUNCTIONS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev Mints `amount` tokens to `to`, increasing the total supply. /// /// Emits a {Transfer} event. function _mint(address to, uint256 amount) internal virtual { _beforeTokenTransfer(address(0), to, amount); /// @solidity memory-safe-assembly assembly { let totalSupplyBefore := sload(_TOTAL_SUPPLY_SLOT) let totalSupplyAfter := add(totalSupplyBefore, amount) // Revert if the total supply overflows. if lt(totalSupplyAfter, totalSupplyBefore) { mstore(0x00, 0xe5cfe957) // `TotalSupplyOverflow()`. revert(0x1c, 0x04) } // Store the updated total supply. sstore(_TOTAL_SUPPLY_SLOT, totalSupplyAfter) // Compute the balance slot and load its value. mstore(0x0c, _BALANCE_SLOT_SEED) mstore(0x00, to) let toBalanceSlot := keccak256(0x0c, 0x20) // Add and store the updated balance. sstore(toBalanceSlot, add(sload(toBalanceSlot), amount)) // Emit the {Transfer} event. mstore(0x20, amount) log3(0x20, 0x20, _TRANSFER_EVENT_SIGNATURE, 0, shr(96, mload(0x0c))) } _afterTokenTransfer(address(0), to, amount); } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* INTERNAL BURN FUNCTIONS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev Burns `amount` tokens from `from`, reducing the total supply. /// /// Emits a {Transfer} event. function _burn(address from, uint256 amount) internal virtual { _beforeTokenTransfer(from, address(0), amount); /// @solidity memory-safe-assembly assembly { // Compute the balance slot and load its value. mstore(0x0c, _BALANCE_SLOT_SEED) mstore(0x00, from) let fromBalanceSlot := keccak256(0x0c, 0x20) let fromBalance := sload(fromBalanceSlot) // Revert if insufficient balance. if gt(amount, fromBalance) { mstore(0x00, 0xf4d678b8) // `InsufficientBalance()`. revert(0x1c, 0x04) } // Subtract and store the updated balance. sstore(fromBalanceSlot, sub(fromBalance, amount)) // Subtract and store the updated total supply. sstore(_TOTAL_SUPPLY_SLOT, sub(sload(_TOTAL_SUPPLY_SLOT), amount)) // Emit the {Transfer} event. mstore(0x00, amount) log3(0x00, 0x20, _TRANSFER_EVENT_SIGNATURE, shr(96, shl(96, from)), 0) } _afterTokenTransfer(from, address(0), amount); } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* INTERNAL TRANSFER FUNCTIONS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev Moves `amount` of tokens from `from` to `to`. function _transfer(address from, address to, uint256 amount) internal virtual { _beforeTokenTransfer(from, to, amount); /// @solidity memory-safe-assembly assembly { let from_ := shl(96, from) // Compute the balance slot and load its value. mstore(0x0c, or(from_, _BALANCE_SLOT_SEED)) let fromBalanceSlot := keccak256(0x0c, 0x20) let fromBalance := sload(fromBalanceSlot) // Revert if insufficient balance. if gt(amount, fromBalance) { mstore(0x00, 0xf4d678b8) // `InsufficientBalance()`. revert(0x1c, 0x04) } // Subtract and store the updated balance. sstore(fromBalanceSlot, sub(fromBalance, amount)) // Compute the balance slot of `to`. mstore(0x00, to) let toBalanceSlot := keccak256(0x0c, 0x20) // Add and store the updated balance of `to`. // Will not overflow because the sum of all user balances // cannot exceed the maximum uint256 value. sstore(toBalanceSlot, add(sload(toBalanceSlot), amount)) // Emit the {Transfer} event. mstore(0x20, amount) log3(0x20, 0x20, _TRANSFER_EVENT_SIGNATURE, shr(96, from_), shr(96, mload(0x0c))) } _afterTokenTransfer(from, to, amount); } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* INTERNAL ALLOWANCE FUNCTIONS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev Updates the allowance of `owner` for `spender` based on spent `amount`. function _spendAllowance(address owner, address spender, uint256 amount) internal virtual { /// @solidity memory-safe-assembly assembly { // Compute the allowance slot and load its value. mstore(0x20, spender) mstore(0x0c, _ALLOWANCE_SLOT_SEED) mstore(0x00, owner) let allowanceSlot := keccak256(0x0c, 0x34) let allowance_ := sload(allowanceSlot) // If the allowance is not the maximum uint256 value. if iszero(eq(allowance_, not(0))) { // Revert if the amount to be transferred exceeds the allowance. if gt(amount, allowance_) { mstore(0x00, 0x13be252b) // `InsufficientAllowance()`. revert(0x1c, 0x04) } // Subtract and store the updated allowance. sstore(allowanceSlot, sub(allowance_, amount)) } } } /// @dev Sets `amount` as the allowance of `spender` over the tokens of `owner`. /// /// Emits a {Approval} event. function _approve(address owner, address spender, uint256 amount) internal virtual { /// @solidity memory-safe-assembly assembly { let owner_ := shl(96, owner) // Compute the allowance slot and store the amount. mstore(0x20, spender) mstore(0x0c, or(owner_, _ALLOWANCE_SLOT_SEED)) sstore(keccak256(0x0c, 0x34), amount) // Emit the {Approval} event. mstore(0x00, amount) log3(0x00, 0x20, _APPROVAL_EVENT_SIGNATURE, shr(96, owner_), shr(96, mload(0x2c))) } } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* HOOKS TO OVERRIDE */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev Hook that is called before any transfer of tokens. /// This includes minting and burning. function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual {} /// @dev Hook that is called after any transfer of tokens. /// This includes minting and burning. function _afterTokenTransfer(address from, address to, uint256 amount) internal virtual {} }
27,457
9
// -------------------------------- SUBIR CERTIFICADOS --------------------------------
1,766
133
// Require msg.sender to be the creator of the token id /
modifier creatorOnly(uint256 _id)
modifier creatorOnly(uint256 _id)
754
105
// Given a continuous token amount, calculates the amount of reserve tokens returned./
function getContinuousBurnRefund(uint _continuousTokenAmount) external view returns (uint);
function getContinuousBurnRefund(uint _continuousTokenAmount) external view returns (uint);
27,130
30
// Transfer tokens to the next exchange wrapper
transfer(token, wrappers[1], tokenBalance);
transfer(token, wrappers[1], tokenBalance);
16,705
986
// Helper to register allowed vault calls
function __registerVaultCalls(address[] memory _contracts, bytes4[] memory _selectors) private { require( _contracts.length == _selectors.length, "__registerVaultCalls: Uneven input arrays" ); for (uint256 i; i < _contracts.length; i++) { require(
function __registerVaultCalls(address[] memory _contracts, bytes4[] memory _selectors) private { require( _contracts.length == _selectors.length, "__registerVaultCalls: Uneven input arrays" ); for (uint256 i; i < _contracts.length; i++) { require(
44,442
358
// Collybus/`Collybus` stores a spot price and discount rate for every Vault / asset.
contract Collybus is Guarded, ICollybus { /// ======== Custom Errors ======== /// error Collybus__setParam_notLive(); error Collybus__setParam_unrecognizedParam(); error Collybus__updateSpot_notLive(); error Collybus__updateDiscountRate_notLive(); error Collybus__updateDiscountRate_invalidRateId(); error Collybus__updateDiscountRate_invalidRate(); using PRBMathUD60x18 for uint256; /// ======== Storage ======== /// struct VaultConfig { // Liquidation ratio [wad] uint128 liquidationRatio; // Default fixed interest rate oracle system rateId uint128 defaultRateId; } /// @notice Vault Configuration /// @dev Vault => Vault Config mapping(address => VaultConfig) public override vaults; /// @notice Spot prices by token address /// @dev Token address => spot price [wad] mapping(address => uint256) public override spots; /// @notice Fixed interest rate oracle system rateId /// @dev RateId => Discount Rate [wad] mapping(uint256 => uint256) public override rates; // Fixed interest rate oracle system rateId for each TokenId // Vault => TokenId => RateId mapping(address => mapping(uint256 => uint256)) public override rateIds; /// @notice Redemption Price of a Credit unit [wad] uint256 public immutable override redemptionPrice; /// @notice Boolean indicating if this contract is live (0 - not live, 1 - live) uint256 public override live; /// ======== Events ======== /// event SetParam(bytes32 indexed param, uint256 data); event SetParam(address indexed vault, bytes32 indexed param, uint256 data); event SetParam(address indexed vault, uint256 indexed tokenId, bytes32 indexed param, uint256 data); event UpdateSpot(address indexed token, uint256 spot); event UpdateDiscountRate(uint256 indexed rateId, uint256 rate); event Lock(); // TODO: why not making timeScale and redemption price function arguments? constructor() Guarded() { redemptionPrice = WAD; // 1.0 live = 1; } /// ======== Configuration ======== /// /// @notice Sets various variables for this contract /// @dev Sender has to be allowed to call this method /// @param param Name of the variable to set /// @param data New value to set for the variable [wad] function setParam(bytes32 param, uint256 data) external override checkCaller { if (live == 0) revert Collybus__setParam_notLive(); if (param == "live") live = data; else revert Collybus__setParam_unrecognizedParam(); emit SetParam(address(0), param, data); } /// @notice Sets various variables for a Vault /// @dev Sender has to be allowed to call this method /// @param vault Address of the Vault /// @param param Name of the variable to set /// @param data New value to set for the variable [wad] function setParam( address vault, bytes32 param, uint128 data ) external override checkCaller { if (live == 0) revert Collybus__setParam_notLive(); if (param == "liquidationRatio") vaults[vault].liquidationRatio = data; else if (param == "defaultRateId") vaults[vault].defaultRateId = data; else revert Collybus__setParam_unrecognizedParam(); emit SetParam(vault, param, data); } /// @notice Sets various variables for a Vault /// @dev Sender has to be allowed to call this method /// @param vault Address of the Vault /// @param param Name of the variable to set /// @param tokenId ERC1155 or ERC721 style TokenId (leave at 0 for ERC20) /// @param data New value to set for the variable [wad] function setParam( address vault, uint256 tokenId, bytes32 param, uint256 data ) external override checkCaller { if (live == 0) revert Collybus__setParam_notLive(); if (param == "rateId") rateIds[vault][tokenId] = data; else revert Collybus__setParam_unrecognizedParam(); emit SetParam(vault, tokenId, param, data); } /// ======== Spot Prices ======== /// /// @notice Sets a token's spot price /// @dev Sender has to be allowed to call this method /// @param token Address of the token /// @param spot Spot price [wad] function updateSpot(address token, uint256 spot) external override checkCaller { if (live == 0) revert Collybus__updateSpot_notLive(); spots[token] = spot; emit UpdateSpot(token, spot); } /// ======== Discount Rate ======== /// /// @notice Sets the discount rate by RateId /// @param rateId RateId of the discount rate feed /// @param rate Discount rate [wad] function updateDiscountRate(uint256 rateId, uint256 rate) external override checkCaller { if (live == 0) revert Collybus__updateDiscountRate_notLive(); if (rateId >= type(uint128).max) revert Collybus__updateDiscountRate_invalidRateId(); if (rate >= 2e10) revert Collybus__updateDiscountRate_invalidRate(); rates[rateId] = rate; emit UpdateDiscountRate(rateId, rate); } /// @notice Returns the internal price for an asset /// @dev /// redemptionPrice /// v = ---------------------------------------- /// (maturity - timestamp) /// (1 + discountRate) /// /// @param vault Address of the asset corresponding Vault /// @param tokenId ERC1155 or ERC721 style TokenId (leave at 0 for ERC20) /// @param maturity Maturity of the asset [unix timestamp in seconds] /// @param net Boolean (true - with liquidation safety margin, false - without) /// @return price Internal price [wad] function read( address vault, address underlier, uint256 tokenId, uint256 maturity, bool net ) external view override returns (uint256 price) { VaultConfig memory vaultConfig = vaults[vault]; // fetch applicable fixed interest rate oracle system rateId uint256 rateId = rateIds[vault][tokenId]; if (rateId == uint256(0)) rateId = vaultConfig.defaultRateId; // if not set, use default rateId // fetch discount rate uint256 discountRate = rates[rateId]; // apply discount rate if discountRate > 0 if (discountRate != 0 && maturity > block.timestamp) { uint256 rate = add(WAD, discountRate).powu(sub(maturity, block.timestamp)); price = wdiv(redemptionPrice, rate); // den. in Underlier } else { price = redemptionPrice; // den. in Underlier } price = wmul(price, spots[underlier]); // den. in USD if (net) price = wdiv(price, vaultConfig.liquidationRatio); // with liquidation safety margin } /// ======== Shutdown ======== /// /// @notice Locks the contract /// @dev Sender has to be allowed to call this method function lock() external override checkCaller { live = 0; emit Lock(); } }// Copyright (C) 2020-2021 Maker Ecosystem Growth Holdings, INC.
contract Collybus is Guarded, ICollybus { /// ======== Custom Errors ======== /// error Collybus__setParam_notLive(); error Collybus__setParam_unrecognizedParam(); error Collybus__updateSpot_notLive(); error Collybus__updateDiscountRate_notLive(); error Collybus__updateDiscountRate_invalidRateId(); error Collybus__updateDiscountRate_invalidRate(); using PRBMathUD60x18 for uint256; /// ======== Storage ======== /// struct VaultConfig { // Liquidation ratio [wad] uint128 liquidationRatio; // Default fixed interest rate oracle system rateId uint128 defaultRateId; } /// @notice Vault Configuration /// @dev Vault => Vault Config mapping(address => VaultConfig) public override vaults; /// @notice Spot prices by token address /// @dev Token address => spot price [wad] mapping(address => uint256) public override spots; /// @notice Fixed interest rate oracle system rateId /// @dev RateId => Discount Rate [wad] mapping(uint256 => uint256) public override rates; // Fixed interest rate oracle system rateId for each TokenId // Vault => TokenId => RateId mapping(address => mapping(uint256 => uint256)) public override rateIds; /// @notice Redemption Price of a Credit unit [wad] uint256 public immutable override redemptionPrice; /// @notice Boolean indicating if this contract is live (0 - not live, 1 - live) uint256 public override live; /// ======== Events ======== /// event SetParam(bytes32 indexed param, uint256 data); event SetParam(address indexed vault, bytes32 indexed param, uint256 data); event SetParam(address indexed vault, uint256 indexed tokenId, bytes32 indexed param, uint256 data); event UpdateSpot(address indexed token, uint256 spot); event UpdateDiscountRate(uint256 indexed rateId, uint256 rate); event Lock(); // TODO: why not making timeScale and redemption price function arguments? constructor() Guarded() { redemptionPrice = WAD; // 1.0 live = 1; } /// ======== Configuration ======== /// /// @notice Sets various variables for this contract /// @dev Sender has to be allowed to call this method /// @param param Name of the variable to set /// @param data New value to set for the variable [wad] function setParam(bytes32 param, uint256 data) external override checkCaller { if (live == 0) revert Collybus__setParam_notLive(); if (param == "live") live = data; else revert Collybus__setParam_unrecognizedParam(); emit SetParam(address(0), param, data); } /// @notice Sets various variables for a Vault /// @dev Sender has to be allowed to call this method /// @param vault Address of the Vault /// @param param Name of the variable to set /// @param data New value to set for the variable [wad] function setParam( address vault, bytes32 param, uint128 data ) external override checkCaller { if (live == 0) revert Collybus__setParam_notLive(); if (param == "liquidationRatio") vaults[vault].liquidationRatio = data; else if (param == "defaultRateId") vaults[vault].defaultRateId = data; else revert Collybus__setParam_unrecognizedParam(); emit SetParam(vault, param, data); } /// @notice Sets various variables for a Vault /// @dev Sender has to be allowed to call this method /// @param vault Address of the Vault /// @param param Name of the variable to set /// @param tokenId ERC1155 or ERC721 style TokenId (leave at 0 for ERC20) /// @param data New value to set for the variable [wad] function setParam( address vault, uint256 tokenId, bytes32 param, uint256 data ) external override checkCaller { if (live == 0) revert Collybus__setParam_notLive(); if (param == "rateId") rateIds[vault][tokenId] = data; else revert Collybus__setParam_unrecognizedParam(); emit SetParam(vault, tokenId, param, data); } /// ======== Spot Prices ======== /// /// @notice Sets a token's spot price /// @dev Sender has to be allowed to call this method /// @param token Address of the token /// @param spot Spot price [wad] function updateSpot(address token, uint256 spot) external override checkCaller { if (live == 0) revert Collybus__updateSpot_notLive(); spots[token] = spot; emit UpdateSpot(token, spot); } /// ======== Discount Rate ======== /// /// @notice Sets the discount rate by RateId /// @param rateId RateId of the discount rate feed /// @param rate Discount rate [wad] function updateDiscountRate(uint256 rateId, uint256 rate) external override checkCaller { if (live == 0) revert Collybus__updateDiscountRate_notLive(); if (rateId >= type(uint128).max) revert Collybus__updateDiscountRate_invalidRateId(); if (rate >= 2e10) revert Collybus__updateDiscountRate_invalidRate(); rates[rateId] = rate; emit UpdateDiscountRate(rateId, rate); } /// @notice Returns the internal price for an asset /// @dev /// redemptionPrice /// v = ---------------------------------------- /// (maturity - timestamp) /// (1 + discountRate) /// /// @param vault Address of the asset corresponding Vault /// @param tokenId ERC1155 or ERC721 style TokenId (leave at 0 for ERC20) /// @param maturity Maturity of the asset [unix timestamp in seconds] /// @param net Boolean (true - with liquidation safety margin, false - without) /// @return price Internal price [wad] function read( address vault, address underlier, uint256 tokenId, uint256 maturity, bool net ) external view override returns (uint256 price) { VaultConfig memory vaultConfig = vaults[vault]; // fetch applicable fixed interest rate oracle system rateId uint256 rateId = rateIds[vault][tokenId]; if (rateId == uint256(0)) rateId = vaultConfig.defaultRateId; // if not set, use default rateId // fetch discount rate uint256 discountRate = rates[rateId]; // apply discount rate if discountRate > 0 if (discountRate != 0 && maturity > block.timestamp) { uint256 rate = add(WAD, discountRate).powu(sub(maturity, block.timestamp)); price = wdiv(redemptionPrice, rate); // den. in Underlier } else { price = redemptionPrice; // den. in Underlier } price = wmul(price, spots[underlier]); // den. in USD if (net) price = wdiv(price, vaultConfig.liquidationRatio); // with liquidation safety margin } /// ======== Shutdown ======== /// /// @notice Locks the contract /// @dev Sender has to be allowed to call this method function lock() external override checkCaller { live = 0; emit Lock(); } }// Copyright (C) 2020-2021 Maker Ecosystem Growth Holdings, INC.
64,107
382
// batch mint a token with no manager. Can only be called by an admin.Returns tokenId minted /
function adminMintBatch(address to, uint16 count) external returns (uint256[] memory);
function adminMintBatch(address to, uint16 count) external returns (uint256[] memory);
56,271
57
// Finalize a succcesful crowdsale. The owner can triggre a call the contract that provides post-crowdsale actions, like releasing the tokens. /
function finalize() public inState(State.Success) onlyOwner stopInEmergency { // Already finalized if(finalized) { throw; } // Finalizing is optional. We only call it if we are given a finalizing agent. if(address(finalizeAgent) != 0) { finalizeAgent.finalizeCrowdsale(); } finalized = true; }
function finalize() public inState(State.Success) onlyOwner stopInEmergency { // Already finalized if(finalized) { throw; } // Finalizing is optional. We only call it if we are given a finalizing agent. if(address(finalizeAgent) != 0) { finalizeAgent.finalizeCrowdsale(); } finalized = true; }
4,052
25
// Ensure the amount supplied is less than the collateral limit of the system
require( totalSupplied <= collateralLimit || collateralLimit == 0, "operateAction(): collateral locked cannot be greater than limit" );
require( totalSupplied <= collateralLimit || collateralLimit == 0, "operateAction(): collateral locked cannot be greater than limit" );
49,862
148
// Returns the state of an authorization authorizerAuthorizer's address nonce Nonce of the authorizationreturn Authorization state /
function authorizationState(address authorizer, bytes32 nonce)
function authorizationState(address authorizer, bytes32 nonce)
77,507
11
// 向合约出售货币的函数 /
function sell(uint amount) returns (uint revenue){ if (balanceOf[msg.sender] < amount ) throw; // checks if the sender has enough to sell balanceOf[this] += amount; // adds the amount to owner's balance balanceOf[msg.sender] -= amount; // subtracts the amount from seller's balance revenue = amount * sellPrice; // calculate the revenue msg.sender.send(revenue); // sends ether to the seller Transfer(msg.sender, this, amount); // executes an event reflecting on the change return revenue; // ends function and returns }
function sell(uint amount) returns (uint revenue){ if (balanceOf[msg.sender] < amount ) throw; // checks if the sender has enough to sell balanceOf[this] += amount; // adds the amount to owner's balance balanceOf[msg.sender] -= amount; // subtracts the amount from seller's balance revenue = amount * sellPrice; // calculate the revenue msg.sender.send(revenue); // sends ether to the seller Transfer(msg.sender, this, amount); // executes an event reflecting on the change return revenue; // ends function and returns }
3,739
0
// uint used for currency amount (there are no doubles or floats) and for dates (in unix time)
uint x;
uint x;
16,233
31
// ) external returns (uint256) { require(price > 0, "Price must be greater than 0.");
19,503
0
// Interface of the upgradeable master contract (defines notice period duration and allows finish upgrade during preparation of it)/Matter Labs
interface UpgradeableMaster { /// @notice Notice period before activation preparation status of upgrade mode function getNoticePeriod() external returns (uint256); /// @notice Checks that contract is ready for upgrade /// @return bool flag indicating that contract is ready for upgrade function isReadyForUpgrade() external returns (bool); }
interface UpgradeableMaster { /// @notice Notice period before activation preparation status of upgrade mode function getNoticePeriod() external returns (uint256); /// @notice Checks that contract is ready for upgrade /// @return bool flag indicating that contract is ready for upgrade function isReadyForUpgrade() external returns (bool); }
7,082
203
// PRIVELEGED MODULE FUNCTION. Increases the "account" balance by the "quantity". /
function mint(address _account, uint256 _quantity) external onlyModule whenLockedOnlyLocker { _mint(_account, _quantity); }
function mint(address _account, uint256 _quantity) external onlyModule whenLockedOnlyLocker { _mint(_account, _quantity); }
14,968
72
// the start timestamp of the timed period
uint256 public startTime;
uint256 public startTime;
3,594
24
// ------------------------------------------------------------------------ Freeze Tokens ------------------------------------------------------------------------
function medalFreeze(address user, uint amount, uint period) public onlyOwner { require(medalBalances[user] >= amount); medalFreezed[user] = true; medalUnlockTime[user] = uint(now) + period; medalFreezeAmount[user] = amount; }
function medalFreeze(address user, uint amount, uint period) public onlyOwner { require(medalBalances[user] >= amount); medalFreezed[user] = true; medalUnlockTime[user] = uint(now) + period; medalFreezeAmount[user] = amount; }
57,948
398
// Unpauses all token transfers.
function unpause() public virtual onlyRole(DEFAULT_ADMIN_ROLE) { _unpause(); }
function unpause() public virtual onlyRole(DEFAULT_ADMIN_ROLE) { _unpause(); }
63,606
128
// success determines whether the staticcall succeeded and result determines whether the contract at account indicates support of _interfaceId
(bool success, bool result) = _callERC165SupportsInterface(account, interfaceId); return (success && result);
(bool success, bool result) = _callERC165SupportsInterface(account, interfaceId); return (success && result);
24,041
72
// Used as the URI for all token types by relying on ID substitution, e.g. https:token-cdn-domain/{id}.json所有token的URI
string private _uri;
string private _uri;
47,320
51
// See {ERC20-allowance}. /
function allowance(address owner, address spender) external override view returns (uint256) { return _allowances[owner][spender]; }
function allowance(address owner, address spender) external override view returns (uint256) { return _allowances[owner][spender]; }
25,983
34
// Allow contributions to this crowdfunding.
function invest() public payable stopInEmergency { require(getState() == State.Funding); require(msg.value > 0); uint weiAmount = msg.value; address investor = msg.sender; if(investedAmountOf[investor] == 0) { // A new investor investorCount++; } // calculate online fee uint onlineFeeAmount = (weiAmount * ETHERFUNDME_ONLINE_FEE) / 100; Withdraw(feeReceiverWallet, onlineFeeAmount); // send online fee feeReceiverWallet.transfer(onlineFeeAmount); uint investedAmount = weiAmount - onlineFeeAmount; // Update investor investedAmountOf[investor] += investedAmount; // Tell us invest was success Invested(investor, investedAmount); }
function invest() public payable stopInEmergency { require(getState() == State.Funding); require(msg.value > 0); uint weiAmount = msg.value; address investor = msg.sender; if(investedAmountOf[investor] == 0) { // A new investor investorCount++; } // calculate online fee uint onlineFeeAmount = (weiAmount * ETHERFUNDME_ONLINE_FEE) / 100; Withdraw(feeReceiverWallet, onlineFeeAmount); // send online fee feeReceiverWallet.transfer(onlineFeeAmount); uint investedAmount = weiAmount - onlineFeeAmount; // Update investor investedAmountOf[investor] += investedAmount; // Tell us invest was success Invested(investor, investedAmount); }
48,128
6
// Kyber Network interface
interface KyberNetworkInterface { function maxGasPrice() public view returns(uint); function getUserCapInWei(address user) public view returns(uint); function getUserCapInTokenWei(address user, ERC20 token) public view returns(uint); function enabled() public view returns(bool); function info(bytes32 id) public view returns(uint); function getExpectedRate(ERC20 src, ERC20 dest, uint srcQty) public view returns (uint expectedRate, uint slippageRate); function tradeWithHint(address trader, ERC20 src, uint srcAmount, ERC20 dest, address destAddress, uint maxDestAmount, uint minConversionRate, address walletId, bytes hint) public payable returns(uint); }
interface KyberNetworkInterface { function maxGasPrice() public view returns(uint); function getUserCapInWei(address user) public view returns(uint); function getUserCapInTokenWei(address user, ERC20 token) public view returns(uint); function enabled() public view returns(bool); function info(bytes32 id) public view returns(uint); function getExpectedRate(ERC20 src, ERC20 dest, uint srcQty) public view returns (uint expectedRate, uint slippageRate); function tradeWithHint(address trader, ERC20 src, uint srcAmount, ERC20 dest, address destAddress, uint maxDestAmount, uint minConversionRate, address walletId, bytes hint) public payable returns(uint); }
61,205
295
// The primary position's upper tick bound
int24 primaryUpper;
int24 primaryUpper;
57,857
3
// Address of fromToken => hashes (orders)
mapping(address => bytes32[]) internal _hashesOfFromToken;
mapping(address => bytes32[]) internal _hashesOfFromToken;
48,567
79
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) internal operatorApprovals;
mapping (address => mapping (address => bool)) internal operatorApprovals;
6,582
7
// return users[i].accountPriviledge;
level = users[i].accountPriviledge; break;
level = users[i].accountPriviledge; break;
13,613
26
// Set the curation percentage of query fees sent to curators. _percentage Percentage of query fees sent to curators /
function setCurationPercentage(uint32 _percentage) external override onlyGovernor { _setCurationPercentage(_percentage); }
function setCurationPercentage(uint32 _percentage) external override onlyGovernor { _setCurationPercentage(_percentage); }
22,047
483
// claim vesper token from pool rewards
vspPool.claimReward(address(this)); uint256 vspRewardsAmount = vesperToken.balanceOf(address(this));
vspPool.claimReward(address(this)); uint256 vspRewardsAmount = vesperToken.balanceOf(address(this));
34,489
2
// uint型可変配列を取り出す
function getArray() public view returns (uint256[] memory) { return uintArray; }
function getArray() public view returns (uint256[] memory) { return uintArray; }
21,501
3
// decode token address and amount of collateral
(address collateralToken, uint256 collateralAmount) = decodeCollateralObject(terms.contractReference_2.object); require( IERC20(collateralToken).allowance(collateralizer, address(this)) >= collateralAmount, "Custodian.lockCollateral: INSUFFICIENT_ALLOWANCE" );
(address collateralToken, uint256 collateralAmount) = decodeCollateralObject(terms.contractReference_2.object); require( IERC20(collateralToken).allowance(collateralizer, address(this)) >= collateralAmount, "Custodian.lockCollateral: INSUFFICIENT_ALLOWANCE" );
46,873
7
// A title that should describe the contract/interface/The name of the author/Explain to an end user what this does/Explain to a developer any extra details
contract AnconVerifier is ICS23 { address public owner; constructor(address onlyOwner) public { owner = onlyOwner; } function convertProof( bytes memory key, bytes memory value, bytes memory _prefix, uint256[] memory _leafOpUint, bytes[][] memory _innerOp, uint256 existenceProofInnerOpHash ) public pure returns (ExistenceProof memory) { LeafOp memory leafOp = LeafOp( true, HashOp((_leafOpUint[0])), HashOp((_leafOpUint[1])), HashOp((_leafOpUint[2])), LengthOp((_leafOpUint[3])), _prefix ); // // innerOpArr InnerOp[] memory innerOpArr = new InnerOp[](_innerOp.length); for (uint256 i = 0; i < _innerOp.length; i++) { bytes[] memory temp = _innerOp[i]; innerOpArr[i] = InnerOp({ valid: true, hash: HashOp(existenceProofInnerOpHash), prefix: temp[0], suffix: temp[1] }); } ExistenceProof memory proof = ExistenceProof({ valid: true, key: key, value: value, leaf: leafOp, path: innerOpArr }); return proof; } function queryRootCalculation( uint256[] memory leafOpUint, bytes memory prefix, bytes[][] memory existenceProofInnerOp, uint256 existenceProofInnerOpHash, bytes memory existenceProofKey, bytes memory existenceProofValue ) public view returns (bytes memory) { ExistenceProof memory proof = convertProof( existenceProofKey, existenceProofValue, prefix, leafOpUint, existenceProofInnerOp, existenceProofInnerOpHash ); return bytes(calculate(proof)); } function verifyProof( uint256[] memory leafOpUint, bytes memory prefix, bytes[][] memory existenceProofInnerOp, uint256 existenceProofInnerOpHash, bytes memory existenceProofKey, bytes memory existenceProofValue, bytes memory root, bytes memory key, bytes memory value ) public pure returns (bool) { // todo: verify not empty ExistenceProof memory proof = convertProof( existenceProofKey, existenceProofValue, prefix, leafOpUint, existenceProofInnerOp, existenceProofInnerOpHash ); // Verify membership verify(proof, getIavlSpec(), root, key, value); return true; } }
contract AnconVerifier is ICS23 { address public owner; constructor(address onlyOwner) public { owner = onlyOwner; } function convertProof( bytes memory key, bytes memory value, bytes memory _prefix, uint256[] memory _leafOpUint, bytes[][] memory _innerOp, uint256 existenceProofInnerOpHash ) public pure returns (ExistenceProof memory) { LeafOp memory leafOp = LeafOp( true, HashOp((_leafOpUint[0])), HashOp((_leafOpUint[1])), HashOp((_leafOpUint[2])), LengthOp((_leafOpUint[3])), _prefix ); // // innerOpArr InnerOp[] memory innerOpArr = new InnerOp[](_innerOp.length); for (uint256 i = 0; i < _innerOp.length; i++) { bytes[] memory temp = _innerOp[i]; innerOpArr[i] = InnerOp({ valid: true, hash: HashOp(existenceProofInnerOpHash), prefix: temp[0], suffix: temp[1] }); } ExistenceProof memory proof = ExistenceProof({ valid: true, key: key, value: value, leaf: leafOp, path: innerOpArr }); return proof; } function queryRootCalculation( uint256[] memory leafOpUint, bytes memory prefix, bytes[][] memory existenceProofInnerOp, uint256 existenceProofInnerOpHash, bytes memory existenceProofKey, bytes memory existenceProofValue ) public view returns (bytes memory) { ExistenceProof memory proof = convertProof( existenceProofKey, existenceProofValue, prefix, leafOpUint, existenceProofInnerOp, existenceProofInnerOpHash ); return bytes(calculate(proof)); } function verifyProof( uint256[] memory leafOpUint, bytes memory prefix, bytes[][] memory existenceProofInnerOp, uint256 existenceProofInnerOpHash, bytes memory existenceProofKey, bytes memory existenceProofValue, bytes memory root, bytes memory key, bytes memory value ) public pure returns (bool) { // todo: verify not empty ExistenceProof memory proof = convertProof( existenceProofKey, existenceProofValue, prefix, leafOpUint, existenceProofInnerOp, existenceProofInnerOpHash ); // Verify membership verify(proof, getIavlSpec(), root, key, value); return true; } }
36,854
49
// Get the maximum available borrow amount/baseToken Base token of the pool/baseAmt The collateral from the borrower
function getMaxBorrowAmount(address baseToken, uint baseAmt)
function getMaxBorrowAmount(address baseToken, uint baseAmt)
60,946
3,638
// 1820
entry "overentitled" : ENG_ADJECTIVE
entry "overentitled" : ENG_ADJECTIVE
18,432
78
// Token to exchange.
ATxAssetProxy public token;
ATxAssetProxy public token;
579
163
// Internal function for updating address of the used ERC721 token image. _image address of the new token image. /
function _setTokenImage(address _image) internal { require(Address.isContract(_image)); addressStorage[TOKEN_IMAGE_CONTRACT] = _image; }
function _setTokenImage(address _image) internal { require(Address.isContract(_image)); addressStorage[TOKEN_IMAGE_CONTRACT] = _image; }
39,104
1
// whattoken is this out of remaining supply
uint256 tokenPosition; uint256 price;
uint256 tokenPosition; uint256 price;
8,782
8
// Authorizes a controller to control the registrar controller The address of the controller /
function addController(address controller) external override onlyOwner { require( !controllers[controller], "Zer0 Registrar: Controller is already added" ); controllers[controller] = true; emit ControllerAdded(controller); }
function addController(address controller) external override onlyOwner { require( !controllers[controller], "Zer0 Registrar: Controller is already added" ); controllers[controller] = true; emit ControllerAdded(controller); }
51,697
21
// Set Rent Period
nft.due_date = block.timestamp + 7 days;
nft.due_date = block.timestamp + 7 days;
27,731
3
// scope to prevent "stack too deep"
{ Position storage _position = getOrCreatePosition(recipient, bottomTick, topTick); (amount0, amount1) = _updatePositionTicksAndFees(_position, bottomTick, topTick, liquidityActual.toInt128()); }
{ Position storage _position = getOrCreatePosition(recipient, bottomTick, topTick); (amount0, amount1) = _updatePositionTicksAndFees(_position, bottomTick, topTick, liquidityActual.toInt128()); }
24,261
5
// Modifier to check if the function is called by the entry point, the contract itself or the owner
modifier onlyFromEntryPointOrOwnerOrSelf() { require( msg.sender == address(entryPoint) || msg.sender == address(this), "account: not from entrypoint or owner or self" ); _; }
modifier onlyFromEntryPointOrOwnerOrSelf() { require( msg.sender == address(entryPoint) || msg.sender == address(this), "account: not from entrypoint or owner or self" ); _; }
26,352
13
// Allow the delegate to act on your behalf for a specific token delegate The hotwallet to act on your behalf contract_ The address for the contract you're delegating tokenId The token id for the token you're delegating value Whether to enable or disable delegation for this address, true for setting and false for revoking /
function delegateForToken(
function delegateForToken(
17,060
10
// Borrow BNB, wraps into WBNB
uint256 result = vtoken.borrow(amountUnderlying); require(result == 0, "Borrow failed"); WBNB wbnb = WBNB(payable(address(_wbnb))); wbnb.deposit.value(address(this).balance)();
uint256 result = vtoken.borrow(amountUnderlying); require(result == 0, "Borrow failed"); WBNB wbnb = WBNB(payable(address(_wbnb))); wbnb.deposit.value(address(this).balance)();
30,402
0
// maximum alpha score for a Wolf
uint8 public constant MAX_ALPHA = 8;
uint8 public constant MAX_ALPHA = 8;
75,483
24
// Simpler implementation
contract LEGENDS_RAFFLE is VRFConsumerBaseV2 { VRFCoordinatorV2Interface COORDINATOR; // see https://docs.chain.link/docs/vrf-contracts/#configurations address vrfCoordinator = 0x271682DEB8C4E0901D1a1550aD2e64D568E69909; // MAINNET IS 0x27 // The gas lane to use, which specifies the maximum gas price to bump to. // For a list of available gas lanes on each network, // see https://docs.chain.link/docs/vrf-contracts/#configurations bytes32 keyHash = 0x8af398995b04c28e9951adb9721ef74c74f93e6a478f39e7e0777be13527e7ef; // MAINNET IS 0x8af398995b04c28e9951adb9721ef74c74f93e6a478f39e7e0777be13527e7ef // Depends on the number of requested values that you want sent to the // fulfillRandomWords() function. Storing each word costs about 20,000 gas, // so 100,000 is a safe default for this example contract. Test and adjust // this limit based on the network that you select, the size of the request, // and the processing of the callback request in the fulfillRandomWords() // function. // uint32 callbackGasLimit = 100000; // The default is 3, but you can set this higher. uint16 requestConfirmations = 3; uint public mint_index = 0; uint public genesisTokens = 8000; // For this example, retrieve 2 random values in one request. // Cannot exceed VRFCoordinatorV2.MAX_NUM_WORDS. // uint32 numWords = 2; uint256[] public s_randomWords; uint256 public s_requestId; uint64 public s_subscriptionId; address public s_owner; address public mintingContract; address public genesisContract; constructor() VRFConsumerBaseV2(vrfCoordinator) { COORDINATOR = VRFCoordinatorV2Interface(vrfCoordinator); s_owner = msg.sender; } function setSubscriptionId(uint64 _s_subscriptionId) public onlyOwner { s_subscriptionId = _s_subscriptionId; } function setMintingContract(address mintingContract_) public onlyOwner { mintingContract = mintingContract_; } function setGenesisContract(address genesisContract_) public onlyOwner { genesisContract = genesisContract_; } function setGenesisTokens(uint genesisTokens_) public onlyOwner { genesisTokens = genesisTokens_; } function setVRFCoordinator(address coord) public onlyOwner { vrfCoordinator = coord; } // Assumes the subscription is funded sufficiently. function requestRandomWords(uint32 _numWords, uint32 _callbackGasLimit) external onlyOwner { // Will revert if subscription is not set and funded. s_requestId = COORDINATOR.requestRandomWords( keyHash, s_subscriptionId, requestConfirmations, _callbackGasLimit, _numWords ); } function fulfillRandomWords( uint256, /* requestId */ uint256[] memory randomWords ) internal override { for (uint i = 0; i < randomWords.length; i++) { s_randomWords.push(randomWords[i] % genesisTokens); } } // get all words function words() public view returns (uint256[] memory) { uint256[] memory words_ = new uint256[](s_randomWords.length); for (uint256 idx = 0; idx < s_randomWords.length; idx++) { words_[idx] = s_randomWords[idx]; } return words_; } function identifyFirstDupe(uint startIdx, uint endIdx) public view returns (uint) { require(endIdx > startIdx, "End index must be greater than start end"); require(s_randomWords.length >= endIdx, "End index cannot exceed random words length"); for (uint256 idx = startIdx; idx < endIdx; idx++) { for (uint256 jdx = idx; jdx < endIdx; jdx++) { if (idx == jdx) { continue; } uint word1 = s_randomWords[idx]; uint word2 = s_randomWords[jdx]; if (word1 == word2) { return idx; } } } return 0; } function dedupWords(uint startIdx, uint endIdx) public onlyOwner { require(endIdx > startIdx, "End index must be greater than start end"); require(s_randomWords.length >= endIdx, "End index cannot exceed random words length"); for (uint256 idx = startIdx; idx < endIdx; idx++) { for (uint256 jdx = idx; jdx < endIdx; jdx++) { if (idx == jdx) { continue; } uint word1 = s_randomWords[idx]; uint word2 = s_randomWords[jdx]; if (word1 == word2) { s_randomWords[jdx] = (word2 + 1) % genesisTokens; } } } } function genesisOwnerOf(uint tokenId) public view returns (address) { address owner = IERC721(genesisContract).ownerOf(tokenId); return owner; } // minting function // mint index function mintRaffleWinners(uint32 numToMint) public onlyOwner { require(s_randomWords.length >= numToMint + mint_index, "Not enough words"); require(genesisContract != address(0), "Must set genesis contract"); require(mintingContract != 0x0000000000000000000000000000000000000000, "Need to set minting contract"); for (uint idx = mint_index; idx < numToMint + mint_index; idx++) { uint tokenId = s_randomWords[idx]; address owner = IERC721(genesisContract).ownerOf(tokenId); IERC721(mintingContract).mint(owner, 1); } mint_index = numToMint + mint_index; } modifier onlyOwner() { require(msg.sender == s_owner); _; } }
contract LEGENDS_RAFFLE is VRFConsumerBaseV2 { VRFCoordinatorV2Interface COORDINATOR; // see https://docs.chain.link/docs/vrf-contracts/#configurations address vrfCoordinator = 0x271682DEB8C4E0901D1a1550aD2e64D568E69909; // MAINNET IS 0x27 // The gas lane to use, which specifies the maximum gas price to bump to. // For a list of available gas lanes on each network, // see https://docs.chain.link/docs/vrf-contracts/#configurations bytes32 keyHash = 0x8af398995b04c28e9951adb9721ef74c74f93e6a478f39e7e0777be13527e7ef; // MAINNET IS 0x8af398995b04c28e9951adb9721ef74c74f93e6a478f39e7e0777be13527e7ef // Depends on the number of requested values that you want sent to the // fulfillRandomWords() function. Storing each word costs about 20,000 gas, // so 100,000 is a safe default for this example contract. Test and adjust // this limit based on the network that you select, the size of the request, // and the processing of the callback request in the fulfillRandomWords() // function. // uint32 callbackGasLimit = 100000; // The default is 3, but you can set this higher. uint16 requestConfirmations = 3; uint public mint_index = 0; uint public genesisTokens = 8000; // For this example, retrieve 2 random values in one request. // Cannot exceed VRFCoordinatorV2.MAX_NUM_WORDS. // uint32 numWords = 2; uint256[] public s_randomWords; uint256 public s_requestId; uint64 public s_subscriptionId; address public s_owner; address public mintingContract; address public genesisContract; constructor() VRFConsumerBaseV2(vrfCoordinator) { COORDINATOR = VRFCoordinatorV2Interface(vrfCoordinator); s_owner = msg.sender; } function setSubscriptionId(uint64 _s_subscriptionId) public onlyOwner { s_subscriptionId = _s_subscriptionId; } function setMintingContract(address mintingContract_) public onlyOwner { mintingContract = mintingContract_; } function setGenesisContract(address genesisContract_) public onlyOwner { genesisContract = genesisContract_; } function setGenesisTokens(uint genesisTokens_) public onlyOwner { genesisTokens = genesisTokens_; } function setVRFCoordinator(address coord) public onlyOwner { vrfCoordinator = coord; } // Assumes the subscription is funded sufficiently. function requestRandomWords(uint32 _numWords, uint32 _callbackGasLimit) external onlyOwner { // Will revert if subscription is not set and funded. s_requestId = COORDINATOR.requestRandomWords( keyHash, s_subscriptionId, requestConfirmations, _callbackGasLimit, _numWords ); } function fulfillRandomWords( uint256, /* requestId */ uint256[] memory randomWords ) internal override { for (uint i = 0; i < randomWords.length; i++) { s_randomWords.push(randomWords[i] % genesisTokens); } } // get all words function words() public view returns (uint256[] memory) { uint256[] memory words_ = new uint256[](s_randomWords.length); for (uint256 idx = 0; idx < s_randomWords.length; idx++) { words_[idx] = s_randomWords[idx]; } return words_; } function identifyFirstDupe(uint startIdx, uint endIdx) public view returns (uint) { require(endIdx > startIdx, "End index must be greater than start end"); require(s_randomWords.length >= endIdx, "End index cannot exceed random words length"); for (uint256 idx = startIdx; idx < endIdx; idx++) { for (uint256 jdx = idx; jdx < endIdx; jdx++) { if (idx == jdx) { continue; } uint word1 = s_randomWords[idx]; uint word2 = s_randomWords[jdx]; if (word1 == word2) { return idx; } } } return 0; } function dedupWords(uint startIdx, uint endIdx) public onlyOwner { require(endIdx > startIdx, "End index must be greater than start end"); require(s_randomWords.length >= endIdx, "End index cannot exceed random words length"); for (uint256 idx = startIdx; idx < endIdx; idx++) { for (uint256 jdx = idx; jdx < endIdx; jdx++) { if (idx == jdx) { continue; } uint word1 = s_randomWords[idx]; uint word2 = s_randomWords[jdx]; if (word1 == word2) { s_randomWords[jdx] = (word2 + 1) % genesisTokens; } } } } function genesisOwnerOf(uint tokenId) public view returns (address) { address owner = IERC721(genesisContract).ownerOf(tokenId); return owner; } // minting function // mint index function mintRaffleWinners(uint32 numToMint) public onlyOwner { require(s_randomWords.length >= numToMint + mint_index, "Not enough words"); require(genesisContract != address(0), "Must set genesis contract"); require(mintingContract != 0x0000000000000000000000000000000000000000, "Need to set minting contract"); for (uint idx = mint_index; idx < numToMint + mint_index; idx++) { uint tokenId = s_randomWords[idx]; address owner = IERC721(genesisContract).ownerOf(tokenId); IERC721(mintingContract).mint(owner, 1); } mint_index = numToMint + mint_index; } modifier onlyOwner() { require(msg.sender == s_owner); _; } }
7,354
4
// The new number of pending requests will outsize the lowest supplied token pool. /
error InvalidPoolSize();
error InvalidPoolSize();
34,918
23
// ERC20 comaptibility for liquidity tokens
bytes32 public name; bytes32 public symbol; uint256 public decimals; function transfer(address _to, uint256 _value) external returns (bool); function transferFrom(address _from, address _to, uint256 value) external returns (bool); function approve(address _spender, uint256 _value) external returns (bool); function allowance(address _owner, address _spender) external view returns (uint256); function balanceOf(address _owner) external view returns (uint256); function totalSupply() external view returns (uint256);
bytes32 public name; bytes32 public symbol; uint256 public decimals; function transfer(address _to, uint256 _value) external returns (bool); function transferFrom(address _from, address _to, uint256 value) external returns (bool); function approve(address _spender, uint256 _value) external returns (bool); function allowance(address _owner, address _spender) external view returns (uint256); function balanceOf(address _owner) external view returns (uint256); function totalSupply() external view returns (uint256);
14,535
5
// The Authorizable constructor sets the first `authorized` of the contract to the senderaccount. /
constructor() public { authorize(msg.sender); }
constructor() public { authorize(msg.sender); }
23,795
0
// Add the first content as iteration as well
iterations.push(_contentAddress);
iterations.push(_contentAddress);
4,594
57
// Update OSM
OsmAbstract(PIP_USDT).rely(OSM_MOM); MedianAbstract(OsmAbstract(PIP_USDT).src()).kiss(PIP_USDT); OsmAbstract(PIP_USDT).kiss(MCD_SPOT); OsmAbstract(PIP_USDT).kiss(MCD_END); OsmMomAbstract(OSM_MOM).setOsm(ilkUSDTA, PIP_USDT);
OsmAbstract(PIP_USDT).rely(OSM_MOM); MedianAbstract(OsmAbstract(PIP_USDT).src()).kiss(PIP_USDT); OsmAbstract(PIP_USDT).kiss(MCD_SPOT); OsmAbstract(PIP_USDT).kiss(MCD_END); OsmMomAbstract(OSM_MOM).setOsm(ilkUSDTA, PIP_USDT);
43,121
100
// Pay the caller for updating the rate
rewardCaller(feeReceiver, callerReward);
rewardCaller(feeReceiver, callerReward);
7,402