file_name
stringlengths
71
779k
comments
stringlengths
20
182k
code_string
stringlengths
20
36.9M
__index_level_0__
int64
0
17.2M
input_ids
sequence
attention_mask
sequence
labels
sequence
./full_match/4/0x50D7cB8eE3e347E22cB6210C1Ca57458EF1B59ec/sources/Users/lugondev/DEV/truffle-sample/contracts/TokenCrowdsale.sol
* @dev Constructor, takes crowdsale opening and closing times. @param openingTime Crowdsale opening time @param closingTime Crowdsale closing time/ solhint-disable-next-line not-rely-on-time require( openingTime >= block.timestamp, "TimedCrowdsale: opening time is before current time" ); solhint-disable-next-line max-line-length
constructor(uint256 openingTime, uint256 closingTime) public { require( closingTime > openingTime, "TimedCrowdsale: opening time is not before closing time" ); _openingTime = openingTime; _closingTime = closingTime; }
690,666
[ 1, 6293, 16, 5530, 276, 492, 2377, 5349, 10890, 471, 7647, 4124, 18, 225, 10890, 950, 385, 492, 2377, 5349, 10890, 813, 225, 7647, 950, 385, 492, 2377, 5349, 7647, 813, 19, 3704, 11317, 17, 8394, 17, 4285, 17, 1369, 486, 17, 266, 715, 17, 265, 17, 957, 2583, 12, 377, 10890, 950, 1545, 1203, 18, 5508, 16, 377, 315, 19336, 39, 492, 2377, 5349, 30, 10890, 813, 353, 1865, 783, 813, 6, 11272, 3704, 11317, 17, 8394, 17, 4285, 17, 1369, 943, 17, 1369, 17, 2469, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 3885, 12, 11890, 5034, 10890, 950, 16, 2254, 5034, 7647, 950, 13, 1071, 288, 203, 3639, 2583, 12, 203, 5411, 7647, 950, 405, 10890, 950, 16, 203, 5411, 315, 19336, 39, 492, 2377, 5349, 30, 10890, 813, 353, 486, 1865, 7647, 813, 6, 203, 3639, 11272, 203, 203, 3639, 389, 3190, 310, 950, 273, 10890, 950, 31, 203, 3639, 389, 19506, 950, 273, 7647, 950, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x5D4Aa78B08Bc7C530e21bf7447988b1Be7991322/sources/src/BaseDelegation.sol
* @notice returns eip-2612 compatible domain separator @dev we expect that existing tokens, ie Aave, already have, so we want to reuse @return domain separator/* @notice gets the delegation state of a user @param user address @return state of a user's delegation/* @notice returns the token balance of a user @param user address @return current nonce before increase/* @notice increases and return the current nonce of a user @dev should use `return nonce++;` pattern @param user address @return current nonce before increase/* @notice sets the delegation state of a user @param user address @param delegationState state of a user's delegation/ @inheritdoc IGovernancePowerDelegationToken
function _getDomainSeparator() internal view virtual returns (bytes32); function _getDelegationState(address user) internal view virtual returns (DelegationState memory); function _getBalance(address user) internal view virtual returns (uint256); function _incrementNonces(address user) internal virtual returns (uint256); function _setDelegationState(address user, DelegationState memory delegationState) internal virtual; function delegateByType(address delegatee, GovernancePowerType delegationType) external virtual override { _delegateByType(msg.sender, delegatee, delegationType); }
8,423,909
[ 1, 6154, 425, 625, 17, 5558, 2138, 7318, 2461, 4182, 225, 732, 4489, 716, 2062, 2430, 16, 9228, 432, 836, 16, 1818, 1240, 16, 1427, 732, 2545, 358, 11827, 327, 2461, 4182, 19, 225, 5571, 326, 23595, 919, 434, 279, 729, 225, 729, 1758, 327, 919, 434, 279, 729, 1807, 23595, 19, 225, 1135, 326, 1147, 11013, 434, 279, 729, 225, 729, 1758, 327, 783, 7448, 1865, 10929, 19, 225, 7033, 3304, 471, 327, 326, 783, 7448, 434, 279, 729, 225, 1410, 999, 1375, 2463, 7448, 9904, 31, 68, 1936, 225, 729, 1758, 327, 783, 7448, 1865, 10929, 19, 225, 1678, 326, 23595, 919, 434, 279, 729, 225, 729, 1758, 225, 23595, 1119, 919, 434, 279, 729, 1807, 23595, 19, 632, 10093, 13102, 1643, 82, 1359, 13788, 15608, 20611, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 389, 588, 3748, 6581, 1435, 2713, 1476, 5024, 1135, 261, 3890, 1578, 1769, 203, 203, 225, 445, 389, 588, 26945, 1119, 12, 2867, 729, 13, 2713, 1476, 5024, 1135, 261, 26945, 1119, 3778, 1769, 203, 203, 225, 445, 389, 588, 13937, 12, 2867, 729, 13, 2713, 1476, 5024, 1135, 261, 11890, 5034, 1769, 203, 203, 225, 445, 389, 15016, 3989, 764, 12, 2867, 729, 13, 2713, 5024, 1135, 261, 11890, 5034, 1769, 203, 203, 225, 445, 389, 542, 26945, 1119, 12, 2867, 729, 16, 24117, 367, 1119, 3778, 23595, 1119, 13, 203, 565, 2713, 203, 565, 5024, 31, 203, 203, 225, 445, 7152, 14145, 12, 2867, 7152, 73, 16, 611, 1643, 82, 1359, 13788, 559, 23595, 559, 13, 203, 565, 3903, 203, 565, 5024, 203, 565, 3849, 203, 225, 288, 203, 565, 389, 22216, 14145, 12, 3576, 18, 15330, 16, 7152, 73, 16, 23595, 559, 1769, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// Bitcoin transaction parsing library // Copyright 2016 rain <https://keybase.io/rain> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // https://en.bitcoin.it/wiki/Protocol_documentation#tx // // Raw Bitcoin transaction structure: // // field | size | type | description // version | 4 | int32 | transaction version number // n_tx_in | 1-9 | var_int | number of transaction inputs // tx_in | 41+ | tx_in[] | list of transaction inputs // n_tx_out | 1-9 | var_int | number of transaction outputs // tx_out | 9+ | tx_out[] | list of transaction outputs // lock_time | 4 | uint32 | block number / timestamp at which tx locked // // Transaction input (tx_in) structure: // // field | size | type | description // previous | 36 | outpoint | Previous output transaction reference // script_len | 1-9 | var_int | Length of the signature script // sig_script | ? | uchar[] | Script for confirming transaction authorization // sequence | 4 | uint32 | Sender transaction version // // OutPoint structure: // // field | size | type | description // hash | 32 | char[32] | The hash of the referenced transaction // index | 4 | uint32 | The index of this output in the referenced transaction // // Transaction output (tx_out) structure: // // field | size | type | description // value | 8 | int64 | Transaction value (Satoshis) // pk_script_len | 1-9 | var_int | Length of the public key script // pk_script | ? | uchar[] | Public key as a Bitcoin script. // // Variable integers (var_int) can be encoded differently depending // on the represented value, to save space. Variable integers always // precede an array of a variable length data type (e.g. tx_in). // // Variable integer encodings as a function of represented value: // // value | bytes | format // <0xFD (253) | 1 | uint8 // <=0xFFFF (65535)| 3 | 0xFD followed by length as uint16 // <=0xFFFF FFFF | 5 | 0xFE followed by length as uint32 // - | 9 | 0xFF followed by length as uint64 // // Public key scripts `pk_script` are set on the output and can // take a number of forms. The regular transaction script is // called 'pay-to-pubkey-hash' (P2PKH): // // OP_DUP OP_HASH160 <pubKeyHash> OP_EQUALVERIFY OP_CHECKSIG // // OP_x are Bitcoin script opcodes. The bytes representation (including // the 0x14 20-byte stack push) is: // // 0x76 0xA9 0x14 <pubKeyHash> 0x88 0xAC // // The <pubKeyHash> is the ripemd160 hash of the sha256 hash of // the public key, preceded by a network version byte. (21 bytes total) // // Network version bytes: 0x00 (mainnet); 0x6f (testnet); 0x34 (namecoin) // // The Bitcoin address is derived from the pubKeyHash. The binary form is the // pubKeyHash, plus a checksum at the end. The checksum is the first 4 bytes // of the (32 byte) double sha256 of the pubKeyHash. (25 bytes total) // This is converted to base58 to form the publicly used Bitcoin address. // Mainnet P2PKH transaction scripts are to addresses beginning with '1'. // // P2SH ('pay to script hash') scripts only supply a script hash. The spender // must then provide the script that would allow them to redeem this output. // This allows for arbitrarily complex scripts to be funded using only a // hash of the script, and moves the onus on providing the script from // the spender to the redeemer. // // The P2SH script format is simple: // // OP_HASH160 <scriptHash> OP_EQUAL // // 0xA9 0x14 <scriptHash> 0x87 // // The <scriptHash> is the ripemd160 hash of the sha256 hash of the // redeem script. The P2SH address is derived from the scriptHash. // Addresses are the scriptHash with a version prefix of 5, encoded as // Base58check. These addresses begin with a '3'. pragma solidity ^0.5.10; // parse a raw bitcoin transaction byte array library BtcParser { // Convert a variable integer into something useful and return it and // the index to after it. function parseVarInt(bytes memory txBytes, uint pos) public returns (uint, uint) { // the first byte tells us how big the integer is uint8 ibit = uint8(txBytes[pos]); pos += 1; // skip ibit if (ibit < 0xfd) { return (ibit, pos); } else if (ibit == 0xfd) { return (getBytesLE(txBytes, pos, 16), pos + 2); } else if (ibit == 0xfe) { return (getBytesLE(txBytes, pos, 32), pos + 4); } else if (ibit == 0xff) { return (getBytesLE(txBytes, pos, 64), pos + 8); } } // convert little endian bytes to uint function getBytesLE(bytes memory data, uint pos, uint bits) public returns (uint) { if (bits == 8) { return uint8(data[pos]); } else if (bits == 16) { return uint16(uint8(data[pos])) + uint16(uint8(data[pos + 1])) * 2 ** 8; } else if (bits == 32) { return uint32(uint8(data[pos])) + uint32(uint8(data[pos + 1])) * 2 ** 8 + uint32(uint8(data[pos + 2])) * 2 ** 16 + uint32(uint8(data[pos + 3])) * 2 ** 24; } else if (bits == 64) { return uint64(uint8(data[pos])) + uint64(uint8(data[pos + 1])) * 2 ** 8 + uint64(uint8(data[pos + 2])) * 2 ** 16 + uint64(uint8(data[pos + 3])) * 2 ** 24 + uint64(uint8(data[pos + 4])) * 2 ** 32 + uint64(uint8(data[pos + 5])) * 2 ** 40 + uint64(uint8(data[pos + 6])) * 2 ** 48 + uint64(uint8(data[pos + 7])) * 2 ** 56; } } // scan the full transaction bytes and return the first two output // values (in satoshis) and addresses (in binary) function getFirstTwoOutputs(bytes memory txBytes) public returns (uint, bytes20, uint, bytes20) { uint pos; uint[] memory input_script_lens = new uint[](2); uint[] memory output_script_lens = new uint[](2); uint[] memory script_starts = new uint[](2); uint[] memory output_values = new uint[](2); bytes20[] memory output_addresses = new bytes20[](2); pos = 4; // skip version (input_script_lens, pos) = scanInputs(txBytes, pos, 0); (output_values, script_starts, output_script_lens, pos) = scanOutputs(txBytes, pos, 2); for (uint i = 0; i < 2; i++) { bytes20 pkhash = parseOutputScript(txBytes, script_starts[i], output_script_lens[i]); output_addresses[i] = pkhash; } return (output_values[0], output_addresses[0], output_values[1], output_addresses[1]); } // Check whether `btcAddress` is in the transaction outputs *and* // whether *at least* `value` has been sent to it. function checkValueSent(bytes memory txBytes, bytes20 btcAddress, uint value) public returns (bool) { uint pos = 4; // skip version (, pos) = scanInputs(txBytes, pos, 0); // find end of inputs // scan *all* the outputs and find where they are (uint[] memory output_values, uint[] memory script_starts, uint[] memory output_script_lens,) = scanOutputs(txBytes, pos, 0); // look at each output and check whether it at least value to btcAddress for (uint i = 0; i < output_values.length; i++) { bytes20 pkhash = parseOutputScript(txBytes, script_starts[i], output_script_lens[i]); if (pkhash == btcAddress && output_values[i] >= value) { return true; } } } // scan the inputs and find the script lengths. // return an array of script lengths and the end position // of the inputs. // takes a 'stop' argument which sets the maximum number of // outputs to scan through. stop=0 => scan all. function scanInputs(bytes memory txBytes, uint pos, uint stop) public returns (uint[] memory, uint) { uint n_inputs; uint halt; uint script_len; (n_inputs, pos) = parseVarInt(txBytes, pos); if (stop == 0 || stop > n_inputs) { halt = n_inputs; } else { halt = stop; } uint[] memory script_lens = new uint[](halt); for (uint8 i = 0; i < halt; i++) { pos += 36; // skip outpoint (script_len, pos) = parseVarInt(txBytes, pos); script_lens[i] = script_len; pos += script_len + 4; // skip sig_script, seq } return (script_lens, pos); } // scan the outputs and find the values and script lengths. // return array of values, array of script lengths and the // end position of the outputs. // takes a 'stop' argument which sets the maximum number of // outputs to scan through. stop=0 => scan all. function scanOutputs(bytes memory txBytes, uint pos, uint stop) public returns ( uint[] memory, uint[] memory, uint[] memory, uint) { uint n_outputs; uint halt; uint script_len; (n_outputs, pos) = parseVarInt(txBytes, pos); if (stop == 0 || stop > n_outputs) { halt = n_outputs; } else { halt = stop; } uint[] memory script_starts = new uint[](halt); uint[] memory script_lens = new uint[](halt); uint[] memory output_values = new uint[](halt); for (uint i = 0; i < halt; i++) { output_values[i] = getBytesLE(txBytes, pos, 64); pos += 8; (script_len, pos) = parseVarInt(txBytes, pos); script_starts[i] = pos; script_lens[i] = script_len; pos += script_len; } return (output_values, script_starts, script_lens, pos); } // Slice 20 contiguous bytes from bytes `data`, starting at `start` function sliceBytes20(bytes memory data, uint start) public returns (bytes20) { uint160 slice = 0; for (uint160 i = 0; i < 20; i++) { slice += uint160(uint8(data[i + start])) << (8 * (19 - i)); } return bytes20(slice); } // returns true if the bytes located in txBytes by pos and // script_len represent a P2PKH script function isP2PKH(bytes memory txBytes, uint pos, uint script_len) public returns (bool) { return (script_len == 25) // 20 byte pubkeyhash + 5 bytes of script && (txBytes[pos] == 0x76) // OP_DUP && (txBytes[pos + 1] == 0xa9) // OP_HASH160 && (txBytes[pos + 2] == 0x14) // bytes to push && (txBytes[pos + 23] == 0x88) // OP_EQUALVERIFY && (txBytes[pos + 24] == 0xac); // OP_CHECKSIG } // returns true if the bytes located in txBytes by pos and // script_len represent a P2SH script function isP2SH(bytes memory txBytes, uint pos, uint script_len) public returns (bool) { return (script_len == 23) // 20 byte scripthash + 3 bytes of script && (txBytes[pos + 0] == 0xa9) // OP_HASH160 && (txBytes[pos + 1] == 0x14) // bytes to push && (txBytes[pos + 22] == 0x87); // OP_EQUAL } // Get the pubkeyhash / scripthash from an output script. Assumes // pay-to-pubkey-hash (P2PKH) or pay-to-script-hash (P2SH) outputs. // Returns the pubkeyhash/ scripthash, or zero if unknown output. function parseOutputScript(bytes memory txBytes, uint pos, uint script_len) public returns (bytes20) { if (isP2PKH(txBytes, pos, script_len)) { return sliceBytes20(txBytes, pos + 3); } else if (isP2SH(txBytes, pos, script_len)) { return sliceBytes20(txBytes, pos + 2); } else { return bytes20(0); } } //NOTE: Only supports segwit txs //https://bitcoin.stackexchange.com/questions/79723/where-is-the-pubkey-for-segwit-inputs //if multisig, it will just grab the first pubkey function getPubKeyFromTx(bytes memory txBytes) public returns(bytes memory) { uint pos = 0; bytes memory pubkey; for(uint i = 0; i < txBytes.length; i++) { //byte with value 0x21 is used to show the start of the pubkey in the raw tx if(txBytes[i] == 0x21) { pos = i + 1; break; } } uint index = 0; for(uint i = pos; i < pos + 33; i++) { pubkey[index] = txBytes[i]; index++; } return pubkey; } function getSegtwitSignature(bytes memory txBytes) public returns(bytes memory) { uint pos = 0; bytes memory signature; for(uint i = 0; i < txBytes.length; i++) { //byte with value 0x47 is used to show the start of the signature in the raw tx if(txBytes[i] == 0x47) { pos = i + 1; break; } } uint index = 0; for(uint i = pos; i < pos + 71; i++) { signature[index] = txBytes[i]; index++; } return signature; } }
Get the pubkeyhash / scripthash from an output script. Assumes pay-to-pubkey-hash (P2PKH) or pay-to-script-hash (P2SH) outputs. Returns the pubkeyhash/ scripthash, or zero if unknown output.
function parseOutputScript(bytes memory txBytes, uint pos, uint script_len) public returns (bytes20) { if (isP2PKH(txBytes, pos, script_len)) { return sliceBytes20(txBytes, pos + 3); return sliceBytes20(txBytes, pos + 2); return bytes20(0); } }
12,672,462
[ 1, 967, 326, 15649, 2816, 342, 2728, 2816, 628, 392, 876, 2728, 18, 25374, 8843, 17, 869, 17, 23428, 17, 2816, 261, 52, 22, 8784, 44, 13, 578, 8843, 17, 869, 17, 4263, 17, 2816, 261, 52, 22, 2664, 13, 6729, 18, 2860, 326, 15649, 2816, 19, 2728, 2816, 16, 578, 3634, 309, 5917, 876, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1109, 1447, 3651, 12, 3890, 3778, 2229, 2160, 16, 2254, 949, 16, 2254, 2728, 67, 1897, 13, 1071, 203, 565, 1135, 261, 3890, 3462, 13, 203, 565, 288, 203, 3639, 309, 261, 291, 52, 22, 8784, 44, 12, 978, 2160, 16, 949, 16, 2728, 67, 1897, 3719, 288, 203, 5411, 327, 2788, 2160, 3462, 12, 978, 2160, 16, 949, 397, 890, 1769, 203, 5411, 327, 2788, 2160, 3462, 12, 978, 2160, 16, 949, 397, 576, 1769, 203, 5411, 327, 1731, 3462, 12, 20, 1769, 203, 3639, 289, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.18; // 数学ライブラリ /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { // 乗算 function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } // 除算 function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return c; } // 減算 function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } // 加算 function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } // オーナー権限 /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization * control functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); // コンストラクタ /** * @dev The Ownable constructor sets the original `owner` of the contract to the * sender account. */ function Ownable() public { owner = msg.sender; } // modifier /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } // オーナー権移転 /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } // ERC223規格 /** * @title ERC223 * @dev ERC223 contract interface with ERC20 functions and events * Fully backward compatible with ERC20 * Recommended implementation used at https://github.com/Dexaran/ERC223-token-standard/tree/Recommended */ contract ERC223 { uint public totalSupply; // ERC223 and ERC20 functions and events function balanceOf(address who) public view returns (uint); function totalSupply() public view returns (uint256 _supply); function transfer(address to, uint value) public returns (bool ok); function transfer(address to, uint value, bytes data) public returns (bool ok); function transfer(address to, uint value, bytes data, string customFallback) public returns (bool ok); event Transfer(address indexed from, address indexed to, uint value, bytes indexed data); // ERC223 functions function name() public view returns (string _name); function symbol() public view returns (string _symbol); function decimals() public view returns (uint8 _decimals); // ERC20 functions and events function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); function approve(address _spender, uint256 _value) public returns (bool success); function allowance(address _owner, address _spender) public view returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint _value); } // ConractReceiver /** * @title ContractReceiver * @dev Contract that is working with ERC223 tokens */ contract ContractReceiver { struct TKN { address sender; uint value; bytes data; bytes4 sig; } function tokenFallback(address _from, uint _value, bytes _data) public pure { TKN memory tkn; tkn.sender = _from; tkn.value = _value; tkn.data = _data; uint32 u = uint32(_data[3]) + (uint32(_data[2]) << 8) + (uint32(_data[1]) << 16) + (uint32(_data[0]) << 24); tkn.sig = bytes4(u); /* * tkn variable is analogue of msg variable of Ether transaction * tkn.sender is person who initiated this token transaction (analogue of msg.sender) * tkn.value the number of tokens that were sent (analogue of msg.value) * tkn.data is data of token transaction (analogue of msg.data) * tkn.sig is 4 bytes signature of function if data of token transaction is a function execution */ } } // CryptoHarborExchange /** * @title CryptoHarborExchange * @author CryptoHarborExchange Author * @dev CryptoHarborExchange is an ERC223 Token with ERC20 functions and events * Fully backward compatible with ERC20 */ contract CryptoHarborExchange is ERC223, Ownable { using SafeMath for uint256; string public name = "CryptoHarborExchange"; string public symbol = "CHE"; string public constant AAcontributors = "CryptoHarborExchange Author"; uint8 public decimals = 8; uint256 public totalSupply = 50e9 * 1e8; uint256 public distributeAmount = 0; bool public mintingFinished = false; address public Loading = 0x8F9D96B9Ddb9b6Bdcc5BCcB6C2C2704c9Be58771; address public Angel = 0x0FC77220fD0b32052bB405109C9FfF678A2eeD53; address public Development = 0x6f40E9d6D10E0B5C29327b7134Dd54bB42dD55De; address public Public = 0x82a87119dd74c9459E4316ac928f544631102b8B; address public Management = 0xD3931315DD5AAeE4a64Ff9B4BF7a57EDB5249ba9; address public Lockup = 0x4828716D7845BAAA94420ccEdD0ba2cC08e3d663; mapping(address => uint256) public balanceOf; mapping(address => mapping (address => uint256)) public allowance; mapping (address => bool) public frozenAccount; mapping (address => uint256) public unlockUnixTime; event FrozenFunds(address indexed target, bool frozen); event LockedFunds(address indexed target, uint256 locked); //event Burn(address indexed from, uint256 amount); //event Mint(address indexed to, uint256 amount); //event MintFinished(); // コンストラクタ /** * @dev Constructor is called only once and can not be called again */ function CryptoHarborExchange() public { owner = 0xfB668006e725bf35b961910F4c66BEf949c17d6b; balanceOf[Loading] = totalSupply.mul(40).div(100); balanceOf[Angel] = totalSupply.mul(4).div(100); balanceOf[Development] = totalSupply.mul(14).div(100); balanceOf[Public] = totalSupply.mul(13).div(100); balanceOf[Management] = totalSupply.mul(10).div(100); balanceOf[Lockup] = totalSupply.mul(19).div(100); } function name() public view returns (string _name) { return name; } function symbol() public view returns (string _symbol) { return symbol; } function decimals() public view returns (uint8 _decimals) { return decimals; } function totalSupply() public view returns (uint256 _totalSupply) { return totalSupply; } function balanceOf(address _owner) public view returns (uint256 balance) { return balanceOf[_owner]; } // アカウント凍結 /** * @dev Prevent targets from sending or receiving tokens * @param targets Addresses to be frozen * @param isFrozen either to freeze it or not */ function freezeAccounts(address[] targets, bool isFrozen) onlyOwner public { require(targets.length > 0); for (uint j = 0; j < targets.length; j++) { require(targets[j] != 0x0); frozenAccount[targets[j]] = isFrozen; FrozenFunds(targets[j], isFrozen); } } // ロックアップ /** * @dev Prevent targets from sending or receiving tokens by setting Unix times * @param targets Addresses to be locked funds * @param unixTimes Unix times when locking up will be finished */ function lockupAccounts(address[] targets, uint[] unixTimes) onlyOwner public { require(targets.length > 0 && targets.length == unixTimes.length); for(uint j = 0; j < targets.length; j++){ require(unlockUnixTime[targets[j]] < unixTimes[j]); unlockUnixTime[targets[j]] = unixTimes[j]; LockedFunds(targets[j], unixTimes[j]); } } // Transfer /** * @dev Function that is called when a user or another contract wants to transfer funds */ function transfer(address _to, uint _value, bytes _data, string _custom_fallback) public returns (bool success) { require(_value > 0 && frozenAccount[msg.sender] == false && frozenAccount[_to] == false && now > unlockUnixTime[msg.sender] && now > unlockUnixTime[_to]); if (isContract(_to)) { require(balanceOf[msg.sender] >= _value); balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); assert(_to.call.value(0)(bytes4(keccak256(_custom_fallback)), msg.sender, _value, _data)); Transfer(msg.sender, _to, _value, _data); Transfer(msg.sender, _to, _value); return true; } else { return transferToAddress(_to, _value, _data); } } function transfer(address _to, uint _value, bytes _data) public returns (bool success) { require(_value > 0 && frozenAccount[msg.sender] == false && frozenAccount[_to] == false && now > unlockUnixTime[msg.sender] && now > unlockUnixTime[_to]); if (isContract(_to)) { return transferToContract(_to, _value, _data); } else { return transferToAddress(_to, _value, _data); } } /** * @dev Standard function transfer similar to ERC20 transfer with no _data * Added due to backwards compatibility reasons */ function transfer(address _to, uint _value) public returns (bool success) { require(_value > 0 && frozenAccount[msg.sender] == false && frozenAccount[_to] == false && now > unlockUnixTime[msg.sender] && now > unlockUnixTime[_to]); bytes memory empty; if (isContract(_to)) { return transferToContract(_to, _value, empty); } else { return transferToAddress(_to, _value, empty); } } // assemble the given address bytecode. If bytecode exists then the _addr is a contract. function isContract(address _addr) private view returns (bool is_contract) { uint length; assembly { //retrieve the size of the code on target address, this needs assembly length := extcodesize(_addr) } return (length > 0); } // function that is called when transaction target is an address function transferToAddress(address _to, uint _value, bytes _data) private returns (bool success) { require(balanceOf[msg.sender] >= _value); balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); Transfer(msg.sender, _to, _value, _data); Transfer(msg.sender, _to, _value); return true; } // function that is called when transaction target is a contract function transferToContract(address _to, uint _value, bytes _data) private returns (bool success) { require(balanceOf[msg.sender] >= _value); balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); ContractReceiver receiver = ContractReceiver(_to); receiver.tokenFallback(msg.sender, _value, _data); Transfer(msg.sender, _to, _value, _data); Transfer(msg.sender, _to, _value); return true; } /** * @dev Transfer tokens from one address to another * Added due to backwards compatibility with ERC20 * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_to != address(0) && _value > 0 && balanceOf[_from] >= _value && allowance[_from][msg.sender] >= _value && frozenAccount[_from] == false && frozenAccount[_to] == false && now > unlockUnixTime[_from] && now > unlockUnixTime[_to]); balanceOf[_from] = balanceOf[_from].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Allows _spender to spend no more than _value tokens in your behalf * Added due to backwards compatibility with ERC20 * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender * Added due to backwards compatibility with ERC20 * @param _owner address The address which owns the funds * @param _spender address The address which will spend the funds */ function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return allowance[_owner][_spender]; } /** * @dev Burns a specific amount of tokens. * @param _from The address that will burn the tokens. * @param _unitAmount The amount of token to be burned. */ /* function burn(address _from, uint256 _unitAmount) onlyOwner public { require(_unitAmount > 0 && balanceOf[_from] >= _unitAmount); balanceOf[_from] = balanceOf[_from].sub(_unitAmount); totalSupply = totalSupply.sub(_unitAmount); Burn(_from, _unitAmount); } */ /* modifier canMint() { require(!mintingFinished); _; } */ /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _unitAmount The amount of tokens to mint. */ /* function mint(address _to, uint256 _unitAmount) onlyOwner canMint public returns (bool) { require(_unitAmount > 0); totalSupply = totalSupply.add(_unitAmount); balanceOf[_to] = balanceOf[_to].add(_unitAmount); Mint(_to, _unitAmount); Transfer(address(0), _to, _unitAmount); return true; } */ /** * @dev Function to stop minting new tokens. */ /* function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; MintFinished(); return true; } */ /** * @dev Function to distribute tokens to the list of addresses by the provided amount */ function distributeAirdrop(address[] addresses, uint256 amount) public returns (bool) { require(amount > 0 && addresses.length > 0 && frozenAccount[msg.sender] == false && now > unlockUnixTime[msg.sender]); amount = amount.mul(1e8); uint256 totalAmount = amount.mul(addresses.length); require(balanceOf[msg.sender] >= totalAmount); for (uint j = 0; j < addresses.length; j++) { require(addresses[j] != 0x0 && frozenAccount[addresses[j]] == false && now > unlockUnixTime[addresses[j]]); balanceOf[addresses[j]] = balanceOf[addresses[j]].add(amount); Transfer(msg.sender, addresses[j], amount); } balanceOf[msg.sender] = balanceOf[msg.sender].sub(totalAmount); return true; } function distributeAirdrop(address[] addresses, uint[] amounts) public returns (bool) { require(addresses.length > 0 && addresses.length == amounts.length && frozenAccount[msg.sender] == false && now > unlockUnixTime[msg.sender]); uint256 totalAmount = 0; for(uint j = 0; j < addresses.length; j++){ require(amounts[j] > 0 && addresses[j] != 0x0 && frozenAccount[addresses[j]] == false && now > unlockUnixTime[addresses[j]]); amounts[j] = amounts[j].mul(1e8); totalAmount = totalAmount.add(amounts[j]); } require(balanceOf[msg.sender] >= totalAmount); for (j = 0; j < addresses.length; j++) { balanceOf[addresses[j]] = balanceOf[addresses[j]].add(amounts[j]); Transfer(msg.sender, addresses[j], amounts[j]); } balanceOf[msg.sender] = balanceOf[msg.sender].sub(totalAmount); return true; } /** * @dev Function to collect tokens from the list of addresses */ function collectTokens(address[] addresses, uint[] amounts) onlyOwner public returns (bool) { require(addresses.length > 0 && addresses.length == amounts.length); uint256 totalAmount = 0; for (uint j = 0; j < addresses.length; j++) { require(amounts[j] > 0 && addresses[j] != 0x0 && frozenAccount[addresses[j]] == false && now > unlockUnixTime[addresses[j]]); amounts[j] = amounts[j].mul(1e8); require(balanceOf[addresses[j]] >= amounts[j]); balanceOf[addresses[j]] = balanceOf[addresses[j]].sub(amounts[j]); totalAmount = totalAmount.add(amounts[j]); Transfer(addresses[j], msg.sender, amounts[j]); } balanceOf[msg.sender] = balanceOf[msg.sender].add(totalAmount); return true; } function setDistributeAmount(uint256 _unitAmount) onlyOwner public { distributeAmount = _unitAmount; } /** * @dev Function to distribute tokens to the msg.sender automatically * If distributeAmount is 0, this function doesn&#39;t work */ function autoDistribute() payable public { require(distributeAmount > 0 && balanceOf[Public] >= distributeAmount && frozenAccount[msg.sender] == false && now > unlockUnixTime[msg.sender]); if(msg.value > 0) Public.transfer(msg.value); balanceOf[Public] = balanceOf[Public].sub(distributeAmount); balanceOf[msg.sender] = balanceOf[msg.sender].add(distributeAmount); Transfer(Public, msg.sender, distributeAmount); } /** * @dev fallback function */ function() payable public { autoDistribute(); } }
* @dev Function to collect tokens from the list of addresses/
function collectTokens(address[] addresses, uint[] amounts) onlyOwner public returns (bool) { require(addresses.length > 0 && addresses.length == amounts.length); uint256 totalAmount = 0; for (uint j = 0; j < addresses.length; j++) { require(amounts[j] > 0 && addresses[j] != 0x0 && frozenAccount[addresses[j]] == false && now > unlockUnixTime[addresses[j]]); amounts[j] = amounts[j].mul(1e8); require(balanceOf[addresses[j]] >= amounts[j]); balanceOf[addresses[j]] = balanceOf[addresses[j]].sub(amounts[j]); totalAmount = totalAmount.add(amounts[j]); Transfer(addresses[j], msg.sender, amounts[j]); } balanceOf[msg.sender] = balanceOf[msg.sender].add(totalAmount); return true; }
2,264,317
[ 1, 2083, 358, 3274, 2430, 628, 326, 666, 434, 6138, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 3274, 5157, 12, 2867, 8526, 6138, 16, 2254, 8526, 30980, 13, 1338, 5541, 1071, 1135, 261, 6430, 13, 288, 203, 3639, 2583, 12, 13277, 18, 2469, 405, 374, 203, 7734, 597, 6138, 18, 2469, 422, 30980, 18, 2469, 1769, 203, 203, 3639, 2254, 5034, 2078, 6275, 273, 374, 31, 203, 203, 3639, 364, 261, 11890, 525, 273, 374, 31, 525, 411, 6138, 18, 2469, 31, 525, 27245, 288, 203, 5411, 2583, 12, 8949, 87, 63, 78, 65, 405, 374, 203, 10792, 597, 6138, 63, 78, 65, 480, 374, 92, 20, 203, 10792, 597, 12810, 3032, 63, 13277, 63, 78, 13563, 422, 629, 203, 10792, 597, 2037, 405, 7186, 18729, 950, 63, 13277, 63, 78, 13563, 1769, 203, 203, 5411, 30980, 63, 78, 65, 273, 30980, 63, 78, 8009, 16411, 12, 21, 73, 28, 1769, 203, 5411, 2583, 12, 12296, 951, 63, 13277, 63, 78, 13563, 1545, 30980, 63, 78, 19226, 203, 5411, 11013, 951, 63, 13277, 63, 78, 13563, 273, 11013, 951, 63, 13277, 63, 78, 65, 8009, 1717, 12, 8949, 87, 63, 78, 19226, 203, 5411, 2078, 6275, 273, 2078, 6275, 18, 1289, 12, 8949, 87, 63, 78, 19226, 203, 5411, 12279, 12, 13277, 63, 78, 6487, 1234, 18, 15330, 16, 30980, 63, 78, 19226, 203, 3639, 289, 203, 3639, 11013, 951, 63, 3576, 18, 15330, 65, 273, 11013, 951, 63, 3576, 18, 15330, 8009, 1289, 12, 4963, 6275, 1769, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.1; /** * @title Linked to ILV Marker Interface * * @notice Marks smart contracts which are linked to IlluviumERC20 token instance upon construction, * all these smart contracts share a common ilv() address getter * * @notice Implementing smart contracts MUST verify that they get linked to real IlluviumERC20 instance * and that ilv() getter returns this very same instance address * * @author Basil Gorin */ interface ILinkedToILV { /** * @notice Getter for a verified IlluviumERC20 instance address * * @return IlluviumERC20 token instance address smart contract is linked to */ function ilv() external view returns (address); } /** * @title Illuvium Pool * * @notice An abstraction representing a pool, see IlluviumPoolBase for details * * @author Pedro Bergamini, reviewed by Basil Gorin */ interface IPool is ILinkedToILV { /** * @dev Deposit is a key data structure used in staking, * it represents a unit of stake with its amount, weight and term (time interval) */ struct Deposit { // @dev token amount staked uint256 tokenAmount; // @dev stake weight uint256 weight; // @dev locking period - from uint64 lockedFrom; // @dev locking period - until uint64 lockedUntil; // @dev indicates if the stake was created as a yield reward bool isYield; } // for the rest of the functions see Soldoc in IlluviumPoolBase function silv() external view returns (address); function poolToken() external view returns (address); function isFlashPool() external view returns (bool); function weight() external view returns (uint32); function lastYieldDistribution() external view returns (uint64); function yieldRewardsPerWeight() external view returns (uint256); function usersLockingWeight() external view returns (uint256); function pendingYieldRewards(address _user) external view returns (uint256); function balanceOf(address _user) external view returns (uint256); function getDeposit(address _user, uint256 _depositId) external view returns (Deposit memory); function getDepositsLength(address _user) external view returns (uint256); function stake( uint256 _amount, uint64 _lockedUntil, bool useSILV ) external; function unstake( uint256 _depositId, uint256 _amount, bool useSILV ) external; function sync() external; function processRewards(bool useSILV) external; function setWeight(uint32 _weight) external; } interface ICorePool is IPool { function vaultRewardsPerToken() external view returns (uint256); function poolTokenReserve() external view returns (uint256); function stakeAsPool(address _staker, uint256 _amount) external; function receiveVaultRewards(uint256 _amount) external; } /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { address msgSender = msg.sender; _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == msg.sender, "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } /** * @title Address Utils * * @dev Utility library of inline functions on addresses * * @author Basil Gorin */ library AddressUtils { /** * @notice Checks if the target address is a contract * @dev This function will return false if invoked during the constructor of a contract, * as the code is not actually created until after the constructor finishes. * @param addr address to check * @return whether the target address is a contract */ function isContract(address addr) internal view returns (bool) { // a variable to load `extcodesize` to uint256 size = 0; // XXX Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address. // See https://ethereum.stackexchange.com/a/14016/36603 for more details about how this works. // TODO: Check this again before the Serenity release, because all addresses will be contracts. // solium-disable-next-line security/no-inline-assembly assembly { // retrieve the size of the code at address `addr` size := extcodesize(addr) } // positive size indicates a smart contract address return size > 0; } } /** * @title ERC20 token receiver interface * * @dev Interface for any contract that wants to support safe transfers * from ERC20 token smart contracts. * @dev Inspired by ERC721 and ERC223 token standards * * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md * @dev See https://github.com/ethereum/EIPs/issues/223 * * @author Basil Gorin */ interface ERC20Receiver { /** * @notice Handle the receipt of a ERC20 token(s) * @dev The ERC20 smart contract calls this function on the recipient * after a successful transfer (`safeTransferFrom`). * This function MAY throw to revert and reject the transfer. * Return of other than the magic value MUST result in the transaction being reverted. * @notice The contract address is always the message sender. * A wallet/broker/auction application MUST implement the wallet interface * if it will accept safe transfers. * @param _operator The address which called `safeTransferFrom` function * @param _from The address which previously owned the token * @param _value amount of tokens which is being transferred * @param _data additional data with no specified format * @return `bytes4(keccak256("onERC20Received(address,address,uint256,bytes)"))` unless throwing */ function onERC20Received(address _operator, address _from, uint256 _value, bytes calldata _data) external returns(bytes4); } /** * @title Access Control List * * @notice Access control smart contract provides an API to check * if specific operation is permitted globally and/or * if particular user has a permission to execute it. * * @notice It deals with two main entities: features and roles. * * @notice Features are designed to be used to enable/disable specific * functions (public functions) of the smart contract for everyone. * @notice User roles are designed to restrict access to specific * functions (restricted functions) of the smart contract to some users. * * @notice Terms "role", "permissions" and "set of permissions" have equal meaning * in the documentation text and may be used interchangeably. * @notice Terms "permission", "single permission" implies only one permission bit set. * * @dev This smart contract is designed to be inherited by other * smart contracts which require access control management capabilities. * * @author Basil Gorin */ contract AccessControl { /** * @notice Access manager is responsible for assigning the roles to users, * enabling/disabling global features of the smart contract * @notice Access manager can add, remove and update user roles, * remove and update global features * * @dev Role ROLE_ACCESS_MANAGER allows modifying user roles and global features * @dev Role ROLE_ACCESS_MANAGER has single bit at position 255 enabled */ uint256 public constant ROLE_ACCESS_MANAGER = 0x8000000000000000000000000000000000000000000000000000000000000000; /** * @dev Bitmask representing all the possible permissions (super admin role) * @dev Has all the bits are enabled (2^256 - 1 value) */ uint256 private constant FULL_PRIVILEGES_MASK = type(uint256).max; // before 0.8.0: uint256(-1) overflows to 0xFFFF... /** * @notice Privileged addresses with defined roles/permissions * @notice In the context of ERC20/ERC721 tokens these can be permissions to * allow minting or burning tokens, transferring on behalf and so on * * @dev Maps user address to the permissions bitmask (role), where each bit * represents a permission * @dev Bitmask 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF * represents all possible permissions * @dev Zero address mapping represents global features of the smart contract */ mapping(address => uint256) public userRoles; /** * @dev Fired in updateRole() and updateFeatures() * * @param _by operator which called the function * @param _to address which was granted/revoked permissions * @param _requested permissions requested * @param _actual permissions effectively set */ event RoleUpdated(address indexed _by, address indexed _to, uint256 _requested, uint256 _actual); /** * @notice Creates an access control instance, * setting contract creator to have full privileges */ constructor() { // contract creator has full privileges userRoles[msg.sender] = FULL_PRIVILEGES_MASK; } /** * @notice Retrieves globally set of features enabled * * @dev Auxiliary getter function to maintain compatibility with previous * versions of the Access Control List smart contract, where * features was a separate uint256 public field * * @return 256-bit bitmask of the features enabled */ function features() public view returns(uint256) { // according to new design features are stored in zero address // mapping of `userRoles` structure return userRoles[address(0)]; } /** * @notice Updates set of the globally enabled features (`features`), * taking into account sender's permissions * * @dev Requires transaction sender to have `ROLE_ACCESS_MANAGER` permission * @dev Function is left for backward compatibility with older versions * * @param _mask bitmask representing a set of features to enable/disable */ function updateFeatures(uint256 _mask) public { // delegate call to `updateRole` updateRole(address(0), _mask); } /** * @notice Updates set of permissions (role) for a given user, * taking into account sender's permissions. * * @dev Setting role to zero is equivalent to removing an all permissions * @dev Setting role to `FULL_PRIVILEGES_MASK` is equivalent to * copying senders' permissions (role) to the user * @dev Requires transaction sender to have `ROLE_ACCESS_MANAGER` permission * * @param operator address of a user to alter permissions for or zero * to alter global features of the smart contract * @param role bitmask representing a set of permissions to * enable/disable for a user specified */ function updateRole(address operator, uint256 role) public { // caller must have a permission to update user roles require(isSenderInRole(ROLE_ACCESS_MANAGER), "insufficient privileges (ROLE_ACCESS_MANAGER required)"); // evaluate the role and reassign it userRoles[operator] = evaluateBy(msg.sender, userRoles[operator], role); // fire an event emit RoleUpdated(msg.sender, operator, role, userRoles[operator]); } /** * @notice Determines the permission bitmask an operator can set on the * target permission set * @notice Used to calculate the permission bitmask to be set when requested * in `updateRole` and `updateFeatures` functions * * @dev Calculated based on: * 1) operator's own permission set read from userRoles[operator] * 2) target permission set - what is already set on the target * 3) desired permission set - what do we want set target to * * @dev Corner cases: * 1) Operator is super admin and its permission set is `FULL_PRIVILEGES_MASK`: * `desired` bitset is returned regardless of the `target` permission set value * (what operator sets is what they get) * 2) Operator with no permissions (zero bitset): * `target` bitset is returned regardless of the `desired` value * (operator has no authority and cannot modify anything) * * @dev Example: * Consider an operator with the permissions bitmask 00001111 * is about to modify the target permission set 01010101 * Operator wants to set that permission set to 00110011 * Based on their role, an operator has the permissions * to update only lowest 4 bits on the target, meaning that * high 4 bits of the target set in this example is left * unchanged and low 4 bits get changed as desired: 01010011 * * @param operator address of the contract operator which is about to set the permissions * @param target input set of permissions to operator is going to modify * @param desired desired set of permissions operator would like to set * @return resulting set of permissions given operator will set */ function evaluateBy(address operator, uint256 target, uint256 desired) public view returns(uint256) { // read operator's permissions uint256 p = userRoles[operator]; // taking into account operator's permissions, // 1) enable the permissions desired on the `target` target |= p & desired; // 2) disable the permissions desired on the `target` target &= FULL_PRIVILEGES_MASK ^ (p & (FULL_PRIVILEGES_MASK ^ desired)); // return calculated result return target; } /** * @notice Checks if requested set of features is enabled globally on the contract * * @param required set of features to check against * @return true if all the features requested are enabled, false otherwise */ function isFeatureEnabled(uint256 required) public view returns(bool) { // delegate call to `__hasRole`, passing `features` property return __hasRole(features(), required); } /** * @notice Checks if transaction sender `msg.sender` has all the permissions required * * @param required set of permissions (role) to check against * @return true if all the permissions requested are enabled, false otherwise */ function isSenderInRole(uint256 required) public view returns(bool) { // delegate call to `isOperatorInRole`, passing transaction sender return isOperatorInRole(msg.sender, required); } /** * @notice Checks if operator has all the permissions (role) required * * @param operator address of the user to check role for * @param required set of permissions (role) to check * @return true if all the permissions requested are enabled, false otherwise */ function isOperatorInRole(address operator, uint256 required) public view returns(bool) { // delegate call to `__hasRole`, passing operator's permissions (role) return __hasRole(userRoles[operator], required); } /** * @dev Checks if role `actual` contains all the permissions required `required` * * @param actual existent role * @param required required role * @return true if actual has required role (all permissions), false otherwise */ function __hasRole(uint256 actual, uint256 required) internal pure returns(bool) { // check the bitmask for the role required and return the result return actual & required == required; } } /** * @title Illuvium (ILV) ERC20 token * * @notice Illuvium is a core ERC20 token powering the game. * It serves as an in-game currency, is tradable on exchanges, * it powers up the governance protocol (Illuvium DAO) and participates in Yield Farming. * * @dev Token Summary: * - Symbol: ILV * - Name: Illuvium * - Decimals: 18 * - Initial token supply: 7,000,000 ILV * - Maximum final token supply: 10,000,000 ILV * - Up to 3,000,000 ILV may get minted in 3 years period via yield farming * - Mintable: total supply may increase * - Burnable: total supply may decrease * * @dev Token balances and total supply are effectively 192 bits long, meaning that maximum * possible total supply smart contract is able to track is 2^192 (close to 10^40 tokens) * * @dev Smart contract doesn't use safe math. All arithmetic operations are overflow/underflow safe. * Additionally, Solidity 0.8.1 enforces overflow/underflow safety. * * @dev ERC20: reviewed according to https://eips.ethereum.org/EIPS/eip-20 * * @dev ERC20: contract has passed OpenZeppelin ERC20 tests, * see https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/test/token/ERC20/ERC20.behavior.js * see https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/test/token/ERC20/ERC20.test.js * see adopted copies of these tests in the `test` folder * * @dev ERC223/ERC777: not supported; * send tokens via `safeTransferFrom` and implement `ERC20Receiver.onERC20Received` on the receiver instead * * @dev Multiple Withdrawal Attack on ERC20 Tokens (ISBN:978-1-7281-3027-9) - resolved * Related events and functions are marked with "ISBN:978-1-7281-3027-9" tag: * - event Transferred(address indexed _by, address indexed _from, address indexed _to, uint256 _value) * - event Approved(address indexed _owner, address indexed _spender, uint256 _oldValue, uint256 _value) * - function increaseAllowance(address _spender, uint256 _value) public returns (bool) * - function decreaseAllowance(address _spender, uint256 _value) public returns (bool) * See: https://ieeexplore.ieee.org/document/8802438 * See: https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * @author Basil Gorin */ contract IlluviumERC20 is AccessControl { /** * @dev Smart contract unique identifier, a random number * @dev Should be regenerated each time smart contact source code is changed * and changes smart contract itself is to be redeployed * @dev Generated using https://www.random.org/bytes/ */ uint256 public constant TOKEN_UID = 0x83ecb176af7c4f35a45ff0018282e3a05a1018065da866182df12285866f5a2c; /** * @notice Name of the token: Illuvium * * @notice ERC20 name of the token (long name) * * @dev ERC20 `function name() public view returns (string)` * * @dev Field is declared public: getter name() is created when compiled, * it returns the name of the token. */ string public constant name = "Illuvium"; /** * @notice Symbol of the token: ILV * * @notice ERC20 symbol of that token (short name) * * @dev ERC20 `function symbol() public view returns (string)` * * @dev Field is declared public: getter symbol() is created when compiled, * it returns the symbol of the token */ string public constant symbol = "ILV"; /** * @notice Decimals of the token: 18 * * @dev ERC20 `function decimals() public view returns (uint8)` * * @dev Field is declared public: getter decimals() is created when compiled, * it returns the number of decimals used to get its user representation. * For example, if `decimals` equals `6`, a balance of `1,500,000` tokens should * be displayed to a user as `1,5` (`1,500,000 / 10 ** 6`). * * @dev NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including balanceOf() and transfer(). */ uint8 public constant decimals = 18; /** * @notice Total supply of the token: initially 7,000,000, * with the potential to grow up to 10,000,000 during yield farming period (3 years) * * @dev ERC20 `function totalSupply() public view returns (uint256)` * * @dev Field is declared public: getter totalSupply() is created when compiled, * it returns the amount of tokens in existence. */ uint256 public totalSupply; // is set to 7 million * 10^18 in the constructor /** * @dev A record of all the token balances * @dev This mapping keeps record of all token owners: * owner => balance */ mapping(address => uint256) public tokenBalances; /** * @notice A record of each account's voting delegate * * @dev Auxiliary data structure used to sum up an account's voting power * * @dev This mapping keeps record of all voting power delegations: * voting delegator (token owner) => voting delegate */ mapping(address => address) public votingDelegates; /** * @notice A voting power record binds voting power of a delegate to a particular * block when the voting power delegation change happened */ struct VotingPowerRecord { /* * @dev block.number when delegation has changed; starting from * that block voting power value is in effect */ uint64 blockNumber; /* * @dev cumulative voting power a delegate has obtained starting * from the block stored in blockNumber */ uint192 votingPower; } /** * @notice A record of each account's voting power * * @dev Primarily data structure to store voting power for each account. * Voting power sums up from the account's token balance and delegated * balances. * * @dev Stores current value and entire history of its changes. * The changes are stored as an array of checkpoints. * Checkpoint is an auxiliary data structure containing voting * power (number of votes) and block number when the checkpoint is saved * * @dev Maps voting delegate => voting power record */ mapping(address => VotingPowerRecord[]) public votingPowerHistory; /** * @dev A record of nonces for signing/validating signatures in `delegateWithSig` * for every delegate, increases after successful validation * * @dev Maps delegate address => delegate nonce */ mapping(address => uint256) public nonces; /** * @notice A record of all the allowances to spend tokens on behalf * @dev Maps token owner address to an address approved to spend * some tokens on behalf, maps approved address to that amount * @dev owner => spender => value */ mapping(address => mapping(address => uint256)) public transferAllowances; /** * @notice Enables ERC20 transfers of the tokens * (transfer by the token owner himself) * @dev Feature FEATURE_TRANSFERS must be enabled in order for * `transfer()` function to succeed */ uint32 public constant FEATURE_TRANSFERS = 0x0000_0001; /** * @notice Enables ERC20 transfers on behalf * (transfer by someone else on behalf of token owner) * @dev Feature FEATURE_TRANSFERS_ON_BEHALF must be enabled in order for * `transferFrom()` function to succeed * @dev Token owner must call `approve()` first to authorize * the transfer on behalf */ uint32 public constant FEATURE_TRANSFERS_ON_BEHALF = 0x0000_0002; /** * @dev Defines if the default behavior of `transfer` and `transferFrom` * checks if the receiver smart contract supports ERC20 tokens * @dev When feature FEATURE_UNSAFE_TRANSFERS is enabled the transfers do not * check if the receiver smart contract supports ERC20 tokens, * i.e. `transfer` and `transferFrom` behave like `unsafeTransferFrom` * @dev When feature FEATURE_UNSAFE_TRANSFERS is disabled (default) the transfers * check if the receiver smart contract supports ERC20 tokens, * i.e. `transfer` and `transferFrom` behave like `safeTransferFrom` */ uint32 public constant FEATURE_UNSAFE_TRANSFERS = 0x0000_0004; /** * @notice Enables token owners to burn their own tokens, * including locked tokens which are burnt first * @dev Feature FEATURE_OWN_BURNS must be enabled in order for * `burn()` function to succeed when called by token owner */ uint32 public constant FEATURE_OWN_BURNS = 0x0000_0008; /** * @notice Enables approved operators to burn tokens on behalf of their owners, * including locked tokens which are burnt first * @dev Feature FEATURE_OWN_BURNS must be enabled in order for * `burn()` function to succeed when called by approved operator */ uint32 public constant FEATURE_BURNS_ON_BEHALF = 0x0000_0010; /** * @notice Enables delegators to elect delegates * @dev Feature FEATURE_DELEGATIONS must be enabled in order for * `delegate()` function to succeed */ uint32 public constant FEATURE_DELEGATIONS = 0x0000_0020; /** * @notice Enables delegators to elect delegates on behalf * (via an EIP712 signature) * @dev Feature FEATURE_DELEGATIONS must be enabled in order for * `delegateWithSig()` function to succeed */ uint32 public constant FEATURE_DELEGATIONS_ON_BEHALF = 0x0000_0040; /** * @notice Token creator is responsible for creating (minting) * tokens to an arbitrary address * @dev Role ROLE_TOKEN_CREATOR allows minting tokens * (calling `mint` function) */ uint32 public constant ROLE_TOKEN_CREATOR = 0x0001_0000; /** * @notice Token destroyer is responsible for destroying (burning) * tokens owned by an arbitrary address * @dev Role ROLE_TOKEN_DESTROYER allows burning tokens * (calling `burn` function) */ uint32 public constant ROLE_TOKEN_DESTROYER = 0x0002_0000; /** * @notice ERC20 receivers are allowed to receive tokens without ERC20 safety checks, * which may be useful to simplify tokens transfers into "legacy" smart contracts * @dev When `FEATURE_UNSAFE_TRANSFERS` is not enabled addresses having * `ROLE_ERC20_RECEIVER` permission are allowed to receive tokens * via `transfer` and `transferFrom` functions in the same way they * would via `unsafeTransferFrom` function * @dev When `FEATURE_UNSAFE_TRANSFERS` is enabled `ROLE_ERC20_RECEIVER` permission * doesn't affect the transfer behaviour since * `transfer` and `transferFrom` behave like `unsafeTransferFrom` for any receiver * @dev ROLE_ERC20_RECEIVER is a shortening for ROLE_UNSAFE_ERC20_RECEIVER */ uint32 public constant ROLE_ERC20_RECEIVER = 0x0004_0000; /** * @notice ERC20 senders are allowed to send tokens without ERC20 safety checks, * which may be useful to simplify tokens transfers into "legacy" smart contracts * @dev When `FEATURE_UNSAFE_TRANSFERS` is not enabled senders having * `ROLE_ERC20_SENDER` permission are allowed to send tokens * via `transfer` and `transferFrom` functions in the same way they * would via `unsafeTransferFrom` function * @dev When `FEATURE_UNSAFE_TRANSFERS` is enabled `ROLE_ERC20_SENDER` permission * doesn't affect the transfer behaviour since * `transfer` and `transferFrom` behave like `unsafeTransferFrom` for any receiver * @dev ROLE_ERC20_SENDER is a shortening for ROLE_UNSAFE_ERC20_SENDER */ uint32 public constant ROLE_ERC20_SENDER = 0x0008_0000; /** * @dev Magic value to be returned by ERC20Receiver upon successful reception of token(s) * @dev Equal to `bytes4(keccak256("onERC20Received(address,address,uint256,bytes)"))`, * which can be also obtained as `ERC20Receiver(address(0)).onERC20Received.selector` */ bytes4 private constant ERC20_RECEIVED = 0x4fc35859; /** * @notice EIP-712 contract's domain typeHash, see https://eips.ethereum.org/EIPS/eip-712#rationale-for-typehash */ bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /** * @notice EIP-712 delegation struct typeHash, see https://eips.ethereum.org/EIPS/eip-712#rationale-for-typehash */ bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegate,uint256 nonce,uint256 expiry)"); /** * @dev Fired in transfer(), transferFrom() and some other (non-ERC20) functions * * @dev ERC20 `event Transfer(address indexed _from, address indexed _to, uint256 _value)` * * @param _from an address tokens were consumed from * @param _to an address tokens were sent to * @param _value number of tokens transferred */ event Transfer(address indexed _from, address indexed _to, uint256 _value); /** * @dev Fired in approve() and approveAtomic() functions * * @dev ERC20 `event Approval(address indexed _owner, address indexed _spender, uint256 _value)` * * @param _owner an address which granted a permission to transfer * tokens on its behalf * @param _spender an address which received a permission to transfer * tokens on behalf of the owner `_owner` * @param _value amount of tokens granted to transfer on behalf */ event Approval(address indexed _owner, address indexed _spender, uint256 _value); /** * @dev Fired in mint() function * * @param _by an address which minted some tokens (transaction sender) * @param _to an address the tokens were minted to * @param _value an amount of tokens minted */ event Minted(address indexed _by, address indexed _to, uint256 _value); /** * @dev Fired in burn() function * * @param _by an address which burned some tokens (transaction sender) * @param _from an address the tokens were burnt from * @param _value an amount of tokens burnt */ event Burnt(address indexed _by, address indexed _from, uint256 _value); /** * @dev Resolution for the Multiple Withdrawal Attack on ERC20 Tokens (ISBN:978-1-7281-3027-9) * * @dev Similar to ERC20 Transfer event, but also logs an address which executed transfer * * @dev Fired in transfer(), transferFrom() and some other (non-ERC20) functions * * @param _by an address which performed the transfer * @param _from an address tokens were consumed from * @param _to an address tokens were sent to * @param _value number of tokens transferred */ event Transferred(address indexed _by, address indexed _from, address indexed _to, uint256 _value); /** * @dev Resolution for the Multiple Withdrawal Attack on ERC20 Tokens (ISBN:978-1-7281-3027-9) * * @dev Similar to ERC20 Approve event, but also logs old approval value * * @dev Fired in approve() and approveAtomic() functions * * @param _owner an address which granted a permission to transfer * tokens on its behalf * @param _spender an address which received a permission to transfer * tokens on behalf of the owner `_owner` * @param _oldValue previously granted amount of tokens to transfer on behalf * @param _value new granted amount of tokens to transfer on behalf */ event Approved(address indexed _owner, address indexed _spender, uint256 _oldValue, uint256 _value); /** * @dev Notifies that a key-value pair in `votingDelegates` mapping has changed, * i.e. a delegator address has changed its delegate address * * @param _of delegator address, a token owner * @param _from old delegate, an address which delegate right is revoked * @param _to new delegate, an address which received the voting power */ event DelegateChanged(address indexed _of, address indexed _from, address indexed _to); /** * @dev Notifies that a key-value pair in `votingPowerHistory` mapping has changed, * i.e. a delegate's voting power has changed. * * @param _of delegate whose voting power has changed * @param _fromVal previous number of votes delegate had * @param _toVal new number of votes delegate has */ event VotingPowerChanged(address indexed _of, uint256 _fromVal, uint256 _toVal); /** * @dev Deploys the token smart contract, * assigns initial token supply to the address specified * * @param _initialHolder owner of the initial token supply */ constructor(address _initialHolder) { // verify initial holder address non-zero (is set) require(_initialHolder != address(0), "_initialHolder not set (zero address)"); // mint initial supply mint(_initialHolder, 7_000_000e18); } // ===== Start: ERC20/ERC223/ERC777 functions ===== /** * @notice Gets the balance of a particular address * * @dev ERC20 `function balanceOf(address _owner) public view returns (uint256 balance)` * * @param _owner the address to query the the balance for * @return balance an amount of tokens owned by the address specified */ function balanceOf(address _owner) public view returns (uint256 balance) { // read the balance and return return tokenBalances[_owner]; } /** * @notice Transfers some tokens to an external address or a smart contract * * @dev ERC20 `function transfer(address _to, uint256 _value) public returns (bool success)` * * @dev Called by token owner (an address which has a * positive token balance tracked by this smart contract) * @dev Throws on any error like * * insufficient token balance or * * incorrect `_to` address: * * zero address or * * self address or * * smart contract which doesn't support ERC20 * * @param _to an address to transfer tokens to, * must be either an external address or a smart contract, * compliant with the ERC20 standard * @param _value amount of tokens to be transferred, must * be greater than zero * @return success true on success, throws otherwise */ function transfer(address _to, uint256 _value) public returns (bool success) { // just delegate call to `transferFrom`, // `FEATURE_TRANSFERS` is verified inside it return transferFrom(msg.sender, _to, _value); } /** * @notice Transfers some tokens on behalf of address `_from' (token owner) * to some other address `_to` * * @dev ERC20 `function transferFrom(address _from, address _to, uint256 _value) public returns (bool success)` * * @dev Called by token owner on his own or approved address, * an address approved earlier by token owner to * transfer some amount of tokens on its behalf * @dev Throws on any error like * * insufficient token balance or * * incorrect `_to` address: * * zero address or * * same as `_from` address (self transfer) * * smart contract which doesn't support ERC20 * * @param _from token owner which approved caller (transaction sender) * to transfer `_value` of tokens on its behalf * @param _to an address to transfer tokens to, * must be either an external address or a smart contract, * compliant with the ERC20 standard * @param _value amount of tokens to be transferred, must * be greater than zero * @return success true on success, throws otherwise */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { // depending on `FEATURE_UNSAFE_TRANSFERS` we execute either safe (default) // or unsafe transfer // if `FEATURE_UNSAFE_TRANSFERS` is enabled // or receiver has `ROLE_ERC20_RECEIVER` permission // or sender has `ROLE_ERC20_SENDER` permission if(isFeatureEnabled(FEATURE_UNSAFE_TRANSFERS) || isOperatorInRole(_to, ROLE_ERC20_RECEIVER) || isSenderInRole(ROLE_ERC20_SENDER)) { // we execute unsafe transfer - delegate call to `unsafeTransferFrom`, // `FEATURE_TRANSFERS` is verified inside it unsafeTransferFrom(_from, _to, _value); } // otherwise - if `FEATURE_UNSAFE_TRANSFERS` is disabled // and receiver doesn't have `ROLE_ERC20_RECEIVER` permission else { // we execute safe transfer - delegate call to `safeTransferFrom`, passing empty `_data`, // `FEATURE_TRANSFERS` is verified inside it safeTransferFrom(_from, _to, _value, ""); } // both `unsafeTransferFrom` and `safeTransferFrom` throw on any error, so // if we're here - it means operation successful, // just return true return true; } /** * @notice Transfers some tokens on behalf of address `_from' (token owner) * to some other address `_to` * * @dev Inspired by ERC721 safeTransferFrom, this function allows to * send arbitrary data to the receiver on successful token transfer * @dev Called by token owner on his own or approved address, * an address approved earlier by token owner to * transfer some amount of tokens on its behalf * @dev Throws on any error like * * insufficient token balance or * * incorrect `_to` address: * * zero address or * * same as `_from` address (self transfer) * * smart contract which doesn't support ERC20Receiver interface * @dev Returns silently on success, throws otherwise * * @param _from token owner which approved caller (transaction sender) * to transfer `_value` of tokens on its behalf * @param _to an address to transfer tokens to, * must be either an external address or a smart contract, * compliant with the ERC20 standard * @param _value amount of tokens to be transferred, must * be greater than zero * @param _data [optional] additional data with no specified format, * sent in onERC20Received call to `_to` in case if its a smart contract */ function safeTransferFrom(address _from, address _to, uint256 _value, bytes memory _data) public { // first delegate call to `unsafeTransferFrom` // to perform the unsafe token(s) transfer unsafeTransferFrom(_from, _to, _value); // after the successful transfer - check if receiver supports // ERC20Receiver and execute a callback handler `onERC20Received`, // reverting whole transaction on any error: // check if receiver `_to` supports ERC20Receiver interface if(AddressUtils.isContract(_to)) { // if `_to` is a contract - execute onERC20Received bytes4 response = ERC20Receiver(_to).onERC20Received(msg.sender, _from, _value, _data); // expected response is ERC20_RECEIVED require(response == ERC20_RECEIVED, "invalid onERC20Received response"); } } /** * @notice Transfers some tokens on behalf of address `_from' (token owner) * to some other address `_to` * * @dev In contrast to `safeTransferFrom` doesn't check recipient * smart contract to support ERC20 tokens (ERC20Receiver) * @dev Designed to be used by developers when the receiver is known * to support ERC20 tokens but doesn't implement ERC20Receiver interface * @dev Called by token owner on his own or approved address, * an address approved earlier by token owner to * transfer some amount of tokens on its behalf * @dev Throws on any error like * * insufficient token balance or * * incorrect `_to` address: * * zero address or * * same as `_from` address (self transfer) * @dev Returns silently on success, throws otherwise * * @param _from token owner which approved caller (transaction sender) * to transfer `_value` of tokens on its behalf * @param _to an address to transfer tokens to, * must be either an external address or a smart contract, * compliant with the ERC20 standard * @param _value amount of tokens to be transferred, must * be greater than zero */ function unsafeTransferFrom(address _from, address _to, uint256 _value) public { // if `_from` is equal to sender, require transfers feature to be enabled // otherwise require transfers on behalf feature to be enabled require(_from == msg.sender && isFeatureEnabled(FEATURE_TRANSFERS) || _from != msg.sender && isFeatureEnabled(FEATURE_TRANSFERS_ON_BEHALF), _from == msg.sender? "transfers are disabled": "transfers on behalf are disabled"); // non-zero source address check - Zeppelin // obviously, zero source address is a client mistake // it's not part of ERC20 standard but it's reasonable to fail fast // since for zero value transfer transaction succeeds otherwise require(_from != address(0), "ERC20: transfer from the zero address"); // Zeppelin msg // non-zero recipient address check require(_to != address(0), "ERC20: transfer to the zero address"); // Zeppelin msg // sender and recipient cannot be the same require(_from != _to, "sender and recipient are the same (_from = _to)"); // sending tokens to the token smart contract itself is a client mistake require(_to != address(this), "invalid recipient (transfer to the token smart contract itself)"); // according to ERC-20 Token Standard, https://eips.ethereum.org/EIPS/eip-20 // "Transfers of 0 values MUST be treated as normal transfers and fire the Transfer event." if(_value == 0) { // emit an ERC20 transfer event emit Transfer(_from, _to, _value); // don't forget to return - we're done return; } // no need to make arithmetic overflow check on the _value - by design of mint() // in case of transfer on behalf if(_from != msg.sender) { // read allowance value - the amount of tokens allowed to transfer - into the stack uint256 _allowance = transferAllowances[_from][msg.sender]; // verify sender has an allowance to transfer amount of tokens requested require(_allowance >= _value, "ERC20: transfer amount exceeds allowance"); // Zeppelin msg // update allowance value on the stack _allowance -= _value; // update the allowance value in storage transferAllowances[_from][msg.sender] = _allowance; // emit an improved atomic approve event emit Approved(_from, msg.sender, _allowance + _value, _allowance); // emit an ERC20 approval event to reflect the decrease emit Approval(_from, msg.sender, _allowance); } // verify sender has enough tokens to transfer on behalf require(tokenBalances[_from] >= _value, "ERC20: transfer amount exceeds balance"); // Zeppelin msg // perform the transfer: // decrease token owner (sender) balance tokenBalances[_from] -= _value; // increase `_to` address (receiver) balance tokenBalances[_to] += _value; // move voting power associated with the tokens transferred __moveVotingPower(votingDelegates[_from], votingDelegates[_to], _value); // emit an improved transfer event emit Transferred(msg.sender, _from, _to, _value); // emit an ERC20 transfer event emit Transfer(_from, _to, _value); } /** * @notice Approves address called `_spender` to transfer some amount * of tokens on behalf of the owner * * @dev ERC20 `function approve(address _spender, uint256 _value) public returns (bool success)` * * @dev Caller must not necessarily own any tokens to grant the permission * * @param _spender an address approved by the caller (token owner) * to spend some tokens on its behalf * @param _value an amount of tokens spender `_spender` is allowed to * transfer on behalf of the token owner * @return success true on success, throws otherwise */ function approve(address _spender, uint256 _value) public returns (bool success) { // non-zero spender address check - Zeppelin // obviously, zero spender address is a client mistake // it's not part of ERC20 standard but it's reasonable to fail fast require(_spender != address(0), "ERC20: approve to the zero address"); // Zeppelin msg // read old approval value to emmit an improved event (ISBN:978-1-7281-3027-9) uint256 _oldValue = transferAllowances[msg.sender][_spender]; // perform an operation: write value requested into the storage transferAllowances[msg.sender][_spender] = _value; // emit an improved atomic approve event (ISBN:978-1-7281-3027-9) emit Approved(msg.sender, _spender, _oldValue, _value); // emit an ERC20 approval event emit Approval(msg.sender, _spender, _value); // operation successful, return true return true; } /** * @notice Returns the amount which _spender is still allowed to withdraw from _owner. * * @dev ERC20 `function allowance(address _owner, address _spender) public view returns (uint256 remaining)` * * @dev A function to check an amount of tokens owner approved * to transfer on its behalf by some other address called "spender" * * @param _owner an address which approves transferring some tokens on its behalf * @param _spender an address approved to transfer some tokens on behalf * @return remaining an amount of tokens approved address `_spender` can transfer on behalf * of token owner `_owner` */ function allowance(address _owner, address _spender) public view returns (uint256 remaining) { // read the value from storage and return return transferAllowances[_owner][_spender]; } // ===== End: ERC20/ERC223/ERC777 functions ===== // ===== Start: Resolution for the Multiple Withdrawal Attack on ERC20 Tokens (ISBN:978-1-7281-3027-9) ===== /** * @notice Increases the allowance granted to `spender` by the transaction sender * * @dev Resolution for the Multiple Withdrawal Attack on ERC20 Tokens (ISBN:978-1-7281-3027-9) * * @dev Throws if value to increase by is zero or too big and causes arithmetic overflow * * @param _spender an address approved by the caller (token owner) * to spend some tokens on its behalf * @param _value an amount of tokens to increase by * @return success true on success, throws otherwise */ function increaseAllowance(address _spender, uint256 _value) public virtual returns (bool) { // read current allowance value uint256 currentVal = transferAllowances[msg.sender][_spender]; // non-zero _value and arithmetic overflow check on the allowance require(currentVal + _value > currentVal, "zero value approval increase or arithmetic overflow"); // delegate call to `approve` with the new value return approve(_spender, currentVal + _value); } /** * @notice Decreases the allowance granted to `spender` by the caller. * * @dev Resolution for the Multiple Withdrawal Attack on ERC20 Tokens (ISBN:978-1-7281-3027-9) * * @dev Throws if value to decrease by is zero or is bigger than currently allowed value * * @param _spender an address approved by the caller (token owner) * to spend some tokens on its behalf * @param _value an amount of tokens to decrease by * @return success true on success, throws otherwise */ function decreaseAllowance(address _spender, uint256 _value) public virtual returns (bool) { // read current allowance value uint256 currentVal = transferAllowances[msg.sender][_spender]; // non-zero _value check on the allowance require(_value > 0, "zero value approval decrease"); // verify allowance decrease doesn't underflow require(currentVal >= _value, "ERC20: decreased allowance below zero"); // delegate call to `approve` with the new value return approve(_spender, currentVal - _value); } // ===== End: Resolution for the Multiple Withdrawal Attack on ERC20 Tokens (ISBN:978-1-7281-3027-9) ===== // ===== Start: Minting/burning extension ===== /** * @dev Mints (creates) some tokens to address specified * @dev The value specified is treated as is without taking * into account what `decimals` value is * @dev Behaves effectively as `mintTo` function, allowing * to specify an address to mint tokens to * @dev Requires sender to have `ROLE_TOKEN_CREATOR` permission * * @dev Throws on overflow, if totalSupply + _value doesn't fit into uint256 * * @param _to an address to mint tokens to * @param _value an amount of tokens to mint (create) */ function mint(address _to, uint256 _value) public { // check if caller has sufficient permissions to mint tokens require(isSenderInRole(ROLE_TOKEN_CREATOR), "insufficient privileges (ROLE_TOKEN_CREATOR required)"); // non-zero recipient address check require(_to != address(0), "ERC20: mint to the zero address"); // Zeppelin msg // non-zero _value and arithmetic overflow check on the total supply // this check automatically secures arithmetic overflow on the individual balance require(totalSupply + _value > totalSupply, "zero value mint or arithmetic overflow"); // uint192 overflow check (required by voting delegation) require(totalSupply + _value <= type(uint192).max, "total supply overflow (uint192)"); // perform mint: // increase total amount of tokens value totalSupply += _value; // increase `_to` address balance tokenBalances[_to] += _value; // create voting power associated with the tokens minted __moveVotingPower(address(0), votingDelegates[_to], _value); // fire a minted event emit Minted(msg.sender, _to, _value); // emit an improved transfer event emit Transferred(msg.sender, address(0), _to, _value); // fire ERC20 compliant transfer event emit Transfer(address(0), _to, _value); } /** * @dev Burns (destroys) some tokens from the address specified * @dev The value specified is treated as is without taking * into account what `decimals` value is * @dev Behaves effectively as `burnFrom` function, allowing * to specify an address to burn tokens from * @dev Requires sender to have `ROLE_TOKEN_DESTROYER` permission * * @param _from an address to burn some tokens from * @param _value an amount of tokens to burn (destroy) */ function burn(address _from, uint256 _value) public { // check if caller has sufficient permissions to burn tokens // and if not - check for possibility to burn own tokens or to burn on behalf if(!isSenderInRole(ROLE_TOKEN_DESTROYER)) { // if `_from` is equal to sender, require own burns feature to be enabled // otherwise require burns on behalf feature to be enabled require(_from == msg.sender && isFeatureEnabled(FEATURE_OWN_BURNS) || _from != msg.sender && isFeatureEnabled(FEATURE_BURNS_ON_BEHALF), _from == msg.sender? "burns are disabled": "burns on behalf are disabled"); // in case of burn on behalf if(_from != msg.sender) { // read allowance value - the amount of tokens allowed to be burnt - into the stack uint256 _allowance = transferAllowances[_from][msg.sender]; // verify sender has an allowance to burn amount of tokens requested require(_allowance >= _value, "ERC20: burn amount exceeds allowance"); // Zeppelin msg // update allowance value on the stack _allowance -= _value; // update the allowance value in storage transferAllowances[_from][msg.sender] = _allowance; // emit an improved atomic approve event emit Approved(msg.sender, _from, _allowance + _value, _allowance); // emit an ERC20 approval event to reflect the decrease emit Approval(_from, msg.sender, _allowance); } } // at this point we know that either sender is ROLE_TOKEN_DESTROYER or // we burn own tokens or on behalf (in latest case we already checked and updated allowances) // we have left to execute balance checks and burning logic itself // non-zero burn value check require(_value != 0, "zero value burn"); // non-zero source address check - Zeppelin require(_from != address(0), "ERC20: burn from the zero address"); // Zeppelin msg // verify `_from` address has enough tokens to destroy // (basically this is a arithmetic overflow check) require(tokenBalances[_from] >= _value, "ERC20: burn amount exceeds balance"); // Zeppelin msg // perform burn: // decrease `_from` address balance tokenBalances[_from] -= _value; // decrease total amount of tokens value totalSupply -= _value; // destroy voting power associated with the tokens burnt __moveVotingPower(votingDelegates[_from], address(0), _value); // fire a burnt event emit Burnt(msg.sender, _from, _value); // emit an improved transfer event emit Transferred(msg.sender, _from, address(0), _value); // fire ERC20 compliant transfer event emit Transfer(_from, address(0), _value); } // ===== End: Minting/burning extension ===== // ===== Start: DAO Support (Compound-like voting delegation) ===== /** * @notice Gets current voting power of the account `_of` * @param _of the address of account to get voting power of * @return current cumulative voting power of the account, * sum of token balances of all its voting delegators */ function getVotingPower(address _of) public view returns (uint256) { // get a link to an array of voting power history records for an address specified VotingPowerRecord[] storage history = votingPowerHistory[_of]; // lookup the history and return latest element return history.length == 0? 0: history[history.length - 1].votingPower; } /** * @notice Gets past voting power of the account `_of` at some block `_blockNum` * @dev Throws if `_blockNum` is not in the past (not the finalized block) * @param _of the address of account to get voting power of * @param _blockNum block number to get the voting power at * @return past cumulative voting power of the account, * sum of token balances of all its voting delegators at block number `_blockNum` */ function getVotingPowerAt(address _of, uint256 _blockNum) public view returns (uint256) { // make sure block number is not in the past (not the finalized block) require(_blockNum < block.number, "not yet determined"); // Compound msg // get a link to an array of voting power history records for an address specified VotingPowerRecord[] storage history = votingPowerHistory[_of]; // if voting power history for the account provided is empty if(history.length == 0) { // than voting power is zero - return the result return 0; } // check latest voting power history record block number: // if history was not updated after the block of interest if(history[history.length - 1].blockNumber <= _blockNum) { // we're done - return last voting power record return getVotingPower(_of); } // check first voting power history record block number: // if history was never updated before the block of interest if(history[0].blockNumber > _blockNum) { // we're done - voting power at the block num of interest was zero return 0; } // `votingPowerHistory[_of]` is an array ordered by `blockNumber`, ascending; // apply binary search on `votingPowerHistory[_of]` to find such an entry number `i`, that // `votingPowerHistory[_of][i].blockNumber <= _blockNum`, but in the same time // `votingPowerHistory[_of][i + 1].blockNumber > _blockNum` // return the result - voting power found at index `i` return history[__binaryLookup(_of, _blockNum)].votingPower; } /** * @dev Reads an entire voting power history array for the delegate specified * * @param _of delegate to query voting power history for * @return voting power history array for the delegate of interest */ function getVotingPowerHistory(address _of) public view returns(VotingPowerRecord[] memory) { // return an entire array as memory return votingPowerHistory[_of]; } /** * @dev Returns length of the voting power history array for the delegate specified; * useful since reading an entire array just to get its length is expensive (gas cost) * * @param _of delegate to query voting power history length for * @return voting power history array length for the delegate of interest */ function getVotingPowerHistoryLength(address _of) public view returns(uint256) { // read array length and return return votingPowerHistory[_of].length; } /** * @notice Delegates voting power of the delegator `msg.sender` to the delegate `_to` * * @dev Accepts zero value address to delegate voting power to, effectively * removing the delegate in that case * * @param _to address to delegate voting power to */ function delegate(address _to) public { // verify delegations are enabled require(isFeatureEnabled(FEATURE_DELEGATIONS), "delegations are disabled"); // delegate call to `__delegate` __delegate(msg.sender, _to); } /** * @notice Delegates voting power of the delegator (represented by its signature) to the delegate `_to` * * @dev Accepts zero value address to delegate voting power to, effectively * removing the delegate in that case * * @dev Compliant with EIP-712: Ethereum typed structured data hashing and signing, * see https://eips.ethereum.org/EIPS/eip-712 * * @param _to address to delegate voting power to * @param _nonce nonce used to construct the signature, and used to validate it; * nonce is increased by one after successful signature validation and vote delegation * @param _exp signature expiration time * @param v the recovery byte of the signature * @param r half of the ECDSA signature pair * @param s half of the ECDSA signature pair */ function delegateWithSig(address _to, uint256 _nonce, uint256 _exp, uint8 v, bytes32 r, bytes32 s) public { // verify delegations on behalf are enabled require(isFeatureEnabled(FEATURE_DELEGATIONS_ON_BEHALF), "delegations on behalf are disabled"); // build the EIP-712 contract domain separator bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), block.chainid, address(this))); // build the EIP-712 hashStruct of the delegation message bytes32 hashStruct = keccak256(abi.encode(DELEGATION_TYPEHASH, _to, _nonce, _exp)); // calculate the EIP-712 digest "\x19\x01" ‖ domainSeparator ‖ hashStruct(message) bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, hashStruct)); // recover the address who signed the message with v, r, s address signer = ecrecover(digest, v, r, s); // perform message integrity and security validations require(signer != address(0), "invalid signature"); // Compound msg require(_nonce == nonces[signer], "invalid nonce"); // Compound msg require(block.timestamp < _exp, "signature expired"); // Compound msg // update the nonce for that particular signer to avoid replay attack nonces[signer]++; // delegate call to `__delegate` - execute the logic required __delegate(signer, _to); } /** * @dev Auxiliary function to delegate delegator's `_from` voting power to the delegate `_to` * @dev Writes to `votingDelegates` and `votingPowerHistory` mappings * * @param _from delegator who delegates his voting power * @param _to delegate who receives the voting power */ function __delegate(address _from, address _to) private { // read current delegate to be replaced by a new one address _fromDelegate = votingDelegates[_from]; // read current voting power (it is equal to token balance) uint256 _value = tokenBalances[_from]; // reassign voting delegate to `_to` votingDelegates[_from] = _to; // update voting power for `_fromDelegate` and `_to` __moveVotingPower(_fromDelegate, _to, _value); // emit an event emit DelegateChanged(_from, _fromDelegate, _to); } /** * @dev Auxiliary function to move voting power `_value` * from delegate `_from` to the delegate `_to` * * @dev Doesn't have any effect if `_from == _to`, or if `_value == 0` * * @param _from delegate to move voting power from * @param _to delegate to move voting power to * @param _value voting power to move from `_from` to `_to` */ function __moveVotingPower(address _from, address _to, uint256 _value) private { // if there is no move (`_from == _to`) or there is nothing to move (`_value == 0`) if(_from == _to || _value == 0) { // return silently with no action return; } // if source address is not zero - decrease its voting power if(_from != address(0)) { // read current source address voting power uint256 _fromVal = getVotingPower(_from); // calculate decreased voting power // underflow is not possible by design: // voting power is limited by token balance which is checked by the callee uint256 _toVal = _fromVal - _value; // update source voting power from `_fromVal` to `_toVal` __updateVotingPower(_from, _fromVal, _toVal); } // if destination address is not zero - increase its voting power if(_to != address(0)) { // read current destination address voting power uint256 _fromVal = getVotingPower(_to); // calculate increased voting power // overflow is not possible by design: // max token supply limits the cumulative voting power uint256 _toVal = _fromVal + _value; // update destination voting power from `_fromVal` to `_toVal` __updateVotingPower(_to, _fromVal, _toVal); } } /** * @dev Auxiliary function to update voting power of the delegate `_of` * from value `_fromVal` to value `_toVal` * * @param _of delegate to update its voting power * @param _fromVal old voting power of the delegate * @param _toVal new voting power of the delegate */ function __updateVotingPower(address _of, uint256 _fromVal, uint256 _toVal) private { // get a link to an array of voting power history records for an address specified VotingPowerRecord[] storage history = votingPowerHistory[_of]; // if there is an existing voting power value stored for current block if(history.length != 0 && history[history.length - 1].blockNumber == block.number) { // update voting power which is already stored in the current block history[history.length - 1].votingPower = uint192(_toVal); } // otherwise - if there is no value stored for current block else { // add new element into array representing the value for current block history.push(VotingPowerRecord(uint64(block.number), uint192(_toVal))); } // emit an event emit VotingPowerChanged(_of, _fromVal, _toVal); } /** * @dev Auxiliary function to lookup an element in a sorted (asc) array of elements * * @dev This function finds the closest element in an array to the value * of interest (not exceeding that value) and returns its index within an array * * @dev An array to search in is `votingPowerHistory[_to][i].blockNumber`, * it is sorted in ascending order (blockNumber increases) * * @param _to an address of the delegate to get an array for * @param n value of interest to look for * @return an index of the closest element in an array to the value * of interest (not exceeding that value) */ function __binaryLookup(address _to, uint256 n) private view returns(uint256) { // get a link to an array of voting power history records for an address specified VotingPowerRecord[] storage history = votingPowerHistory[_to]; // left bound of the search interval, originally start of the array uint256 i = 0; // right bound of the search interval, originally end of the array uint256 j = history.length - 1; // the iteration process narrows down the bounds by // splitting the interval in a half oce per each iteration while(j > i) { // get an index in the middle of the interval [i, j] uint256 k = j - (j - i) / 2; // read an element to compare it with the value of interest VotingPowerRecord memory cp = history[k]; // if we've got a strict equal - we're lucky and done if(cp.blockNumber == n) { // just return the result - index `k` return k; } // if the value of interest is bigger - move left bound to the middle else if (cp.blockNumber < n) { // move left bound `i` to the middle position `k` i = k; } // otherwise, when the value of interest is smaller - move right bound to the middle else { // move right bound `j` to the middle position `k - 1`: // element at position `k` is bigger and cannot be the result j = k - 1; } } // reaching that point means no exact match found // since we're interested in the element which is not bigger than the // element of interest, we return the lower bound `i` return i; } } // ===== End: DAO Support (Compound-like voting delegation) ===== /** * @title Illuvium Aware * * @notice Helper smart contract to be inherited by other smart contracts requiring to * be linked to verified IlluviumERC20 instance and performing some basic tasks on it * * @author Basil Gorin */ abstract contract IlluviumAware is ILinkedToILV { /// @dev Link to ILV ERC20 Token IlluviumERC20 instance address public immutable override ilv; /** * @dev Creates IlluviumAware instance, requiring to supply deployed IlluviumERC20 instance address * * @param _ilv deployed IlluviumERC20 instance address */ constructor(address _ilv) { // verify ILV address is set and is correct require(_ilv != address(0), "ILV address not set"); require(IlluviumERC20(_ilv).TOKEN_UID() == 0x83ecb176af7c4f35a45ff0018282e3a05a1018065da866182df12285866f5a2c, "unexpected TOKEN_UID"); // write ILV address ilv = _ilv; } /** * @dev Executes IlluviumERC20.safeTransferFrom(address(this), _to, _value, "") * on the bound IlluviumERC20 instance * * @dev Reentrancy safe due to the IlluviumERC20 design */ function transferIlv(address _to, uint256 _value) internal { // just delegate call to the target transferIlvFrom(address(this), _to, _value); } /** * @dev Executes IlluviumERC20.transferFrom(_from, _to, _value) * on the bound IlluviumERC20 instance * * @dev Reentrancy safe due to the IlluviumERC20 design */ function transferIlvFrom(address _from, address _to, uint256 _value) internal { // just delegate call to the target IlluviumERC20(ilv).transferFrom(_from, _to, _value); } /** * @dev Executes IlluviumERC20.mint(_to, _values) * on the bound IlluviumERC20 instance * * @dev Reentrancy safe due to the IlluviumERC20 design */ function mintIlv(address _to, uint256 _value) internal { // just delegate call to the target IlluviumERC20(ilv).mint(_to, _value); } } /** * @title Illuvium Pool Base * * @notice An abstract contract containing common logic for any pool, * be it a flash pool (temporary pool like SNX) or a core pool (permanent pool like ILV/ETH or ILV pool) * * @dev Deployment and initialization. * Any pool deployed must be bound to the deployed pool factory (IlluviumPoolFactory) * Additionally, 3 token instance addresses must be defined on deployment: * - ILV token address * - sILV token address, used to mint sILV rewards * - pool token address, it can be ILV token address, ILV/ETH pair address, and others * * @dev Pool weight defines the fraction of the yield current pool receives among the other pools, * pool factory is responsible for the weight synchronization between the pools. * @dev The weight is logically 10% for ILV pool and 90% for ILV/ETH pool. * Since Solidity doesn't support fractions the weight is defined by the division of * pool weight by total pools weight (sum of all registered pools within the factory) * @dev For ILV Pool we use 100 as weight and for ILV/ETH pool - 900. * * @author Pedro Bergamini, reviewed by Basil Gorin */ abstract contract IlluviumPoolBase is IPool, IlluviumAware, ReentrancyGuard { /// @dev Data structure representing token holder using a pool struct User { // @dev Total staked amount uint256 tokenAmount; // @dev Total weight uint256 totalWeight; // @dev Auxiliary variable for yield calculation uint256 subYieldRewards; // @dev Auxiliary variable for vault rewards calculation uint256 subVaultRewards; // @dev An array of holder's deposits Deposit[] deposits; } /// @dev Token holder storage, maps token holder address to their data record mapping(address => User) public users; /// @dev Link to sILV ERC20 Token EscrowedIlluviumERC20 instance address public immutable override silv; /// @dev Link to the pool factory IlluviumPoolFactory instance IlluviumPoolFactory public immutable factory; /// @dev Link to the pool token instance, for example ILV or ILV/ETH pair address public immutable override poolToken; /// @dev Pool weight, 100 for ILV pool or 900 for ILV/ETH uint32 public override weight; /// @dev Block number of the last yield distribution event uint64 public override lastYieldDistribution; /// @dev Used to calculate yield rewards /// @dev This value is different from "reward per token" used in locked pool /// @dev Note: stakes are different in duration and "weight" reflects that uint256 public override yieldRewardsPerWeight; /// @dev Used to calculate yield rewards, keeps track of the tokens weight locked in staking uint256 public override usersLockingWeight; /** * @dev Stake weight is proportional to deposit amount and time locked, precisely * "deposit amount wei multiplied by (fraction of the year locked plus one)" * @dev To avoid significant precision loss due to multiplication by "fraction of the year" [0, 1], * weight is stored multiplied by 1e6 constant, as an integer * @dev Corner case 1: if time locked is zero, weight is deposit amount multiplied by 1e6 * @dev Corner case 2: if time locked is one year, fraction of the year locked is one, and * weight is a deposit amount multiplied by 2 * 1e6 */ uint256 internal constant WEIGHT_MULTIPLIER = 1e6; /** * @dev When we know beforehand that staking is done for a year, and fraction of the year locked is one, * we use simplified calculation and use the following constant instead previos one */ uint256 internal constant YEAR_STAKE_WEIGHT_MULTIPLIER = 2 * WEIGHT_MULTIPLIER; /** * @dev Rewards per weight are stored multiplied by 1e12, as integers. */ uint256 internal constant REWARD_PER_WEIGHT_MULTIPLIER = 1e12; /** * @dev Fired in _stake() and stake() * * @param _by an address which performed an operation, usually token holder * @param _from token holder address, the tokens will be returned to that address * @param amount amount of tokens staked */ event Staked(address indexed _by, address indexed _from, uint256 amount); /** * @dev Fired in _updateStakeLock() and updateStakeLock() * * @param _by an address which performed an operation * @param depositId updated deposit ID * @param lockedFrom deposit locked from value * @param lockedUntil updated deposit locked until value */ event StakeLockUpdated(address indexed _by, uint256 depositId, uint64 lockedFrom, uint64 lockedUntil); /** * @dev Fired in _unstake() and unstake() * * @param _by an address which performed an operation, usually token holder * @param _to an address which received the unstaked tokens, usually token holder * @param amount amount of tokens unstaked */ event Unstaked(address indexed _by, address indexed _to, uint256 amount); /** * @dev Fired in _sync(), sync() and dependent functions (stake, unstake, etc.) * * @param _by an address which performed an operation * @param yieldRewardsPerWeight updated yield rewards per weight value * @param lastYieldDistribution usually, current block number */ event Synchronized(address indexed _by, uint256 yieldRewardsPerWeight, uint64 lastYieldDistribution); /** * @dev Fired in _processRewards(), processRewards() and dependent functions (stake, unstake, etc.) * * @param _by an address which performed an operation * @param _to an address which claimed the yield reward * @param sIlv flag indicating if reward was paid (minted) in sILV * @param amount amount of yield paid */ event YieldClaimed(address indexed _by, address indexed _to, bool sIlv, uint256 amount); /** * @dev Fired in setWeight() * * @param _by an address which performed an operation, always a factory * @param _fromVal old pool weight value * @param _toVal new pool weight value */ event PoolWeightUpdated(address indexed _by, uint32 _fromVal, uint32 _toVal); /** * @dev Overridden in sub-contracts to construct the pool * * @param _ilv ILV ERC20 Token IlluviumERC20 address * @param _silv sILV ERC20 Token EscrowedIlluviumERC20 address * @param _factory Pool factory IlluviumPoolFactory instance/address * @param _poolToken token the pool operates on, for example ILV or ILV/ETH pair * @param _initBlock initial block used to calculate the rewards * note: _initBlock can be set to the future effectively meaning _sync() calls will do nothing * @param _weight number representing a weight of the pool, actual weight fraction * is calculated as that number divided by the total pools weight and doesn't exceed one */ constructor( address _ilv, address _silv, IlluviumPoolFactory _factory, address _poolToken, uint64 _initBlock, uint32 _weight ) IlluviumAware(_ilv) { // verify the inputs are set require(_silv != address(0), "sILV address not set"); require(address(_factory) != address(0), "ILV Pool fct address not set"); require(_poolToken != address(0), "pool token address not set"); require(_initBlock > 0, "init block not set"); require(_weight > 0, "pool weight not set"); // verify sILV instance supplied require( EscrowedIlluviumERC20(_silv).TOKEN_UID() == 0xac3051b8d4f50966afb632468a4f61483ae6a953b74e387a01ef94316d6b7d62, "unexpected sILV TOKEN_UID" ); // verify IlluviumPoolFactory instance supplied require( _factory.FACTORY_UID() == 0xc5cfd88c6e4d7e5c8a03c255f03af23c0918d8e82cac196f57466af3fd4a5ec7, "unexpected FACTORY_UID" ); // save the inputs into internal state variables silv = _silv; factory = _factory; poolToken = _poolToken; weight = _weight; // init the dependent internal state variables lastYieldDistribution = _initBlock; } /** * @notice Calculates current yield rewards value available for address specified * * @param _staker an address to calculate yield rewards value for * @return calculated yield reward value for the given address */ function pendingYieldRewards(address _staker) external view override returns (uint256) { // `newYieldRewardsPerWeight` will store stored or recalculated value for `yieldRewardsPerWeight` uint256 newYieldRewardsPerWeight; // if smart contract state was not updated recently, `yieldRewardsPerWeight` value // is outdated and we need to recalculate it in order to calculate pending rewards correctly if (blockNumber() > lastYieldDistribution && usersLockingWeight != 0) { uint256 endBlock = factory.endBlock(); uint256 multiplier = blockNumber() > endBlock ? endBlock - lastYieldDistribution : blockNumber() - lastYieldDistribution; uint256 ilvRewards = (multiplier * weight * factory.ilvPerBlock()) / factory.totalWeight(); // recalculated value for `yieldRewardsPerWeight` newYieldRewardsPerWeight = rewardToWeight(ilvRewards, usersLockingWeight) + yieldRewardsPerWeight; } else { // if smart contract state is up to date, we don't recalculate newYieldRewardsPerWeight = yieldRewardsPerWeight; } // based on the rewards per weight value, calculate pending rewards; User memory user = users[_staker]; uint256 pending = weightToReward(user.totalWeight, newYieldRewardsPerWeight) - user.subYieldRewards; return pending; } /** * @notice Returns total staked token balance for the given address * * @param _user an address to query balance for * @return total staked token balance */ function balanceOf(address _user) external view override returns (uint256) { // read specified user token amount and return return users[_user].tokenAmount; } /** * @notice Returns information on the given deposit for the given address * * @dev See getDepositsLength * * @param _user an address to query deposit for * @param _depositId zero-indexed deposit ID for the address specified * @return deposit info as Deposit structure */ function getDeposit(address _user, uint256 _depositId) external view override returns (Deposit memory) { // read deposit at specified index and return return users[_user].deposits[_depositId]; } /** * @notice Returns number of deposits for the given address. Allows iteration over deposits. * * @dev See getDeposit * * @param _user an address to query deposit length for * @return number of deposits for the given address */ function getDepositsLength(address _user) external view override returns (uint256) { // read deposits array length and return return users[_user].deposits.length; } /** * @notice Stakes specified amount of tokens for the specified amount of time, * and pays pending yield rewards if any * * @dev Requires amount to stake to be greater than zero * * @param _amount amount of tokens to stake * @param _lockUntil stake period as unix timestamp; zero means no locking * @param _useSILV a flag indicating if previous reward to be paid as sILV */ function stake( uint256 _amount, uint64 _lockUntil, bool _useSILV ) external override { // delegate call to an internal function _stake(msg.sender, _amount, _lockUntil, _useSILV, false); } /** * @notice Unstakes specified amount of tokens, and pays pending yield rewards if any * * @dev Requires amount to unstake to be greater than zero * * @param _depositId deposit ID to unstake from, zero-indexed * @param _amount amount of tokens to unstake * @param _useSILV a flag indicating if reward to be paid as sILV */ function unstake( uint256 _depositId, uint256 _amount, bool _useSILV ) external override { // delegate call to an internal function _unstake(msg.sender, _depositId, _amount, _useSILV); } /** * @notice Extends locking period for a given deposit * * @dev Requires new lockedUntil value to be: * higher than the current one, and * in the future, but * no more than 1 year in the future * * @param depositId updated deposit ID * @param lockedUntil updated deposit locked until value * @param useSILV used for _processRewards check if it should use ILV or sILV */ function updateStakeLock( uint256 depositId, uint64 lockedUntil, bool useSILV ) external { // sync and call processRewards _sync(); _processRewards(msg.sender, useSILV, false); // delegate call to an internal function _updateStakeLock(msg.sender, depositId, lockedUntil); } /** * @notice Service function to synchronize pool state with current time * * @dev Can be executed by anyone at any time, but has an effect only when * at least one block passes between synchronizations * @dev Executed internally when staking, unstaking, processing rewards in order * for calculations to be correct and to reflect state progress of the contract * @dev When timing conditions are not met (executed too frequently, or after factory * end block), function doesn't throw and exits silently */ function sync() external override { // delegate call to an internal function _sync(); } /** * @notice Service function to calculate and pay pending yield rewards to the sender * * @dev Can be executed by anyone at any time, but has an effect only when * executed by deposit holder and when at least one block passes from the * previous reward processing * @dev Executed internally when staking and unstaking, executes sync() under the hood * before making further calculations and payouts * @dev When timing conditions are not met (executed too frequently, or after factory * end block), function doesn't throw and exits silently * * @param _useSILV flag indicating whether to mint sILV token as a reward or not; * when set to true - sILV reward is minted immediately and sent to sender, * when set to false - new ILV reward deposit gets created if pool is an ILV pool * (poolToken is ILV token), or new pool deposit gets created together with sILV minted * when pool is not an ILV pool (poolToken is not an ILV token) */ function processRewards(bool _useSILV) external virtual override { // delegate call to an internal function _processRewards(msg.sender, _useSILV, true); } /** * @dev Executed by the factory to modify pool weight; the factory is expected * to keep track of the total pools weight when updating * * @dev Set weight to zero to disable the pool * * @param _weight new weight to set for the pool */ function setWeight(uint32 _weight) external override { // verify function is executed by the factory require(msg.sender == address(factory), "access denied"); // emit an event logging old and new weight values emit PoolWeightUpdated(msg.sender, weight, _weight); // set the new weight value weight = _weight; } /** * @dev Similar to public pendingYieldRewards, but performs calculations based on * current smart contract state only, not taking into account any additional * time/blocks which might have passed * * @param _staker an address to calculate yield rewards value for * @return pending calculated yield reward value for the given address */ function _pendingYieldRewards(address _staker) internal view returns (uint256 pending) { // read user data structure into memory User memory user = users[_staker]; // and perform the calculation using the values read return weightToReward(user.totalWeight, yieldRewardsPerWeight) - user.subYieldRewards; } /** * @dev Used internally, mostly by children implementations, see stake() * * @param _staker an address which stakes tokens and which will receive them back * @param _amount amount of tokens to stake * @param _lockUntil stake period as unix timestamp; zero means no locking * @param _useSILV a flag indicating if previous reward to be paid as sILV * @param _isYield a flag indicating if that stake is created to store yield reward * from the previously unstaked stake */ function _stake( address _staker, uint256 _amount, uint64 _lockUntil, bool _useSILV, bool _isYield ) internal virtual { // validate the inputs require(_amount > 0, "zero amount"); require( _lockUntil == 0 || (_lockUntil > now256() && _lockUntil - now256() <= 365 days), "invalid lock interval" ); // update smart contract state _sync(); // get a link to user data struct, we will write to it later User storage user = users[_staker]; // process current pending rewards if any if (user.tokenAmount > 0) { _processRewards(_staker, _useSILV, false); } // in most of the cases added amount `addedAmount` is simply `_amount` // however for deflationary tokens this can be different // read the current balance uint256 previousBalance = IERC20(poolToken).balanceOf(address(this)); // transfer `_amount`; note: some tokens may get burnt here transferPoolTokenFrom(address(msg.sender), address(this), _amount); // read new balance, usually this is just the difference `previousBalance - _amount` uint256 newBalance = IERC20(poolToken).balanceOf(address(this)); // calculate real amount taking into account deflation uint256 addedAmount = newBalance - previousBalance; // set the `lockFrom` and `lockUntil` taking into account that // zero value for `_lockUntil` means "no locking" and leads to zero values // for both `lockFrom` and `lockUntil` uint64 lockFrom = _lockUntil > 0 ? uint64(now256()) : 0; uint64 lockUntil = _lockUntil; // stake weight formula rewards for locking uint256 stakeWeight = (((lockUntil - lockFrom) * WEIGHT_MULTIPLIER) / 365 days + WEIGHT_MULTIPLIER) * addedAmount; // makes sure stakeWeight is valid assert(stakeWeight > 0); // create and save the deposit (append it to deposits array) Deposit memory deposit = Deposit({ tokenAmount: addedAmount, weight: stakeWeight, lockedFrom: lockFrom, lockedUntil: lockUntil, isYield: _isYield }); // deposit ID is an index of the deposit in `deposits` array user.deposits.push(deposit); // update user record user.tokenAmount += addedAmount; user.totalWeight += stakeWeight; user.subYieldRewards = weightToReward(user.totalWeight, yieldRewardsPerWeight); // update global variable usersLockingWeight += stakeWeight; // emit an event emit Staked(msg.sender, _staker, _amount); } /** * @dev Used internally, mostly by children implementations, see unstake() * * @param _staker an address which unstakes tokens (which previously staked them) * @param _depositId deposit ID to unstake from, zero-indexed * @param _amount amount of tokens to unstake * @param _useSILV a flag indicating if reward to be paid as sILV */ function _unstake( address _staker, uint256 _depositId, uint256 _amount, bool _useSILV ) internal virtual { // verify an amount is set require(_amount > 0, "zero amount"); // get a link to user data struct, we will write to it later User storage user = users[_staker]; // get a link to the corresponding deposit, we may write to it later Deposit storage stakeDeposit = user.deposits[_depositId]; // deposit structure may get deleted, so we save isYield flag to be able to use it bool isYield = stakeDeposit.isYield; // verify available balance // if staker address ot deposit doesn't exist this check will fail as well require(stakeDeposit.tokenAmount >= _amount, "amount exceeds stake"); // update smart contract state _sync(); // and process current pending rewards if any _processRewards(_staker, _useSILV, false); // recalculate deposit weight uint256 previousWeight = stakeDeposit.weight; uint256 newWeight = (((stakeDeposit.lockedUntil - stakeDeposit.lockedFrom) * WEIGHT_MULTIPLIER) / 365 days + WEIGHT_MULTIPLIER) * (stakeDeposit.tokenAmount - _amount); // update the deposit, or delete it if its depleted if (stakeDeposit.tokenAmount - _amount == 0) { delete user.deposits[_depositId]; } else { stakeDeposit.tokenAmount -= _amount; stakeDeposit.weight = newWeight; } // update user record user.tokenAmount -= _amount; user.totalWeight = user.totalWeight - previousWeight + newWeight; user.subYieldRewards = weightToReward(user.totalWeight, yieldRewardsPerWeight); // update global variable usersLockingWeight = usersLockingWeight - previousWeight + newWeight; // if the deposit was created by the pool itself as a yield reward if (isYield) { // mint the yield via the factory factory.mintYieldTo(msg.sender, _amount); } else { // otherwise just return tokens back to holder transferPoolToken(msg.sender, _amount); } // emit an event emit Unstaked(msg.sender, _staker, _amount); } /** * @dev Used internally, mostly by children implementations, see sync() * * @dev Updates smart contract state (`yieldRewardsPerWeight`, `lastYieldDistribution`), * updates factory state via `updateILVPerBlock` */ function _sync() internal virtual { // update ILV per block value in factory if required if (factory.shouldUpdateRatio()) { factory.updateILVPerBlock(); } // check bound conditions and if these are not met - // exit silently, without emitting an event uint256 endBlock = factory.endBlock(); if (lastYieldDistribution >= endBlock) { return; } if (blockNumber() <= lastYieldDistribution) { return; } // if locking weight is zero - update only `lastYieldDistribution` and exit if (usersLockingWeight == 0) { lastYieldDistribution = uint64(blockNumber()); return; } // to calculate the reward we need to know how many blocks passed, and reward per block uint256 currentBlock = blockNumber() > endBlock ? endBlock : blockNumber(); uint256 blocksPassed = currentBlock - lastYieldDistribution; uint256 ilvPerBlock = factory.ilvPerBlock(); // calculate the reward uint256 ilvReward = (blocksPassed * ilvPerBlock * weight) / factory.totalWeight(); // update rewards per weight and `lastYieldDistribution` yieldRewardsPerWeight += rewardToWeight(ilvReward, usersLockingWeight); lastYieldDistribution = uint64(currentBlock); // emit an event emit Synchronized(msg.sender, yieldRewardsPerWeight, lastYieldDistribution); } /** * @dev Used internally, mostly by children implementations, see processRewards() * * @param _staker an address which receives the reward (which has staked some tokens earlier) * @param _useSILV flag indicating whether to mint sILV token as a reward or not, see processRewards() * @param _withUpdate flag allowing to disable synchronization (see sync()) if set to false * @return pendingYield the rewards calculated and optionally re-staked */ function _processRewards( address _staker, bool _useSILV, bool _withUpdate ) internal virtual returns (uint256 pendingYield) { // update smart contract state if required if (_withUpdate) { _sync(); } // calculate pending yield rewards, this value will be returned pendingYield = _pendingYieldRewards(_staker); // if pending yield is zero - just return silently if (pendingYield == 0) return 0; // get link to a user data structure, we will write into it later User storage user = users[_staker]; // if sILV is requested if (_useSILV) { // - mint sILV mintSIlv(_staker, pendingYield); } else if (poolToken == ilv) { // calculate pending yield weight, // 2e6 is the bonus weight when staking for 1 year uint256 depositWeight = pendingYield * YEAR_STAKE_WEIGHT_MULTIPLIER; // if the pool is ILV Pool - create new ILV deposit // and save it - push it into deposits array Deposit memory newDeposit = Deposit({ tokenAmount: pendingYield, lockedFrom: uint64(now256()), lockedUntil: uint64(now256() + 365 days), // staking yield for 1 year weight: depositWeight, isYield: true }); user.deposits.push(newDeposit); // update user record user.tokenAmount += pendingYield; user.totalWeight += depositWeight; // update global variable usersLockingWeight += depositWeight; } else { // for other pools - stake as pool address ilvPool = factory.getPoolAddress(ilv); ICorePool(ilvPool).stakeAsPool(_staker, pendingYield); } // update users's record for `subYieldRewards` if requested if (_withUpdate) { user.subYieldRewards = weightToReward(user.totalWeight, yieldRewardsPerWeight); } // emit an event emit YieldClaimed(msg.sender, _staker, _useSILV, pendingYield); } /** * @dev See updateStakeLock() * * @param _staker an address to update stake lock * @param _depositId updated deposit ID * @param _lockedUntil updated deposit locked until value */ function _updateStakeLock( address _staker, uint256 _depositId, uint64 _lockedUntil ) internal { // validate the input time require(_lockedUntil > now256(), "lock should be in the future"); // get a link to user data struct, we will write to it later User storage user = users[_staker]; // get a link to the corresponding deposit, we may write to it later Deposit storage stakeDeposit = user.deposits[_depositId]; // validate the input against deposit structure require(_lockedUntil > stakeDeposit.lockedUntil, "invalid new lock"); // verify locked from and locked until values if (stakeDeposit.lockedFrom == 0) { require(_lockedUntil - now256() <= 365 days, "max lock period is 365 days"); stakeDeposit.lockedFrom = uint64(now256()); } else { require(_lockedUntil - stakeDeposit.lockedFrom <= 365 days, "max lock period is 365 days"); } // update locked until value, calculate new weight stakeDeposit.lockedUntil = _lockedUntil; uint256 newWeight = (((stakeDeposit.lockedUntil - stakeDeposit.lockedFrom) * WEIGHT_MULTIPLIER) / 365 days + WEIGHT_MULTIPLIER) * stakeDeposit.tokenAmount; // save previous weight uint256 previousWeight = stakeDeposit.weight; // update weight stakeDeposit.weight = newWeight; // update user total weight and global locking weight user.totalWeight = user.totalWeight - previousWeight + newWeight; usersLockingWeight = usersLockingWeight - previousWeight + newWeight; // emit an event emit StakeLockUpdated(_staker, _depositId, stakeDeposit.lockedFrom, _lockedUntil); } /** * @dev Converts stake weight (not to be mixed with the pool weight) to * ILV reward value, applying the 10^12 division on weight * * @param _weight stake weight * @param rewardPerWeight ILV reward per weight * @return reward value normalized to 10^12 */ function weightToReward(uint256 _weight, uint256 rewardPerWeight) public pure returns (uint256) { // apply the formula and return return (_weight * rewardPerWeight) / REWARD_PER_WEIGHT_MULTIPLIER; } /** * @dev Converts reward ILV value to stake weight (not to be mixed with the pool weight), * applying the 10^12 multiplication on the reward * - OR - * @dev Converts reward ILV value to reward/weight if stake weight is supplied as second * function parameter instead of reward/weight * * @param reward yield reward * @param rewardPerWeight reward/weight (or stake weight) * @return stake weight (or reward/weight) */ function rewardToWeight(uint256 reward, uint256 rewardPerWeight) public pure returns (uint256) { // apply the reverse formula and return return (reward * REWARD_PER_WEIGHT_MULTIPLIER) / rewardPerWeight; } /** * @dev Testing time-dependent functionality is difficult and the best way of * doing it is to override block number in helper test smart contracts * * @return `block.number` in mainnet, custom values in testnets (if overridden) */ function blockNumber() public view virtual returns (uint256) { // return current block number return block.number; } /** * @dev Testing time-dependent functionality is difficult and the best way of * doing it is to override time in helper test smart contracts * * @return `block.timestamp` in mainnet, custom values in testnets (if overridden) */ function now256() public view virtual returns (uint256) { // return current block timestamp return block.timestamp; } /** * @dev Executes EscrowedIlluviumERC20.mint(_to, _values) * on the bound EscrowedIlluviumERC20 instance * * @dev Reentrancy safe due to the EscrowedIlluviumERC20 design */ function mintSIlv(address _to, uint256 _value) private { // just delegate call to the target EscrowedIlluviumERC20(silv).mint(_to, _value); } /** * @dev Executes SafeERC20.safeTransfer on a pool token * * @dev Reentrancy safety enforced via `ReentrancyGuard.nonReentrant` */ function transferPoolToken(address _to, uint256 _value) internal nonReentrant { // just delegate call to the target SafeERC20.safeTransfer(IERC20(poolToken), _to, _value); } /** * @dev Executes SafeERC20.safeTransferFrom on a pool token * * @dev Reentrancy safety enforced via `ReentrancyGuard.nonReentrant` */ function transferPoolTokenFrom( address _from, address _to, uint256 _value ) internal nonReentrant { // just delegate call to the target SafeERC20.safeTransferFrom(IERC20(poolToken), _from, _to, _value); } } /** * @title Illuvium Core Pool * * @notice Core pools represent permanent pools like ILV or ILV/ETH Pair pool, * core pools allow staking for arbitrary periods of time up to 1 year * * @dev See IlluviumPoolBase for more details * * @author Pedro Bergamini, reviewed by Basil Gorin */ contract IlluviumCorePool is IlluviumPoolBase { /// @dev Flag indicating pool type, false means "core pool" bool public constant override isFlashPool = false; /// @dev Link to deployed IlluviumVault instance address public vault; /// @dev Used to calculate vault rewards /// @dev This value is different from "reward per token" used in locked pool /// @dev Note: stakes are different in duration and "weight" reflects that uint256 public vaultRewardsPerWeight; /// @dev Pool tokens value available in the pool; /// pool token examples are ILV (ILV core pool) or ILV/ETH pair (LP core pool) /// @dev For LP core pool this value doesnt' count for ILV tokens received as Vault rewards /// while for ILV core pool it does count for such tokens as well uint256 public poolTokenReserve; /** * @dev Fired in receiveVaultRewards() * * @param _by an address that sent the rewards, always a vault * @param amount amount of tokens received */ event VaultRewardsReceived(address indexed _by, uint256 amount); /** * @dev Fired in _processVaultRewards() and dependent functions, like processRewards() * * @param _by an address which executed the function * @param _to an address which received a reward * @param amount amount of reward received */ event VaultRewardsClaimed(address indexed _by, address indexed _to, uint256 amount); /** * @dev Fired in setVault() * * @param _by an address which executed the function, always a factory owner */ event VaultUpdated(address indexed _by, address _fromVal, address _toVal); /** * @dev Creates/deploys an instance of the core pool * * @param _ilv ILV ERC20 Token IlluviumERC20 address * @param _silv sILV ERC20 Token EscrowedIlluviumERC20 address * @param _factory Pool factory IlluviumPoolFactory instance/address * @param _poolToken token the pool operates on, for example ILV or ILV/ETH pair * @param _initBlock initial block used to calculate the rewards * @param _weight number representing a weight of the pool, actual weight fraction * is calculated as that number divided by the total pools weight and doesn't exceed one */ constructor( address _ilv, address _silv, IlluviumPoolFactory _factory, address _poolToken, uint64 _initBlock, uint32 _weight ) IlluviumPoolBase(_ilv, _silv, _factory, _poolToken, _initBlock, _weight) {} /** * @notice Calculates current vault rewards value available for address specified * * @dev Performs calculations based on current smart contract state only, * not taking into account any additional time/blocks which might have passed * * @param _staker an address to calculate vault rewards value for * @return pending calculated vault reward value for the given address */ function pendingVaultRewards(address _staker) public view returns (uint256 pending) { User memory user = users[_staker]; return weightToReward(user.totalWeight, vaultRewardsPerWeight) - user.subVaultRewards; } /** * @dev Executed only by the factory owner to Set the vault * * @param _vault an address of deployed IlluviumVault instance */ function setVault(address _vault) external { // verify function is executed by the factory owner require(factory.owner() == msg.sender, "access denied"); // verify input is set require(_vault != address(0), "zero input"); // emit an event emit VaultUpdated(msg.sender, vault, _vault); // update vault address vault = _vault; } /** * @dev Executed by the vault to transfer vault rewards ILV from the vault * into the pool * * @dev This function is executed only for ILV core pools * * @param _rewardsAmount amount of ILV rewards to transfer into the pool */ function receiveVaultRewards(uint256 _rewardsAmount) external { require(msg.sender == vault, "access denied"); // return silently if there is no reward to receive if (_rewardsAmount == 0) { return; } require(usersLockingWeight > 0, "zero locking weight"); transferIlvFrom(msg.sender, address(this), _rewardsAmount); vaultRewardsPerWeight += rewardToWeight(_rewardsAmount, usersLockingWeight); // update `poolTokenReserve` only if this is a ILV Core Pool if (poolToken == ilv) { poolTokenReserve += _rewardsAmount; } emit VaultRewardsReceived(msg.sender, _rewardsAmount); } /** * @notice Service function to calculate and pay pending vault and yield rewards to the sender * * @dev Internally executes similar function `_processRewards` from the parent smart contract * to calculate and pay yield rewards; adds vault rewards processing * * @dev Can be executed by anyone at any time, but has an effect only when * executed by deposit holder and when at least one block passes from the * previous reward processing * @dev Executed internally when "staking as a pool" (`stakeAsPool`) * @dev When timing conditions are not met (executed too frequently, or after factory * end block), function doesn't throw and exits silently * * @dev _useSILV flag has a context of yield rewards only * * @param _useSILV flag indicating whether to mint sILV token as a reward or not; * when set to true - sILV reward is minted immediately and sent to sender, * when set to false - new ILV reward deposit gets created if pool is an ILV pool * (poolToken is ILV token), or new pool deposit gets created together with sILV minted * when pool is not an ILV pool (poolToken is not an ILV token) */ function processRewards(bool _useSILV) external override { _processRewards(msg.sender, _useSILV, true); } /** * @dev Executed internally by the pool itself (from the parent `IlluviumPoolBase` smart contract) * as part of yield rewards processing logic (`IlluviumPoolBase._processRewards` function) * @dev Executed when _useSILV is false and pool is not an ILV pool - see `IlluviumPoolBase._processRewards` * * @param _staker an address which stakes (the yield reward) * @param _amount amount to be staked (yield reward amount) */ function stakeAsPool(address _staker, uint256 _amount) external { require(factory.poolExists(msg.sender), "access denied"); _sync(); User storage user = users[_staker]; if (user.tokenAmount > 0) { _processRewards(_staker, true, false); } uint256 depositWeight = _amount * YEAR_STAKE_WEIGHT_MULTIPLIER; Deposit memory newDeposit = Deposit({ tokenAmount: _amount, lockedFrom: uint64(now256()), lockedUntil: uint64(now256() + 365 days), weight: depositWeight, isYield: true }); user.tokenAmount += _amount; user.totalWeight += depositWeight; user.deposits.push(newDeposit); usersLockingWeight += depositWeight; user.subYieldRewards = weightToReward(user.totalWeight, yieldRewardsPerWeight); user.subVaultRewards = weightToReward(user.totalWeight, vaultRewardsPerWeight); // update `poolTokenReserve` only if this is a LP Core Pool (stakeAsPool can be executed only for LP pool) poolTokenReserve += _amount; } /** * @inheritdoc IlluviumPoolBase * * @dev Additionally to the parent smart contract, updates vault rewards of the holder, * and updates (increases) pool token reserve (pool tokens value available in the pool) */ function _stake( address _staker, uint256 _amount, uint64 _lockedUntil, bool _useSILV, bool _isYield ) internal override { super._stake(_staker, _amount, _lockedUntil, _useSILV, _isYield); User storage user = users[_staker]; user.subVaultRewards = weightToReward(user.totalWeight, vaultRewardsPerWeight); poolTokenReserve += _amount; } /** * @inheritdoc IlluviumPoolBase * * @dev Additionally to the parent smart contract, updates vault rewards of the holder, * and updates (decreases) pool token reserve (pool tokens value available in the pool) */ function _unstake( address _staker, uint256 _depositId, uint256 _amount, bool _useSILV ) internal override { User storage user = users[_staker]; Deposit memory stakeDeposit = user.deposits[_depositId]; require(stakeDeposit.lockedFrom == 0 || now256() > stakeDeposit.lockedUntil, "deposit not yet unlocked"); poolTokenReserve -= _amount; super._unstake(_staker, _depositId, _amount, _useSILV); user.subVaultRewards = weightToReward(user.totalWeight, vaultRewardsPerWeight); } /** * @inheritdoc IlluviumPoolBase * * @dev Additionally to the parent smart contract, processes vault rewards of the holder, * and for ILV pool updates (increases) pool token reserve (pool tokens value available in the pool) */ function _processRewards( address _staker, bool _useSILV, bool _withUpdate ) internal override returns (uint256 pendingYield) { _processVaultRewards(_staker); pendingYield = super._processRewards(_staker, _useSILV, _withUpdate); // update `poolTokenReserve` only if this is a ILV Core Pool if (poolToken == ilv && !_useSILV) { poolTokenReserve += pendingYield; } } /** * @dev Used internally to process vault rewards for the staker * * @param _staker address of the user (staker) to process rewards for */ function _processVaultRewards(address _staker) private { User storage user = users[_staker]; uint256 pendingVaultClaim = pendingVaultRewards(_staker); if (pendingVaultClaim == 0) return; // read ILV token balance of the pool via standard ERC20 interface uint256 ilvBalance = IERC20(ilv).balanceOf(address(this)); require(ilvBalance >= pendingVaultClaim, "contract ILV balance too low"); // update `poolTokenReserve` only if this is a ILV Core Pool if (poolToken == ilv) { // protects against rounding errors poolTokenReserve -= pendingVaultClaim > poolTokenReserve ? poolTokenReserve : pendingVaultClaim; } user.subVaultRewards = weightToReward(user.totalWeight, vaultRewardsPerWeight); // transfer fails if pool ILV balance is not enough - which is a desired behavior transferIlv(_staker, pendingVaultClaim); emit VaultRewardsClaimed(msg.sender, _staker, pendingVaultClaim); } } /** * @title Illuvium Pool Factory * * @notice ILV Pool Factory manages Illuvium Yield farming pools, provides a single * public interface to access the pools, provides an interface for the pools * to mint yield rewards, access pool-related info, update weights, etc. * * @notice The factory is authorized (via its owner) to register new pools, change weights * of the existing pools, removing the pools (by changing their weights to zero) * * @dev The factory requires ROLE_TOKEN_CREATOR permission on the ILV token to mint yield * (see `mintYieldTo` function) * * @author Pedro Bergamini, reviewed by Basil Gorin */ contract IlluviumPoolFactory is Ownable, IlluviumAware { /** * @dev Smart contract unique identifier, a random number * @dev Should be regenerated each time smart contact source code is changed * and changes smart contract itself is to be redeployed * @dev Generated using https://www.random.org/bytes/ */ uint256 public constant FACTORY_UID = 0xc5cfd88c6e4d7e5c8a03c255f03af23c0918d8e82cac196f57466af3fd4a5ec7; /// @dev Auxiliary data structure used only in getPoolData() view function struct PoolData { // @dev pool token address (like ILV) address poolToken; // @dev pool address (like deployed core pool instance) address poolAddress; // @dev pool weight (200 for ILV pools, 800 for ILV/ETH pools - set during deployment) uint32 weight; // @dev flash pool flag bool isFlashPool; } /** * @dev ILV/block determines yield farming reward base * used by the yield pools controlled by the factory */ uint192 public ilvPerBlock; /** * @dev The yield is distributed proportionally to pool weights; * total weight is here to help in determining the proportion */ uint32 public totalWeight; /** * @dev ILV/block decreases by 3% every blocks/update (set to 91252 blocks during deployment); * an update is triggered by executing `updateILVPerBlock` public function */ uint32 public immutable blocksPerUpdate; /** * @dev End block is the last block when ILV/block can be decreased; * it is implied that yield farming stops after that block */ uint32 public endBlock; /** * @dev Each time the ILV/block ratio gets updated, the block number * when the operation has occurred gets recorded into `lastRatioUpdate` * @dev This block number is then used to check if blocks/update `blocksPerUpdate` * has passed when decreasing yield reward by 3% */ uint32 public lastRatioUpdate; /// @dev sILV token address is used to create ILV core pool(s) address public immutable silv; /// @dev Maps pool token address (like ILV) -> pool address (like core pool instance) mapping(address => address) public pools; /// @dev Keeps track of registered pool addresses, maps pool address -> exists flag mapping(address => bool) public poolExists; /** * @dev Fired in createPool() and registerPool() * * @param _by an address which executed an action * @param poolToken pool token address (like ILV) * @param poolAddress deployed pool instance address * @param weight pool weight * @param isFlashPool flag indicating if pool is a flash pool */ event PoolRegistered( address indexed _by, address indexed poolToken, address indexed poolAddress, uint64 weight, bool isFlashPool ); /** * @dev Fired in changePoolWeight() * * @param _by an address which executed an action * @param poolAddress deployed pool instance address * @param weight new pool weight */ event WeightUpdated(address indexed _by, address indexed poolAddress, uint32 weight); /** * @dev Fired in updateILVPerBlock() * * @param _by an address which executed an action * @param newIlvPerBlock new ILV/block value */ event IlvRatioUpdated(address indexed _by, uint256 newIlvPerBlock); /** * @dev Creates/deploys a factory instance * * @param _ilv ILV ERC20 token address * @param _silv sILV ERC20 token address * @param _ilvPerBlock initial ILV/block value for rewards * @param _blocksPerUpdate how frequently the rewards gets updated (decreased by 3%), blocks * @param _initBlock block number to measure _blocksPerUpdate from * @param _endBlock block number when farming stops and rewards cannot be updated anymore */ constructor( address _ilv, address _silv, uint192 _ilvPerBlock, uint32 _blocksPerUpdate, uint32 _initBlock, uint32 _endBlock ) IlluviumAware(_ilv) { // verify the inputs are set require(_silv != address(0), "sILV address not set"); require(_ilvPerBlock > 0, "ILV/block not set"); require(_blocksPerUpdate > 0, "blocks/update not set"); require(_initBlock > 0, "init block not set"); require(_endBlock > _initBlock, "invalid end block: must be greater than init block"); // verify sILV instance supplied require( EscrowedIlluviumERC20(_silv).TOKEN_UID() == 0xac3051b8d4f50966afb632468a4f61483ae6a953b74e387a01ef94316d6b7d62, "unexpected sILV TOKEN_UID" ); // save the inputs into internal state variables silv = _silv; ilvPerBlock = _ilvPerBlock; blocksPerUpdate = _blocksPerUpdate; lastRatioUpdate = _initBlock; endBlock = _endBlock; } /** * @notice Given a pool token retrieves corresponding pool address * * @dev A shortcut for `pools` mapping * * @param poolToken pool token address (like ILV) to query pool address for * @return pool address for the token specified */ function getPoolAddress(address poolToken) external view returns (address) { // read the mapping and return return pools[poolToken]; } /** * @notice Reads pool information for the pool defined by its pool token address, * designed to simplify integration with the front ends * * @param _poolToken pool token address to query pool information for * @return pool information packed in a PoolData struct */ function getPoolData(address _poolToken) public view returns (PoolData memory) { // get the pool address from the mapping address poolAddr = pools[_poolToken]; // throw if there is no pool registered for the token specified require(poolAddr != address(0), "pool not found"); // read pool information from the pool smart contract // via the pool interface (IPool) address poolToken = IPool(poolAddr).poolToken(); bool isFlashPool = IPool(poolAddr).isFlashPool(); uint32 weight = IPool(poolAddr).weight(); // create the in-memory structure and return it return PoolData({ poolToken: poolToken, poolAddress: poolAddr, weight: weight, isFlashPool: isFlashPool }); } /** * @dev Verifies if `blocksPerUpdate` has passed since last ILV/block * ratio update and if ILV/block reward can be decreased by 3% * * @return true if enough time has passed and `updateILVPerBlock` can be executed */ function shouldUpdateRatio() public view returns (bool) { // if yield farming period has ended if (blockNumber() > endBlock) { // ILV/block reward cannot be updated anymore return false; } // check if blocks/update (91252 blocks) have passed since last update return blockNumber() >= lastRatioUpdate + blocksPerUpdate; } /** * @dev Creates a core pool (IlluviumCorePool) and registers it within the factory * * @dev Can be executed by the pool factory owner only * * @param poolToken pool token address (like ILV, or ILV/ETH pair) * @param initBlock init block to be used for the pool created * @param weight weight of the pool to be created */ function createPool( address poolToken, uint64 initBlock, uint32 weight ) external virtual onlyOwner { // create/deploy new core pool instance IPool pool = new IlluviumCorePool(ilv, silv, this, poolToken, initBlock, weight); // register it within a factory registerPool(address(pool)); } /** * @dev Registers an already deployed pool instance within the factory * * @dev Can be executed by the pool factory owner only * * @param poolAddr address of the already deployed pool instance */ function registerPool(address poolAddr) public onlyOwner { // read pool information from the pool smart contract // via the pool interface (IPool) address poolToken = IPool(poolAddr).poolToken(); bool isFlashPool = IPool(poolAddr).isFlashPool(); uint32 weight = IPool(poolAddr).weight(); // ensure that the pool is not already registered within the factory require(pools[poolToken] == address(0), "this pool is already registered"); // create pool structure, register it within the factory pools[poolToken] = poolAddr; poolExists[poolAddr] = true; // update total pool weight of the factory totalWeight += weight; // emit an event emit PoolRegistered(msg.sender, poolToken, poolAddr, weight, isFlashPool); } /** * @notice Decreases ILV/block reward by 3%, can be executed * no more than once per `blocksPerUpdate` blocks */ function updateILVPerBlock() external { // checks if ratio can be updated i.e. if blocks/update (91252 blocks) have passed require(shouldUpdateRatio(), "too frequent"); // decreases ILV/block reward by 3% ilvPerBlock = (ilvPerBlock * 97) / 100; // set current block as the last ratio update block lastRatioUpdate = uint32(blockNumber()); // emit an event emit IlvRatioUpdated(msg.sender, ilvPerBlock); } /** * @dev Mints ILV tokens; executed by ILV Pool only * * @dev Requires factory to have ROLE_TOKEN_CREATOR permission * on the ILV ERC20 token instance * * @param _to an address to mint tokens to * @param _amount amount of ILV tokens to mint */ function mintYieldTo(address _to, uint256 _amount) external { // verify that sender is a pool registered withing the factory require(poolExists[msg.sender], "access denied"); // mint ILV tokens as required mintIlv(_to, _amount); } /** * @dev Changes the weight of the pool; * executed by the pool itself or by the factory owner * * @param poolAddr address of the pool to change weight for * @param weight new weight value to set to */ function changePoolWeight(address poolAddr, uint32 weight) external { // verify function is executed either by factory owner or by the pool itself require(msg.sender == owner() || poolExists[msg.sender]); // recalculate total weight totalWeight = totalWeight + weight - IPool(poolAddr).weight(); // set the new pool weight IPool(poolAddr).setWeight(weight); // emit an event emit WeightUpdated(msg.sender, poolAddr, weight); } /** * @dev Testing time-dependent functionality is difficult and the best way of * doing it is to override block number in helper test smart contracts * * @return `block.number` in mainnet, custom values in testnets (if overridden) */ function blockNumber() public view virtual returns (uint256) { // return current block number return block.number; } } /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.3._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.3._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) private pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ // Copied from Open Zeppelin contract ERC20 is IERC20 { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @notice Token creator is responsible for creating (minting) * tokens to an arbitrary address * @dev Role ROLE_TOKEN_CREATOR allows minting tokens * (calling `mint` function) */ uint32 public constant ROLE_TOKEN_CREATOR = 0x0001_0000; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(msg.sender, recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(msg.sender, spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender] - amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender] - subtractedValue); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender] - amount; _balances[recipient] = _balances[recipient] + amount; emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply + amount; _balances[account] = _balances[account] + amount; emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account] - amount; _totalSupply = _totalSupply - amount; emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } contract EscrowedIlluviumERC20 is ERC20("Escrowed Illuvium", "sILV"), AccessControl { /** * @dev Smart contract unique identifier, a random number * @dev Should be regenerated each time smart contact source code is changed * and changes smart contract itself is to be redeployed * @dev Generated using https://www.random.org/bytes/ */ uint256 public constant TOKEN_UID = 0xac3051b8d4f50966afb632468a4f61483ae6a953b74e387a01ef94316d6b7d62; /** * @notice Must be called by ROLE_TOKEN_CREATOR addresses. * * @param recipient address to receive the tokens. * @param amount number of tokens to be minted. */ function mint(address recipient, uint256 amount) external { require(isSenderInRole(ROLE_TOKEN_CREATOR), "insufficient privileges (ROLE_TOKEN_CREATOR required)"); _mint(recipient, amount); } /** * @param amount number of tokens to be burned. */ function burn(uint256 amount) external { _burn(msg.sender, amount); } } /** * @title Flash Pool Base * * @notice An abstract contract containing logic for a new Flash Pool version. * It fixes the REWARD_PER_WEIGHT_MULTIPLIER constant to allow bigger supply * tokens flash pools. * * @dev Deployment and initialization. * Any pool deployed must be bound to the deployed pool factory (IlluviumPoolFactory) * Additionally, 3 token instance addresses must be defined on deployment: * - ILV token address * - sILV token address, used to mint sILV rewards * - pool token address, it can be ILV token address, ILV/ETH pair address, and others * * @dev Pool weight defines the fraction of the yield current pool receives among the other pools, * pool factory is responsible for the weight synchronization between the pools. * @dev The weight is logically 10% for ILV pool and 90% for ILV/ETH pool. * Since Solidity doesn't support fractions the weight is defined by the division of * pool weight by total pools weight (sum of all registered pools within the factory) * @dev For ILV Pool we use 200 as weight and for ILV/ETH pool 800. * * @author Pedro Bergamini, reviewed by Basil Gorin */ abstract contract FlashPoolBase is IPool, IlluviumAware, ReentrancyGuard { /// @dev Data structure representing token holder using a pool struct User { // @dev Total staked amount uint256 tokenAmount; // @dev Total weight uint256 totalWeight; // @dev Auxiliary variable for yield calculation uint256 subYieldRewards; // @dev Auxiliary variable for vault rewards calculation uint256 subVaultRewards; // @dev An array of holder's deposits Deposit[] deposits; } /// @dev Token holder storage, maps token holder address to their data record mapping(address => User) public users; /// @dev Link to sILV ERC20 Token EscrowedIlluviumERC20 instance address public immutable override silv; /// @dev Link to the pool factory IlluviumPoolFactory instance IlluviumPoolFactory public immutable factory; /// @dev Link to the internal token instance, for example SNX or XYZ address public immutable internalToken; /// @dev Pool weight, 100 for ILV pool or 900 for ILV/ETH uint32 public override weight; /// @dev Block number of the last yield distribution event uint64 public override lastYieldDistribution; /// @dev Used to calculate yield rewards /// @dev This value is different from "reward per token" used in locked pool /// @dev Note: stakes are different in duration and "weight" reflects that uint256 public override yieldRewardsPerWeight; /// @dev Used to calculate yield rewards, keeps track of the tokens weight locked in staking uint256 public override usersLockingWeight; /** * @dev Stake weight is proportional to deposit amount and time locked, precisely * "deposit amount wei multiplied by (fraction of the year locked plus one)" * @dev To avoid significant precision loss due to multiplication by "fraction of the year" [0, 1], * weight is stored multiplied by 1e6 constant, as an integer * @dev Corner case 1: if time locked is zero, weight is deposit amount multiplied by 1e6 * @dev Corner case 2: if time locked is one year, fraction of the year locked is one, and * weight is a deposit amount multiplied by 2 * 1e6 */ uint256 internal constant WEIGHT_MULTIPLIER = 1e6; /** * @dev When we know beforehand that staking is done for a year, and fraction of the year locked is one, * we use simplified calculation and use the following constant instead previos one */ uint256 internal constant YEAR_STAKE_WEIGHT_MULTIPLIER = 2 * WEIGHT_MULTIPLIER; /** * @dev Rewards per weight are stored multiplied by 1e12, as integers. */ uint256 internal constant REWARD_PER_WEIGHT_MULTIPLIER = 1e18; /** * @dev Fired in _stake() and stake() * * @param _by an address which performed an operation, usually token holder * @param _from token holder address, the tokens will be returned to that address * @param amount amount of tokens staked */ event Staked(address indexed _by, address indexed _from, uint256 amount); /** * @dev Fired in _updateStakeLock() and updateStakeLock() * * @param _by an address which performed an operation * @param depositId updated deposit ID * @param lockedFrom deposit locked from value * @param lockedUntil updated deposit locked until value */ event StakeLockUpdated(address indexed _by, uint256 depositId, uint64 lockedFrom, uint64 lockedUntil); /** * @dev Fired in _unstake() and unstake() * * @param _by an address which performed an operation, usually token holder * @param _to an address which received the unstaked tokens, usually token holder * @param amount amount of tokens unstaked */ event Unstaked(address indexed _by, address indexed _to, uint256 amount); /** * @dev Fired in _sync(), sync() and dependent functions (stake, unstake, etc.) * * @param _by an address which performed an operation * @param yieldRewardsPerWeight updated yield rewards per weight value * @param lastYieldDistribution usually, current block number */ event Synchronized(address indexed _by, uint256 yieldRewardsPerWeight, uint64 lastYieldDistribution); /** * @dev Fired in _processRewards(), processRewards() and dependent functions (stake, unstake, etc.) * * @param _by an address which performed an operation * @param _to an address which claimed the yield reward * @param sIlv flag indicating if reward was paid (minted) in sILV * @param amount amount of yield paid */ event YieldClaimed(address indexed _by, address indexed _to, bool sIlv, uint256 amount); /** * @dev Fired in setWeight() * * @param _by an address which performed an operation, always a factory * @param _fromVal old pool weight value * @param _toVal new pool weight value */ event PoolWeightUpdated(address indexed _by, uint32 _fromVal, uint32 _toVal); /** * @dev Overridden in sub-contracts to construct the pool * * @param _ilv ILV ERC20 Token IlluviumERC20 address * @param _silv sILV ERC20 Token EscrowedIlluviumERC20 address * @param _factory Pool factory IlluviumPoolFactory instance/address * @param _internalToken token the pool operates on * @param _initBlock initial block used to calculate the rewards * note: _initBlock can be set to the future effectively meaning _sync() calls will do nothing * @param _weight number representing a weight of the pool, actual weight fraction * is calculated as that number divided by the total pools weight and doesn't exceed one */ constructor( address _ilv, address _silv, IlluviumPoolFactory _factory, address _internalToken, uint64 _initBlock, uint32 _weight ) IlluviumAware(_ilv) { // verify the inputs are set require(_silv != address(0), "sILV address not set"); require(address(_factory) != address(0), "ILV Pool fct address not set"); require(_internalToken != address(0), "token address not set"); require(_initBlock > 0, "init block not set"); require(_weight > 0, "pool weight not set"); // verify sILV instance supplied require( EscrowedIlluviumERC20(_silv).TOKEN_UID() == 0xac3051b8d4f50966afb632468a4f61483ae6a953b74e387a01ef94316d6b7d62, "unexpected sILV TOKEN_UID" ); // verify IlluviumPoolFactory instance supplied require( _factory.FACTORY_UID() == 0xc5cfd88c6e4d7e5c8a03c255f03af23c0918d8e82cac196f57466af3fd4a5ec7, "unexpected FACTORY_UID" ); // save the inputs into internal state variables silv = _silv; factory = _factory; internalToken = _internalToken; weight = _weight; // init the dependent internal state variables lastYieldDistribution = _initBlock; } /** * @dev Faked link to the pool token instance */ function poolToken() external view override returns(address) { return address(this); } /** * @notice Calculates current yield rewards value available for address specified * * @param _staker an address to calculate yield rewards value for * @return calculated yield reward value for the given address */ function pendingYieldRewards(address _staker) external view override returns (uint256) { // `newYieldRewardsPerWeight` will store stored or recalculated value for `yieldRewardsPerWeight` uint256 newYieldRewardsPerWeight; // if smart contract state was not updated recently, `yieldRewardsPerWeight` value // is outdated and we need to recalculate it in order to calculate pending rewards correctly if (blockNumber() > lastYieldDistribution && usersLockingWeight != 0) { uint256 endBlock = factory.endBlock(); uint256 multiplier = blockNumber() > endBlock ? endBlock - lastYieldDistribution : blockNumber() - lastYieldDistribution; uint256 ilvRewards = (multiplier * weight * factory.ilvPerBlock()) / factory.totalWeight(); // recalculated value for `yieldRewardsPerWeight` newYieldRewardsPerWeight = rewardToWeight(ilvRewards, usersLockingWeight) + yieldRewardsPerWeight; } else { // if smart contract state is up to date, we don't recalculate newYieldRewardsPerWeight = yieldRewardsPerWeight; } // based on the rewards per weight value, calculate pending rewards; User memory user = users[_staker]; uint256 pending = weightToReward(user.totalWeight, newYieldRewardsPerWeight) - user.subYieldRewards; return pending; } /** * @notice Returns total staked token balance for the given address * * @param _user an address to query balance for * @return total staked token balance */ function balanceOf(address _user) external view override returns (uint256) { // read specified user token amount and return return users[_user].tokenAmount; } /** * @notice Returns information on the given deposit for the given address * * @dev See getDepositsLength * * @param _user an address to query deposit for * @param _depositId zero-indexed deposit ID for the address specified * @return deposit info as Deposit structure */ function getDeposit(address _user, uint256 _depositId) external view override returns (Deposit memory) { // read deposit at specified index and return return users[_user].deposits[_depositId]; } /** * @notice Returns number of deposits for the given address. Allows iteration over deposits. * * @dev See getDeposit * * @param _user an address to query deposit length for * @return number of deposits for the given address */ function getDepositsLength(address _user) external view override returns (uint256) { // read deposits array length and return return users[_user].deposits.length; } /** * @notice Stakes specified amount of tokens for the specified amount of time, * and pays pending yield rewards if any * * @dev Requires amount to stake to be greater than zero * * @param _amount amount of tokens to stake * @param _lockUntil stake period as unix timestamp; zero means no locking * @param _useSILV a flag indicating if previous reward to be paid as sILV */ function stake( uint256 _amount, uint64 _lockUntil, bool _useSILV ) external override { // delegate call to an internal function _stake(msg.sender, _amount, _lockUntil, _useSILV, false); } /** * @notice Unstakes specified amount of tokens, and pays pending yield rewards if any * * @dev Requires amount to unstake to be greater than zero * * @param _depositId deposit ID to unstake from, zero-indexed * @param _amount amount of tokens to unstake * @param _useSILV a flag indicating if reward to be paid as sILV */ function unstake( uint256 _depositId, uint256 _amount, bool _useSILV ) external override { // delegate call to an internal function _unstake(msg.sender, _depositId, _amount, _useSILV); } /** * @notice Extends locking period for a given deposit * * @dev Requires new lockedUntil value to be: * higher than the current one, and * in the future, but * no more than 1 year in the future * * @param depositId updated deposit ID * @param lockedUntil updated deposit locked until value * @param useSILV used for _processRewards check if it should use ILV or sILV */ function updateStakeLock( uint256 depositId, uint64 lockedUntil, bool useSILV ) external { // sync and call processRewards _sync(); _processRewards(msg.sender, useSILV, false); // delegate call to an internal function _updateStakeLock(msg.sender, depositId, lockedUntil); } /** * @notice Service function to synchronize pool state with current time * * @dev Can be executed by anyone at any time, but has an effect only when * at least one block passes between synchronizations * @dev Executed internally when staking, unstaking, processing rewards in order * for calculations to be correct and to reflect state progress of the contract * @dev When timing conditions are not met (executed too frequently, or after factory * end block), function doesn't throw and exits silently */ function sync() external override { // delegate call to an internal function _sync(); } /** * @notice Service function to calculate and pay pending yield rewards to the sender * * @dev Can be executed by anyone at any time, but has an effect only when * executed by deposit holder and when at least one block passes from the * previous reward processing * @dev Executed internally when staking and unstaking, executes sync() under the hood * before making further calculations and payouts * @dev When timing conditions are not met (executed too frequently, or after factory * end block), function doesn't throw and exits silently * * @param _useSILV flag indicating whether to mint sILV token as a reward or not; * when set to true - sILV reward is minted immediately and sent to sender, * when set to false - new pool deposit gets created together with sILV minted */ function processRewards(bool _useSILV) external virtual override { // delegate call to an internal function _processRewards(msg.sender, _useSILV, true); } /** * @dev Executed by the factory to modify pool weight; the factory is expected * to keep track of the total pools weight when updating * * @dev Set weight to zero to disable the pool * * @param _weight new weight to set for the pool */ function setWeight(uint32 _weight) external override { // verify function is executed by the factory require(msg.sender == address(factory), "access denied"); // emit an event logging old and new weight values emit PoolWeightUpdated(msg.sender, weight, _weight); // set the new weight value weight = _weight; } /** * @dev Similar to public pendingYieldRewards, but performs calculations based on * current smart contract state only, not taking into account any additional * time/blocks which might have passed * * @param _staker an address to calculate yield rewards value for * @return pending calculated yield reward value for the given address */ function _pendingYieldRewards(address _staker) internal view returns (uint256 pending) { // read user data structure into memory User memory user = users[_staker]; // and perform the calculation using the values read return weightToReward(user.totalWeight, yieldRewardsPerWeight) - user.subYieldRewards; } /** * @dev Used internally, mostly by children implementations, see stake() * * @param _staker an address which stakes tokens and which will receive them back * @param _amount amount of tokens to stake * @param _lockUntil stake period as unix timestamp; zero means no locking * @param _useSILV a flag indicating if previous reward to be paid as sILV * @param _isYield a flag indicating if that stake is created to store yield reward * from the previously unstaked stake */ function _stake( address _staker, uint256 _amount, uint64 _lockUntil, bool _useSILV, bool _isYield ) internal virtual { // validate the inputs require(_amount > 0, "zero amount"); require( _lockUntil == 0 || (_lockUntil > now256() && _lockUntil - now256() <= 365 days), "invalid lock interval" ); // update smart contract state _sync(); // get a link to user data struct, we will write to it later User storage user = users[_staker]; // process current pending rewards if any if (user.tokenAmount > 0) { _processRewards(_staker, _useSILV, false); } // in most of the cases added amount `addedAmount` is simply `_amount` // however for deflationary tokens this can be different // read the current balance uint256 previousBalance = IERC20(internalToken).balanceOf(address(this)); // transfer `_amount`; note: some tokens may get burnt here transferPoolTokenFrom(address(msg.sender), address(this), _amount); // read new balance, usually this is just the difference `previousBalance - _amount` uint256 newBalance = IERC20(internalToken).balanceOf(address(this)); // calculate real amount taking into account deflation uint256 addedAmount = newBalance - previousBalance; // set the `lockFrom` and `lockUntil` taking into account that // zero value for `_lockUntil` means "no locking" and leads to zero values // for both `lockFrom` and `lockUntil` uint64 lockFrom = _lockUntil > 0 ? uint64(now256()) : 0; uint64 lockUntil = _lockUntil; // stake weight formula rewards for locking uint256 stakeWeight = (((lockUntil - lockFrom) * WEIGHT_MULTIPLIER) / 365 days + WEIGHT_MULTIPLIER) * addedAmount; // makes sure stakeWeight is valid assert(stakeWeight > 0); // create and save the deposit (append it to deposits array) Deposit memory deposit = Deposit({ tokenAmount: addedAmount, weight: stakeWeight, lockedFrom: lockFrom, lockedUntil: lockUntil, isYield: _isYield }); // deposit ID is an index of the deposit in `deposits` array user.deposits.push(deposit); // update user record user.tokenAmount += addedAmount; user.totalWeight += stakeWeight; user.subYieldRewards = weightToReward(user.totalWeight, yieldRewardsPerWeight); // update global variable usersLockingWeight += stakeWeight; // emit an event emit Staked(msg.sender, _staker, _amount); } /** * @dev Used internally, mostly by children implementations, see unstake() * * @param _staker an address which unstakes tokens (which previously staked them) * @param _depositId deposit ID to unstake from, zero-indexed * @param _amount amount of tokens to unstake * @param _useSILV a flag indicating if reward to be paid as sILV */ function _unstake( address _staker, uint256 _depositId, uint256 _amount, bool _useSILV ) internal virtual { // verify an amount is set require(_amount > 0, "zero amount"); // get a link to user data struct, we will write to it later User storage user = users[_staker]; // get a link to the corresponding deposit, we may write to it later Deposit storage stakeDeposit = user.deposits[_depositId]; // deposit structure may get deleted, so we save isYield flag to be able to use it bool isYield = stakeDeposit.isYield; // verify available balance // if staker address ot deposit doesn't exist this check will fail as well require(stakeDeposit.tokenAmount >= _amount, "amount exceeds stake"); // update smart contract state _sync(); // and process current pending rewards if any _processRewards(_staker, _useSILV, false); // recalculate deposit weight uint256 previousWeight = stakeDeposit.weight; uint256 newWeight = (((stakeDeposit.lockedUntil - stakeDeposit.lockedFrom) * WEIGHT_MULTIPLIER) / 365 days + WEIGHT_MULTIPLIER) * (stakeDeposit.tokenAmount - _amount); // update the deposit, or delete it if its depleted if (stakeDeposit.tokenAmount - _amount == 0) { delete user.deposits[_depositId]; } else { stakeDeposit.tokenAmount -= _amount; stakeDeposit.weight = newWeight; } // update user record user.tokenAmount -= _amount; user.totalWeight = user.totalWeight - previousWeight + newWeight; user.subYieldRewards = weightToReward(user.totalWeight, yieldRewardsPerWeight); // update global variable usersLockingWeight = usersLockingWeight - previousWeight + newWeight; // if the deposit was created by the pool itself as a yield reward if (isYield) { // mint the yield via the factory factory.mintYieldTo(msg.sender, _amount); } else { // otherwise just return tokens back to holder transferPoolToken(msg.sender, _amount); } // emit an event emit Unstaked(msg.sender, _staker, _amount); } /** * @dev Used internally, mostly by children implementations, see sync() * * @dev Updates smart contract state (`yieldRewardsPerWeight`, `lastYieldDistribution`), * updates factory state via `updateILVPerBlock` */ function _sync() internal virtual { // update ILV per block value in factory if required if (factory.shouldUpdateRatio()) { factory.updateILVPerBlock(); } // check bound conditions and if these are not met - // exit silently, without emitting an event uint256 endBlock = factory.endBlock(); if (lastYieldDistribution >= endBlock) { return; } if (blockNumber() <= lastYieldDistribution) { return; } // if locking weight is zero - update only `lastYieldDistribution` and exit if (usersLockingWeight == 0) { lastYieldDistribution = uint64(blockNumber()); return; } // to calculate the reward we need to know how many blocks passed, and reward per block uint256 currentBlock = blockNumber() > endBlock ? endBlock : blockNumber(); uint256 blocksPassed = currentBlock - lastYieldDistribution; uint256 ilvPerBlock = factory.ilvPerBlock(); // calculate the reward uint256 ilvReward = (blocksPassed * ilvPerBlock * weight) / factory.totalWeight(); // update rewards per weight and `lastYieldDistribution` yieldRewardsPerWeight += rewardToWeight(ilvReward, usersLockingWeight); lastYieldDistribution = uint64(currentBlock); // emit an event emit Synchronized(msg.sender, yieldRewardsPerWeight, lastYieldDistribution); } /** * @dev Used internally, mostly by children implementations, see processRewards() * * @param _staker an address which receives the reward (which has staked some tokens earlier) * @param _useSILV flag indicating whether to mint sILV token as a reward or not, see processRewards() * @param _withUpdate flag allowing to disable synchronization (see sync()) if set to false * @return pendingYield the rewards calculated and optionally re-staked */ function _processRewards( address _staker, bool _useSILV, bool _withUpdate ) internal virtual returns (uint256 pendingYield) { // update smart contract state if required if (_withUpdate) { _sync(); } // calculate pending yield rewards, this value will be returned pendingYield = _pendingYieldRewards(_staker); // if pending yield is zero - just return silently if (pendingYield == 0) return 0; // get link to a user data structure, we will write into it later User storage user = users[_staker]; // if sILV is requested if (_useSILV) { // - mint sILV mintSIlv(_staker, pendingYield); } else { // for other pools - stake as pool address ilvPool = factory.getPoolAddress(ilv); ICorePool(ilvPool).stakeAsPool(_staker, pendingYield); } // update users's record for `subYieldRewards` if requested if (_withUpdate) { user.subYieldRewards = weightToReward(user.totalWeight, yieldRewardsPerWeight); } // emit an event emit YieldClaimed(msg.sender, _staker, _useSILV, pendingYield); } /** * @dev See updateStakeLock() * * @param _staker an address to update stake lock * @param _depositId updated deposit ID * @param _lockedUntil updated deposit locked until value */ function _updateStakeLock( address _staker, uint256 _depositId, uint64 _lockedUntil ) internal { // validate the input time require(_lockedUntil > now256(), "lock should be in the future"); // get a link to user data struct, we will write to it later User storage user = users[_staker]; // get a link to the corresponding deposit, we may write to it later Deposit storage stakeDeposit = user.deposits[_depositId]; // validate the input against deposit structure require(_lockedUntil > stakeDeposit.lockedUntil, "invalid new lock"); // verify locked from and locked until values if (stakeDeposit.lockedFrom == 0) { require(_lockedUntil - now256() <= 365 days, "max lock period is 365 days"); stakeDeposit.lockedFrom = uint64(now256()); } else { require(_lockedUntil - stakeDeposit.lockedFrom <= 365 days, "max lock period is 365 days"); } // update locked until value, calculate new weight stakeDeposit.lockedUntil = _lockedUntil; uint256 newWeight = (((stakeDeposit.lockedUntil - stakeDeposit.lockedFrom) * WEIGHT_MULTIPLIER) / 365 days + WEIGHT_MULTIPLIER) * stakeDeposit.tokenAmount; // save previous weight uint256 previousWeight = stakeDeposit.weight; // update weight stakeDeposit.weight = newWeight; // update user total weight and global locking weight user.totalWeight = user.totalWeight - previousWeight + newWeight; usersLockingWeight = usersLockingWeight - previousWeight + newWeight; // emit an event emit StakeLockUpdated(_staker, _depositId, stakeDeposit.lockedFrom, _lockedUntil); } /** * @dev Converts stake weight (not to be mixed with the pool weight) to * ILV reward value, applying the 10^12 division on weight * * @param _weight stake weight * @param rewardPerWeight ILV reward per weight * @return reward value normalized to 10^12 */ function weightToReward(uint256 _weight, uint256 rewardPerWeight) public pure returns (uint256) { // apply the formula and return return (_weight * rewardPerWeight) / REWARD_PER_WEIGHT_MULTIPLIER; } /** * @dev Converts reward ILV value to stake weight (not to be mixed with the pool weight), * applying the 10^12 multiplication on the reward * - OR - * @dev Converts reward ILV value to reward/weight if stake weight is supplied as second * function parameter instead of reward/weight * * @param reward yield reward * @param rewardPerWeight reward/weight (or stake weight) * @return stake weight (or reward/weight) */ function rewardToWeight(uint256 reward, uint256 rewardPerWeight) public pure returns (uint256) { // apply the reverse formula and return return (reward * REWARD_PER_WEIGHT_MULTIPLIER) / rewardPerWeight; } /** * @dev Testing time-dependent functionality is difficult and the best way of * doing it is to override block number in helper test smart contracts * * @return `block.number` in mainnet, custom values in testnets (if overridden) */ function blockNumber() public view virtual returns (uint256) { // return current block number return block.number; } /** * @dev Testing time-dependent functionality is difficult and the best way of * doing it is to override time in helper test smart contracts * * @return `block.timestamp` in mainnet, custom values in testnets (if overridden) */ function now256() public view virtual returns (uint256) { // return current block timestamp return block.timestamp; } /** * @dev Executes EscrowedIlluviumERC20.mint(_to, _values) * on the bound EscrowedIlluviumERC20 instance * * @dev Reentrancy safe due to the EscrowedIlluviumERC20 design */ function mintSIlv(address _to, uint256 _value) private { // just delegate call to the target EscrowedIlluviumERC20(silv).mint(_to, _value); } /** * @dev Executes SafeERC20.safeTransfer on a pool token * * @dev Reentrancy safety enforced via `ReentrancyGuard.nonReentrant` */ function transferPoolToken(address _to, uint256 _value) internal nonReentrant { // just delegate call to the target SafeERC20.safeTransfer(IERC20(internalToken), _to, _value); } /** * @dev Executes SafeERC20.safeTransferFrom on a pool token * * @dev Reentrancy safety enforced via `ReentrancyGuard.nonReentrant` */ function transferPoolTokenFrom( address _from, address _to, uint256 _value ) internal nonReentrant { // just delegate call to the target SafeERC20.safeTransferFrom(IERC20(internalToken), _from, _to, _value); } } /** * @title Flash Pool V2 * * @notice Flash pools represent temporary pools like SNX pool. * * @notice Flash pools doesn't lock tokens, staked tokens can be unstaked at any time * * @dev See FlashPoolBase for more details * * @author Pedro Bergamini, reviewed by Basil Gorin */ contract FlashPoolV2 is FlashPoolBase { /// @dev Pool expiration time, the pool considered to be disabled once end block is reached /// @dev Expired pools don't process any rewards, users are expected to withdraw staked tokens /// from the flash pools once they expire uint64 public endBlock; /// @dev Flag indicating pool type, true means "flash pool" bool public constant override isFlashPool = true; /** * @dev Creates/deploys an instance of the flash pool * * @param _ilv ILV ERC20 Token IlluviumERC20 address * @param _silv sILV ERC20 Token EscrowedIlluviumERC20 address * @param _factory Pool factory IlluviumPoolFactory instance/address * @param _internalToken token the pool operates on, for example ILV or ILV/ETH pair * @param _initBlock initial block used to calculate the rewards * @param _weight number representing a weight of the pool, actual weight fraction * is calculated as that number divided by the total pools weight and doesn't exceed one * @param _endBlock pool expiration time (as block number) */ constructor( address _ilv, address _silv, IlluviumPoolFactory _factory, address _internalToken, uint64 _initBlock, uint32 _weight, uint64 _endBlock ) FlashPoolBase(_ilv, _silv, _factory, _internalToken, _initBlock, _weight) { // check the inputs which are not checked by the pool base require(_endBlock > _initBlock, "end block must be higher than init block"); // assign the end block endBlock = _endBlock; } /** * @notice The function to check pool state. Flash pool is considered "disabled" * once time reaches its "end block" * * @return true if pool is disabled (time has reached end block), false otherwise */ function isPoolDisabled() public view returns (bool) { // verify the pool expiration condition and return the result return blockNumber() >= endBlock; } /** * @inheritdoc FlashPoolBase * * @dev Overrides the _stake() in base by setting the locked until value to 1 year in the future; * locked until value has only locked weight effect and doesn't do any real token locking * * @param _lockedUntil not used, overridden with now + 1 year just to have correct calculation * of the locking weights */ function _stake( address _staker, uint256 _amount, uint64 _lockedUntil, bool useSILV, bool isYield ) internal override { // override the `_lockedUntil` and execute parent // we set "locked period" to 365 days only to have correct calculation of locking weights, // the tokens are not really locked since _unstake in the core pool doesn't check the "locked period" super._stake(_staker, _amount, uint64(now256() + 365 days), useSILV, isYield); } /** * @inheritdoc FlashPoolBase * * @dev In addition to regular sync() routine of the base, set the pool weight * to zero, effectively disabling the pool in the factory * @dev If the pool is disabled regular sync() routine is ignored */ function _sync() internal override { // if pool is disabled/expired if (isPoolDisabled()) { // if weight is not yet set if (weight != 0) { // set the pool weight (sets both factory and local values) factory.changePoolWeight(address(this), 0); } // and exit return; } // for enabled pools perform regular sync() routine super._sync(); } }
===== End: DAO Support (Compound-like voting delegation) =====* @title Illuvium Aware @notice Helper smart contract to be inherited by other smart contracts requiring to be linked to verified IlluviumERC20 instance and performing some basic tasks on it @author Basil Gorin/
abstract contract IlluviumAware is ILinkedToILV { address public immutable override ilv; constructor(address _ilv) { require(_ilv != address(0), "ILV address not set"); require(IlluviumERC20(_ilv).TOKEN_UID() == 0x83ecb176af7c4f35a45ff0018282e3a05a1018065da866182df12285866f5a2c, "unexpected TOKEN_UID"); ilv = _ilv; } function transferIlv(address _to, uint256 _value) internal { transferIlvFrom(address(this), _to, _value); } function transferIlvFrom(address _from, address _to, uint256 _value) internal { IlluviumERC20(ilv).transferFrom(_from, _to, _value); } function mintIlv(address _to, uint256 _value) internal { IlluviumERC20(ilv).mint(_to, _value); } }
6,185,574
[ 1, 894, 33, 4403, 30, 463, 20463, 13619, 261, 16835, 17, 5625, 331, 17128, 23595, 13, 422, 12275, 225, 467, 2906, 89, 522, 379, 432, 2726, 225, 9705, 13706, 6835, 358, 506, 12078, 635, 1308, 13706, 20092, 29468, 358, 1377, 506, 8459, 358, 13808, 467, 2906, 89, 522, 379, 654, 39, 3462, 791, 471, 14928, 2690, 5337, 4592, 603, 518, 225, 605, 345, 330, 611, 280, 267, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 17801, 6835, 467, 2906, 89, 522, 379, 10155, 353, 467, 13174, 774, 2627, 58, 288, 203, 225, 1758, 1071, 11732, 3849, 277, 3070, 31, 203, 203, 225, 3885, 12, 2867, 389, 330, 90, 13, 288, 203, 565, 2583, 24899, 330, 90, 480, 1758, 12, 20, 3631, 315, 2627, 58, 1758, 486, 444, 8863, 203, 565, 2583, 12, 45, 2906, 89, 522, 379, 654, 39, 3462, 24899, 330, 90, 2934, 8412, 67, 3060, 1435, 422, 374, 92, 10261, 557, 70, 28493, 1727, 27, 71, 24, 74, 4763, 69, 7950, 1403, 713, 2643, 6030, 22, 73, 23, 69, 6260, 69, 15168, 3672, 9222, 2414, 5292, 26, 28246, 2180, 2138, 6030, 25, 5292, 26, 74, 25, 69, 22, 71, 16, 315, 21248, 14275, 67, 3060, 8863, 203, 203, 565, 277, 3070, 273, 389, 330, 90, 31, 203, 225, 289, 203, 203, 225, 445, 7412, 45, 3070, 12, 2867, 389, 869, 16, 2254, 5034, 389, 1132, 13, 2713, 288, 203, 565, 7412, 45, 3070, 1265, 12, 2867, 12, 2211, 3631, 389, 869, 16, 389, 1132, 1769, 203, 225, 289, 203, 203, 225, 445, 7412, 45, 3070, 1265, 12, 2867, 389, 2080, 16, 1758, 389, 869, 16, 2254, 5034, 389, 1132, 13, 2713, 288, 203, 565, 467, 2906, 89, 522, 379, 654, 39, 3462, 12, 330, 90, 2934, 13866, 1265, 24899, 2080, 16, 389, 869, 16, 389, 1132, 1769, 203, 225, 289, 203, 203, 225, 445, 312, 474, 45, 3070, 12, 2867, 389, 869, 16, 2254, 5034, 389, 1132, 13, 2713, 288, 203, 565, 467, 2906, 89, 522, 379, 2 ]
./full_match/1/0xD8A2FCcD1e2887817B0121A529477F3EF45f30E5/sources/contracts/rUSTP.sol
* @dev rUSTP balances are dynamic and are calculated based on the accounts' shares and the total amount of Ether controlled by the protocol. Account shares aren't normalized, so the contract also stores the sum of all shares to calculate each account's token balance which equals to: shares[account] _getTotalSupplyrUSTP() / _getTotalShares()/* @dev Allowances are nominated in tokens, not token shares./* @notice An executed shares transfer from `sender` to `recipient`. @dev emitted in pair with an ERC20-defined `Transfer` event./* @notice An executed `burnShares` request @dev Reports simultaneously burnt shares amount and corresponding rUSTP amount. The rUSTP amount is calculated twice: before and after the burning incurred rebase. @param account holder of the burnt shares @param preRebaseTokenAmount amount of rUSTP the burnt shares corresponded to before the burn @param postRebaseTokenAmount amount of rUSTP the burnt shares corresponded to after the burn @param sharesAmount amount of burnt shares/* @return the number of decimals for getting user representation of a token amount./
function decimals() public pure override returns (uint8) { return 18; }
4,924,708
[ 1, 86, 5996, 52, 324, 26488, 854, 5976, 471, 854, 8894, 2511, 603, 326, 9484, 11, 24123, 471, 326, 2078, 3844, 434, 512, 1136, 25934, 635, 326, 1771, 18, 6590, 24123, 11526, 1404, 5640, 16, 1427, 326, 6835, 2546, 9064, 326, 2142, 434, 777, 24123, 358, 4604, 1517, 2236, 1807, 1147, 11013, 1492, 1606, 358, 30, 282, 24123, 63, 4631, 65, 225, 389, 588, 5269, 3088, 1283, 86, 5996, 52, 1435, 342, 389, 588, 5269, 24051, 1435, 19, 225, 7852, 6872, 854, 12457, 7458, 316, 2430, 16, 486, 1147, 24123, 18, 19, 225, 1922, 7120, 24123, 7412, 628, 1375, 15330, 68, 358, 1375, 20367, 8338, 225, 17826, 316, 3082, 598, 392, 4232, 39, 3462, 17, 2178, 1375, 5912, 68, 871, 18, 19, 225, 1922, 7120, 1375, 70, 321, 24051, 68, 590, 225, 868, 4363, 27504, 715, 18305, 88, 24123, 3844, 471, 4656, 436, 5996, 52, 3844, 18, 1021, 436, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 202, 915, 15105, 1435, 1071, 16618, 3849, 1135, 261, 11890, 28, 13, 288, 203, 202, 202, 2463, 6549, 31, 203, 202, 97, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.18; // ==== Open Zeppelin library === /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { function safeTransfer(ERC20Basic token, address to, uint256 value) internal { assert(token.transfer(to, value)); } function safeTransferFrom(ERC20 token, address from, address to, uint256 value) internal { assert(token.transferFrom(from, to, value)); } function safeApprove(ERC20 token, address spender, uint256 value) internal { assert(token.approve(spender, value)); } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title Contracts that should not own Ether * @author Remco Bloemen <remco@2π.com> * @dev This tries to block incoming ether to prevent accidental loss of Ether. Should Ether end up * in the contract, it will allow the owner to reclaim this ether. * @notice Ether can still be send to this contract by: * calling functions labeled `payable` * `selfdestruct(contract_address)` * mining directly to the contract address */ contract HasNoEther is Ownable { /** * @dev Constructor that rejects incoming Ether * @dev The `payable` flag is added so we can access `msg.value` without compiler warning. If we * leave out payable, then Solidity will allow inheriting contracts to implement a payable * constructor. By doing it this way we prevent a payable constructor from working. Alternatively * we could use assembly to access msg.value. */ function HasNoEther() public payable { require(msg.value == 0); } /** * @dev Disallows direct send by settings a default function without the `payable` flag. */ function() external { } /** * @dev Transfer all Ether held by the contract to the owner. */ function reclaimEther() external onlyOwner { assert(owner.send(this.balance)); } } /** * @title Contracts that should not own Contracts * @author Remco Bloemen <remco@2π.com> * @dev Should contracts (anything Ownable) end up being owned by this contract, it allows the owner * of this contract to reclaim ownership of the contracts. */ contract HasNoContracts is Ownable { /** * @dev Reclaim ownership of Ownable contracts * @param contractAddr The address of the Ownable to be reclaimed. */ function reclaimContract(address contractAddr) external onlyOwner { Ownable contractInst = Ownable(contractAddr); contractInst.transferOwnership(owner); } } /** * @title Contracts that should be able to recover tokens * @author SylTi * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. * This will prevent any accidental loss of tokens. */ contract CanReclaimToken is Ownable { using SafeERC20 for ERC20Basic; /** * @dev Reclaim all ERC20Basic compatible tokens * @param token ERC20Basic The address of the token contract */ function reclaimToken(ERC20Basic token) external onlyOwner { uint256 balance = token.balanceOf(this); token.safeTransfer(owner, balance); } } /** * @title Contracts that should not own Tokens * @author Remco Bloemen <remco@2π.com> * @dev This blocks incoming ERC23 tokens to prevent accidental loss of tokens. * Should tokens (any ERC20Basic compatible) end up in the contract, it allows the * owner to reclaim the tokens. */ contract HasNoTokens is CanReclaimToken { /** * @dev Reject all ERC23 compatible tokens * @param from_ address The address that is transferring the tokens * @param value_ uint256 the amount of the specified token * @param data_ Bytes The data passed from the caller. */ function tokenFallback(address from_, uint256 value_, bytes data_) pure external { from_; value_; data_; revert(); } } /** * @title Base contract for contracts that should not own things. * @author Remco Bloemen <remco@2π.com> * @dev Solves a class of errors where a contract accidentally becomes owner of Ether, Tokens or * Owned contracts. See respective base contracts for details. */ contract NoOwner is HasNoEther, HasNoTokens, HasNoContracts { } /** * @title Destructible * @dev Base contract that can be destroyed by owner. All funds in contract will be sent to the owner. */ contract Destructible is Ownable { function Destructible() public payable { } /** * @dev Transfers the current balance to the owner and terminates the contract. */ function destroy() onlyOwner public { selfdestruct(owner); } function destroyAndSend(address _recipient) onlyOwner public { selfdestruct(_recipient); } } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; MintFinished(); return true; } } /** * @title TokenVesting * @dev A token holder contract that can release its token balance gradually like a * typical vesting scheme, with a cliff and vesting period. Optionally revocable by the * owner. */ contract TokenVesting is Ownable { using SafeMath for uint256; using SafeERC20 for ERC20Basic; event Released(uint256 amount); event Revoked(); // beneficiary of tokens after they are released address public beneficiary; uint256 public cliff; uint256 public start; uint256 public duration; bool public revocable; mapping (address => uint256) public released; mapping (address => bool) public revoked; /** * @dev Creates a vesting contract that vests its balance of any ERC20 token to the * _beneficiary, gradually in a linear fashion until _start + _duration. By then all * of the balance will have vested. * @param _beneficiary address of the beneficiary to whom vested tokens are transferred * @param _cliff duration in seconds of the cliff in which tokens will begin to vest * @param _duration duration in seconds of the period in which the tokens will vest * @param _revocable whether the vesting is revocable or not */ function TokenVesting(address _beneficiary, uint256 _start, uint256 _cliff, uint256 _duration, bool _revocable) public { require(_beneficiary != address(0)); require(_cliff <= _duration); beneficiary = _beneficiary; revocable = _revocable; duration = _duration; cliff = _start.add(_cliff); start = _start; } /** * @notice Transfers vested tokens to beneficiary. * @param token ERC20 token which is being vested */ function release(ERC20Basic token) public { uint256 unreleased = releasableAmount(token); require(unreleased > 0); released[token] = released[token].add(unreleased); token.safeTransfer(beneficiary, unreleased); Released(unreleased); } /** * @notice Allows the owner to revoke the vesting. Tokens already vested * remain in the contract, the rest are returned to the owner. * @param token ERC20 token which is being vested */ function revoke(ERC20Basic token) public onlyOwner { require(revocable); require(!revoked[token]); uint256 balance = token.balanceOf(this); uint256 unreleased = releasableAmount(token); uint256 refund = balance.sub(unreleased); revoked[token] = true; token.safeTransfer(owner, refund); Revoked(); } /** * @dev Calculates the amount that has already vested but hasn't been released yet. * @param token ERC20 token which is being vested */ function releasableAmount(ERC20Basic token) public view returns (uint256) { return vestedAmount(token).sub(released[token]); } /** * @dev Calculates the amount that has already vested. * @param token ERC20 token which is being vested */ function vestedAmount(ERC20Basic token) public view returns (uint256) { uint256 currentBalance = token.balanceOf(this); uint256 totalBalance = currentBalance.add(released[token]); if (now < cliff) { return 0; } else if (now >= start.add(duration) || revoked[token]) { return totalBalance; } else { return totalBalance.mul(now.sub(start)).div(duration); } } } // ==== AALM Contracts === contract AALMToken is MintableToken, NoOwner { //MintableToken is StandardToken, Ownable string public symbol = 'AALM'; string public name = 'Alm Token'; uint8 public constant decimals = 18; address founder; //founder address to allow him transfer tokens while minting function init(address _founder) onlyOwner public{ founder = _founder; } /** * Allow transfer only after crowdsale finished */ modifier canTransfer() { require(mintingFinished || msg.sender == founder); _; } function transfer(address _to, uint256 _value) canTransfer public returns (bool) { return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) canTransfer public returns (bool) { return super.transferFrom(_from, _to, _value); } } contract AALMCrowdsale is Ownable, CanReclaimToken, Destructible { using SafeMath for uint256; uint32 private constant PERCENT_DIVIDER = 100; struct BulkBonus { uint256 minAmount; //Minimal amount to receive bonus (including this amount) uint32 bonusPercent; //a bonus percent, so that bonus = amount.mul(bonusPercent).div(PERCENT_DIVIDER) } uint64 public startTimestamp; //Crowdsale start timestamp uint64 public endTimestamp; //Crowdsale end timestamp uint256 public minCap; //minimal amount of sold tokens (if not reached - ETH may be refunded) uint256 public hardCap; //total amount of tokens available uint256 public baseRate; //how many tokens will be minted for 1 ETH (like 1000 AALM for 1 ETH) without bonuses uint32 public maxTimeBonusPercent; //A maximum time bonus percent: at the start of crowdsale timeBonus = value.mul(baseRate).mul(maxTimeBonusPercent).div(PERCENT_DIVIDER) uint32 public referrerBonusPercent; //A bonus percent that refferer will receive, so that referrerBonus = value.mul(baseRate).mul(referrerBonusPercent).div(PERCENT_DIVIDER) uint32 public referralBonusPercent; //A bonus percent that refferal will receive, so that referralBonus = value.mul(baseRate).mul(referralBonusPercent).div(PERCENT_DIVIDER) BulkBonus[] public bulkBonuses; //Bulk Bonuses sorted by ether amount (minimal amount first) uint256 public tokensMinted; //total amount of minted tokens uint256 public tokensSold; //total amount of tokens sold(!) on ICO, including all bonuses uint256 public collectedEther; //total amount of ether collected during ICO (without Pre-ICO) mapping(address => uint256) contributions; //amount of ether (in wei)received from a buyer AALMToken public token; TokenVesting public founderVestingContract; //Contract which holds Founder's tokens bool public finalized; function AALMCrowdsale(uint64 _startTimestamp, uint64 _endTimestamp, uint256 _hardCap, uint256 _minCap, uint256 _founderTokensImmediate, uint256 _founderTokensVested, uint256 _vestingDuration, uint256 _baseRate, uint32 _maxTimeBonusPercent, uint32 _referrerBonusPercent, uint32 _referralBonusPercent, uint256[] bulkBonusMinAmounts, uint32[] bulkBonusPercents ) public { require(_startTimestamp > now); require(_startTimestamp < _endTimestamp); startTimestamp = _startTimestamp; endTimestamp = _endTimestamp; require(_hardCap > 0); hardCap = _hardCap; minCap = _minCap; initRatesAndBonuses(_baseRate, _maxTimeBonusPercent, _referrerBonusPercent, _referralBonusPercent, bulkBonusMinAmounts, bulkBonusPercents); token = new AALMToken(); token.init(owner); require(_founderTokensImmediate.add(_founderTokensVested) < _hardCap); mintTokens(owner, _founderTokensImmediate); founderVestingContract = new TokenVesting(owner, endTimestamp, 0, _vestingDuration, false); mintTokens(founderVestingContract, _founderTokensVested); } function initRatesAndBonuses( uint256 _baseRate, uint32 _maxTimeBonusPercent, uint32 _referrerBonusPercent, uint32 _referralBonusPercent, uint256[] bulkBonusMinAmounts, uint32[] bulkBonusPercents ) internal { require(_baseRate > 0); baseRate = _baseRate; maxTimeBonusPercent = _maxTimeBonusPercent; referrerBonusPercent = _referrerBonusPercent; referralBonusPercent = _referralBonusPercent; uint256 prevBulkAmount = 0; require(bulkBonusMinAmounts.length == bulkBonusPercents.length); bulkBonuses.length = bulkBonusMinAmounts.length; for(uint8 i=0; i < bulkBonuses.length; i++){ bulkBonuses[i] = BulkBonus({minAmount:bulkBonusMinAmounts[i], bonusPercent:bulkBonusPercents[i]}); BulkBonus storage bb = bulkBonuses[i]; require(prevBulkAmount < bb.minAmount); prevBulkAmount = bb.minAmount; } } /** * @notice Distribute tokens sold during Pre-ICO * @param beneficiaries Array of beneficiari addresses * @param amounts Array of amounts of tokens to send */ function distributePreICOTokens(address[] beneficiaries, uint256[] amounts) onlyOwner public { require(beneficiaries.length == amounts.length); for(uint256 i=0; i<beneficiaries.length; i++){ mintTokens(beneficiaries[i], amounts[i]); } } /** * @notice Sell tokens directly, without referral bonuses */ function () payable public { sale(msg.sender, msg.value, address(0)); } /** * @notice Sell tokens via RefferalCrowdsale contract * @param beneficiary Original sender (buyer) * @param referrer The partner who referered the buyer */ function referralSale(address beneficiary, address referrer) payable public returns(bool) { sale(beneficiary, msg.value, referrer); return true; } /** * @dev Internal functions to sell tokens * @param beneficiary who should receive tokens (the buyer) * @param value of ether sent by buyer * @param referrer who should receive referrer bonus, if any. Zero address if no referral bonuses should be paid */ function sale(address beneficiary, uint256 value, address referrer) internal { require(crowdsaleOpen()); require(value > 0); collectedEther = collectedEther.add(value); contributions[beneficiary] = contributions[beneficiary].add(value); uint256 amount; if(referrer == address(0)){ amount = getTokensWithBonuses(value, false); } else{ amount = getTokensWithBonuses(value, true); uint256 referrerAmount = getReferrerBonus(value); tokensSold = tokensSold.add(referrerAmount); mintTokens(referrer, referrerAmount); } tokensSold = tokensSold.add(amount); mintTokens(beneficiary, amount); } /** * @notice Mint tokens for purshases with Non-Ether currencies * @param beneficiary whom to send tokend * @param amount how much tokens to send * param message reason why we are sending tokens (not stored anythere, only in transaction itself) */ function saleNonEther(address beneficiary, uint256 amount, string /*message*/) public onlyOwner { mintTokens(beneficiary, amount); } /** * @notice If crowdsale is running */ function crowdsaleOpen() view public returns(bool) { return (!finalized) && (tokensMinted < hardCap) && (startTimestamp <= now) && (now <= endTimestamp); } /** * @notice Calculates how many tokens are left to sale * @return amount of tokens left before hard cap reached */ function getTokensLeft() view public returns(uint256) { return hardCap.sub(tokensMinted); } /** * @notice Calculates how many tokens one should receive at curent time for a specified value of ether * @param value of ether to get bonus for * @param withReferralBonus if should add referral bonus * @return bonus tokens */ function getTokensWithBonuses(uint256 value, bool withReferralBonus) view public returns(uint256) { uint256 amount = value.mul(baseRate); amount = amount.add(getTimeBonus(value)).add(getBulkBonus(value)); if(withReferralBonus){ amount = amount.add(getReferralBonus(value)); } return amount; } /** * @notice Calculates current time bonus * @param value of ether to get bonus for * @return bonus tokens */ function getTimeBonus(uint256 value) view public returns(uint256) { uint256 maxBonus = value.mul(baseRate).mul(maxTimeBonusPercent).div(PERCENT_DIVIDER); return maxBonus.mul(endTimestamp - now).div(endTimestamp - startTimestamp); } /** * @notice Calculates a bulk bonus for a specified value of ether * @param value of ether to get bonus for * @return bonus tokens */ function getBulkBonus(uint256 value) view public returns(uint256) { for(uint8 i=uint8(bulkBonuses.length); i > 0; i--){ uint8 idx = i - 1; //if i = bulkBonuses.length-1 to 0, i-- fails on last iteration if (value >= bulkBonuses[idx].minAmount) { return value.mul(baseRate).mul(bulkBonuses[idx].bonusPercent).div(PERCENT_DIVIDER); } } return 0; } /** * @notice Calculates referrer bonus * @param value of ether to get bonus for * @return bonus tokens */ function getReferrerBonus(uint256 value) view public returns(uint256) { return value.mul(baseRate).mul(referrerBonusPercent).div(PERCENT_DIVIDER); } /** * @notice Calculates referral bonus * @param value of ether to get bonus for * @return bonus tokens */ function getReferralBonus(uint256 value) view public returns(uint256) { return value.mul(baseRate).mul(referralBonusPercent).div(PERCENT_DIVIDER); } /** * @dev Helper function to mint tokens and increase tokensMinted counter */ function mintTokens(address beneficiary, uint256 amount) internal { tokensMinted = tokensMinted.add(amount); require(tokensMinted <= hardCap); assert(token.mint(beneficiary, amount)); } /** * @notice Sends all contributed ether back if minimum cap is not reached by the end of crowdsale */ function refund() public returns(bool){ return refundTo(msg.sender); } function refundTo(address beneficiary) public returns(bool) { require(contributions[beneficiary] > 0); require(finalized || (now > endTimestamp)); require(tokensSold < minCap); uint256 _refund = contributions[beneficiary]; contributions[beneficiary] = 0; beneficiary.transfer(_refund); return true; } /** * @notice Closes crowdsale, finishes minting (allowing token transfers), transfers token ownership to the owner */ function finalizeCrowdsale() public onlyOwner { finalized = true; token.finishMinting(); token.transferOwnership(owner); if(tokensSold >= minCap && this.balance > 0){ owner.transfer(this.balance); } } /** * @notice Claim collected ether without closing crowdsale */ function claimEther() public onlyOwner { require(tokensSold >= minCap); owner.transfer(this.balance); } }
* @notice Calculates current time bonus @param value of ether to get bonus for @return bonus tokens/
function getTimeBonus(uint256 value) view public returns(uint256) { uint256 maxBonus = value.mul(baseRate).mul(maxTimeBonusPercent).div(PERCENT_DIVIDER); return maxBonus.mul(endTimestamp - now).div(endTimestamp - startTimestamp); }
14,049,942
[ 1, 10587, 783, 813, 324, 22889, 225, 460, 434, 225, 2437, 358, 336, 324, 22889, 364, 327, 324, 22889, 2430, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 6135, 38, 22889, 12, 11890, 5034, 460, 13, 1476, 1071, 1135, 12, 11890, 5034, 13, 288, 203, 3639, 2254, 5034, 943, 38, 22889, 273, 460, 18, 16411, 12, 1969, 4727, 2934, 16411, 12, 1896, 950, 38, 22889, 8410, 2934, 2892, 12, 3194, 19666, 67, 2565, 20059, 1769, 203, 3639, 327, 943, 38, 22889, 18, 16411, 12, 409, 4921, 300, 2037, 2934, 2892, 12, 409, 4921, 300, 787, 4921, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT LICENSE pragma solidity ^0.8.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/security/Pausable.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "./interfaces/IWnDGame.sol"; import "./interfaces/ITrainingGrounds.sol"; import "./interfaces/ITraits.sol"; import "./interfaces/IGP.sol"; import "./interfaces/IWnD.sol"; import "./interfaces/ISacrificialAlter.sol"; contract WnDGameTG is IWnDGame, Ownable, ReentrancyGuard, Pausable { struct MintCommit { address recipient; bool stake; uint16 amount; } struct TrainingCommit { address tokenOwner; uint16 tokenId; bool isAdding; // If false, the commit is for claiming rewards bool isUnstaking; // If !isAdding, this will determine if user is unstaking bool isTraining; // If !isAdding, this will define where the staked token is (only necessary for wizards) } uint256 public constant TREASURE_CHEST = 5; // max $GP cost uint256 private maxGpCost = 72000 ether; /** =========== MINTING COMMIT AND REVEAL VARIABLES =========== */ // commitId -> array of all pending commits mapping(uint16 => MintCommit[]) private commitQueueMints; // Track when a commitId started accepting commits mapping(uint16 => uint256) private commitIdStartTimeMints; mapping(address => uint16) private pendingMintCommitsForAddr; // Tracks the current commitId batch to put new commits into uint16 private _commitIdCurMints = 1; // tracks the oldest commitId that has commits needing to be revealed uint16 private _commitIdPendingMints = 0; /** =========== TRAINING COMMIT AND REVEAL VARIABLES =========== */ // commitId -> array of all pending commits mapping(uint16 => TrainingCommit[]) private commitQueueTraining; // Track when a commitId started accepting commits mapping(uint16 => uint256) private commitIdStartTimeTraining; mapping(address => uint16) private pendingTrainingCommitsForAddr; mapping(uint256 => bool) private tokenHasPendingCommit; // Tracks the current commitId batch to put new commits into uint16 private _commitIdCurTraining = 1; // tracks the oldest commitId that has commits needing to be revealed uint16 private _commitIdPendingTraining = 0; // Time from starting a commit batch to allow new commits to enter uint64 private timePerCommitBatch = 5 minutes; // Time from starting a commit batch to allow users to reveal these in exchange for $GP uint64 private timeToAllowArb = 1 hours; uint16 private pendingMintAmt; bool public allowCommits = true; uint256 private revealRewardAmt = 36000 ether; uint256 private stakingCost = 8000 ether; // reference to the TrainingGrounds ITrainingGrounds public trainingGrounds; // reference to $GP for burning on mint IGP public gpToken; // reference to Traits ITraits public traits; // reference to NFT collection IWnD public wndNFT; // reference to alter collection ISacrificialAlter public alter; constructor() { _pause(); } /** CRITICAL TO SETUP */ modifier requireContractsSet() { require(address(gpToken) != address(0) && address(traits) != address(0) && address(wndNFT) != address(0) && address(alter) != address(0) && address(trainingGrounds) != address(0) , "Contracts not set"); _; } function setContracts(address _gp, address _traits, address _wnd, address _alter, address _trainingGrounds) external onlyOwner { gpToken = IGP(_gp); traits = ITraits(_traits); wndNFT = IWnD(_wnd); alter = ISacrificialAlter(_alter); trainingGrounds = ITrainingGrounds(_trainingGrounds); } /** EXTERNAL */ function getPendingMintCommits(address addr) external view returns (uint16) { return pendingMintCommitsForAddr[addr]; } function getPendingTrainingCommits(address addr) external view returns (uint16) { return pendingTrainingCommitsForAddr[addr]; } function isTokenPendingReveal(uint256 tokenId) external view returns (bool) { return tokenHasPendingCommit[tokenId]; } function hasStaleMintCommit() external view returns (bool) { uint16 pendingId = _commitIdPendingMints; // Check if the revealable commitId has anything to commit and increment it until it does, or is the same as the current commitId while(commitQueueMints[pendingId].length == 0 && pendingId < _commitIdCurMints) { // Only iterate if the commit pending is empty and behind the current id. // This is to prevent it from being in front of the current id and missing commits. pendingId += 1; } return commitIdStartTimeMints[pendingId] < block.timestamp - timeToAllowArb && commitQueueMints[pendingId].length > 0; } function hasStaleTrainingCommit() external view returns (bool) { uint16 pendingId = _commitIdPendingTraining; // Check if the revealable commitId has anything to commit and increment it until it does, or is the same as the current commitId while(commitQueueTraining[pendingId].length == 0 && pendingId < _commitIdCurTraining) { // Only iterate if the commit pending is empty and behind the current id. // This is to prevent it from being in front of the current id and missing commits. pendingId += 1; } return commitIdStartTimeTraining[pendingId] < block.timestamp - timeToAllowArb && commitQueueTraining[pendingId].length > 0; } /** Allow users to reveal the oldest commit for GP. Mints commits must be stale to be able to be revealed this way */ function revealOldestMint() external whenNotPaused { require(tx.origin == _msgSender(), "Only EOA"); // Check if the revealable commitId has anything to commit and increment it until it does, or is the same as the current commitId while(commitQueueMints[_commitIdPendingMints].length == 0 && _commitIdPendingMints < _commitIdCurMints) { // Only iterate if the commit pending is empty and behind the current id. // This is to prevent it from being in front of the current id and missing commits. _commitIdPendingMints += 1; } // Check if there is a commit in a revealable batch and pop/reveal it require(commitIdStartTimeMints[_commitIdPendingMints] < block.timestamp - timeToAllowArb && commitQueueMints[_commitIdPendingMints].length > 0, "No stale commits to reveal"); // If the pending batch is old enough to be revealed and has stuff in it, mine one. MintCommit memory commit = commitQueueMints[_commitIdPendingMints][commitQueueMints[_commitIdPendingMints].length - 1]; commitQueueMints[_commitIdPendingMints].pop(); revealMint(commit); gpToken.mint(_msgSender(), revealRewardAmt * commit.amount); } /** Allow users to reveal the oldest commit for GP. Mints commits must be stale to be able to be revealed this way */ function skipOldestMint() external onlyOwner { // Check if the revealable commitId has anything to commit and increment it until it does, or is the same as the current commitId while(commitQueueMints[_commitIdPendingMints].length == 0 && _commitIdPendingMints < _commitIdCurMints) { // Only iterate if the commit pending is empty and behind the current id. // This is to prevent it from being in front of the current id and missing commits. _commitIdPendingMints += 1; } // Check if there is a commit in a revealable batch and pop/reveal it require(commitQueueMints[_commitIdPendingMints].length > 0, "No stale commits to reveal"); // If the pending batch is old enough to be revealed and has stuff in it, mine one. commitQueueMints[_commitIdPendingMints].pop(); // Do not reveal the commit, only pop it from the queue and move on. // revealMint(commit); } function revealOldestTraining() external whenNotPaused { require(tx.origin == _msgSender(), "Only EOA"); // Check if the revealable commitId has anything to commit and increment it until it does, or is the same as the current commitId while(commitQueueTraining[_commitIdPendingTraining].length == 0 && _commitIdPendingTraining < _commitIdCurTraining) { // Only iterate if the commit pending is empty and behind the current id. // This is to prevent it from being in front of the current id and missing commits. _commitIdPendingTraining += 1; } // Check if there is a commit in a revealable batch and pop/reveal it require(commitIdStartTimeTraining[_commitIdPendingTraining] < block.timestamp - timeToAllowArb && commitQueueTraining[_commitIdPendingTraining].length > 0, "No stale commits to reveal"); // If the pending batch is old enough to be revealed and has stuff in it, mine one. TrainingCommit memory commit = commitQueueTraining[_commitIdPendingTraining][commitQueueTraining[_commitIdPendingTraining].length - 1]; commitQueueTraining[_commitIdPendingTraining].pop(); revealTraining(commit); gpToken.mint(_msgSender(), revealRewardAmt); } function skipOldestTraining() external onlyOwner { // Check if the revealable commitId has anything to commit and increment it until it does, or is the same as the current commitId while(commitQueueTraining[_commitIdPendingTraining].length == 0 && _commitIdPendingTraining < _commitIdCurTraining) { // Only iterate if the commit pending is empty and behind the current id. // This is to prevent it from being in front of the current id and missing commits. _commitIdPendingTraining += 1; } // Check if there is a commit in a revealable batch and pop/reveal it require(commitQueueTraining[_commitIdPendingTraining].length > 0, "No stale commits to reveal"); // If the pending batch is old enough to be revealed and has stuff in it, mine one. TrainingCommit memory commit = commitQueueTraining[_commitIdPendingTraining][commitQueueTraining[_commitIdPendingTraining].length - 1]; commitQueueTraining[_commitIdPendingTraining].pop(); // Do not reveal the commit, only pop it from the queue and move on. // revealTraining(commit); tokenHasPendingCommit[commit.tokenId] = false; } /** Initiate the start of a mint. This action burns $GP, as the intent of committing is that you cannot back out once you've started. * This will add users into the pending queue, to be revealed after a random seed is generated and assigned to the commit id this * commit was added to. */ function mintCommit(uint256 amount, bool stake) external whenNotPaused nonReentrant { require(allowCommits, "adding commits disallowed"); require(tx.origin == _msgSender(), "Only EOA"); uint16 minted = wndNFT.minted(); uint256 maxTokens = wndNFT.getMaxTokens(); require(minted + pendingMintAmt + amount <= maxTokens, "All tokens minted"); require(amount > 0 && amount <= 10, "Invalid mint amount"); if(commitIdStartTimeMints[_commitIdCurMints] == 0) { commitIdStartTimeMints[_commitIdCurMints] = block.timestamp; } // Check if current commit batch is past the threshold for time and increment commitId if so if(commitIdStartTimeMints[_commitIdCurMints] < block.timestamp - timePerCommitBatch) { // increment commitId to start a new batch _commitIdCurMints += 1; commitIdStartTimeMints[_commitIdCurMints] = block.timestamp; } // Add this mint request to the commit queue for the current commitId uint256 totalGpCost = 0; // Loop through the amount of for (uint i = 1; i <= amount; i++) { // Add N number of commits to the queue. This is so people reveal the same number of commits as they added. commitQueueMints[_commitIdCurMints].push(MintCommit(_msgSender(), stake, 1)); totalGpCost += mintCost(minted + pendingMintAmt + i, maxTokens); } if (totalGpCost > 0) { gpToken.burn(_msgSender(), totalGpCost); gpToken.updateOriginAccess(); } uint16 amt = uint16(amount); pendingMintCommitsForAddr[_msgSender()] += amt; pendingMintAmt += amt; // Check if the revealable commitId has anything to commit and increment it until it does, or is the same as the current commitId while(commitQueueMints[_commitIdPendingMints].length == 0 && _commitIdPendingMints < _commitIdCurMints) { // Only iterate if the commit pending is empty and behind the current id. // This is to prevent it from being in front of the current id and missing commits. _commitIdPendingMints += 1; } // Check if there is a commit in a revealable batch and pop/reveal it if(commitIdStartTimeMints[_commitIdPendingMints] < block.timestamp - timePerCommitBatch && commitQueueMints[_commitIdPendingMints].length > 0) { // If the pending batch is old enough to be revealed and has stuff in it, mine the number that was added to the queue. for (uint256 i = 0; i < amount; i++) { // First iteration is guaranteed to have 1 commit to mine, so we can always retroactively check that we can continue to reveal after MintCommit memory commit = commitQueueMints[_commitIdPendingMints][commitQueueMints[_commitIdPendingMints].length - 1]; commitQueueMints[_commitIdPendingMints].pop(); revealMint(commit); // Check to see if we are able to continue mining commits if(commitQueueMints[_commitIdPendingMints].length == 0 && _commitIdPendingMints < _commitIdCurMints) { _commitIdPendingMints += 1; if(commitIdStartTimeMints[_commitIdPendingMints] > block.timestamp - timePerCommitBatch || commitQueueMints[_commitIdPendingMints].length == 0 || _commitIdPendingMints == _commitIdCurMints) { // If there are no more commits to reveal, exit break; } } } } } function revealMint(MintCommit memory commit) internal { uint16 minted = wndNFT.minted(); pendingMintAmt -= commit.amount; uint16[] memory tokenIds = new uint16[](commit.amount); uint16[] memory tokenIdsToStake = new uint16[](commit.amount); uint256 seed = uint256(keccak256(abi.encode(commit.recipient, minted, commitIdStartTimeMints[_commitIdPendingMints]))); for (uint k = 0; k < commit.amount; k++) { minted++; // scramble the random so the steal / treasure mechanic are different per mint seed = uint256(keccak256(abi.encode(seed, commit.recipient))); address recipient = selectRecipient(seed, commit.recipient); if(recipient != commit.recipient && alter.balanceOf(commit.recipient, TREASURE_CHEST) > 0) { // If the mint is going to be stolen, there's a 50% chance // a dragon will prefer a treasure chest over it if(seed & 1 == 1) { alter.safeTransferFrom(commit.recipient, recipient, TREASURE_CHEST, 1, ""); recipient = commit.recipient; } } tokenIds[k] = minted; if (!commit.stake || recipient != commit.recipient) { wndNFT.mint(recipient, seed); } else { wndNFT.mint(address(trainingGrounds), seed); tokenIdsToStake[k] = minted; } } wndNFT.updateOriginAccess(tokenIds); if(commit.stake) { trainingGrounds.addManyToTowerAndFlight(commit.recipient, tokenIdsToStake); } pendingMintCommitsForAddr[commit.recipient] -= commit.amount; } function addToTower(uint16[] calldata tokenIds) external whenNotPaused { require(_msgSender() == tx.origin, "Only EOA"); for (uint256 i = 0; i < tokenIds.length; i++) { require(!tokenHasPendingCommit[tokenIds[i]], "token has pending commit"); } trainingGrounds.addManyToTowerAndFlight(tx.origin, tokenIds); } function addToTrainingCommit(uint16[] calldata tokenIds) external whenNotPaused { require(allowCommits, "adding commits disallowed"); require(tx.origin == _msgSender(), "Only EOA"); if(commitIdStartTimeTraining[_commitIdCurTraining] == 0) { commitIdStartTimeTraining[_commitIdCurTraining] = block.timestamp; } // Check if current commit batch is past the threshold for time and increment commitId if so if(commitIdStartTimeTraining[_commitIdCurTraining] < block.timestamp - timePerCommitBatch) { // increment commitId to start a new batch _commitIdCurTraining += 1; commitIdStartTimeTraining[_commitIdCurTraining] = block.timestamp; } // Loop through the amount of tokens being added uint16 numDragons; for (uint i = 0; i < tokenIds.length; i++) { require(address(trainingGrounds) != wndNFT.ownerOf(tokenIds[i]), "token already staked"); require(!tokenHasPendingCommit[tokenIds[i]], "token has pending commit"); require(_msgSender() == wndNFT.ownerOf(tokenIds[i]), "token already staked"); uint64 lastTokenWrite = wndNFT.getTokenWriteBlock(tokenIds[i]); // Must check this, as getTokenTraits will be allowed since this contract is an admin require(lastTokenWrite < block.number, "hmmmm what doing?"); if(!wndNFT.isWizard(tokenIds[i])) { numDragons += 1; } tokenHasPendingCommit[tokenIds[i]] = true; // Add N number of commits to the queue. This is so people reveal the same number of commits as they added. commitQueueTraining[_commitIdCurTraining].push(TrainingCommit(_msgSender(), tokenIds[i], true, false, true)); } gpToken.burn(_msgSender(), stakingCost * (tokenIds.length - numDragons)); // Dragons are free to stake gpToken.updateOriginAccess(); pendingTrainingCommitsForAddr[_msgSender()] += uint16(tokenIds.length); tryRevealTraining(tokenIds.length); } function claimTrainingsCommit(uint16[] calldata tokenIds, bool isUnstaking, bool isTraining) external whenNotPaused { require(allowCommits, "adding commits disallowed"); require(tx.origin == _msgSender(), "Only EOA"); if(commitIdStartTimeTraining[_commitIdCurTraining] == 0) { commitIdStartTimeTraining[_commitIdCurTraining] = block.timestamp; } // Check if current commit batch is past the threshold for time and increment commitId if so if(commitIdStartTimeTraining[_commitIdCurTraining] < block.timestamp - timePerCommitBatch) { // increment commitId to start a new batch _commitIdCurTraining += 1; commitIdStartTimeTraining[_commitIdCurTraining] = block.timestamp; } // Loop through the amount of tokens being added for (uint i = 0; i < tokenIds.length; i++) { require(!tokenHasPendingCommit[tokenIds[i]], "token has pending commit"); require(trainingGrounds.isTokenStaked(tokenIds[i], isTraining) && trainingGrounds.ownsToken(tokenIds[i]) , "Token not in staking pool"); uint64 lastTokenWrite = wndNFT.getTokenWriteBlock(tokenIds[i]); // Must check this, as getTokenTraits will be allowed since this contract is an admin require(lastTokenWrite < block.number, "hmmmm what doing?"); if(isUnstaking && wndNFT.isWizard(tokenIds[i])) { // Check to see if the wizard has earned enough to withdraw. // If emissions run out, allow them to attempt to withdraw anyways. if(isTraining) { require(trainingGrounds.curWhipsEmitted() >= 16000 || trainingGrounds.calculateErcEmissionRewards(tokenIds[i]) > 0, "can't unstake wizard yet"); } else { require(trainingGrounds.totalGPEarned() > 500000000 ether - 4000 ether || trainingGrounds.calculateGpRewards(tokenIds[i]) >= 4000 ether, "can't unstake wizard yet"); } } tokenHasPendingCommit[tokenIds[i]] = true; // Add N number of commits to the queue. This is so people reveal the same number of commits as they added. commitQueueTraining[_commitIdCurTraining].push(TrainingCommit(_msgSender(), tokenIds[i], false, isUnstaking, isTraining)); } gpToken.burn(_msgSender(), stakingCost * tokenIds.length); gpToken.updateOriginAccess(); pendingTrainingCommitsForAddr[_msgSender()] += uint16(tokenIds.length); tryRevealTraining(tokenIds.length); } function tryRevealTraining(uint256 amount) internal { // Check if the revealable commitId has anything to commit and increment it until it does, or is the same as the current commitId while(commitQueueTraining[_commitIdPendingTraining].length == 0 && _commitIdPendingTraining < _commitIdCurTraining) { // Only iterate if the commit pending is empty and behind the current id. // This is to prevent it from being in front of the current id and missing commits. _commitIdPendingTraining += 1; } // Check if there is a commit in a revealable batch and pop/reveal it if(commitIdStartTimeTraining[_commitIdPendingTraining] < block.timestamp - timePerCommitBatch && commitQueueTraining[_commitIdPendingTraining].length > 0) { // If the pending batch is old enough to be revealed and has stuff in it, mine the number that was added to the queue. for (uint256 i = 0; i < amount; i++) { // First iteration is guaranteed to have 1 commit to mine, so we can always retroactively check that we can continue to reveal after TrainingCommit memory commit = commitQueueTraining[_commitIdPendingTraining][commitQueueTraining[_commitIdPendingTraining].length - 1]; commitQueueTraining[_commitIdPendingTraining].pop(); revealTraining(commit); // Check to see if we are able to continue mining commits if(commitQueueTraining[_commitIdPendingTraining].length == 0 && _commitIdPendingTraining < _commitIdCurTraining) { _commitIdPendingTraining += 1; if(commitIdStartTimeTraining[_commitIdPendingTraining] > block.timestamp - timePerCommitBatch || commitQueueTraining[_commitIdPendingTraining].length == 0 || _commitIdPendingTraining == _commitIdCurTraining) { // If there are no more commits to reveal, exit break; } } } } } function revealTraining(TrainingCommit memory commit) internal { uint16[] memory idSingle = new uint16[](1); idSingle[0] = commit.tokenId; tokenHasPendingCommit[commit.tokenId] = false; if(commit.isAdding) { if(wndNFT.ownerOf(commit.tokenId) != commit.tokenOwner) { // The owner has transferred their token and can no longer be staked. We can simply skip this reveal. return; } if(wndNFT.isWizard(commit.tokenId)) { // Add to training since tower staking doesn't need C+R uint256 seed = random(commit.tokenId, commitIdStartTimeTraining[_commitIdPendingTraining], commit.tokenOwner); try trainingGrounds.addManyToTrainingAndFlight(seed, commit.tokenOwner, idSingle) { // Do nothing. It worked. } catch { // Return instead of reverting so that the queue can process this. return; } } else { // Dragons go to the tower but really they are in both pools. This just avoids the stealing logic. try trainingGrounds.addManyToTowerAndFlight(commit.tokenOwner, idSingle) { // Do nothing. It worked. } catch { // Return instead of reverting so that the queue can process this. return; } } } else { if(!trainingGrounds.isTokenStaked(commit.tokenId, commit.isTraining)) { // Skip reveals if the token has already been claimed since committing to this tx (like claiming multiple times unknowingly) return; } if(commit.isTraining) { uint256 seed = random(commit.tokenId, commitIdStartTimeTraining[_commitIdPendingTraining], commit.tokenOwner); try trainingGrounds.claimManyFromTrainingAndFlight(seed, commit.tokenOwner, idSingle, commit.isUnstaking) { // Do nothing. It worked. } catch { // Return instead of reverting so that the queue can process this. return; } } else { try trainingGrounds.claimManyFromTowerAndFlight(commit.tokenOwner, idSingle, commit.isUnstaking) { // Do nothing. It worked. } catch { // Return instead of reverting so that the queue can process this. return; } } } pendingTrainingCommitsForAddr[commit.tokenOwner] -= 1; } /** Deterministically random. This assumes the call was a part of commit+reveal design * that disallowed the benefactor of this outcome to make this call */ function random(uint16 tokenId, uint256 time, address owner) internal pure returns (uint256) { return uint256(keccak256(abi.encodePacked( owner, tokenId, time ))); } /** * @param tokenId the ID to check the cost of to mint * @return the cost of the given token ID */ function mintCost(uint256 tokenId, uint256 maxTokens) public view returns (uint256) { if (tokenId <= maxTokens * 8 / 20) return 24000 ether; if (tokenId <= maxTokens * 11 / 20) return 36000 ether; if (tokenId <= maxTokens * 14 / 20) return 48000 ether; if (tokenId <= maxTokens * 17 / 20) return 60000 ether; // if (tokenId > maxTokens * 17 / 20) return maxGpCost; } function makeTreasureChests(uint16 qty) external whenNotPaused { require(tx.origin == _msgSender(), "Only EOA"); // $GP exchange amount handled within alter contract // Will fail if sender doesn't have enough $GP // Transfer does not need approved, // as there is established trust between this contract and the alter contract alter.mint(TREASURE_CHEST, qty, _msgSender()); } function sellTreasureChests(uint16 qty) external whenNotPaused { require(tx.origin == _msgSender(), "Only EOA"); // $GP exchange amount handled within alter contract alter.burn(TREASURE_CHEST, qty, _msgSender()); } /** INTERNAL */ /** * the first 25% (ETH purchases) go to the minter * the remaining 80% have a 10% chance to be given to a random staked dragon * @param seed a random value to select a recipient from * @return the address of the recipient (either the minter or the Dragon thief's owner) */ function selectRecipient(uint256 seed, address committer) internal view returns (address) { if (((seed >> 245) % 10) != 0) return committer; // top 10 bits haven't been used address thief = trainingGrounds.randomDragonOwner(seed >> 144); // 144 bits reserved for trait selection if (thief == address(0x0)) return committer; return thief; } /** ADMIN */ /** * enables owner to pause / unpause contract */ function setPaused(bool _paused) external requireContractsSet onlyOwner { if (_paused) _pause(); else _unpause(); } function setMaxGpCost(uint256 _amount) external requireContractsSet onlyOwner { maxGpCost = _amount; } function setAllowCommits(bool allowed) external onlyOwner { allowCommits = allowed; } function setRevealRewardAmt(uint256 rewardAmt) external onlyOwner { revealRewardAmt = rewardAmt; } /** Allow the contract owner to set the pending mint amount. * This allows any long-standing pending commits to be overwritten, say for instance if the max supply has been * reached but there are many stale pending commits, it could be used to free up those spaces if needed/desired by the community. * This function should not be called lightly, this will have negative consequences on the game. */ function setPendingMintAmt(uint256 pendingAmt) external onlyOwner { pendingMintAmt = uint16(pendingAmt); } /** * allows owner to withdraw funds from minting */ function withdraw() external onlyOwner { payable(owner()).transfer(address(this).balance); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT LICENSE pragma solidity ^0.8.0; interface IWnDGame { } // SPDX-License-Identifier: MIT LICENSE pragma solidity ^0.8.0; interface ITrainingGrounds { function addManyToTowerAndFlight(address tokenOwner, uint16[] calldata tokenIds) external; function claimManyFromTowerAndFlight(address tokenOwner, uint16[] calldata tokenIds, bool unstake) external; function addManyToTrainingAndFlight(uint256 seed, address tokenOwner, uint16[] calldata tokenIds) external; function claimManyFromTrainingAndFlight(uint256 seed, address tokenOwner, uint16[] calldata tokenIds, bool unstake) external; function randomDragonOwner(uint256 seed) external view returns (address); function isTokenStaked(uint256 tokenId, bool isTraining) external view returns (bool); function ownsToken(uint256 tokenId) external view returns (bool); function calculateGpRewards(uint256 tokenId) external view returns (uint256 owed); function calculateErcEmissionRewards(uint256 tokenId) external view returns (uint256 owed); function curWhipsEmitted() external view returns (uint16); function curMagicRunesEmitted() external view returns (uint16); function totalGPEarned() external view returns (uint256); } // SPDX-License-Identifier: MIT LICENSE pragma solidity ^0.8.0; interface ITraits { function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT LICENSE pragma solidity ^0.8.0; interface IGP { function mint(address to, uint256 amount) external; function burn(address from, uint256 amount) external; function updateOriginAccess() external; function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); } // SPDX-License-Identifier: MIT LICENSE pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol"; interface IWnD is IERC721Enumerable { // game data storage struct WizardDragon { bool isWizard; uint8 body; uint8 head; uint8 spell; uint8 eyes; uint8 neck; uint8 mouth; uint8 wand; uint8 tail; uint8 rankIndex; } function minted() external returns (uint16); function updateOriginAccess(uint16[] memory tokenIds) external; function mint(address recipient, uint256 seed) external; function burn(uint256 tokenId) external; function getMaxTokens() external view returns (uint256); function getPaidTokens() external view returns (uint256); function getTokenTraits(uint256 tokenId) external view returns (WizardDragon memory); function getTokenWriteBlock(uint256 tokenId) external view returns(uint64); function isWizard(uint256 tokenId) external view returns(bool); } // SPDX-License-Identifier: MIT LICENSE pragma solidity ^0.8.0; interface ISacrificialAlter { function mint(uint256 typeId, uint16 qty, address recipient) external; function burn(uint256 typeId, uint16 qty, address burnFrom) external; function updateOriginAccess() external; function balanceOf(address account, uint256 id) external returns (uint256); function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes memory data) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); }
Loop through the amount of tokens being added
uint16 numDragons;
7,014,593
[ 1, 6452, 3059, 326, 3844, 434, 2430, 3832, 3096, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 2313, 818, 11728, 7008, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.7.6; pragma abicoder v2; import './SafeMath.sol'; import './AggregatorV3Interface.sol'; import './Wallet.sol'; // Crowdsale contract for ZAPP. Functionalities: // - Timed: opens Jan 14, 2021, 6:00:00PM UTC (1610647200) and closes Feb 14, 2021, 6:00:00PM UTC (1613325600) // - Capped: soft cap of 6M ZAPP, hard cap of 120M ZAPP // - Refundable: ETH can be refunded if soft cap hasn't been reached // - Post Delivery: ZAPP can be claimed after Token Sale end, if soft cap has been reached // - Early Adopter: Bonus ZAPP for a set duration // - Referral System: Bonus ZAPP when buying with referral link contract ZappermintTokenSale { using SafeMath for uint256; // Avoid overflow issues using WalletInterface for Wallet; // Wallet functionality // ---- // Variables // ---- // Token Sale configuration uint256 private _openingTime; // Start of Token Sale uint256 private _closingTime; // End of Token Sale uint256 private _claimTime; // Claim opening time uint256 private _softCap; // Minimum amount of ZAPP to sell (18 decimals) uint256 private _hardCap; // Maximum amount of ZAPP to sell (18 decimals) uint256 private _ethPrice; // Fallback ETH/USD price in case ChainLink breaks (8 decimals) uint256 private _zappPrice; // ZAPP/USD price (8 decimals) address private _zappContract; // Zappermint Token Contract address private _owner; // Owner of the contract // Wallets mapping(address => Wallet) private _wallets; // Addresses that have interacted with the Token Sale address[] _walletKeys; // Address list, for iterating over `_wallets` // Early Adopters uint256 private _earlyAdoptionEndTime; // End of early adoption bonus uint256 private _earlyAdoptionBonus; // Percentage of purchase to receive as bonus (8 decimals) // Referrals uint256 private _referrerMin; // Referrer minimum ZAPP bits (18 decimals) uint256 private _refereeMin; // Referee minimum ZAPP bits (18 decimals) uint256 private _referralBonus; // Percentage of purchase to receive as bonus (8 decimals) uint256[5] private _rankRewards; // Referrer rank reward list mapping(bytes3 => address) private _codes; // Referral codes // Bounty Hunters address[] _registeredHunters; // Registered hunter list uint256 private _maxHunters; // Maximum amount of registered bounty hunters uint256 private _registerBonus; // Bonus for registering as bounty hunter // Token Sale progress uint256 private _soldZAPP; // Amount of ZAPP sold (18 decimals) bool private _ended; // Whether the Token Sale has ended // Third party AggregatorV3Interface private _priceFeed; // ChainLink ETH/USD Price Feed // ---- // Modifiers // ---- /** * Only allow function with this modifier to run while the Token Sale is open */ modifier whileOpen { require(isOpen(), "Token Sale not open"); _; } /** * Only allow function with this modifier to run while the Token Sale is not closed * NOTE The difference with whileOpen is that this returns true also before Token Sale opens */ modifier whileNotClosed { require(!isClosed(), "Token Sale closed"); _; } /** * Only allow function with this modifier to run while the claims are open */ modifier whileClaimable { require(isClaimable(), "ZAPP can't be claimed yet"); _; } /** * Only allow function with this modifier to run after the Token Sale has ended */ modifier afterEnd { require(_ended, "Token Sale not ended"); _; } /** * Only allow function with this modifier to run before the Token Sale has ended */ modifier beforeEnd { require(!_ended, "Token Sale ended"); _; } /** * Only allow function with this modifier to run when the Token Sale has reached the soft cap */ modifier aboveSoftCap { require(isSoftCapReached(), "Token Sale hasn't reached soft cap"); _; } /** * Only allow function with this modifier to run when the Token Sale hasn't reached the soft cap */ modifier belowSoftCap { require(!isSoftCapReached(), "Token Sale reached soft cap"); _; } /** * Only allow function with this modifier to be run by the Zappermint Token Contract */ modifier onlyZAPPContract { require(msg.sender == _zappContract, "Only the Zappermint Token Contract can do this"); _; } /** * Only allow function with this modifier to be run by the owner */ modifier onlyOwner { require(msg.sender == _owner, "Only the owner can do this"); _; } // ---- // Constructor // ---- /** * Solves the Stack too deep error for the constructor * @param openingTime start time of the Token Sale (epoch) * @param closingTime end time of the Token Sale (epoch) * @param claimTime claim opening time (epoch) * @param softCap minimum amount of ZAPP to sell (18 decimals) * @param hardCap maximum amount of ZAPP to sell (18 decimals) * @param ethPrice price of 1 ETH in USD (8 decimals) to use in case ChainLink breaks * @param zappPrice price of 1 ZAPP in USD (8 decimals) * @param referrerMin minimum amount of ZAPP referrer must have purchased before getting a referral link (18 decimals) * @param refereeMin minimum amount of ZAPP referee must purchase to get referral bonus (18 decimals) * @param referralBonus percentage of purchase to receive as bonus (8 decimals) * @param rankRewards referrer rank reward list * @param earlyAdoptionEndTime end of early adoption bonus * @param earlyAdoptionBonus percentage of purchase to receive as bonus (8 decimals) * @param maxHunters maximum amount of bounty hunters * @param registerBonus bonus for registering as bounty hunter * @param aggregator address of ChainLink Aggregator price feed */ struct ContractArguments { uint256 openingTime; uint256 closingTime; uint256 claimTime; uint256 softCap; uint256 hardCap; uint256 ethPrice; uint256 zappPrice; uint256 referrerMin; uint256 refereeMin; uint256 referralBonus; uint256[5] rankRewards; uint256 earlyAdoptionEndTime; uint256 earlyAdoptionBonus; uint256 maxHunters; uint256 registerBonus; address aggregator; } constructor(ContractArguments memory args) { require(args.openingTime >= block.timestamp, "Opening time is before current time"); require(args.closingTime > args.openingTime, "Opening time is not before closing time"); require(args.claimTime >= args.closingTime, "Claiming time is not after closing time"); require(args.softCap < args.hardCap, "Hard cap is below soft cap"); _openingTime = args.openingTime; _closingTime = args.closingTime; _claimTime = args.claimTime; _softCap = args.softCap; _hardCap = args.hardCap; _ethPrice = args.ethPrice; _zappPrice = args.zappPrice; _referrerMin = args.referrerMin; _refereeMin = args.refereeMin; _referralBonus = args.referralBonus; _rankRewards = args.rankRewards; _earlyAdoptionEndTime = args.earlyAdoptionEndTime; _earlyAdoptionBonus = args.earlyAdoptionBonus; _maxHunters = args.maxHunters; _registerBonus = args.registerBonus; _priceFeed = AggregatorV3Interface(args.aggregator); _owner = msg.sender; } // ---- // Getters // ---- /** * @return Token Sale opening time */ function getOpeningTime() public view returns (uint256) { return _openingTime; } /** * @return Whether Token Sale is open */ function isOpen() public view returns (bool) { return block.timestamp >= _openingTime && block.timestamp <= _closingTime && !_ended; } /** * @return Token Sale closing time */ function getClosingTime() public view returns (uint256) { return _closingTime; } /** * @return Whether Token Sale is closed */ function isClosed() public view returns (bool) { return block.timestamp > _closingTime || _ended; } /** * @return Whether the Token Sale has been ended by the owner */ function isEnded() public view returns (bool) { return _ended; } /** * @return Early adoption end time */ function getEarlyAdoptionEndTime() public view returns (uint256) { return _earlyAdoptionEndTime; } /** * @return Whether the early adoption is active */ function isEarlyAdoptionActive() public view returns (bool) { return block.timestamp <= _earlyAdoptionEndTime; } /** * @return Percentage of purchase to receive as bonus during early adoption (8 decimals) */ function getEarlyAdoptionBonus() public view returns (uint256) { return _earlyAdoptionBonus; } /** * @return The claim opening time */ function getClaimTime() public view returns (uint256) { return _claimTime; } /** * @return Whether the ZAPP can be claimed */ function isClaimable() public view returns (bool) { return block.timestamp >= _claimTime && _ended && _zappContract != address(0); } /** * @return The minimum amount of ZAPP to sell (18 decimals) */ function getSoftCap() public view returns (uint256) { return _softCap; } /** * @return Whether the soft cap has been reached */ function isSoftCapReached() public view returns (bool) { return _soldZAPP >= _softCap; } /** * @return The maximum amount of ZAPP to sell (18 decimals) */ function getHardCap() public view returns (uint256) { return _hardCap; } /** * @return Whether the hard cap has been reached */ function isHardCapReached() public view returns (bool) { return _soldZAPP >= _hardCap; } /** * @return The total amount of ZAPP sold so far (18 decimals) */ function getSoldZAPP() public view returns (uint256) { return _soldZAPP; } /** * @return The current number of ZAPP a buyer gets per 1 ETH * NOTE Based on ETH/USD pair. 1 ZAPP = 0.05 USD */ function getRate() public view returns (uint256) { return getLatestPrice().div(_zappPrice); // 8 decimals } /** * @return The price of 1 ETH in USD. Attempts using ChainLink Aggregator, falls back to `_ethPrice` if broken. * NOTE 8 decimals */ function getLatestPrice() public view returns (uint256) { // Try/catch only works on external function calls. `this.f()` uses a message call instead of a direct jump, // which is considered external. // https://docs.soliditylang.org/en/v0.7.6/control-structures.html#external-function-calls // Note when ChainLink is broken, this will log an internal `revert` error, but the code will complete successfully try this.getChainlinkPrice() returns (uint256 price) { return price; } catch { return _ethPrice; } } /** * @return The price of 1 ETH in USD (from ChainLink Aggregator) * NOTE 8 decimals */ function getChainlinkPrice() public view returns (uint256) { // Get the ETH/USD price from ChainLink's Aggregator (,int256 p,,,) = _priceFeed.latestRoundData(); // This price is a signed int, so make sure it's higher than 0 require(p > 0, "Price feed invalid"); // We can now safely cast it to unsigned int and use SafeMath on it uint256 price = uint256(p); // Verify the number of decimals. We work with 8 decimals for USD prices, // but ChainLink can choose to change this at any point outside of our control. // We ensure that the price has 8 decimals with the math below. // Note that the exponent must be positive, so we use div instead of mul in case // the number of decimals is smaller than 8. uint8 decimals = _priceFeed.decimals(); if (decimals == 8) return price; else if (decimals < 8) return price.div(10**(8 - decimals)); else return price.mul(10**(decimals - 8)); } /** * @return Minimum amount of ZAPP a referrer must have bought to get a referral link (18 decimals) */ function getReferrerMin() public view returns (uint256) { return _referrerMin; } /** * @return Minimum amount of ZAPP a referee must buy to get referral bonus (18 decimals) */ function getRefereeMin() public view returns (uint256) { return _refereeMin; } /** * @return Percentage of purchase to receive as bonus (8 decimals) */ function getReferralBonus() public view returns (uint256) { return _referralBonus; } /** * @return The referral code for this address */ function getReferralCode() public view returns (bytes3) { return _wallets[msg.sender].referrer.code; } /** * @param code referral code * @return Whether the referral code is valid */ function isReferralCodeValid(bytes3 code) public view returns (bool) { return _codes[code] != address(0) && _codes[code] != msg.sender; } /** * @return The referral rank reward list */ function getRankRewards() public view returns (uint256[5] memory) { return _rankRewards; } /** * @return The amount of registered Bounty Hunters */ function getRegisteredHunters() public view returns (uint256) { return _registeredHunters.length; } /** * @return The maximum number of Bounty Hunters that can register */ function getMaxHunters() public view returns (uint256) { return _maxHunters; } /** * @return The bonus for registering as Bounty Hunter */ function getRegisterBonus() public view returns (uint256) { return _registerBonus; } /** * @return Whether Bounty Hunters can still register */ function canRegister() public view returns (bool) { return getRegisteredHunters() < getMaxHunters(); } /** * @param addr address to check * @return Whether the address is a Bounty Hunter */ function isHunter(address addr) public view returns (bool) { return _wallets[addr].isHunter; } /** * @param addr address to check * @return Whether the address is a registered Bounty Hunter */ function isHunterRegistered(address addr) public view returns (bool) { for (uint256 i = 0; i < _registeredHunters.length; ++i) { if (_registeredHunters[i] == addr) return true; } return false; } /** * @return Whether the Bounty Hunter is verified by Zappermint */ function isHunterVerified(address addr) public view returns (bool) { return _wallets[addr].hunter.verified; } /** * @param addr address to get ETH of * @return The amount of wei this address has spent (18 decimals) */ function getBuyerETH(address addr) public view returns (uint256) { if (hasWalletClaimed(addr)) return 0; return _wallets[addr].buyer.eth; } /** * @param addr address to get ZAPP of * @return The amount of ZAPP bits this address has bought (18 decimals) */ function getBuyerZAPP(address addr) public view returns (uint256) { if (hasWalletClaimed(addr)) return 0; return _wallets[addr].buyer.zapp; } /** * @param addr address to get bonus of * @return The amount of ZAPP bits this address will get as early adopter bonus (18 decimals) */ function getEarlyAdopterBonus(address addr) public view returns (uint256) { if (hasWalletClaimed(addr)) return 0; return _wallets[addr].getEarlyAdopterBonus(_earlyAdoptionBonus); } /** * @param addr address to get bonus of * @return The amount of ZAPP bits this address will get as referrer bonus (18 decimals) */ function getReferrerBonus(address addr) public view returns (uint256) { if (hasWalletClaimed(addr)) return 0; return _wallets[addr].getReferrerBonus(_referralBonus, _referrerMin, isClaimable()); } /** * @param addr address to get bonus of * @return The amount of ZAPP bits this address will receive as bonus for his purchase(s) (18 decimals) */ function getRefereeBonus(address addr) public view returns (uint256) { if (hasWalletClaimed(addr)) return 0; return _wallets[addr].getRefereeBonus(_referralBonus); } /** * @param addr address to get bonus of * @return The amount of ZAPP bits this address will receive as bonus for his bounty campaign (18 decimals) */ function getHunterBonus(address addr) public view returns (uint256) { if (hasWalletClaimed(addr)) return 0; return _wallets[addr].getHunterBonus(isClaimable()); } /** * @param addr address to get reward of * @return The amount of ZAPP bits this address will be rewarded with for referrer rank (18 decimals) */ function getReferrerRankReward(address addr) public view returns (uint256) { if (hasWalletClaimed(addr)) return 0; uint256 rank = getReferrerRank(addr); if (rank == 0) return 0; --rank; if (rank < _rankRewards.length) return _rankRewards[rank]; return 0; } /** * @param addr address to get reward of * @return The total amount of ZAPP bits this address will get as bonus (18 decimals) * NOTE Hunter and referrer rank rewards only added when claimable */ function getWalletTotalBonus(address addr) public view returns (uint256) { if (hasWalletClaimed(addr)) return 0; uint256 total = getEarlyAdopterBonus(addr) .add(getReferrerBonus(addr)) .add(getRefereeBonus(addr)); bool verified = isHunterVerified(addr); bool claimable = isClaimable(); // Add hunter bonus when verified if (verified) { total = total.add(getHunterBonus(addr)); } // Also add hunter bonus when not claimable yet else if (!claimable) { total = total.add(getHunterBonus(addr)); } // Add rank reward when claimable if (claimable) { total = total.add(getReferrerRankReward(addr)); } return total; } /** * @param addr address to get ZAPP of * @return The total amount of ZAPP bits this address can claim (18 decimals) */ function getWalletTotalZAPP(address addr) public view returns (uint256) { if (hasWalletClaimed(addr)) return 0; return getBuyerZAPP(addr) .add(getWalletTotalBonus(addr)); } /** * @param addr address to get claimed state of * @return Whether this address has claimed their ZAPP */ function hasWalletClaimed(address addr) public view returns (bool) { return _wallets[addr].claimed; } /** * @param addr address to get referrals of * @return The list of successful referrals of the referrer */ function getReferrals(address addr) public view returns (uint256[] memory) { uint256 length = _wallets[addr].referrer.referrals.length; uint256[] memory referrals = new uint256[](length); for (uint256 i = 0; i < length; ++i) { referrals[i] = _wallets[addr].referrer.referrals[i].zapp; } return referrals; } /** * Get the ranking position of the referrer * @param addr referrer address * @return The one-based rank of the referrer. 0 if not a referrer */ function getReferrerRank(address addr) public view returns (uint256) { // Non-referrers don't have a rank if (!_wallets[addr].isReferrer) return 0; // Must have at least one referral if (_wallets[addr].referrer.referrals.length == 0) return 0; // Start at rank 1 uint256 rank = 1; uint256 amount1 = _wallets[addr].calculateReferredAmount(_referrerMin, isClaimable()); if (amount1 == 0) return 0; // Find every referrer with a higher referral sum for (uint256 key = 0; key < _walletKeys.length; ++key) { // Skip self if (addr == _walletKeys[key]) continue; // Skip non-referrers if (!_wallets[_walletKeys[key]].isReferrer) continue; uint256 amount2 = _wallets[_walletKeys[key]].calculateReferredAmount(_referrerMin, isClaimable()); if (amount2 == 0) continue; // Increase the rank if another referrer has a higher sum if (amount2 > amount1) ++rank; // Increase the rank if another referrer has same amount but earlier time else if (amount2 == amount1 && _wallets[_walletKeys[key]].referrer.time < _wallets[addr].referrer.time) ++rank; } return rank; } /** * Get the top 5 referrers * @return The array of referred amounts of the top 5 referrers * NOTE This can vary depending on the isClaimable state */ function getTopReferrers() public view returns (uint256[5] memory) { uint256[5] memory top = [uint256(0), uint256(0), uint256(0), uint256(0), uint256(0)]; for (uint256 key = 0; key < _walletKeys.length; ++key) { uint256 amount = _wallets[_walletKeys[key]].calculateReferredAmount(_referrerMin, isClaimable()); for (uint256 t = 0; t < top.length; ++t) { if (amount > top[t]) { for (uint256 i = 4; i > t; --i) { top[i] = top[i - 1]; } top[t] = amount; break; } } } return top; } /** * @return Total amount of ZAPP that has been bought during Early Adoption */ function getTotalEarlyAdoptionZAPP() public view returns (uint256) { uint256 total; for (uint256 i = 0; i < _walletKeys.length; ++i) { total = total.add(_wallets[_walletKeys[i]].earlyAdopter.zapp); } return total; } /** * @return Total amount of ZAPP that has been bought without referral code */ function getTotalWithoutCodeZAPP() public view returns (uint256) { uint256 total; for (uint256 i = 0; i < _walletKeys.length; ++i) { total = total.add(_wallets[_walletKeys[i]].buyer.zapp) .sub(_wallets[_walletKeys[i]].referee.zapp); } return total; } /** * @return Total amount of ZAPP that has been bought with referral code */ function getTotalReferredZAPP() public view returns (uint256) { uint256 total; for (uint256 i = 0; i < _walletKeys.length; ++i) { total = total.add(_wallets[_walletKeys[i]].referee.zapp); } return total; } /** * @return Total amount of ZAPP that has been bought with Bounty Hunter referral code */ function getTotalHunterReferredZAPP() public view returns (uint256) { uint256 total; for (uint256 i = 0; i < _registeredHunters.length; ++i) { total = total.add(_wallets[_registeredHunters[i]].calculateReferredAmount(_referrerMin, false)); } return total; } /** * @return The Zappermint Token Contract address */ function getZAPPContract() public view returns (address) { return _zappContract; } /** * @return The owner of the Token Sale Contract */ function getOwner() public view returns (address) { return _owner; } // ---- // Currency helpers // ---- /** * Calculate amount of ZAPP for a given amount of wei * @param weiAmount amount of wei (18 decimals) * @return ZAPP */ function calculateZAPPAmount(uint256 weiAmount) public view returns (uint256) { return weiAmount.mul(getRate()); } /** * Calculate amount of ETH for a given amount of ZAPP bits * @param zappAmount amount of ZAPP bits (18 decimals) * @return Wei */ function calculateETHAmount(uint256 zappAmount) public view returns (uint256) { return zappAmount.div(getRate()); } // ---- // Setters // ---- /** * Changes the ETH price in case ChainLink breaks * @param price price of 1 ETH in USD (8 decimals) */ function setETHPrice(uint256 price) public beforeEnd onlyOwner { _ethPrice = price; } /** * Changes the max amount of Bounty Hunters that can register * @param max new max amount */ function setMaxHunters(uint256 max) public beforeEnd onlyOwner { _maxHunters = max; } /** * Closes the Token Sale manually */ function endTokenSale() public onlyOwner { _ended = true; } /** * Sets the address of the Zappermint Token Contract * @param zappContract address of the Zappermint Token Contract */ function setZAPPContract(address zappContract) public onlyOwner { _zappContract = zappContract; } /** * Transfers ownership * @param newOwner address of the new owner */ function changeOwner(address newOwner) public onlyOwner { _owner = newOwner; } // ---- // Transaction functions // ---- /** * Fallback function shouldn't do anything, as it won't have any ETH to buy ZAPP with */ fallback () external whileOpen { revert("Fallback function called"); } /** * Receive function to buy ZAPP */ receive() external payable whileOpen { buyZAPP(); } /** * Buy ZAPP without referral code */ function buyZAPP() public payable whileOpen { uint256 zapp = _buyZAPP(msg.sender, msg.value); _assignBonuses(msg.sender, zapp, bytes3(0)); } /** * Buy ZAPP with referral code * @param code used referral code */ function buyZAPPWithCode(bytes3 code) public payable whileOpen { uint256 zapp = _buyZAPP(msg.sender, msg.value); _assignBonuses(msg.sender, zapp, code); } /** * Register as Bounty Hunter * NOTE This generates a code for the address, disregarding the bought zapp amount */ function registerHunter() public whileNotClosed { require(!isHunterRegistered(msg.sender), "Already a Bounty Hunter"); require(canRegister(), "Maximum amount of Bounty Hunters has been reached"); // Register without purchase if (_wallets[msg.sender].addr == address(0)) { _wallets[msg.sender].addr = msg.sender; _walletKeys.push(msg.sender); } _wallets[msg.sender].register(_registerBonus, _codes); _registeredHunters.push(msg.sender); } /** * Verifies Bounty Hunters and adds their collected bounty rewards * @param hunters list of Bounty Hunters * @param bonuses list of bounty rewards (18 decimals) * NOTE Lists need to be of same length */ function verifyHunters(address[] memory hunters, uint256[] memory bonuses) public afterEnd aboveSoftCap onlyOwner { require(hunters.length == bonuses.length, "Data length mismatch"); for (uint256 i = 0; i < hunters.length; ++i) { // Verify without purchase if (_wallets[hunters[i]].addr == address(0)) { _wallets[hunters[i]].addr = payable(hunters[i]); _walletKeys.push(msg.sender); } _wallets[hunters[i]].verify(bonuses[i]); } } /** * Transfers the contract's wei to a wallet, after Token Sale ended and has reached the soft cap * @param wallet address to send wei to */ function claimETH(address payable wallet) public afterEnd aboveSoftCap onlyOwner { wallet.transfer(address(this).balance); } /** * Lets a wallet claim their ZAPP through the Zappermint Token Contract, after claim opening time * and if token sale has reached the soft cap * @return Amount of bought ZAPP and amount of bonus ZAPP * NOTE The payout implementation of this can be found in the Zappermint Token Contract */ function claimZAPP() public afterEnd aboveSoftCap whileClaimable onlyZAPPContract returns (uint256, uint256) { address beneficiary = tx.origin; // Use tx, as msg points to the Zappermint Token Contract require(!hasWalletClaimed(beneficiary), "Already claimed"); uint256 zapp = getBuyerZAPP(beneficiary); uint256 bonus = getWalletTotalBonus(beneficiary); // Adjust claimed state _wallets[beneficiary].claimed = true; // Return amount of ZAPP and bonus of the wallet // NOTE Returned separately so the Token Contract can send the ZAPP from the correct pools return (zapp, bonus); } /** * Lets the buyer claim their ETH, after Token Sale ended and hasn't reached the soft cap */ function claimRefund() public afterEnd belowSoftCap { address beneficiary = msg.sender; require(_wallets[beneficiary].isBuyer, "Not a buyer"); require(!_wallets[beneficiary].claimed, "Already claimed"); // Get buyer variables before changing state (otherwise will return 0!) uint256 zapp = getBuyerZAPP(beneficiary); uint256 eth = getBuyerETH(beneficiary); // Adjust claimed state _wallets[beneficiary].claimed = true; // Adjust Token Sale state _soldZAPP = _soldZAPP.sub(zapp); // Refund the ETH of the buyer _wallets[beneficiary].addr.transfer(eth); } // ---- // Internal functions // ---- /** * Calculate amount of ZAPP for a given amount of wei * @param weiAmount amount of wei * @param rate ZAPP/ETH rate * @return ZAPP bits (18 decimals) * NOTE Internally used as optimization by avoiding multiple Chainlink calls */ function _calculateZAPPAmount(uint256 weiAmount, uint256 rate) internal pure returns (uint256) { return weiAmount.mul(rate); } /** * Calculate amount of ETH for a given amount of ZAPP bits * @param zappAmount amount of ZAPP bits (18 decimals) * @param rate ZAPP/ETH rate * @return wei * NOTE Internally used as optimization by avoiding multiple Chainlink calls */ function _calculateETHAmount(uint256 zappAmount, uint256 rate) internal pure returns (uint256) { return zappAmount.div(rate); } /** * Buys ZAPP * @param beneficiary address of buyer * @param eth amount of ETH sent * @return Amount of ZAPP bought */ function _buyZAPP(address beneficiary, uint256 eth) internal returns (uint256) { // Verify amount of ETH require(eth > 0, "Not enough ETH"); // First purchase if (_wallets[beneficiary].addr == address(0)) { _wallets[beneficiary].addr = payable(beneficiary); _walletKeys.push(beneficiary); } // Make sure the rate is consistent in this purchase uint256 rate = getRate(); // Calculate the amount of ZAPP to receive and add it to the total sold uint256 zapp = _calculateZAPPAmount(eth, rate); _soldZAPP = _soldZAPP.add(zapp); // Verify that this purchase isn't surpassing the hard cap, otherwise refund exceeding amount int256 exceeding = int256(_soldZAPP - _hardCap); uint256 exceedingZAPP = 0; uint256 exceedingETH = 0; if (exceeding > 0) { // Adjust sold amount and close Token Sale _soldZAPP = _hardCap; _ended = true; // Adjust amount of bought ZAPP and paid ETH exceedingZAPP = uint256(exceeding); exceedingETH = _calculateETHAmount(exceedingZAPP, rate); zapp = zapp.sub(exceedingZAPP); eth = eth.sub(exceedingETH); } // Adjust the buyer _wallets[beneficiary].purchase(eth, zapp); // Purchase adds total bought ZAPP to more than referrer minimum if (!_wallets[beneficiary].isReferrer && _wallets[beneficiary].buyer.zapp >= _referrerMin) { _wallets[beneficiary].isReferrer = true; _wallets[beneficiary].generateReferralCode(_codes); } // Refund the exceeding ETH // NOTE Checks-Effects-Interactions pattern if (exceeding > 0) _wallets[beneficiary].addr.transfer(exceedingETH); return zapp; } /** * Assigns all active bonuses for a purchase * @param beneficiary address of the buyer * @param zapp amount of ZAPP bits purchased (18 decimals) * @param code used referral code (set to 0 if no code used) */ function _assignBonuses(address beneficiary, uint256 zapp, bytes3 code) internal { // Referral bonus if code is valid and purchased enough ZAPP if (isReferralCodeValid(code)) { if (zapp >= _refereeMin) { _wallets[beneficiary].referral(zapp, _wallets[_codes[code]]); } } // Early adopter bonus if code invalid and early adoption active else { if (isEarlyAdoptionActive()) { _wallets[beneficiary].earlyAdoption(zapp); } } } }
Zappermint Token Contract
address private _zappContract;
12,585,300
[ 1, 62, 438, 12160, 474, 3155, 13456, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 1758, 3238, 389, 94, 2910, 8924, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.3; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import { IInv, InverseVester } from "./InverseVester.sol"; /** * @title Inverse token vesting factory contract * @author Inverse Finance * @notice Factory contract to create configurable vesting agreement */ contract InverseVesterFactory is Ownable { using SafeERC20 for IInv; using EnumerableSet for EnumerableSet.AddressSet; /// @dev Emitted when vesting is created event VestingCreated(address recipient, address inverseVester, uint256 amount, uint16 vestingDuration); /// @dev Inverse finance governance timelock address public timelock; /// @dev Inverse finance treasury token address public immutable inv; /// @dev Registry of vesting agreements by recipient mapping(address => InverseVester[]) public inverseVestersByRecipient; /// @dev Registry of all recipients EnumerableSet.AddressSet private _allRecipients; constructor(address inv_, address timelock_) { require(inv_ != address(0) && timelock_ != address(0), "InverseVesterFactory:INVALID_ADDRESS"); inv = inv_; timelock = timelock_; transferOwnership(timelock_); } /** * @notice Creates a new vesting agreement * @param recipient Recipient of the vesting agreement * @param vestingAmount Amount to vest * @param vestingDurationInDays Length of the vesting period express in days * @param vestingStartDelayInDays Delay between contract activation and vesting period start * @param reverseVesting True if tokens are owned but the recipient * @param interruptible True if governance can interrupt the agreement */ function newInverseVester( address recipient, uint256 vestingAmount, uint16 vestingDurationInDays, uint16 vestingStartDelayInDays, bool reverseVesting, bool interruptible ) public onlyOwner { InverseVester inverseVester = new InverseVester( inv, timelock, vestingAmount, vestingDurationInDays, vestingStartDelayInDays, reverseVesting, interruptible, recipient ); IInv(inv).safeTransferFrom(timelock, address(inverseVester), vestingAmount); inverseVestersByRecipient[recipient].push(inverseVester); _allRecipients.add(recipient); emit VestingCreated(recipient, address(inverseVester), vestingAmount, vestingDurationInDays); } /** * @notice Convenience function to create a new non interruptible vesting agreement * @param recipient Recipient of the vesting agreement * @param vestingAmount Amount to vest * @param vestingDurationInDays Length of the vesting period express in days * @param vestingStartDelayInDays Delay between contract activation and vesting period start * @param reverseVesting True if tokens are owned but the recipient */ function newNonInterruptibleVestingAgreement( address recipient, uint256 vestingAmount, uint16 vestingDurationInDays, uint16 vestingStartDelayInDays, bool reverseVesting ) external { newInverseVester( recipient, vestingAmount, vestingDurationInDays, vestingStartDelayInDays, reverseVesting, false ); } /** * @notice Convenience function to create a new interruptible vesting agreement * @param recipient Recipient of the vesting agreement * @param vestingAmount Amount to vest * @param vestingDurationInDays Length of the vesting period express in days * @param vestingStartDelayInDays Delay between contract activation and vesting period start * @param reverseVesting True if tokens are owned but the recipient */ function newInterruptibleVestingAgreement( address recipient, uint256 vestingAmount, uint16 vestingDurationInDays, uint16 vestingStartDelayInDays, bool reverseVesting ) external { newInverseVester( recipient, vestingAmount, vestingDurationInDays, vestingStartDelayInDays, reverseVesting, true ); } /** * @notice Convenience function to create a new standard salary agreement * @param recipient Recipient of the vesting agreement * @param vestingAmount Amount to vest * @param vestingDurationInDays Length of the vesting period express in days * @param vestingStartDelayInDays Delay between contract activation and vesting period start */ function newSalaryAgreement( address recipient, uint256 vestingAmount, uint16 vestingDurationInDays, uint16 vestingStartDelayInDays ) external { newInverseVester(recipient, vestingAmount, vestingDurationInDays, vestingStartDelayInDays, false, true); } /** * @notice Returns all recipients of a vesting aggrement * @return recipients all recipients */ function getAllRecipients() external view returns (address[] memory recipients) { uint256 length = _allRecipients.length(); recipients = new address[](length); for (uint256 i = 0; i < length; i++) { recipients[i] = _allRecipients.at(i); } return recipients; } /** * @notice Returns all vesting agreement for a recipient * @param recipient Recipient of the vesting agreements * @return all vesting agreements for recipient */ function getInverseVestersByRecipient(address recipient) external view returns (InverseVester[] memory) { return inverseVestersByRecipient[recipient]; } /** * @notice Replace timelock * @param newTimelock New timelock address */ function setTimelock(address newTimelock) external onlyOwner { require(newTimelock != address(0), "InverseVesterFactory:INVALID_ADDRESS"); timelock = newTimelock; transferOwnership(newTimelock); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "./interfaces/IInv.sol"; /** * @title Inverse token vesting contract * @author Inverse Finance * @notice Contract for vesting agreement on INV tokens * @dev Vesting calculation is linear */ contract InverseVester is Ownable { using SafeERC20 for IInv; /// @dev Emitted when vesting is interrupted event VestingInterrupted(address recipient, uint256 vestingBegin, uint256 vestingAmount); uint256 public constant DAY = 1 days; /// @dev Timestamp for the start of this vesting agreement uint256 public vestingBegin; /// @dev Timestamp for the end of this vesting agreement uint256 public vestingEnd; /// @dev Timestamp for the last time vested tokens were claimed uint256 public lastClaimTimestamp; /// @dev Total amount to be vested uint256 public immutable vestingAmount; /// @dev By how long the vesting should be delayed after activating this contract /// This can be used for multi year vesting agreements uint16 public immutable vestingStartDelayInDays; /// @dev Inverse finance governance timelock contract address public timelock; /// @dev Amount of days the vesting period will last uint16 public immutable vestingDurationInDays; /// @dev Whether this is a reverse vesting agreement bool public immutable reverseVesting; /// @dev Whether this is vesting agreement can be interrupted bool public immutable interruptible; /// @dev Inverse finance treasury token IInv public immutable inv; /** * @dev Prevents non timelock from calling a method */ modifier onlyTimelock() { require(msg.sender == timelock, "InverseVester:ACCESS_DENIED"); _; } constructor( address inv_, address timelock_, uint256 vestingAmount_, uint16 vestingDurationInDays_, uint16 vestingStartDelayInDays_, bool reverseVesting_, bool interruptible_, address recipient ) { require( inv_ != address(0) && timelock_ != address(0) && recipient != address(0), "InverseVester:INVALID_ADDRESS" ); require(vestingAmount_ > 0, "InverseVester:INVALID_AMOUNT"); inv = IInv(inv_); vestingAmount = vestingAmount_; vestingDurationInDays = vestingDurationInDays_; reverseVesting = reverseVesting_; timelock = timelock_; vestingStartDelayInDays = vestingStartDelayInDays_; interruptible = interruptible_; transferOwnership(recipient); } /** * @notice Activates contract */ function activate() public onlyOwner { require(vestingBegin == 0, "InverseVester:ALREADY_ACTIVE"); if (reverseVesting) { inv.delegate(owner()); } else { inv.delegate(timelock); } vestingBegin = lastClaimTimestamp = block.timestamp + (vestingStartDelayInDays * DAY); vestingEnd = vestingBegin + (vestingDurationInDays * DAY); } /** * @notice Delegates all votes owned by this contract * @dev Only available in reverse vesting * @param delegate_ recipient of the votes */ function delegate(address delegate_) public onlyOwner { // If this is non reverse vesting, tokens votes stay with treasury require(reverseVesting, "InverseVester:DELEGATION_NOT_ALLOWED"); inv.delegate(delegate_); } /** * @notice Calculates amount of tokens ready to be claimed * @return amount Tokens ready to be claimed */ function claimable() public view returns (uint256 amount) { if (!active()) { amount = 0; } else if (block.timestamp >= vestingEnd) { amount = inv.balanceOf(address(this)); } else { // Claim linearly starting from when claimed lastly amount = (vestingAmount * (block.timestamp - lastClaimTimestamp)) / (vestingEnd - vestingBegin); } } /** * @notice Calculates amount of tokens still to be vested * @return amount Tokens still to be vested */ function unvested() public view returns (uint256 amount) { uint256 balance = inv.balanceOf(address(this)); amount = active() ? balance - claimable() : balance; } /** * @notice Send claimable tokens to contract's owner */ function claim() public { require(active() && vestingBegin <= block.timestamp, "InverseVester:NOT_STARTED"); uint256 amount = claimable(); lastClaimTimestamp = block.timestamp; inv.safeTransfer(owner(), amount); } /** * @notice Interrupts this vesting agreement and returns * all unvested tokens to the address provided * @param collectionAccount Where to send unvested tokens */ function interrupt(address collectionAccount) external onlyTimelock { require(interruptible || !active(), "InverseVester:CANNOT_INTERRUPT"); require(collectionAccount != address(0), "InverseVester:INVALID_ADDRESS"); inv.safeTransfer(collectionAccount, unvested()); // if interrupted after activation we terminate vesting now if (vestingEnd != 0) { vestingEnd = block.timestamp; } emit VestingInterrupted(owner(), vestingBegin, vestingAmount); } /** * @notice Whether this contract has been activated * @return True if active */ function active() public view returns (bool) { return vestingBegin != 0; } /** * @notice Replace timelock * @param newTimelock New timelock address */ function setTimelock(address newTimelock) external onlyTimelock { require(newTimelock != address(0), "InverseVester:INVALID_ADDRESS"); timelock = newTimelock; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IInv is IERC20 { function delegate(address delegatee) external; }
@dev Emitted when vesting is created @dev Inverse finance governance timelock @dev Inverse finance treasury token @dev Registry of vesting agreements by recipient @dev Registry of all recipients
constructor(address inv_, address timelock_) { require(inv_ != address(0) && timelock_ != address(0), "InverseVesterFactory:INVALID_ADDRESS"); inv = inv_; timelock = timelock_; transferOwnership(timelock_); }
1,590,438
[ 1, 1514, 11541, 1347, 331, 10100, 353, 2522, 225, 657, 2476, 574, 1359, 314, 1643, 82, 1359, 1658, 292, 975, 225, 657, 2476, 574, 1359, 9787, 345, 22498, 1147, 225, 5438, 434, 331, 10100, 19602, 87, 635, 8027, 225, 5438, 434, 777, 12045, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 3885, 12, 2867, 2198, 67, 16, 1758, 1658, 292, 975, 67, 13, 288, 203, 3639, 2583, 12, 5768, 67, 480, 1758, 12, 20, 13, 597, 1658, 292, 975, 67, 480, 1758, 12, 20, 3631, 315, 16376, 58, 7654, 1733, 30, 9347, 67, 15140, 8863, 203, 3639, 2198, 273, 2198, 67, 31, 203, 3639, 1658, 292, 975, 273, 1658, 292, 975, 67, 31, 203, 3639, 7412, 5460, 12565, 12, 8584, 292, 975, 67, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.24; // ---------------------------------------------------------------------------- // Sample token contract // // Symbol : JESUS // Name : Christ Network // Total supply : 33000000000000000000000000 // Decimals : 18 // Owner Account : 0x1b8428570FEE007C6d68B0E6Dee16e796A5fa41c // // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- // Lib: Safe Math // ---------------------------------------------------------------------------- contract SafeMath { function safeAdd(uint a, uint b) public pure returns (uint c) { c = a + b; require(c >= a); } function safeSub(uint a, uint b) public pure returns (uint c) { require(b <= a); c = a - b; } function safeMul(uint a, uint b) public pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function safeDiv(uint a, uint b) public pure returns (uint c) { require(b > 0); c = a / b; } } /** ERC Token Standard #20 Interface https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md */ contract ERC20Interface { function totalSupply() public constant returns (uint); function balanceOf(address tokenOwner) public constant returns (uint balance); function allowance(address tokenOwner, address spender) public constant returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } /** Contract function to receive approval and execute function in one call Borrowed from MiniMeToken */ contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 tokens, address token, bytes data) public; } /** ERC20 Token, with the addition of symbol, name and decimals and assisted token transfers */ contract JESUSToken is ERC20Interface, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public { symbol = "JESUS"; name = "Christ Network"; decimals = 18; _totalSupply = 33000000000000000000000000; balances[0x1b8428570FEE007C6d68B0E6Dee16e796A5fa41c] = _totalSupply; emit Transfer(address(0), 0x1b8428570FEE007C6d68B0E6Dee16e796A5fa41c, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } }
*/ ------------------------------------------------------------------------ Constructor ------------------------------------------------------------------------
contract JESUSToken is ERC20Interface, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; Contract function to receive approval and execute function in one call Borrowed from MiniMeToken } ERC20 Token, with the addition of symbol, name and decimals and assisted token transfers constructor() public { symbol = "JESUS"; name = "Christ Network"; decimals = 18; _totalSupply = 33000000000000000000000000; balances[0x1b8428570FEE007C6d68B0E6Dee16e796A5fa41c] = _totalSupply; emit Transfer(address(0), 0x1b8428570FEE007C6d68B0E6Dee16e796A5fa41c, _totalSupply); } function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); return true; } function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true; } function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } function () public payable { revert(); } }
5,921,317
[ 1, 19, 8879, 17082, 11417, 8879, 17082, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 804, 3991, 5996, 969, 353, 4232, 39, 3462, 1358, 16, 14060, 10477, 288, 203, 565, 533, 1071, 3273, 31, 203, 565, 533, 1071, 225, 508, 31, 203, 565, 2254, 28, 1071, 15105, 31, 203, 565, 2254, 1071, 389, 4963, 3088, 1283, 31, 203, 203, 565, 2874, 12, 2867, 516, 2254, 13, 324, 26488, 31, 203, 565, 2874, 12, 2867, 516, 2874, 12, 2867, 516, 2254, 3719, 2935, 31, 203, 203, 203, 8924, 445, 358, 6798, 23556, 471, 1836, 445, 316, 1245, 745, 203, 203, 38, 15318, 329, 628, 27987, 4667, 1345, 203, 97, 203, 203, 654, 39, 3462, 3155, 16, 598, 326, 2719, 434, 3273, 16, 508, 471, 15105, 471, 1551, 25444, 1147, 29375, 203, 565, 3885, 1435, 1071, 288, 203, 3639, 3273, 273, 315, 46, 3991, 3378, 14432, 203, 3639, 508, 273, 315, 782, 86, 376, 5128, 14432, 203, 3639, 15105, 273, 6549, 31, 203, 3639, 389, 4963, 3088, 1283, 273, 13159, 12648, 12648, 12648, 31, 203, 3639, 324, 26488, 63, 20, 92, 21, 70, 5193, 6030, 25, 7301, 8090, 41, 713, 27, 39, 26, 72, 9470, 38, 20, 41, 26, 758, 73, 2313, 73, 7235, 26, 37, 25, 507, 9803, 71, 65, 273, 389, 4963, 3088, 1283, 31, 203, 3639, 3626, 12279, 12, 2867, 12, 20, 3631, 374, 92, 21, 70, 5193, 6030, 25, 7301, 8090, 41, 713, 27, 39, 26, 72, 9470, 38, 20, 41, 26, 758, 73, 2313, 73, 7235, 26, 37, 25, 507, 9803, 71, 16, 389, 4963, 3088, 1283, 1769, 203, 565, 289, 203, 203, 203, 565, 2 ]
pragma solidity ^0.4.17; /** * @title Ouroboros Contract * @author AL_X * @dev The Ouroboros contract handling the interbank transactions */ contract Ouroboros { uint256 private ouroborosFee; uint256 private purposedFee; address[] private bankAddresses; uint16 private feeVotes; uint16 private entryVotes; address private purposedBank; mapping(address => bool) feeVoting; mapping(address => bool) bankEntryVoting; mapping(address => bool) ouroborosCompatibleBanks; mapping(address => mapping(address => uint256)) ouroborosLedger; event purposedFeeResult(bool result); event purposedBankResult(bool result); /** * @notice Ensures Ouroboros authorized banks are the callers */ modifier bankOnly() { require(ouroborosCompatibleBanks[msg.sender]); _; } /** * @notice The Ouroboros constructor requiring at least 2 banks to comply with the protocol */ function Ouroboros(address secondBank) public { ouroborosCompatibleBanks[msg.sender] = true; ouroborosCompatibleBanks[secondBank] = true; bankAddresses.push(msg.sender); bankAddresses.push(secondBank); } /** * @notice Query the current agreed upon transaction fee * @return _fee The current Ouroboros fee in percentage */ function getFee() public view returns (uint256 _fee) { return ouroborosFee; } /** * @notice Check whether the supplied address is an Ouroboros compatible bank * @param _toCheck The address to check * @return isCompatible Whether or not the address is compatible */ function isOuroborosCompatible(address _toCheck) public view returns(bool isCompatible) { return ouroborosCompatibleBanks[_toCheck]; } /** * @notice Log the specified Euro transaction on the Ouroboros Ledger * @param _senderBank The bank that owes money * @param _recipientBank The bank that credited the transaction * @param _value The amount of money transfered */ function updateInterbankLedger(address _senderBank, address _recipientBank, uint256 _value) public bankOnly { if (ouroborosLedger[_recipientBank][_senderBank] > 0) { if (ouroborosLedger[_recipientBank][_senderBank] < _value) { ouroborosLedger[_senderBank][_recipientBank] = _value - ouroborosLedger[_recipientBank][_senderBank]; ouroborosLedger[_recipientBank][_senderBank] = 0; } else { ouroborosLedger[_recipientBank][_senderBank] -= _value; } } else { ouroborosLedger[_senderBank][_recipientBank] += _value; } } /** * @notice Purpose a new fee to the Ouroboros Network * @param _newFee The new fee percentage */ function purposeNewFee(uint256 _newFee) public bankOnly { require(purposedFee == 0); for (uint16 i = 0; i < bankAddresses.length; i++) { feeVoting[bankAddresses[i]] = false; } purposedFee = _newFee; } /** * @notice Accept the currently purposed fee */ function acceptNewFee() public bankOnly { require(purposedFee > 0 && !feeVoting[msg.sender]); feeVoting[msg.sender] = true; feeVotes++; if (feeVotes == bankAddresses.length) { ouroborosFee = purposedFee; purposedFee = 0; feeVotes = 0; purposedFeeResult(true); } } /** * @notice Decline the currently purposed fee */ function declineNewFee() public bankOnly { purposedFee = 0; feeVotes = 0; purposedFeeResult(false); } /** * @notice Purpose a new bank to the Ouroboros Network * @param newBank The new bank's address */ function purposeNewBank(address newBank) public bankOnly { require(purposedBank == 0x0); for (uint16 i = 0; i < bankAddresses.length; i++) { bankEntryVoting[bankAddresses[i]] = false; } purposedBank = newBank; } /** * @notice Accept the currently purposed bank */ function acceptNewBank() public bankOnly { require(purposedBank != 0x0 && !bankEntryVoting[msg.sender]); bankEntryVoting[msg.sender] = true; entryVotes++; if (entryVotes == bankAddresses.length) { ouroborosCompatibleBanks[purposedBank] = true; bankAddresses.push(purposedBank); purposedBank = 0x0; entryVotes = 0; purposedBankResult(true); } } /** * @notice Accept the currently purposed bank */ function declineNewBank() public bankOnly { purposedBank = 0x0; entryVotes = 0; purposedBankResult(false); } /** * @dev Similarly, other voting systems such as contract acception etc. can be implemented as required. */ /** * @notice Check the Ouroboros ledger * @param _bank1 The first bank * @param _bank2 The second bank * @return amount The amount owed * @return polarity Whether it is positive or not */ function checkLedger(address _bank1, address _bank2) public view returns (uint256 amount, bool polarity) { if (ouroborosLedger[_bank1][_bank2] > 0) { return (ouroborosLedger[_bank1][_bank2],true); } else { return (ouroborosLedger[_bank2][_bank1],false); } } }
* @notice Accept the currently purposed fee/
function acceptNewFee() public bankOnly { require(purposedFee > 0 && !feeVoting[msg.sender]); feeVoting[msg.sender] = true; feeVotes++; if (feeVotes == bankAddresses.length) { ouroborosFee = purposedFee; purposedFee = 0; feeVotes = 0; purposedFeeResult(true); } }
12,896,953
[ 1, 5933, 326, 4551, 5405, 7423, 14036, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2791, 1908, 14667, 1435, 1071, 11218, 3386, 288, 203, 3639, 2583, 12, 12688, 7423, 14667, 405, 374, 597, 401, 21386, 58, 17128, 63, 3576, 18, 15330, 19226, 203, 3639, 14036, 58, 17128, 63, 3576, 18, 15330, 65, 273, 638, 31, 203, 3639, 14036, 29637, 9904, 31, 203, 3639, 309, 261, 21386, 29637, 422, 11218, 7148, 18, 2469, 13, 288, 203, 5411, 3134, 947, 280, 538, 14667, 273, 5405, 7423, 14667, 31, 203, 5411, 5405, 7423, 14667, 273, 374, 31, 203, 5411, 14036, 29637, 273, 374, 31, 203, 5411, 5405, 7423, 14667, 1253, 12, 3767, 1769, 203, 3639, 289, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/4/0x94263a20b1Eea751d6C3B207A7A0ba8fF8Db9E90/sources/contracts/upgradeable_contracts/omnibridge_nft/modules/forwarding_rules/NFTForwardingRulesManager.sol
* @title NFTForwardingRulesManager @dev NFT Omnibrdge module for managing destination AMB lanes permissions./ Forwarding rules mapping token => sender => receiver => destination lane
contract NFTForwardingRulesManager is OmnibridgeModule { address internal constant ANY_ADDRESS = 0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF; mapping(address => mapping(address => mapping(address => int256))) public forwardingRule; event ForwardingRuleUpdated(address token, address sender, address receiver, int256 lane); function initialize(IOwnable _mediator) external { require(address(mediator) == address(0)); mediator = _mediator; } function getModuleInterfacesVersion() external pure override returns ( uint64 major, uint64 minor, uint64 patch ) { return (2, 2, 9); } function destinationLane( address _token, address _sender, address _receiver ) public view returns (int256) { if (lane != 0) return lane; if (lane != 0) return lane; if (lane != 0) return lane; if (lane != 0) return lane; } function setRuleForTokenToPBO(address _token, bool _enable) external { require(_token != ANY_ADDRESS); _setForwardingRule(_token, ANY_ADDRESS, ANY_ADDRESS, _enable ? int256(1) : int256(0)); } function setRuleForTokenAndSenderToPBO( address _token, address _sender, bool _enable ) external { require(_token != ANY_ADDRESS); require(_sender != ANY_ADDRESS); _setForwardingRule(_token, _sender, ANY_ADDRESS, _enable ? int256(1) : int256(0)); } function setRuleForTokenAndReceiverToPBO( address _token, address _receiver, bool _enable ) external { require(_token != ANY_ADDRESS); require(_receiver != ANY_ADDRESS); _setForwardingRule(_token, ANY_ADDRESS, _receiver, _enable ? int256(1) : int256(0)); } function setRuleForSenderOfAnyTokenToPBO(address _sender, bool _enable) external { require(_sender != ANY_ADDRESS); _setForwardingRule(ANY_ADDRESS, _sender, ANY_ADDRESS, _enable ? int256(1) : int256(0)); } function setRuleForReceiverOfAnyTokenToPBO(address _receiver, bool _enable) external { require(_receiver != ANY_ADDRESS); _setForwardingRule(ANY_ADDRESS, ANY_ADDRESS, _receiver, _enable ? int256(1) : int256(0)); } function setRuleForSenderOfAnyTokenToPBU(address _sender, bool _enable) external { require(_sender != ANY_ADDRESS); _setForwardingRule(ANY_ADDRESS, _sender, ANY_ADDRESS, _enable ? int256(-1) : int256(0)); } function setRuleForReceiverOfAnyTokenToPBU(address _receiver, bool _enable) external { require(_receiver != ANY_ADDRESS); _setForwardingRule(ANY_ADDRESS, ANY_ADDRESS, _receiver, _enable ? int256(-1) : int256(0)); } function _setForwardingRule( address _token, address _sender, address _receiver, int256 _lane ) internal onlyOwner { forwardingRule[_token][_sender][_receiver] = _lane; emit ForwardingRuleUpdated(_token, _sender, _receiver, _lane); } }
12,395,076
[ 1, 50, 4464, 21487, 4478, 1318, 225, 423, 4464, 531, 13607, 495, 13623, 908, 1605, 364, 30632, 2929, 432, 7969, 328, 304, 281, 4371, 18, 19, 17206, 310, 2931, 2874, 1147, 516, 5793, 516, 5971, 516, 2929, 328, 8806, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 423, 4464, 21487, 4478, 1318, 353, 531, 13607, 495, 5404, 3120, 288, 203, 565, 1758, 2713, 5381, 16743, 67, 15140, 273, 374, 6356, 74, 42, 74, 42, 1403, 2246, 25449, 2246, 74, 2246, 74, 8998, 42, 1403, 2246, 42, 9460, 42, 74, 2246, 42, 74, 42, 31, 203, 203, 565, 2874, 12, 2867, 516, 2874, 12, 2867, 516, 2874, 12, 2867, 516, 509, 5034, 20349, 1071, 20635, 2175, 31, 203, 203, 565, 871, 17206, 310, 2175, 7381, 12, 2867, 1147, 16, 1758, 5793, 16, 1758, 5971, 16, 509, 5034, 328, 8806, 1769, 203, 203, 565, 445, 4046, 12, 45, 5460, 429, 389, 17113, 13, 3903, 288, 203, 3639, 2583, 12, 2867, 12, 17113, 13, 422, 1758, 12, 20, 10019, 203, 203, 3639, 6735, 10620, 273, 389, 17113, 31, 203, 565, 289, 203, 203, 565, 445, 11251, 10273, 1444, 1435, 203, 3639, 3903, 203, 3639, 16618, 203, 3639, 3849, 203, 3639, 1135, 261, 203, 5411, 2254, 1105, 7888, 16, 203, 5411, 2254, 1105, 8439, 16, 203, 5411, 2254, 1105, 4729, 203, 3639, 262, 203, 565, 288, 203, 3639, 327, 261, 22, 16, 576, 16, 2468, 1769, 203, 565, 289, 203, 203, 565, 445, 2929, 48, 8806, 12, 203, 3639, 1758, 389, 2316, 16, 203, 3639, 1758, 389, 15330, 16, 203, 3639, 1758, 389, 24454, 203, 565, 262, 1071, 1476, 1135, 261, 474, 5034, 13, 288, 203, 3639, 309, 261, 29351, 480, 374, 13, 327, 328, 8806, 31, 203, 3639, 309, 261, 29351, 480, 374, 13, 327, 328, 8806, 31, 203, 3639, 309, 261, 29351, 2 ]
./partial_match/1/0xc8c97d9B0aF219c2329a0179f6AB8C7a55B39fc1/sources/HKMT.sol
* @dev Destoys `amount` tokens from `account`.`amount` is then deducted from the caller's allowance. See `_burn` and `_approve`./
function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, msg.sender, _allowances[account][msg.sender].sub(amount)); } using SafeMath for uint; uint public createdAt = block.timestamp; uint public difficultyIncreaseInPercentPerDay = 1; HKMT public hkmtContract;
15,560,361
[ 1, 9378, 83, 1900, 1375, 8949, 68, 2430, 628, 1375, 4631, 16586, 8949, 68, 353, 1508, 11140, 853, 329, 628, 326, 4894, 1807, 1699, 1359, 18, 2164, 1375, 67, 70, 321, 68, 471, 1375, 67, 12908, 537, 8338, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 70, 321, 1265, 12, 2867, 2236, 16, 2254, 5034, 3844, 13, 2713, 288, 203, 3639, 389, 70, 321, 12, 4631, 16, 3844, 1769, 203, 3639, 389, 12908, 537, 12, 4631, 16, 1234, 18, 15330, 16, 389, 5965, 6872, 63, 4631, 6362, 3576, 18, 15330, 8009, 1717, 12, 8949, 10019, 203, 565, 289, 203, 203, 203, 565, 1450, 14060, 10477, 364, 2254, 31, 203, 565, 2254, 1071, 26083, 273, 1203, 18, 5508, 31, 203, 565, 2254, 1071, 3122, 21934, 382, 11908, 382, 8410, 2173, 4245, 273, 404, 31, 203, 565, 670, 47, 6152, 1071, 366, 79, 1010, 8924, 31, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * _____ __ _ * / ___/____ ________ __/ /__(_) * \__ \/ __ `/ ___/ / / / //_/ / * ___/ / /_/ (__ ) /_/ / ,< / / * /____/\__,_/____/\__,_/_/|_/_/ * * Sasuki | 2022 * @author Josh Stow (jstow.com) */ import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "./ERC721A.sol"; contract Sasuki is ERC721A, Ownable { using Address for address payable; uint256 public constant SSK_PREMINT = 9; uint256 public constant SSK_PUBLIC = 990; uint256 public constant SSK_MAX = SSK_PREMINT + SSK_PUBLIC; // 999 uint256 public constant SSK_PRICE = 0.1 ether; uint256 public publicMinted; string private _baseTokenURI; bool public saleLive; bool public locked; constructor(string memory newBaseTokenURI) ERC721A("Sasuki", "SSK") { _baseTokenURI = newBaseTokenURI; _safeMint(owner(), SSK_PREMINT); } modifier notLocked { require(!locked, "Contract metadata is locked"); _; } /** * @dev Mints number of tokens specified to wallet. * @param quantity uint256 Number of tokens to be minted */ function buy(uint256 quantity) external payable { require(saleLive, "Sale is not currently live"); require(totalSupply() + quantity <= SSK_MAX && publicMinted + quantity <= SSK_PUBLIC, "Quantity exceeds remaining tokens"); require(msg.value >= quantity * SSK_PRICE, "Insufficient funds"); publicMinted += quantity; _safeMint(msg.sender, quantity); } /** * @dev Set base token URI. * @param newBaseURI string New URI to set */ function setBaseURI(string calldata newBaseURI) external onlyOwner notLocked { _baseTokenURI = newBaseURI; } /** * @dev Toggles status of token sale. Only callable by owner. */ function toggleSale() external onlyOwner { saleLive = !saleLive; } /** * @dev Locks contract metadata. Only callable by owner. */ function lockMetadata() external onlyOwner { locked = true; } /** * @dev Withdraw funds from contract. Only callable by owner. */ function withdraw() public onlyOwner { payable(msg.sender).sendValue(address(this).balance); } /** * @dev Returns base token URI. * @return string Base token URI */ function _baseURI() internal view override(ERC721A) returns (string memory) { return _baseTokenURI; } /** * @dev Returns starting tokenId. * @return uint256 Starting token Id */ function _startTokenId() internal pure override(ERC721A) returns (uint256) { return 1; } } // SPDX-License-Identifier: MIT // Creator: Chiru Labs pragma solidity ^0.8.0; import '@openzeppelin/contracts/token/ERC721/IERC721.sol'; import '@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol'; import '@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol'; import '@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol'; import '@openzeppelin/contracts/utils/Address.sol'; import '@openzeppelin/contracts/utils/Context.sol'; import '@openzeppelin/contracts/utils/Strings.sol'; import '@openzeppelin/contracts/utils/introspection/ERC165.sol'; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at 1 (e.g. 1, 2, 3, 4..). * * Does not support burning tokens to address(0). * * Assumes that an owner cannot have more than the 2**128 - 1 (max value of uint128) of supply */ contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using Address for address; using Strings for uint256; struct TokenOwnership { address addr; uint64 startTimestamp; } struct AddressData { uint128 balance; uint128 numberMinted; } uint256 internal _nextTokenId; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details. mapping(uint256 => TokenOwnership) internal _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; _nextTokenId = _startTokenId(); } /** * To change the starting tokenId, please override this function. */ function _startTokenId() internal view virtual returns (uint256) { return 0; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { unchecked { return _nextTokenId - _startTokenId(); } } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view override returns (uint256) { require(index < totalSupply(), 'ERC721A: global index out of bounds'); unchecked { return index + _startTokenId(); } } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { require(index < balanceOf(owner), 'ERC721A: owner index out of bounds'); uint256 numMintedSoFar = totalSupply(); uint256 tokenIdsIdx; address currOwnershipAddr; // Counter overflow is impossible as the loop breaks when uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i = _startTokenId(); i < numMintedSoFar + _startTokenId(); i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } revert('ERC721A: unable to get token of owner by index'); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { require(owner != address(0), 'ERC721A: balance query for the zero address'); return uint256(_addressData[owner].balance); } function _numberMinted(address owner) internal view returns (uint256) { require(owner != address(0), 'ERC721A: number minted query for the zero address'); return uint256(_addressData[owner].numberMinted); } /** * Gas spent here starts off proportional to the maximum mint batch size. * It gradually moves to O(1) as tokens get transferred around in the collection over time. */ function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { require(_exists(tokenId), 'ERC721A: owner query for nonexistent token'); unchecked { uint256 startIndex = _startTokenId(); for (uint256 curr = tokenId; curr >= startIndex; curr--) { TokenOwnership memory ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } } revert('ERC721A: unable to determine the owner of token'); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return ownershipOf(tokenId).addr; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), 'ERC721Metadata: URI query for nonexistent token'); string memory baseURI = _baseURI(); return bytes(baseURI).length != 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ''; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ''; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public override { address owner = ERC721A.ownerOf(tokenId); require(to != owner, 'ERC721A: approval to current owner'); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), 'ERC721A: approve caller is not owner nor approved for all' ); _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { require(_exists(tokenId), 'ERC721A: approved query for nonexistent token'); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public override { require(operator != _msgSender(), 'ERC721A: approve to caller'); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public override { _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public override { safeTransferFrom(from, to, tokenId, ''); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public override { _transfer(from, to, tokenId); require( _checkOnERC721Received(from, to, tokenId, _data), 'ERC721A: transfer to non ERC721Receiver implementer' ); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), */ function _exists(uint256 tokenId) internal view returns (bool) { return tokenId < _nextTokenId && tokenId >= _startTokenId(); } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ''); } /** * @dev Safely mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called for each safe transfer. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { _mint(to, quantity, _data, true); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _mint( address to, uint256 quantity, bytes memory _data, bool safe ) internal { uint256 startTokenId = _nextTokenId; require(to != address(0), 'ERC721A: mint to the zero address'); require(quantity != 0, 'ERC721A: quantity must be greater than 0'); _beforeTokenTransfers(address(0), to, startTokenId, quantity); // Overflows are incredibly unrealistic. // balance or numberMinted overflow if current value of either + quantity > 3.4e38 (2**128) - 1 // updatedIndex overflows if _nextTokenId + quantity > 1.56e77 (2**256) - 1 unchecked { _addressData[to].balance += uint128(quantity); _addressData[to].numberMinted += uint128(quantity); _ownerships[startTokenId].addr = to; _ownerships[startTokenId].startTimestamp = uint64(block.timestamp); uint256 updatedIndex = startTokenId; for (uint256 i; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); if (safe) { require( _checkOnERC721Received(address(0), to, updatedIndex, _data), 'ERC721A: transfer to non ERC721Receiver implementer' ); } updatedIndex++; } _nextTokenId = updatedIndex; } _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers `tokenId` from `from` to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) private { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || getApproved(tokenId) == _msgSender() || isApprovedForAll(prevOwnership.addr, _msgSender())); require(isApprovedOrOwner, 'ERC721A: transfer caller is not owner nor approved'); require(prevOwnership.addr == from, 'ERC721A: transfer from incorrect owner'); require(to != address(0), 'ERC721A: transfer to the zero address'); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**256. unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId].addr = to; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This suffice for _exists(nextTokenId), as _startTokenId() < tokenId < tokenId + 1 if (nextTokenId < _nextTokenId) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert('ERC721A: transfer to non ERC721Receiver implementer'); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/cryptography/MerkleProof.sol) pragma solidity ^0.8.0; /** * @dev These functions deal with verification of Merkle Trees proofs. * * The proofs can be generated using the JavaScript library * https://github.com/miguelmota/merkletreejs[merkletreejs]. * Note: the hashing algorithm should be keccak256 and pair sorting should be enabled. * * See `test/utils/cryptography/MerkleProof.test.js` for some examples. */ library MerkleProof { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify( bytes32[] memory proof, bytes32 root, bytes32 leaf ) internal pure returns (bool) { return processProof(proof, leaf) == root; } /** * @dev Returns the rebuilt hash obtained by traversing a Merklee tree up * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt * hash matches the root of the tree. When processing the proof, the pairs * of leafs & pre-images are assumed to be sorted. * * _Available since v4.4._ */ function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } return computedHash; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Enumerable.sol) pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } }
* the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints. Assumes serials are sequentially minted starting at 1 (e.g. 1, 2, 3, 4..). Does not support burning tokens to address(0). Assumes that an owner cannot have more than the 2128 - 1 (max value of uint128) of supply/
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using Address for address; using Strings for uint256; struct TokenOwnership { address addr; uint64 startTimestamp; } struct AddressData { uint128 balance; uint128 numberMinted; } uint256 internal _nextTokenId; string private _name; string private _symbol; mapping(uint256 => TokenOwnership) internal _ownerships; mapping(address => AddressData) private _addressData; mapping(uint256 => address) private _tokenApprovals; mapping(address => mapping(address => bool)) private _operatorApprovals; constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; _nextTokenId = _startTokenId(); } function _startTokenId() internal view virtual returns (uint256) { return 0; } function totalSupply() public view override returns (uint256) { unchecked { return _nextTokenId - _startTokenId(); } } function totalSupply() public view override returns (uint256) { unchecked { return _nextTokenId - _startTokenId(); } } function tokenByIndex(uint256 index) public view override returns (uint256) { require(index < totalSupply(), 'ERC721A: global index out of bounds'); unchecked { return index + _startTokenId(); } } function tokenByIndex(uint256 index) public view override returns (uint256) { require(index < totalSupply(), 'ERC721A: global index out of bounds'); unchecked { return index + _startTokenId(); } } function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { require(index < balanceOf(owner), 'ERC721A: owner index out of bounds'); uint256 numMintedSoFar = totalSupply(); uint256 tokenIdsIdx; address currOwnershipAddr; unchecked { for (uint256 i = _startTokenId(); i < numMintedSoFar + _startTokenId(); i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } revert('ERC721A: unable to get token of owner by index'); } function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { require(index < balanceOf(owner), 'ERC721A: owner index out of bounds'); uint256 numMintedSoFar = totalSupply(); uint256 tokenIdsIdx; address currOwnershipAddr; unchecked { for (uint256 i = _startTokenId(); i < numMintedSoFar + _startTokenId(); i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } revert('ERC721A: unable to get token of owner by index'); } function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { require(index < balanceOf(owner), 'ERC721A: owner index out of bounds'); uint256 numMintedSoFar = totalSupply(); uint256 tokenIdsIdx; address currOwnershipAddr; unchecked { for (uint256 i = _startTokenId(); i < numMintedSoFar + _startTokenId(); i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } revert('ERC721A: unable to get token of owner by index'); } function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { require(index < balanceOf(owner), 'ERC721A: owner index out of bounds'); uint256 numMintedSoFar = totalSupply(); uint256 tokenIdsIdx; address currOwnershipAddr; unchecked { for (uint256 i = _startTokenId(); i < numMintedSoFar + _startTokenId(); i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } revert('ERC721A: unable to get token of owner by index'); } function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { require(index < balanceOf(owner), 'ERC721A: owner index out of bounds'); uint256 numMintedSoFar = totalSupply(); uint256 tokenIdsIdx; address currOwnershipAddr; unchecked { for (uint256 i = _startTokenId(); i < numMintedSoFar + _startTokenId(); i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } revert('ERC721A: unable to get token of owner by index'); } function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { require(index < balanceOf(owner), 'ERC721A: owner index out of bounds'); uint256 numMintedSoFar = totalSupply(); uint256 tokenIdsIdx; address currOwnershipAddr; unchecked { for (uint256 i = _startTokenId(); i < numMintedSoFar + _startTokenId(); i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } revert('ERC721A: unable to get token of owner by index'); } function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } function balanceOf(address owner) public view override returns (uint256) { require(owner != address(0), 'ERC721A: balance query for the zero address'); return uint256(_addressData[owner].balance); } function _numberMinted(address owner) internal view returns (uint256) { require(owner != address(0), 'ERC721A: number minted query for the zero address'); return uint256(_addressData[owner].numberMinted); } function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { require(_exists(tokenId), 'ERC721A: owner query for nonexistent token'); unchecked { uint256 startIndex = _startTokenId(); for (uint256 curr = tokenId; curr >= startIndex; curr--) { TokenOwnership memory ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } } revert('ERC721A: unable to determine the owner of token'); } function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { require(_exists(tokenId), 'ERC721A: owner query for nonexistent token'); unchecked { uint256 startIndex = _startTokenId(); for (uint256 curr = tokenId; curr >= startIndex; curr--) { TokenOwnership memory ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } } revert('ERC721A: unable to determine the owner of token'); } function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { require(_exists(tokenId), 'ERC721A: owner query for nonexistent token'); unchecked { uint256 startIndex = _startTokenId(); for (uint256 curr = tokenId; curr >= startIndex; curr--) { TokenOwnership memory ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } } revert('ERC721A: unable to determine the owner of token'); } function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { require(_exists(tokenId), 'ERC721A: owner query for nonexistent token'); unchecked { uint256 startIndex = _startTokenId(); for (uint256 curr = tokenId; curr >= startIndex; curr--) { TokenOwnership memory ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } } revert('ERC721A: unable to determine the owner of token'); } function ownerOf(uint256 tokenId) public view override returns (address) { return ownershipOf(tokenId).addr; } function name() public view virtual override returns (string memory) { return _name; } function symbol() public view virtual override returns (string memory) { return _symbol; } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), 'ERC721Metadata: URI query for nonexistent token'); string memory baseURI = _baseURI(); return bytes(baseURI).length != 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ''; } function _baseURI() internal view virtual returns (string memory) { return ''; } function approve(address to, uint256 tokenId) public override { address owner = ERC721A.ownerOf(tokenId); require(to != owner, 'ERC721A: approval to current owner'); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), 'ERC721A: approve caller is not owner nor approved for all' ); _approve(to, tokenId, owner); } function getApproved(uint256 tokenId) public view override returns (address) { require(_exists(tokenId), 'ERC721A: approved query for nonexistent token'); return _tokenApprovals[tokenId]; } function setApprovalForAll(address operator, bool approved) public override { require(operator != _msgSender(), 'ERC721A: approve to caller'); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } function transferFrom( address from, address to, uint256 tokenId ) public override { _transfer(from, to, tokenId); } function safeTransferFrom( address from, address to, uint256 tokenId ) public override { safeTransferFrom(from, to, tokenId, ''); } function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public override { _transfer(from, to, tokenId); require( _checkOnERC721Received(from, to, tokenId, _data), 'ERC721A: transfer to non ERC721Receiver implementer' ); } function _exists(uint256 tokenId) internal view returns (bool) { return tokenId < _nextTokenId && tokenId >= _startTokenId(); } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ''); } function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { _mint(to, quantity, _data, true); } function _mint( address to, uint256 quantity, bytes memory _data, bool safe ) internal { uint256 startTokenId = _nextTokenId; require(to != address(0), 'ERC721A: mint to the zero address'); require(quantity != 0, 'ERC721A: quantity must be greater than 0'); _beforeTokenTransfers(address(0), to, startTokenId, quantity); unchecked { _addressData[to].balance += uint128(quantity); _addressData[to].numberMinted += uint128(quantity); _ownerships[startTokenId].addr = to; _ownerships[startTokenId].startTimestamp = uint64(block.timestamp); uint256 updatedIndex = startTokenId; for (uint256 i; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); if (safe) { require( _checkOnERC721Received(address(0), to, updatedIndex, _data), 'ERC721A: transfer to non ERC721Receiver implementer' ); } updatedIndex++; } _nextTokenId = updatedIndex; } _afterTokenTransfers(address(0), to, startTokenId, quantity); } function _mint( address to, uint256 quantity, bytes memory _data, bool safe ) internal { uint256 startTokenId = _nextTokenId; require(to != address(0), 'ERC721A: mint to the zero address'); require(quantity != 0, 'ERC721A: quantity must be greater than 0'); _beforeTokenTransfers(address(0), to, startTokenId, quantity); unchecked { _addressData[to].balance += uint128(quantity); _addressData[to].numberMinted += uint128(quantity); _ownerships[startTokenId].addr = to; _ownerships[startTokenId].startTimestamp = uint64(block.timestamp); uint256 updatedIndex = startTokenId; for (uint256 i; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); if (safe) { require( _checkOnERC721Received(address(0), to, updatedIndex, _data), 'ERC721A: transfer to non ERC721Receiver implementer' ); } updatedIndex++; } _nextTokenId = updatedIndex; } _afterTokenTransfers(address(0), to, startTokenId, quantity); } function _mint( address to, uint256 quantity, bytes memory _data, bool safe ) internal { uint256 startTokenId = _nextTokenId; require(to != address(0), 'ERC721A: mint to the zero address'); require(quantity != 0, 'ERC721A: quantity must be greater than 0'); _beforeTokenTransfers(address(0), to, startTokenId, quantity); unchecked { _addressData[to].balance += uint128(quantity); _addressData[to].numberMinted += uint128(quantity); _ownerships[startTokenId].addr = to; _ownerships[startTokenId].startTimestamp = uint64(block.timestamp); uint256 updatedIndex = startTokenId; for (uint256 i; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); if (safe) { require( _checkOnERC721Received(address(0), to, updatedIndex, _data), 'ERC721A: transfer to non ERC721Receiver implementer' ); } updatedIndex++; } _nextTokenId = updatedIndex; } _afterTokenTransfers(address(0), to, startTokenId, quantity); } function _mint( address to, uint256 quantity, bytes memory _data, bool safe ) internal { uint256 startTokenId = _nextTokenId; require(to != address(0), 'ERC721A: mint to the zero address'); require(quantity != 0, 'ERC721A: quantity must be greater than 0'); _beforeTokenTransfers(address(0), to, startTokenId, quantity); unchecked { _addressData[to].balance += uint128(quantity); _addressData[to].numberMinted += uint128(quantity); _ownerships[startTokenId].addr = to; _ownerships[startTokenId].startTimestamp = uint64(block.timestamp); uint256 updatedIndex = startTokenId; for (uint256 i; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); if (safe) { require( _checkOnERC721Received(address(0), to, updatedIndex, _data), 'ERC721A: transfer to non ERC721Receiver implementer' ); } updatedIndex++; } _nextTokenId = updatedIndex; } _afterTokenTransfers(address(0), to, startTokenId, quantity); } function _transfer( address from, address to, uint256 tokenId ) private { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || getApproved(tokenId) == _msgSender() || isApprovedForAll(prevOwnership.addr, _msgSender())); require(isApprovedOrOwner, 'ERC721A: transfer caller is not owner nor approved'); require(prevOwnership.addr == from, 'ERC721A: transfer from incorrect owner'); require(to != address(0), 'ERC721A: transfer to the zero address'); _beforeTokenTransfers(from, to, tokenId, 1); _approve(address(0), tokenId, prevOwnership.addr); unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId].addr = to; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { if (nextTokenId < _nextTokenId) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } function _transfer( address from, address to, uint256 tokenId ) private { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || getApproved(tokenId) == _msgSender() || isApprovedForAll(prevOwnership.addr, _msgSender())); require(isApprovedOrOwner, 'ERC721A: transfer caller is not owner nor approved'); require(prevOwnership.addr == from, 'ERC721A: transfer from incorrect owner'); require(to != address(0), 'ERC721A: transfer to the zero address'); _beforeTokenTransfers(from, to, tokenId, 1); _approve(address(0), tokenId, prevOwnership.addr); unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId].addr = to; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { if (nextTokenId < _nextTokenId) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } function _transfer( address from, address to, uint256 tokenId ) private { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || getApproved(tokenId) == _msgSender() || isApprovedForAll(prevOwnership.addr, _msgSender())); require(isApprovedOrOwner, 'ERC721A: transfer caller is not owner nor approved'); require(prevOwnership.addr == from, 'ERC721A: transfer from incorrect owner'); require(to != address(0), 'ERC721A: transfer to the zero address'); _beforeTokenTransfers(from, to, tokenId, 1); _approve(address(0), tokenId, prevOwnership.addr); unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId].addr = to; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { if (nextTokenId < _nextTokenId) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } function _transfer( address from, address to, uint256 tokenId ) private { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || getApproved(tokenId) == _msgSender() || isApprovedForAll(prevOwnership.addr, _msgSender())); require(isApprovedOrOwner, 'ERC721A: transfer caller is not owner nor approved'); require(prevOwnership.addr == from, 'ERC721A: transfer from incorrect owner'); require(to != address(0), 'ERC721A: transfer to the zero address'); _beforeTokenTransfers(from, to, tokenId, 1); _approve(address(0), tokenId, prevOwnership.addr); unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId].addr = to; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { if (nextTokenId < _nextTokenId) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; if (reason.length == 0) { revert('ERC721A: transfer to non ERC721Receiver implementer'); assembly { revert(add(32, reason), mload(reason)) } } } return true; } } function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; if (reason.length == 0) { revert('ERC721A: transfer to non ERC721Receiver implementer'); assembly { revert(add(32, reason), mload(reason)) } } } return true; } } function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; if (reason.length == 0) { revert('ERC721A: transfer to non ERC721Receiver implementer'); assembly { revert(add(32, reason), mload(reason)) } } } return true; } } } catch (bytes memory reason) { function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; if (reason.length == 0) { revert('ERC721A: transfer to non ERC721Receiver implementer'); assembly { revert(add(32, reason), mload(reason)) } } } return true; } } } else { function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; if (reason.length == 0) { revert('ERC721A: transfer to non ERC721Receiver implementer'); assembly { revert(add(32, reason), mload(reason)) } } } return true; } } } else { ) internal virtual {} ) internal virtual {} }
11,785,168
[ 1, 5787, 6912, 471, 6057, 25121, 2710, 18, 27376, 358, 10979, 364, 2612, 16189, 4982, 2581, 312, 28142, 18, 25374, 2734, 87, 854, 695, 6979, 6261, 312, 474, 329, 5023, 622, 404, 261, 73, 18, 75, 18, 404, 16, 576, 16, 890, 16, 1059, 838, 2934, 9637, 486, 2865, 18305, 310, 2430, 358, 1758, 12, 20, 2934, 25374, 716, 392, 3410, 2780, 1240, 1898, 2353, 326, 576, 10392, 300, 404, 261, 1896, 460, 434, 2254, 10392, 13, 434, 14467, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 4232, 39, 27, 5340, 37, 353, 1772, 16, 4232, 39, 28275, 16, 467, 654, 39, 27, 5340, 16, 467, 654, 39, 27, 5340, 2277, 16, 467, 654, 39, 27, 5340, 3572, 25121, 288, 203, 565, 1450, 5267, 364, 1758, 31, 203, 565, 1450, 8139, 364, 2254, 5034, 31, 203, 203, 203, 565, 1958, 3155, 5460, 12565, 288, 203, 3639, 1758, 3091, 31, 203, 3639, 2254, 1105, 787, 4921, 31, 203, 565, 289, 203, 203, 565, 1958, 5267, 751, 288, 203, 3639, 2254, 10392, 11013, 31, 203, 3639, 2254, 10392, 1300, 49, 474, 329, 31, 203, 565, 289, 203, 203, 565, 2254, 5034, 2713, 389, 4285, 1345, 548, 31, 203, 203, 203, 203, 203, 203, 203, 203, 565, 533, 3238, 389, 529, 31, 203, 565, 533, 3238, 389, 7175, 31, 203, 565, 2874, 12, 11890, 5034, 516, 3155, 5460, 12565, 13, 2713, 389, 995, 12565, 87, 31, 203, 565, 2874, 12, 2867, 516, 5267, 751, 13, 3238, 389, 2867, 751, 31, 203, 565, 2874, 12, 11890, 5034, 516, 1758, 13, 3238, 389, 2316, 12053, 4524, 31, 203, 565, 2874, 12, 2867, 516, 2874, 12, 2867, 516, 1426, 3719, 3238, 389, 9497, 12053, 4524, 31, 203, 565, 3885, 12, 1080, 3778, 508, 67, 16, 533, 3778, 3273, 67, 13, 288, 203, 3639, 389, 529, 273, 508, 67, 31, 203, 3639, 389, 7175, 273, 3273, 67, 31, 203, 3639, 389, 4285, 1345, 548, 273, 389, 1937, 1345, 548, 5621, 203, 565, 289, 203, 203, 565, 445, 389, 1937, 1345, 548, 1435, 2713, 1476, 5024, 1135, 261, 2 ]
./full_match/56/0x6Df6a43Be4B706c45BC028D652829299D932d000/sources/juryProject.sol
Query functions this function might be usefull to query for the user new Spon tokens to display in frontend when the user connects his wallet
function newSponBalance(address _user) public view returns (uint256) { uint256 QueryBalance2 = newSponToken.balanceOf(_user); return QueryBalance2; }
3,235,561
[ 1, 1138, 4186, 333, 445, 4825, 506, 999, 2854, 358, 843, 364, 326, 729, 394, 348, 500, 2430, 358, 2562, 316, 15442, 1347, 326, 729, 23441, 18423, 9230, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 30826, 500, 13937, 12, 2867, 389, 1355, 13, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 2254, 5034, 2770, 13937, 22, 273, 30826, 500, 1345, 18, 12296, 951, 24899, 1355, 1769, 203, 3639, 327, 2770, 13937, 22, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0xDe02aB0EC610D5B82073D39C9F92b27478DC076e/sources/packages/contracts/src/DIRTONCHAIN.sol
//*/ @notice Token name (not in ERC1155 standard but still used) @notice Token symbol (not in ERC1155 standard but still used) @notice Overall contract status @notice Mapping of Merkle roots for different NFTs @notice Mapping of image data @notice Mapping of descriptions @notice Mapping of names @notice Mapping of mint status for hashed address + ID combos (as integers)//*/ @notice Throws if called when minting is not enabled
modifier mintingEnabled() { if (!enabled) { revert MintingNotEnabled(); } _; }
2,740,540
[ 1, 28111, 225, 3155, 508, 261, 902, 316, 4232, 39, 2499, 2539, 4529, 1496, 4859, 1399, 13, 225, 3155, 3273, 261, 902, 316, 4232, 39, 2499, 2539, 4529, 1496, 4859, 1399, 13, 225, 10752, 454, 6835, 1267, 225, 9408, 434, 31827, 12876, 364, 3775, 423, 4464, 87, 225, 9408, 434, 1316, 501, 225, 9408, 434, 15550, 225, 9408, 434, 1257, 225, 9408, 434, 312, 474, 1267, 364, 14242, 1758, 397, 1599, 3894, 538, 261, 345, 12321, 13, 28111, 225, 22435, 309, 2566, 1347, 312, 474, 310, 353, 486, 3696, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 9606, 312, 474, 310, 1526, 1435, 288, 203, 3639, 309, 16051, 5745, 13, 288, 203, 5411, 15226, 490, 474, 310, 1248, 1526, 5621, 203, 3639, 289, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** * @authors: [@ferittuncer] * @reviewers: [] * @auditors: [] * @bounties: [] * @deployments: [] */ pragma solidity >=0.6; import './IDisputeResolver.sol'; import "@kleros/ethereum-libraries/contracts/CappedMath.sol"; /** * @title ArbitrableProxy * A general purpose arbitrable contract. Supports non-binary rulings. */ contract ArbitrableProxy is IDisputeResolver { string public constant VERSION = '1.0.0'; using CappedMath for uint; // Operations bounded between 0 and 2**256 - 1. event Contribution(uint indexed localDisputeID, uint indexed round, uint ruling, address indexed contributor, uint amount); event Withdrawal(uint indexed localDisputeID, uint indexed round, uint ruling, address indexed contributor, uint reward); event RulingFunded(uint indexed localDisputeID, uint indexed round, uint indexed ruling); struct Round { mapping(uint => uint) paidFees; // Tracks the fees paid for each ruling option in this round. mapping(uint => bool) hasPaid; // True this ruling option was fully funded has fully paid its fee. False otherwise. mapping(address => mapping(uint => uint)) contributions; // Maps contributors to their contributions for each side. uint256 feeRewards; // Sum of reimbursable appeal fees available to the parties that made contributions to the ruling that ultimately wins a dispute. uint[] fundedSides; // Stores the sides that are fully funded. } struct DisputeStruct { bytes arbitratorExtraData; bool isRuled; uint ruling; uint disputeIDOnArbitratorSide; uint numberOfChoices; } address public governor = msg.sender; IArbitrator public arbitrator; // The required fee stake that a party must pay depends on who won the previous round and is proportional to the arbitration cost such that the fee stake for a round is stake multiplier * arbitration cost for that round. // Multipliers are in basis points. uint public winnerStakeMultiplier; // Multiplier for calculating the fee stake paid by the party that won the previous round. uint public loserStakeMultiplier; // Multiplier for calculating the fee stake paid by the party that lost the previous round. uint public sharedStakeMultiplier; // Multiplier for calculating the fee stake that must be paid in the case where there isn't a winner and loser (e.g. when it's the first round or the arbitrator ruled "refused to rule"/"could not rule"). uint public constant MULTIPLIER_DIVISOR = 10000; // Divisor parameter for multipliers. DisputeStruct[] public disputes; mapping(uint => uint) public override externalIDtoLocalID; // Maps external (arbitrator side) dispute ids to local dispute ids. mapping(uint => Round[]) public disputeIDtoRoundArray; // Maps dispute ids round arrays. /** @dev Constructor * @param _arbitrator Target global arbitrator for any disputes. * @param _winnerStakeMultiplier Multiplier of the arbitration cost that the winner has to pay as fee stake for a round in basis points. * @param _loserStakeMultiplier Multiplier of the arbitration cost that the loser has to pay as fee stake for a round in basis points. * @param _sharedStakeMultiplier Multiplier of the arbitration cost that each party must pay as fee stake for a round when there isn't a winner/loser in the previous round (e.g. when it's the first round or the arbitrator refused to or did not rule). In basis points. */ constructor(IArbitrator _arbitrator, uint _winnerStakeMultiplier, uint _loserStakeMultiplier, uint _sharedStakeMultiplier) public { arbitrator = _arbitrator; winnerStakeMultiplier = _winnerStakeMultiplier; loserStakeMultiplier = _loserStakeMultiplier; sharedStakeMultiplier = _sharedStakeMultiplier; } /** @dev TRUSTED. Calls createDispute function of the specified arbitrator to create a dispute. Note that we don’t need to check that msg.value is enough to pay arbitration fees as it’s the responsibility of the arbitrator contract. * @param _arbitratorExtraData Extra data for the arbitrator of prospective dispute. * @param _metaevidenceURI Link to metaevidence of prospective dispute. * @param _numberOfChoices Number of currentRuling options. * @return disputeID Dispute id (on arbitrator side) of the dispute created. */ function createDispute(bytes calldata _arbitratorExtraData, string calldata _metaevidenceURI, uint _numberOfChoices) external payable returns(uint disputeID) { disputeID = arbitrator.createDispute.value(msg.value)(_numberOfChoices, _arbitratorExtraData); disputes.push(DisputeStruct({ arbitratorExtraData: _arbitratorExtraData, isRuled: false, ruling: 0, disputeIDOnArbitratorSide: disputeID, numberOfChoices: _numberOfChoices })); uint localDisputeID = disputes.length - 1; externalIDtoLocalID[disputeID] = localDisputeID; disputeIDtoRoundArray[localDisputeID].push(); emit MetaEvidence(localDisputeID, _metaevidenceURI); emit Dispute(arbitrator, disputeID, localDisputeID, localDisputeID); } /** @dev Returns number of possible currentRuling options. Valid rulings are [0, return value]. * @param _localDisputeID Dispute id as in arbitrable contract. */ function numberOfRulingOptions(uint _localDisputeID) external view override returns (uint numberOfRulingOptions){ numberOfRulingOptions = disputes[_localDisputeID].numberOfChoices; } /** @dev TRUSTED. Manages contributions and calls appeal function of the specified arbitrator to appeal a dispute. This function lets appeals be crowdfunded. Note that we don’t need to check that msg.value is enough to pay arbitration fees as it’s the responsibility of the arbitrator contract. * @param _localDisputeID Index of the dispute in disputes array. * @param _ruling The ruling to which the caller wants to contribute. * @param fullyFunded Whether _ruling was fully funded after the call. */ function fundAppeal(uint _localDisputeID, uint _ruling) external override payable returns (bool fullyFunded){ DisputeStruct storage dispute = disputes[_localDisputeID]; require(_ruling <= dispute.numberOfChoices && _ruling != 0, "There is no such ruling to fund."); (uint appealPeriodStart, uint appealPeriodEnd) = arbitrator.appealPeriod(dispute.disputeIDOnArbitratorSide); require(now >= appealPeriodStart && now < appealPeriodEnd, "Funding must be made within the appeal period."); uint winner = arbitrator.currentRuling(dispute.disputeIDOnArbitratorSide); uint multiplier; if (winner == _ruling){ multiplier = winnerStakeMultiplier; } else if (winner == 0){ multiplier = sharedStakeMultiplier; } else { multiplier = loserStakeMultiplier; require(now-appealPeriodStart < (appealPeriodEnd-appealPeriodStart)/2, "The loser must contribute during the first half of the appeal period."); } uint appealCost = arbitrator.appealCost(dispute.disputeIDOnArbitratorSide, dispute.arbitratorExtraData); uint totalCost = appealCost.addCap(appealCost.mulCap(multiplier) / MULTIPLIER_DIVISOR); Round[] storage rounds = disputeIDtoRoundArray[_localDisputeID]; Round storage lastRound = rounds[rounds.length - 1]; require(!lastRound.hasPaid[_ruling], "Appeal fee has already been paid."); require(msg.value > 0, "Can't contribute zero"); uint contribution = totalCost.subCap(lastRound.paidFees[_ruling]) > msg.value ? msg.value : totalCost.subCap(lastRound.paidFees[_ruling]); emit Contribution(_localDisputeID, rounds.length - 1, _ruling, msg.sender, contribution); lastRound.contributions[msg.sender][_ruling] += contribution; lastRound.paidFees[_ruling] += contribution; if (lastRound.paidFees[_ruling] >= totalCost) { lastRound.feeRewards += lastRound.paidFees[_ruling]; lastRound.fundedSides.push(_ruling); lastRound.hasPaid[_ruling] = true; emit RulingFunded(_localDisputeID, rounds.length - 1, _ruling); } if (lastRound.fundedSides.length > 1) { // At least two sides are fully funded. rounds.push(); lastRound.feeRewards = lastRound.feeRewards.subCap(appealCost); arbitrator.appeal.value(appealCost)(dispute.disputeIDOnArbitratorSide, dispute.arbitratorExtraData); } msg.sender.transfer(msg.value.subCap(contribution)); // Sending extra value back to contributor. return lastRound.hasPaid[_ruling]; } /** @dev Allows to withdraw any reimbursable fees or rewards after the dispute gets solved. * @param _localDisputeID Index of the dispute in disputes array. * @param _contributor The address to withdraw its rewards. * @param _roundNumber The number of the round caller wants to withdraw from. * @param _ruling A currentRuling option that the caller wannts to withdraw fees and rewards related to it. * @return reward Reward amount that is to be withdrawn. Might be zero if arguments are not qualifying for a reward or reimbursement, or it might be withdrawn already. */ function withdrawFeesAndRewards(uint _localDisputeID, address payable _contributor, uint _roundNumber, uint _ruling) public override returns (uint reward) { DisputeStruct storage dispute = disputes[_localDisputeID]; Round storage round = disputeIDtoRoundArray[_localDisputeID][_roundNumber]; uint finalRuling = dispute.ruling; require(dispute.isRuled, "The dispute should be solved"); if (!round.hasPaid[_ruling]) { // Allow to reimburse if funding was unsuccessful. reward = round.contributions[_contributor][_ruling]; } else if (finalRuling == 0 || !round.hasPaid[finalRuling]) { // Reimburse unspent fees proportionally if there is no winner and loser. reward = round.fundedSides.length > 1 // Means appeal took place. ? (round.contributions[_contributor][_ruling] * round.feeRewards) / (round.paidFees[round.fundedSides[0]] + round.paidFees[round.fundedSides[1]]) : 0; } else if(_ruling == finalRuling) { // Reward the winner. reward = round.paidFees[_ruling] > 0 ? (round.contributions[_contributor][_ruling] * round.feeRewards) / round.paidFees[_ruling] : 0; } round.contributions[_contributor][_ruling] = 0; _contributor.send(reward); // User is responsible for accepting the reward. emit Withdrawal(_localDisputeID, _roundNumber, _ruling, _contributor, reward); } /** @dev Allows to withdraw any reimbursable fees or rewards after the dispute gets solved. For multiple currentRuling options at once. * @param _localDisputeID Index of the dispute in disputes array. * @param _contributor The address to withdraw its rewards. * @param _roundNumber The number of the round caller wants to withdraw from. * @param _contributedTo Rulings that received contributions from contributor. */ function withdrawFeesAndRewardsForMultipleRulings(uint _localDisputeID, address payable _contributor, uint _roundNumber, uint[] memory _contributedTo) public override { Round storage round = disputeIDtoRoundArray[_localDisputeID][_roundNumber]; for (uint contributionNumber = 0; contributionNumber < _contributedTo.length; contributionNumber++) { withdrawFeesAndRewards(_localDisputeID, _contributor, _roundNumber, _contributedTo[contributionNumber]); } } /** @dev Allows to withdraw any rewards or reimbursable fees after the dispute gets resolved. For multiple rulings options and for all rounds at once. * @param _localDisputeID Index of the dispute in disputes array. * @param _contributor The address to withdraw its rewards. * @param _contributedTo Rulings that received contributions from contributor. */ function withdrawFeesAndRewardsForAllRounds(uint _localDisputeID, address payable _contributor, uint[] memory _contributedTo) external override { uint8 noOfRounds = uint8(disputeIDtoRoundArray[_localDisputeID].length); for (uint roundNumber = 0; roundNumber < noOfRounds; roundNumber++) { withdrawFeesAndRewardsForMultipleRulings(_localDisputeID, _contributor, roundNumber, _contributedTo); } } /** @dev To be called by the arbitrator of the dispute, to declare winning ruling. * @param _externalDisputeID ID of the dispute in arbitrator contract. * @param _ruling The currentRuling choice of the arbitration. */ function rule(uint _externalDisputeID, uint _ruling) external override { uint _localDisputeID = externalIDtoLocalID[_externalDisputeID]; DisputeStruct storage dispute = disputes[_localDisputeID]; require(msg.sender == address(arbitrator), "Only the arbitrator can execute this."); require(_ruling <= dispute.numberOfChoices, "Invalid ruling."); require(dispute.isRuled == false, "This dispute has been ruled already."); dispute.isRuled = true; dispute.ruling = _ruling; Round[] storage rounds = disputeIDtoRoundArray[_localDisputeID]; Round storage lastRound = disputeIDtoRoundArray[_localDisputeID][rounds.length - 1]; // If only one ruling option is funded, it wins by default. Note that if any other ruling had funded, an appeal would have been created. if (lastRound.fundedSides.length == 1) { dispute.ruling = lastRound.fundedSides[0]; } emit Ruling(IArbitrator(msg.sender), _externalDisputeID, uint(dispute.ruling)); } /** @dev Allows to submit evidence for a given dispute. * @param _localDisputeID Index of the dispute in disputes array. * @param _evidenceURI Link to evidence. */ function submitEvidence(uint _localDisputeID, string calldata _evidenceURI) external override { DisputeStruct storage dispute = disputes[_localDisputeID]; require(dispute.isRuled == false, "Cannot submit evidence to a resolved dispute."); emit Evidence(arbitrator, _localDisputeID, msg.sender, _evidenceURI); } /** @dev Changes the proportion of appeal fees that must be paid when there is no winner or loser. * @param _sharedStakeMultiplier The new tie multiplier value respect to MULTIPLIER_DIVISOR. */ function changeSharedStakeMultiplier(uint _sharedStakeMultiplier) external { require(msg.sender == governor, "Only the governor can execute this."); sharedStakeMultiplier = _sharedStakeMultiplier; } /** @dev Changes the proportion of appeal fees that must be paid by winner. * @param _winnerStakeMultiplier The new winner multiplier value respect to MULTIPLIER_DIVISOR. */ function changeWinnerStakeMultiplier(uint _winnerStakeMultiplier) external { require(msg.sender == governor, "Only the governor can execute this."); winnerStakeMultiplier = _winnerStakeMultiplier; } /** @dev Changes the proportion of appeal fees that must be paid by loser. * @param _loserStakeMultiplier The new loser multiplier value respect to MULTIPLIER_DIVISOR. */ function changeLoserStakeMultiplier(uint _loserStakeMultiplier) external { require(msg.sender == governor, "Only the governor can execute this."); loserStakeMultiplier = _loserStakeMultiplier; } /** @dev Gets the information of a round of a dispute. * @param _localDisputeID ID of the dispute. * @param _round The round to be queried. */ function getRoundInfo(uint _localDisputeID, uint _round) external view returns ( bool appealed, uint[] memory paidFees, bool[] memory hasPaid, uint feeRewards, uint[] memory fundedSides ) { Round storage round = disputeIDtoRoundArray[_localDisputeID][_round]; fundedSides = round.fundedSides; paidFees = new uint[](round.fundedSides.length); hasPaid = new bool[](round.fundedSides.length); for (uint i = 0; i < round.fundedSides.length; i++) { paidFees[i] = round.paidFees[round.fundedSides[i]]; hasPaid[i] = round.hasPaid[round.fundedSides[i]]; } appealed = _round != (disputeIDtoRoundArray[_localDisputeID].length - 1); feeRewards = round.feeRewards; } /** @dev Gets the information of a round of a dispute. * @param _localDisputeID ID of the dispute. * @param _round The round to be queried. */ function getContributions( uint _localDisputeID, uint _round, address _contributor ) public view returns( uint[] memory fundedSides, uint[] memory contributions ) { Round storage round = disputeIDtoRoundArray[_localDisputeID][_round]; fundedSides = round.fundedSides; contributions = new uint[](round.fundedSides.length); for (uint i = 0; i < contributions.length; i++) { contributions[i] = round.contributions[_contributor][fundedSides[i]]; } } /** @dev Gets the crowdfunding information of a last round of a dispute. * @param _localDisputeID ID of the dispute. * @param _contributor Address of crowdfunding participant to get details of. */ function crowdfundingStatus( uint _localDisputeID, address _contributor ) public view returns( uint[] memory paidFees, bool[] memory hasPaid, uint feeRewards, uint[] memory contributions, uint[] memory fundedSides ) { Round[] storage rounds = disputeIDtoRoundArray[_localDisputeID]; Round storage round = disputeIDtoRoundArray[_localDisputeID][rounds.length -1]; fundedSides = round.fundedSides; contributions = new uint[](round.fundedSides.length); paidFees = new uint[](round.fundedSides.length); hasPaid = new bool[](round.fundedSides.length); feeRewards = round.feeRewards; for (uint i = 0; i < round.fundedSides.length; i++) { paidFees[i] = round.paidFees[round.fundedSides[i]]; hasPaid[i] = round.hasPaid[round.fundedSides[i]]; contributions[i] = round.contributions[_contributor][fundedSides[i]]; } } /** @dev Returns stake multipliers. * @return winner Winners stake multiplier. * @return loser Losers stake multiplier. * @return shared Multiplier when it's tied. * @return divisor Multiplier divisor. */ function getMultipliers() external override view returns(uint winner, uint loser, uint shared, uint divisor){ return (winnerStakeMultiplier, loserStakeMultiplier, sharedStakeMultiplier, MULTIPLIER_DIVISOR); } /** @dev Proxy getter for arbitration cost. * @param _arbitratorExtraData Extra data for arbitration cost calculation. See arbitrator for details. * @return arbitrationFee Arbitration cost of the arbitrator of this contract. */ function getArbitrationCost(bytes calldata _arbitratorExtraData) external view returns (uint arbitrationFee) { arbitrationFee = arbitrator.arbitrationCost(_arbitratorExtraData); } /** @dev Returns active disputes. * @param _cursor Starting point for search. * @param _count Number of items to return. * @return openDisputes Dispute identifiers of open disputes, as in arbitrator. * @return hasMore Whether the search was exhausted (has no more) or not (has more). */ function getOpenDisputes(uint _cursor, uint _count) external view returns (uint[] memory openDisputes, bool hasMore) { uint noOfOpenDisputes = 0; for (uint i = _cursor; i < disputes.length && (noOfOpenDisputes < _count || 0 == _count); i++) { if(disputes[i].isRuled == false){ noOfOpenDisputes++; } } openDisputes = new uint[](noOfOpenDisputes); uint count = 0; hasMore = true; uint i; for (i = _cursor; i < disputes.length && (count < _count || 0 == _count); i++) { if(disputes[i].isRuled == false){ openDisputes[count++] = disputes[i].disputeIDOnArbitratorSide; } } if(i == disputes.length) hasMore = false; } }
* @dev Returns number of possible currentRuling options. Valid rulings are [0, return value]. @param _localDisputeID Dispute id as in arbitrable contract./
function numberOfRulingOptions(uint _localDisputeID) external view override returns (uint numberOfRulingOptions){ numberOfRulingOptions = disputes[_localDisputeID].numberOfChoices; }
1,814,797
[ 1, 1356, 1300, 434, 3323, 783, 54, 332, 310, 702, 18, 2364, 436, 332, 899, 854, 306, 20, 16, 327, 460, 8009, 282, 389, 3729, 1669, 2507, 734, 3035, 2507, 612, 487, 316, 10056, 354, 7119, 6835, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7922, 54, 332, 310, 1320, 12, 11890, 389, 3729, 1669, 2507, 734, 13, 3903, 1476, 3849, 1135, 261, 11890, 7922, 54, 332, 310, 1320, 15329, 203, 3639, 7922, 54, 332, 310, 1320, 273, 1015, 458, 281, 63, 67, 3729, 1669, 2507, 734, 8009, 2696, 951, 17442, 31, 203, 565, 289, 203, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.4.25; library SafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns(uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } uint256 c = _a * _b; require(c / _a == _b); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 _a, uint256 _b) internal pure returns(uint256) { require(_b > 0); // Solidity only automatically asserts when dividing by 0 uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns(uint256) { require(_b <= _a); uint256 c = _a - _b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns(uint256) { uint256 c = _a + _b; require(c >= _a); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns(uint256) { require(b != 0); return a % b; } } interface ICaelumMiner { function getMiningReward() external returns (uint) ; } contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. * @dev Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } contract InterfaceContracts is Ownable { InterfaceContracts public _internalMod; function setModifierContract (address _t) onlyOwner public { _internalMod = InterfaceContracts(_t); } modifier onlyMiningContract() { require(msg.sender == _internalMod._contract_miner(), "Wrong sender"); _; } modifier onlyTokenContract() { require(msg.sender == _internalMod._contract_token(), "Wrong sender"); _; } modifier onlyMasternodeContract() { require(msg.sender == _internalMod._contract_masternode(), "Wrong sender"); _; } modifier onlyVotingOrOwner() { require(msg.sender == _internalMod._contract_voting() || msg.sender == owner, "Wrong sender"); _; } modifier onlyVotingContract() { require(msg.sender == _internalMod._contract_voting() || msg.sender == owner, "Wrong sender"); _; } function _contract_voting () public view returns (address) { return _internalMod._contract_voting(); } function _contract_masternode () public view returns (address) { return _internalMod._contract_masternode(); } function _contract_token () public view returns (address) { return _internalMod._contract_token(); } function _contract_miner () public view returns (address) { return _internalMod._contract_miner(); } } contract CaelumAbstractMasternode is Ownable { struct MasterNode { address accountOwner; bool isActive; bool isTeamMember; uint storedIndex; uint startingRound; uint nodeCount; uint[] indexcounter; } mapping(address => MasterNode) public userByAddress; mapping(uint => MasterNode) public masternodeByIndex; uint public userCounter = 0; uint public masternodeIDcounter = 0; uint public masternodeRound = 0; uint public masternodeCandidate; uint public MINING_PHASE_DURATION_BLOCKS = 4500; uint public miningEpoch; uint public rewardsProofOfWork; uint public rewardsMasternode; bool genesisAdded = false; event NewMasternode(address candidateAddress, uint timeStamp); event RemovedMasternode(address candidateAddress, uint timeStamp); address [] public genesisList = [ 0xdb93CE3cCA2444CE5DA5522a85758af79Af0092D, 0x375E97e59dE97BE46D332Ba17185620B81bdB7cc, 0x14dB686439Aad3C076B793335BC14D9039F32C54, 0x1Ba4b0280163889e7Ee4ab5269C442971F48d13e, 0xE4Ac657af0690E9437f36D3E96886DC880b24404, 0x08Fcf0027E1e91a12981fBc6371dE39A269C3a47, 0x3d664B7B0Eb158798f3E797e194FEe50dD748742, 0xB85aC167079020d93033a014efEaD75f14018522, 0xc6d00915CbcF9ABE9B27403F8d2338551f4ac43b, 0x5256fE3F8e50E0f7f701525e814A2767da2cca06, 0x2cf23c6610A70d58D61eFbdEfD6454960b200c2C ]; function addGenesis() onlyOwner public { require(!genesisAdded); for (uint i=0; i<genesisList.length; i++) { addMasternode(genesisList[i]); } genesisAdded = true; // Forever lock this. } function addOwner() onlyOwner public { addMasternode(owner); updateMasternodeAsTeamMember(owner); } function addMasternode(address _candidate) internal { /** * @dev userByAddress is used for general statistic data. * All masternode interaction happens by masternodeByIndex! */ userByAddress[_candidate].isActive = true; userByAddress[_candidate].accountOwner = _candidate; userByAddress[_candidate].storedIndex = masternodeIDcounter; userByAddress[_candidate].startingRound = masternodeRound + 1; userByAddress[_candidate].indexcounter.push(masternodeIDcounter); masternodeByIndex[masternodeIDcounter].isActive = true; masternodeByIndex[masternodeIDcounter].accountOwner = _candidate; masternodeByIndex[masternodeIDcounter].storedIndex = masternodeIDcounter; masternodeByIndex[masternodeIDcounter].startingRound = masternodeRound + 1; masternodeIDcounter++; userCounter++; } function updateMasternode(uint _index) internal returns(bool) { masternodeByIndex[_index].startingRound++; return true; } function updateMasternodeAsTeamMember(address _candidate) internal returns(bool) { userByAddress[_candidate].isTeamMember = true; return (true); } function deleteMasternode(uint _index) internal { address getUserFrom = getUserFromID(_index); userByAddress[getUserFrom].isActive = false; masternodeByIndex[_index].isActive = false; userCounter--; } function getLastActiveBy(address _candidate) public view returns(uint) { uint lastFound; for (uint i = 0; i < userByAddress[_candidate].indexcounter.length; i++) { if (masternodeByIndex[userByAddress[_candidate].indexcounter[i]].isActive == true) { lastFound = masternodeByIndex[userByAddress[_candidate].indexcounter[i]].storedIndex; } } return lastFound; } function userHasActiveNodes(address _candidate) public view returns(bool) { bool lastFound; for (uint i = 0; i < userByAddress[_candidate].indexcounter.length; i++) { if (masternodeByIndex[userByAddress[_candidate].indexcounter[i]].isActive == true) { lastFound = true; } } return lastFound; } function setMasternodeCandidate() internal returns(address) { uint hardlimitCounter = 0; while (getFollowingCandidate() == 0x0) { // We must return a value not to break the contract. Require is a secondary killswitch now. require(hardlimitCounter < 6, "Failsafe switched on"); // Choose if loop over revert/require to terminate the loop and return a 0 address. if (hardlimitCounter == 5) return (0); masternodeRound = masternodeRound + 1; masternodeCandidate = 0; hardlimitCounter++; } if (masternodeCandidate == masternodeIDcounter - 1) { masternodeRound = masternodeRound + 1; masternodeCandidate = 0; } for (uint i = masternodeCandidate; i < masternodeIDcounter; i++) { if (masternodeByIndex[i].isActive) { if (masternodeByIndex[i].startingRound == masternodeRound) { updateMasternode(i); masternodeCandidate = i; return (masternodeByIndex[i].accountOwner); } } } masternodeRound = masternodeRound + 1; return (0); } function getFollowingCandidate() public view returns(address _address) { uint tmpRound = masternodeRound; uint tmpCandidate = masternodeCandidate; if (tmpCandidate == masternodeIDcounter - 1) { tmpRound = tmpRound + 1; tmpCandidate = 0; } for (uint i = masternodeCandidate; i < masternodeIDcounter; i++) { if (masternodeByIndex[i].isActive) { if (masternodeByIndex[i].startingRound == tmpRound) { tmpCandidate = i; return (masternodeByIndex[i].accountOwner); } } } tmpRound = tmpRound + 1; return (0); } function calculateRewardStructures() internal { //ToDo: Set uint _global_reward_amount = getMiningReward(); uint getStageOfMining = miningEpoch / MINING_PHASE_DURATION_BLOCKS * 10; if (getStageOfMining < 10) { rewardsProofOfWork = _global_reward_amount / 100 * 5; rewardsMasternode = 0; return; } if (getStageOfMining > 90) { rewardsProofOfWork = _global_reward_amount / 100 * 2; rewardsMasternode = _global_reward_amount / 100 * 98; return; } uint _mnreward = (_global_reward_amount / 100) * getStageOfMining; uint _powreward = (_global_reward_amount - _mnreward); setBaseRewards(_powreward, _mnreward); } function setBaseRewards(uint _pow, uint _mn) internal { rewardsMasternode = _mn; rewardsProofOfWork = _pow; } function _arrangeMasternodeFlow() internal { calculateRewardStructures(); setMasternodeCandidate(); miningEpoch++; } function isMasternodeOwner(address _candidate) public view returns(bool) { if (userByAddress[_candidate].indexcounter.length <= 0) return false; if (userByAddress[_candidate].accountOwner == _candidate) return true; } function belongsToUser(address _candidate) public view returns(uint[]) { return userByAddress[_candidate].indexcounter; } function getLastPerUser(address _candidate) public view returns(uint) { return userByAddress[_candidate].indexcounter[userByAddress[_candidate].indexcounter.length - 1]; } function getUserFromID(uint _index) public view returns(address) { return masternodeByIndex[_index].accountOwner; } function getMiningReward() public view returns(uint) { return 50 * 1e8; } function masternodeInfo(uint _index) public view returns ( address, bool, uint, uint ) { return ( masternodeByIndex[_index].accountOwner, masternodeByIndex[_index].isActive, masternodeByIndex[_index].storedIndex, masternodeByIndex[_index].startingRound ); } function contractProgress() public view returns ( uint epoch, uint candidate, uint round, uint miningepoch, uint globalreward, uint powreward, uint masternodereward, uint usercount ) { return ( 0, masternodeCandidate, masternodeRound, miningEpoch, getMiningReward(), rewardsProofOfWork, rewardsMasternode, userCounter ); } } contract CaelumMasternode is InterfaceContracts, CaelumAbstractMasternode { bool minerSet = false; bool tokenSet = false; uint swapStartedBlock = now; address cloneDataFrom = 0x7600bF5112945F9F006c216d5d6db0df2806eDc6; /** * @dev Use this to externaly call the _arrangeMasternodeFlow function. ALWAYS set a modifier ! */ function _externalArrangeFlow() onlyMiningContract public { _arrangeMasternodeFlow(); } /** * @dev Use this to externaly call the addMasternode function. ALWAYS set a modifier ! */ function _externalAddMasternode(address _received) onlyTokenContract public { addMasternode(_received); } /** * @dev Use this to externaly call the deleteMasternode function. ALWAYS set a modifier ! */ function _externalStopMasternode(address _received) onlyTokenContract public { deleteMasternode(getLastActiveBy(_received)); } function getMiningReward() public view returns(uint) { return ICaelumMiner(_contract_miner()).getMiningReward(); } /** * @dev Move the voting away from token. All votes will be made from the voting */ function VoteModifierContract (address _contract) onlyVotingContract external { //_internalMod = CaelumModifierAbstract(_contract); setModifierContract(_contract); } function getDataFromContract() onlyOwner public returns(uint) { CaelumMasternode prev = CaelumMasternode(cloneDataFrom); ( uint epoch, uint candidate, uint round, uint miningepoch, uint globalreward, uint powreward, uint masternodereward, uint usercounter ) = prev.contractProgress(); masternodeRound = round; miningEpoch = miningepoch; rewardsProofOfWork = powreward; rewardsMasternode = masternodereward; } }
* @dev Multiplies two numbers, reverts on overflow./ Gas optimization: this is cheaper than requiring 'a' not being zero, but the benefit is lost if 'b' is also tested. See: https:github.com/OpenZeppelin/openzeppelin-solidity/pull/522
function mul(uint256 _a, uint256 _b) internal pure returns(uint256) { if (_a == 0) { return 0; } uint256 c = _a * _b; require(c / _a == _b); return c; }
1,089,264
[ 1, 5002, 5259, 2795, 5600, 16, 15226, 87, 603, 9391, 18, 19, 31849, 14850, 30, 333, 353, 19315, 7294, 2353, 29468, 296, 69, 11, 486, 3832, 3634, 16, 1496, 326, 27641, 7216, 353, 13557, 309, 296, 70, 11, 353, 2546, 18432, 18, 2164, 30, 2333, 30, 6662, 18, 832, 19, 3678, 62, 881, 84, 292, 267, 19, 3190, 94, 881, 84, 292, 267, 17, 30205, 560, 19, 13469, 19, 25, 3787, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 14064, 12, 11890, 5034, 389, 69, 16, 2254, 5034, 389, 70, 13, 2713, 16618, 1135, 12, 11890, 5034, 13, 288, 203, 3639, 309, 261, 67, 69, 422, 374, 13, 288, 203, 5411, 327, 374, 31, 203, 3639, 289, 203, 203, 3639, 2254, 5034, 276, 273, 389, 69, 380, 389, 70, 31, 203, 3639, 2583, 12, 71, 342, 389, 69, 422, 389, 70, 1769, 203, 203, 3639, 327, 276, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma abicoder v2; import "./interfaces/IOniiChainDescriptor.sol"; import "./interfaces/IOniiChain.sol"; import "./libraries/NFTDescriptor.sol"; import "./libraries/DetailHelper.sol"; import "base64-sol/base64.sol"; /// @title Describes Onii /// @notice Produces a string containing the data URI for a JSON metadata string contract OniiChainDescriptor is IOniiChainDescriptor { /// @dev Max value for defining probabilities uint256 internal constant MAX = 100000; uint256[] internal BACKGROUND_ITEMS = [4000, 3400, 3080, 2750, 2400, 1900, 1200, 0]; uint256[] internal SKIN_ITEMS = [2000, 1000, 0]; uint256[] internal NOSE_ITEMS = [10, 0]; uint256[] internal MARK_ITEMS = [50000, 40000, 31550, 24550, 18550, 13550, 9050, 5550, 2550, 550, 50, 10, 0]; uint256[] internal EYEBROW_ITEMS = [65000, 40000, 20000, 10000, 4000, 0]; uint256[] internal MASK_ITEMS = [20000, 14000, 10000, 6000, 2000, 1000, 100, 0]; uint256[] internal EARRINGS_ITEMS = [50000, 38000, 28000, 20000, 13000, 8000, 5000, 2900, 1000, 100, 30, 0]; uint256[] internal ACCESSORY_ITEMS = [ 50000, 43000, 36200, 29700, 23400, 17400, 11900, 7900, 4400, 1400, 400, 200, 11, 1, 0 ]; uint256[] internal MOUTH_ITEMS = [ 80000, 63000, 48000, 36000, 27000, 19000, 12000, 7000, 4000, 2000, 1000, 500, 50, 0 ]; uint256[] internal HAIR_ITEMS = [ 97000, 94000, 91000, 88000, 85000, 82000, 79000, 76000, 73000, 70000, 67000, 64000, 61000, 58000, 55000, 52000, 49000, 46000, 43000, 40000, 37000, 34000, 31000, 28000, 25000, 22000, 19000, 16000, 13000, 10000, 3000, 1000, 0 ]; uint256[] internal EYE_ITEMS = [ 98000, 96000, 94000, 92000, 90000, 88000, 86000, 84000, 82000, 80000, 78000, 76000, 74000, 72000, 70000, 68000, 60800, 53700, 46700, 39900, 33400, 27200, 21200, 15300, 10600, 6600, 3600, 2600, 1700, 1000, 500, 100, 10, 0 ]; /// @inheritdoc IOniiChainDescriptor function tokenURI(IOniiChain oniiChain, uint256 tokenId) external view override returns (string memory) { NFTDescriptor.SVGParams memory params = getSVGParams(oniiChain, tokenId); params.background = getBackgroundId(params); string memory image = Base64.encode(bytes(NFTDescriptor.generateSVGImage(params))); string memory name = NFTDescriptor.generateName(params, tokenId); string memory description = NFTDescriptor.generateDescription(params); string memory attributes = NFTDescriptor.generateAttributes(params); return string( abi.encodePacked( "data:application/json;base64,", Base64.encode( bytes( abi.encodePacked( '{"name":"', name, '", "description":"', description, '", "attributes":', attributes, ', "image": "', "data:image/svg+xml;base64,", image, '"}' ) ) ) ) ); } /// @inheritdoc IOniiChainDescriptor function generateHairId(uint256 tokenId, uint256 seed) external view override returns (uint8) { return DetailHelper.generate(MAX, seed, HAIR_ITEMS, this.generateHairId.selector, tokenId); } /// @inheritdoc IOniiChainDescriptor function generateEyeId(uint256 tokenId, uint256 seed) external view override returns (uint8) { return DetailHelper.generate(MAX, seed, EYE_ITEMS, this.generateEyeId.selector, tokenId); } /// @inheritdoc IOniiChainDescriptor function generateEyebrowId(uint256 tokenId, uint256 seed) external view override returns (uint8) { return DetailHelper.generate(MAX, seed, EYEBROW_ITEMS, this.generateEyebrowId.selector, tokenId); } /// @inheritdoc IOniiChainDescriptor function generateNoseId(uint256 tokenId, uint256 seed) external view override returns (uint8) { return DetailHelper.generate(MAX, seed, NOSE_ITEMS, this.generateNoseId.selector, tokenId); } /// @inheritdoc IOniiChainDescriptor function generateMouthId(uint256 tokenId, uint256 seed) external view override returns (uint8) { return DetailHelper.generate(MAX, seed, MOUTH_ITEMS, this.generateMouthId.selector, tokenId); } /// @inheritdoc IOniiChainDescriptor function generateMarkId(uint256 tokenId, uint256 seed) external view override returns (uint8) { return DetailHelper.generate(MAX, seed, MARK_ITEMS, this.generateMarkId.selector, tokenId); } /// @inheritdoc IOniiChainDescriptor function generateEarringsId(uint256 tokenId, uint256 seed) external view override returns (uint8) { return DetailHelper.generate(MAX, seed, EARRINGS_ITEMS, this.generateEarringsId.selector, tokenId); } /// @inheritdoc IOniiChainDescriptor function generateAccessoryId(uint256 tokenId, uint256 seed) external view override returns (uint8) { return DetailHelper.generate(MAX, seed, ACCESSORY_ITEMS, this.generateAccessoryId.selector, tokenId); } /// @inheritdoc IOniiChainDescriptor function generateMaskId(uint256 tokenId, uint256 seed) external view override returns (uint8) { return DetailHelper.generate(MAX, seed, MASK_ITEMS, this.generateMaskId.selector, tokenId); } /// @inheritdoc IOniiChainDescriptor function generateSkinId(uint256 tokenId, uint256 seed) external view override returns (uint8) { return DetailHelper.generate(MAX, seed, SKIN_ITEMS, this.generateSkinId.selector, tokenId); } /// @dev Get SVGParams from OniiChain.Detail function getSVGParams(IOniiChain oniiChain, uint256 tokenId) private view returns (NFTDescriptor.SVGParams memory) { IOniiChain.Detail memory detail = oniiChain.details(tokenId); return NFTDescriptor.SVGParams({ hair: detail.hair, eye: detail.eye, eyebrow: detail.eyebrow, nose: detail.nose, mouth: detail.mouth, mark: detail.mark, earring: detail.earrings, accessory: detail.accessory, mask: detail.mask, skin: detail.skin, original: detail.original, background: 0, timestamp: detail.timestamp, creator: detail.creator }); } function getBackgroundId(NFTDescriptor.SVGParams memory params) private view returns (uint8) { uint256 score = itemScorePosition(params.hair, HAIR_ITEMS) + itemScoreProba(params.accessory, ACCESSORY_ITEMS) + itemScoreProba(params.earring, EARRINGS_ITEMS) + itemScoreProba(params.mask, MASK_ITEMS) + itemScorePosition(params.mouth, MOUTH_ITEMS) + (itemScoreProba(params.skin, SKIN_ITEMS) / 2) + itemScoreProba(params.skin, SKIN_ITEMS) + itemScoreProba(params.nose, NOSE_ITEMS) + itemScoreProba(params.mark, MARK_ITEMS) + itemScorePosition(params.eye, EYE_ITEMS) + itemScoreProba(params.eyebrow, EYEBROW_ITEMS); return DetailHelper.pickItems(score, BACKGROUND_ITEMS); } /// @dev Get item score based on his probability function itemScoreProba(uint8 item, uint256[] memory ITEMS) private pure returns (uint256) { uint256 raw = ((item == 1 ? MAX : ITEMS[item - 2]) - ITEMS[item - 1]); return ((raw >= 1000) ? raw * 6 : raw) / 1000; } /// @dev Get item score based on his index function itemScorePosition(uint8 item, uint256[] memory ITEMS) private pure returns (uint256) { uint256 raw = ITEMS[item - 1]; return ((raw >= 1000) ? raw * 6 : raw) / 1000; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma abicoder v2; import "./IOniiChain.sol"; /// @title Describes Onii via URI interface IOniiChainDescriptor { /// @notice Produces the URI describing a particular Onii (token id) /// @dev Note this URI may be a data: URI with the JSON contents directly inlined /// @param oniiChain The OniiChain contract /// @param tokenId The ID of the token for which to produce a description /// @return The URI of the ERC721-compliant metadata function tokenURI(IOniiChain oniiChain, uint256 tokenId) external view returns (string memory); /// @notice Generate randomly an ID for the hair item /// @param tokenId the current tokenId /// @param seed Used for the initialization of the number generator. /// @return the hair item id function generateHairId(uint256 tokenId, uint256 seed) external view returns (uint8); /// @notice Generate randomly an ID for the eye item /// @param tokenId the current tokenId /// @param seed Used for the initialization of the number generator. /// @return the eye item id function generateEyeId(uint256 tokenId, uint256 seed) external view returns (uint8); /// @notice Generate randomly an ID for the eyebrow item /// @param tokenId the current tokenId /// @param seed Used for the initialization of the number generator. /// @return the eyebrow item id function generateEyebrowId(uint256 tokenId, uint256 seed) external view returns (uint8); /// @notice Generate randomly an ID for the nose item /// @param tokenId the current tokenId /// @param seed Used for the initialization of the number generator. /// @return the nose item id function generateNoseId(uint256 tokenId, uint256 seed) external view returns (uint8); /// @notice Generate randomly an ID for the mouth item /// @param tokenId the current tokenId /// @param seed Used for the initialization of the number generator. /// @return the mouth item id function generateMouthId(uint256 tokenId, uint256 seed) external view returns (uint8); /// @notice Generate randomly an ID for the mark item /// @param tokenId the current tokenId /// @param seed Used for the initialization of the number generator. /// @return the mark item id function generateMarkId(uint256 tokenId, uint256 seed) external view returns (uint8); /// @notice Generate randomly an ID for the earrings item /// @param tokenId the current tokenId /// @param seed Used for the initialization of the number generator. /// @return the earrings item id function generateEarringsId(uint256 tokenId, uint256 seed) external view returns (uint8); /// @notice Generate randomly an ID for the accessory item /// @param tokenId the current tokenId /// @param seed Used for the initialization of the number generator. /// @return the accessory item id function generateAccessoryId(uint256 tokenId, uint256 seed) external view returns (uint8); /// @notice Generate randomly an ID for the mask item /// @param tokenId the current tokenId /// @param seed Used for the initialization of the number generator. /// @return the mask item id function generateMaskId(uint256 tokenId, uint256 seed) external view returns (uint8); /// @notice Generate randomly the skin colors /// @param tokenId the current tokenId /// @param seed Used for the initialization of the number generator. /// @return the skin item id function generateSkinId(uint256 tokenId, uint256 seed) external view returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma abicoder v2; /// @title OniiChain NFTs Interface interface IOniiChain { /// @notice Details about the Onii struct Detail { uint8 hair; uint8 eye; uint8 eyebrow; uint8 nose; uint8 mouth; uint8 mark; uint8 earrings; uint8 accessory; uint8 mask; uint8 skin; bool original; uint256 timestamp; address creator; } /// @notice Returns the details associated with a given token ID. /// @dev Throws if the token ID is not valid. /// @param tokenId The ID of the token that represents the Onii /// @return detail memory function details(uint256 tokenId) external view returns (Detail memory detail); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma abicoder v2; import "./details/BackgroundDetail.sol"; import "./details/BodyDetail.sol"; import "./details/HairDetail.sol"; import "./details/MouthDetail.sol"; import "./details/NoseDetail.sol"; import "./details/EyesDetail.sol"; import "./details/EyebrowDetail.sol"; import "./details/MarkDetail.sol"; import "./details/AccessoryDetail.sol"; import "./details/EarringsDetail.sol"; import "./details/MaskDetail.sol"; import "./DetailHelper.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; /// @notice Helper to generate SVGs library NFTDescriptor { struct SVGParams { uint8 hair; uint8 eye; uint8 eyebrow; uint8 nose; uint8 mouth; uint8 mark; uint8 earring; uint8 accessory; uint8 mask; uint8 background; uint8 skin; bool original; uint256 timestamp; address creator; } /// @dev Combine all the SVGs to generate the final image function generateSVGImage(SVGParams memory params) internal view returns (string memory) { return string( abi.encodePacked( generateSVGHead(), DetailHelper.getDetailSVG(address(BackgroundDetail), params.background), generateSVGFace(params), DetailHelper.getDetailSVG(address(EarringsDetail), params.earring), DetailHelper.getDetailSVG(address(HairDetail), params.hair), DetailHelper.getDetailSVG(address(MaskDetail), params.mask), DetailHelper.getDetailSVG(address(AccessoryDetail), params.accessory), generateCopy(params.original), "</svg>" ) ); } /// @dev Combine face items function generateSVGFace(SVGParams memory params) private view returns (string memory) { return string( abi.encodePacked( DetailHelper.getDetailSVG(address(BodyDetail), params.skin), DetailHelper.getDetailSVG(address(MarkDetail), params.mark), DetailHelper.getDetailSVG(address(MouthDetail), params.mouth), DetailHelper.getDetailSVG(address(NoseDetail), params.nose), DetailHelper.getDetailSVG(address(EyesDetail), params.eye), DetailHelper.getDetailSVG(address(EyebrowDetail), params.eyebrow) ) ); } /// @dev generate Json Metadata name function generateName(SVGParams memory params, uint256 tokenId) internal pure returns (string memory) { return string( abi.encodePacked( BackgroundDetail.getItemNameById(params.background), " Onii ", Strings.toString(tokenId) ) ); } /// @dev generate Json Metadata description function generateDescription(SVGParams memory params) internal pure returns (string memory) { return string( abi.encodePacked( "Generated by ", Strings.toHexString(uint256(uint160(params.creator))), " at ", Strings.toString(params.timestamp) ) ); } /// @dev generate SVG header function generateSVGHead() private pure returns (string memory) { return string( abi.encodePacked( '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" x="0px" y="0px"', ' viewBox="0 0 420 420" style="enable-background:new 0 0 420 420;" xml:space="preserve">' ) ); } /// @dev generate the "Copy" SVG if the onii is not the original function generateCopy(bool original) private pure returns (string memory) { return !original ? string( abi.encodePacked( '<g id="Copy">', '<path fill="none" stroke="#F26559" stroke-width="0.5" stroke-miterlimit="10" d="M239.5,300.6c-4.9,1.8-5.9,8.1,1.3,4.1"/>', '<path fill="none" stroke="#F26559" stroke-width="0.5" stroke-miterlimit="10" d="M242.9,299.5c-2.6,0.8-1.8,4.3,0.8,4.2 C246.3,303.1,245.6,298.7,242.9,299.5"/>', '<path fill="none" stroke="#F26559" stroke-width="0.5" stroke-miterlimit="10" d="M247.5,302.9c0.2-1.6-1.4-4-0.8-5.4 c0.4-1.2,2.5-1.4,3.2-0.3c0.1,1.5-0.9,2.7-2.3,2.5"/>', '<path fill="none" stroke="#F26559" stroke-width="0.5" stroke-miterlimit="10" d="M250.6,295.4c1.1-0.1,2.2,0,3.3,0.1 c0.5-0.8,0.7-1.7,0.5-2.7"/>', '<path fill="none" stroke="#F26559" stroke-width="0.5" stroke-miterlimit="10" d="M252.5,299.1c0.5-1.2,1.2-2.3,1.4-3.5"/>', "</g>" ) ) : ""; } /// @dev generate Json Metadata attributes function generateAttributes(SVGParams memory params) internal pure returns (string memory) { return string( abi.encodePacked( "[", getJsonAttribute("Body", BodyDetail.getItemNameById(params.skin), false), getJsonAttribute("Hair", HairDetail.getItemNameById(params.hair), false), getJsonAttribute("Mouth", MouthDetail.getItemNameById(params.mouth), false), getJsonAttribute("Nose", NoseDetail.getItemNameById(params.nose), false), getJsonAttribute("Eyes", EyesDetail.getItemNameById(params.eye), false), getJsonAttribute("Eyebrow", EyebrowDetail.getItemNameById(params.eyebrow), false), abi.encodePacked( getJsonAttribute("Mark", MarkDetail.getItemNameById(params.mark), false), getJsonAttribute("Accessory", AccessoryDetail.getItemNameById(params.accessory), false), getJsonAttribute("Earrings", EarringsDetail.getItemNameById(params.earring), false), getJsonAttribute("Mask", MaskDetail.getItemNameById(params.mask), false), getJsonAttribute("Background", BackgroundDetail.getItemNameById(params.background), false), getJsonAttribute("Original", params.original ? "true" : "false", true), "]" ) ) ); } /// @dev Get the json attribute as /// { /// "trait_type": "Skin", /// "value": "Human" /// } function getJsonAttribute( string memory trait, string memory value, bool end ) private pure returns (string memory json) { return string(abi.encodePacked('{ "trait_type" : "', trait, '", "value" : "', value, '" }', end ? "" : ",")); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma abicoder v2; import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/utils/math/SafeCast.sol"; /// @title Helper for details generation library DetailHelper { /// @notice Call the library item function /// @param lib The library address /// @param id The item ID function getDetailSVG(address lib, uint8 id) internal view returns (string memory) { (bool success, bytes memory data) = lib.staticcall( abi.encodeWithSignature(string(abi.encodePacked("item_", Strings.toString(id), "()"))) ); require(success); return abi.decode(data, (string)); } /// @notice Generate a random number and return the index from the /// corresponding interval. /// @param max The maximum value to generate /// @param seed Used for the initialization of the number generator /// @param intervals the intervals /// @param selector Caller selector /// @param tokenId the current tokenId function generate( uint256 max, uint256 seed, uint256[] memory intervals, bytes4 selector, uint256 tokenId ) internal view returns (uint8) { uint256 generated = generateRandom(max, seed, tokenId, selector); return pickItems(generated, intervals); } /// @notice Generate random number between 1 and max /// @param max Maximum value of the random number /// @param seed Used for the initialization of the number generator /// @param tokenId Current tokenId used as seed /// @param selector Caller selector used as seed function generateRandom( uint256 max, uint256 seed, uint256 tokenId, bytes4 selector ) private view returns (uint256) { return (uint256( keccak256( abi.encodePacked(block.difficulty, block.number, tx.origin, tx.gasprice, selector, seed, tokenId) ) ) % (max + 1)) + 1; } /// @notice Pick an item for the given random value /// @param val The random value /// @param intervals The intervals for the corresponding items /// @return the item ID where : intervals[] index + 1 = item ID function pickItems(uint256 val, uint256[] memory intervals) internal pure returns (uint8) { for (uint256 i; i < intervals.length; i++) { if (val > intervals[i]) { return SafeCast.toUint8(i + 1); } } revert("DetailHelper::pickItems: No item"); } } // SPDX-License-Identifier: MIT /// @title Base64 /// @author Brecht Devos - <[email protected]> /// @notice Provides a function for encoding some bytes in base64 library Base64 { string internal constant TABLE = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; function encode(bytes memory data) internal pure returns (string memory) { if (data.length == 0) return ''; // load the table into memory string memory table = TABLE; // multiply by 4/3 rounded up uint256 encodedLen = 4 * ((data.length + 2) / 3); // add some extra buffer at the end required for the writing string memory result = new string(encodedLen + 32); assembly { // set the actual output length mstore(result, encodedLen) // prepare the lookup table let tablePtr := add(table, 1) // input ptr let dataPtr := data let endPtr := add(dataPtr, mload(data)) // result ptr, jump over length let resultPtr := add(result, 32) // run over the input, 3 bytes at a time for {} lt(dataPtr, endPtr) {} { dataPtr := add(dataPtr, 3) // read 3 bytes let input := mload(dataPtr) // write 4 characters mstore(resultPtr, shl(248, mload(add(tablePtr, and(shr(18, input), 0x3F))))) resultPtr := add(resultPtr, 1) mstore(resultPtr, shl(248, mload(add(tablePtr, and(shr(12, input), 0x3F))))) resultPtr := add(resultPtr, 1) mstore(resultPtr, shl(248, mload(add(tablePtr, and(shr( 6, input), 0x3F))))) resultPtr := add(resultPtr, 1) mstore(resultPtr, shl(248, mload(add(tablePtr, and( input, 0x3F))))) resultPtr := add(resultPtr, 1) } // padding with '=' switch mod(mload(data), 3) case 1 { mstore(sub(resultPtr, 2), shl(240, 0x3d3d)) } case 2 { mstore(sub(resultPtr, 1), shl(248, 0x3d)) } } return result; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma abicoder v2; import "base64-sol/base64.sol"; /// @title Background SVG generator library BackgroundDetail { /// @dev background N°1 => Ordinary function item_1() public pure returns (string memory) { return base("636363", "CFCFCF", "ABABAB"); } /// @dev background N°2 => Unusual function item_2() public pure returns (string memory) { return base("004A06", "61E89B", "12B55F"); } /// @dev background N°3 => Surprising function item_3() public pure returns (string memory) { return base("1A4685", "6BF0E3", "00ADC7"); } /// @dev background N°4 => Impressive function item_4() public pure returns (string memory) { return base("380113", "D87AE6", "8A07BA"); } /// @dev background N°5 => Extraordinary function item_5() public pure returns (string memory) { return base("A33900", "FAF299", "FF9121"); } /// @dev background N°6 => Phenomenal function item_6() public pure returns (string memory) { return base("000000", "C000E8", "DED52C"); } /// @dev background N°7 => Artistic function item_7() public pure returns (string memory) { return base("FF00E3", "E8E18B", "00C4AD"); } /// @dev background N°8 => Unreal function item_8() public pure returns (string memory) { return base("CCCC75", "54054D", "001E2E"); } /// @notice Return the background name of the given id /// @param id The background Id function getItemNameById(uint8 id) public pure returns (string memory name) { name = ""; if (id == 1) { name = "Ordinary"; } else if (id == 2) { name = "Unusual"; } else if (id == 3) { name = "Surprising"; } else if (id == 4) { name = "Impressive"; } else if (id == 5) { name = "Extraordinary"; } else if (id == 6) { name = "Phenomenal"; } else if (id == 7) { name = "Artistic"; } else if (id == 8) { name = "Unreal"; } } /// @dev The base SVG for the backgrounds function base( string memory stop1, string memory stop2, string memory stop3 ) private pure returns (string memory) { return string( abi.encodePacked( '<g id="Background">', '<radialGradient id="gradient" cx="210" cy="-134.05" r="210.025" gradientTransform="matrix(1 0 0 -1 0 76)" gradientUnits="userSpaceOnUse">', "<style>", ".color-anim {animation: col 6s infinite;animation-timing-function: ease-in-out;}", "@keyframes col {0%,51% {stop-color:none} 52% {stop-color:#FFBAF7} 53%,100% {stop-color:none}}", "</style>", "<stop offset='0' class='color-anim' style='stop-color:#", stop1, "'/>", "<stop offset='0.66' style='stop-color:#", stop2, "'><animate attributeName='offset' dur='18s' values='0.54;0.8;0.54' repeatCount='indefinite' keyTimes='0;.4;1'/></stop>", "<stop offset='1' style='stop-color:#", stop3, "'><animate attributeName='offset' dur='18s' values='0.86;1;0.86' repeatCount='indefinite'/></stop>", abi.encodePacked( "</radialGradient>", '<path fill="url(#gradient)" d="M390,420H30c-16.6,0-30-13.4-30-30V30C0,13.4,13.4,0,30,0h360c16.6,0,30,13.4,30,30v360C420,406.6,406.6,420,390,420z"/>', '<path id="Border" opacity="0.4" fill="none" stroke="#FFFFFF" stroke-width="2" stroke-miterlimit="10" d="M383.4,410H36.6C21.9,410,10,398.1,10,383.4V36.6C10,21.9,21.9,10,36.6,10h346.8c14.7,0,26.6,11.9,26.6,26.6v346.8 C410,398.1,398.1,410,383.4,410z"/>', '<path id="Mask" opacity="0.1" fill="#48005E" d="M381.4,410H38.6C22.8,410,10,397.2,10,381.4V38.6 C10,22.8,22.8,10,38.6,10h342.9c15.8,0,28.6,12.8,28.6,28.6v342.9C410,397.2,397.2,410,381.4,410z"/>', "</g>" ) ) ); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma abicoder v2; import "base64-sol/base64.sol"; /// @title Body SVG generator library BodyDetail { /// @dev Body N°1 => Human function item_1() public pure returns (string memory) { return base("FFEBB4", "FFBE94"); } /// @dev Body N°2 => Shadow function item_2() public pure returns (string memory) { return base("2d2d2d", "000000"); } /// @dev Body N°3 => Light function item_3() public pure returns (string memory) { return base("ffffff", "696969"); } /// @notice Return the skin name of the given id /// @param id The skin Id function getItemNameById(uint8 id) public pure returns (string memory name) { name = ""; if (id == 1) { name = "Human"; } else if (id == 2) { name = "Shadow"; } else if (id == 3) { name = "Light"; } } /// @dev The base SVG for the body function base(string memory skin, string memory shadow) private pure returns (string memory) { string memory pathBase = "<path fill-rule='evenodd' clip-rule='evenodd' fill='#"; string memory strokeBase = "' stroke='#000000' stroke-linecap='round' stroke-miterlimit='10'"; return string( abi.encodePacked( '<g id="Body">', pathBase, skin, strokeBase, " d='M177.1,287.1c0.8,9.6,0.3,19.3-1.5,29.2c-0.5,2.5-2.1,4.7-4.5,6c-15.7,8.5-41.1,16.4-68.8,24.2c-7.8,2.2-9.1,11.9-2,15.7c69,37,140.4,40.9,215.4,6.7c6.9-3.2,7-12.2,0.1-15.4c-21.4-9.9-42.1-19.7-53.1-26.2c-2.5-1.5-4-3.9-4.3-6.5c-0.7-7.4-0.9-16.1-0.3-25.5c0.7-10.8,2.5-20.3,4.4-28.2'/>", abi.encodePacked( pathBase, shadow, "' d='M177.1,289c0,0,23.2,33.7,39.3,29.5s40.9-20.5,40.9-20.5c1.2-8.7,2.4-17.5,3.5-26.2c-4.6,4.7-10.9,10.2-19,15.3c-10.8,6.8-21,10.4-28.5,12.4L177.1,289z'/>", pathBase, skin, strokeBase, " d='M301.3,193.6c2.5-4.6,10.7-68.1-19.8-99.1c-29.5-29.9-96-34-128.1-0.3s-23.7,105.6-23.7,105.6s12.4,59.8,24.2,72c0,0,32.3,24.8,40.7,29.5c8.4,4.8,16.4,2.2,16.4,2.2c15.4-5.7,25.1-10.9,33.3-17.4'/>", pathBase ), skin, strokeBase, " d='M141.8,247.2c0.1,1.1-11.6,7.4-12.9-7.1c-1.3-14.5-3.9-18.2-9.3-34.5s9.1-8.4,9.1-8.4'/>", abi.encodePacked( pathBase, skin, strokeBase, " d='M254.8,278.1c7-8.6,13.9-17.2,20.9-25.8c1.2-1.4,2.9-2.1,4.6-1.7c3.9,0.8,11.2,1.2,12.8-6.7c2.3-11,6.5-23.5,12.3-33.6c3.2-5.7,0.7-11.4-2.2-15.3c-2.1-2.8-6.1-2.7-7.9,0.2c-2.6,4-5,7.9-7.6,11.9'/>", "<polygon fill-rule='evenodd' clip-rule='evenodd' fill='#", skin, "' points='272,237.4 251.4,270.4 260.9,268.6 276.9,232.4'/>", "<path d='M193.3,196.4c0.8,5.1,1,10.2,1,15.4c0,2.6-0.1,5.2-0.4,7.7c-0.3,2.6-0.7,5.1-1.3,7.6h-0.1c0.1-2.6,0.3-5.1,0.4-7.7c0.2-2.5,0.4-5.1,0.6-7.6c0.1-2.6,0.2-5.1,0.1-7.7C193.5,201.5,193.4,198.9,193.3,196.4L193.3,196.4z'/>", "<path fill='#", shadow ), "' d='M197.8,242.8l-7.9-3.5c-0.4-0.2-0.5-0.7-0.2-1.1l3.2-3.3c0.4-0.4,1-0.5,1.5-0.3l12.7,4.6c0.6,0.2,0.6,1.1-0.1,1.3l-8.7,2.4C198.1,242.9,197.9,242.9,197.8,242.8z'/>", "</g>" ) ); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma abicoder v2; import "base64-sol/base64.sol"; import "./constants/Colors.sol"; /// @title Hair SVG generator library HairDetail { /// @dev Hair N°1 => Classic Brown function item_1() public pure returns (string memory) { return base(classicHairs(Colors.BROWN)); } /// @dev Hair N°2 => Classic Black function item_2() public pure returns (string memory) { return base(classicHairs(Colors.BLACK)); } /// @dev Hair N°3 => Classic Gray function item_3() public pure returns (string memory) { return base(classicHairs(Colors.GRAY)); } /// @dev Hair N°4 => Classic White function item_4() public pure returns (string memory) { return base(classicHairs(Colors.WHITE)); } /// @dev Hair N°5 => Classic Blue function item_5() public pure returns (string memory) { return base(classicHairs(Colors.BLUE)); } /// @dev Hair N°6 => Classic Yellow function item_6() public pure returns (string memory) { return base(classicHairs(Colors.YELLOW)); } /// @dev Hair N°7 => Classic Pink function item_7() public pure returns (string memory) { return base(classicHairs(Colors.PINK)); } /// @dev Hair N°8 => Classic Red function item_8() public pure returns (string memory) { return base(classicHairs(Colors.RED)); } /// @dev Hair N°9 => Classic Purple function item_9() public pure returns (string memory) { return base(classicHairs(Colors.PURPLE)); } /// @dev Hair N°10 => Classic Green function item_10() public pure returns (string memory) { return base(classicHairs(Colors.GREEN)); } /// @dev Hair N°11 => Classic Saiki function item_11() public pure returns (string memory) { return base(classicHairs(Colors.SAIKI)); } /// @dev Hair N°12 => Classic 2 Brown function item_12() public pure returns (string memory) { return base(classicTwoHairs(Colors.BROWN)); } /// @dev Hair N°13 => Classic 2 Black function item_13() public pure returns (string memory) { return base(classicTwoHairs(Colors.BLACK)); } /// @dev Hair N°14 => Classic 2 Gray function item_14() public pure returns (string memory) { return base(classicTwoHairs(Colors.GRAY)); } /// @dev Hair N°15 => Classic 2 White function item_15() public pure returns (string memory) { return base(classicTwoHairs(Colors.WHITE)); } /// @dev Hair N°16 => Classic 2 Blue function item_16() public pure returns (string memory) { return base(classicTwoHairs(Colors.BLUE)); } /// @dev Hair N°17 => Classic 2 Yellow function item_17() public pure returns (string memory) { return base(classicTwoHairs(Colors.YELLOW)); } /// @dev Hair N°18 => Classic 2 Pink function item_18() public pure returns (string memory) { return base(classicTwoHairs(Colors.PINK)); } /// @dev Hair N°19 => Classic 2 Red function item_19() public pure returns (string memory) { return base(classicTwoHairs(Colors.RED)); } /// @dev Hair N°20 => Classic 2 Purple function item_20() public pure returns (string memory) { return base(classicTwoHairs(Colors.PURPLE)); } /// @dev Hair N°21 => Classic 2 Green function item_21() public pure returns (string memory) { return base(classicTwoHairs(Colors.GREEN)); } /// @dev Hair N°22 => Classic 2 Saiki function item_22() public pure returns (string memory) { return base(classicTwoHairs(Colors.SAIKI)); } /// @dev Hair N°23 => Short Black function item_23() public pure returns (string memory) { return base(shortHairs(Colors.BLACK)); } /// @dev Hair N°24 => Short Blue function item_24() public pure returns (string memory) { return base(shortHairs(Colors.BLUE)); } /// @dev Hair N°25 => Short Pink function item_25() public pure returns (string memory) { return base(shortHairs(Colors.PINK)); } /// @dev Hair N°26 => Short White function item_26() public pure returns (string memory) { return base(shortHairs(Colors.WHITE)); } /// @dev Hair N°27 => Spike Black function item_27() public pure returns (string memory) { return base(spike(Colors.BLACK)); } /// @dev Hair N°28 => Spike Blue function item_28() public pure returns (string memory) { return base(spike(Colors.BLUE)); } /// @dev Hair N°29 => Spike Pink function item_29() public pure returns (string memory) { return base(spike(Colors.PINK)); } /// @dev Hair N°30 => Spike White function item_30() public pure returns (string memory) { return base(spike(Colors.WHITE)); } /// @dev Hair N°31 => Monk function item_31() public pure returns (string memory) { return base(monk()); } /// @dev Hair N°32 => Nihon function item_32() public pure returns (string memory) { return base( string( abi.encodePacked( monk(), '<path opacity="0.36" fill="#6E5454" stroke="#8A8A8A" stroke-width="0.5" stroke-miterlimit="10" d=" M287.5,206.8c0,0,0.1-17.4-2.9-20.3c-3.1-2.9-7.3-8.7-7.3-8.7s0.6-24.8-2.9-31.8c-3.6-7-3.9-24.3-35-23.6 c-30.3,0.7-42.5,5.4-42.5,5.4s-14.2-8.2-43-3.8c-19.3,4.9-17.2,50.1-17.2,50.1s-5.6,9.5-6.2,14.8c-0.6,5.3-0.3,8.3-0.3,8.3 S111,72.1,216.8,70.4c108.4-1.7,87.1,121.7,85.1,122.4C295.4,190.1,293.9,197.7,287.5,206.8z"/>', '<g opacity="0.33">', '<ellipse transform="matrix(0.7071 -0.7071 0.7071 0.7071 0.367 227.089)" fill="#FFFFFF" cx="274.3" cy="113.1" rx="1.4" ry="5.3"/>', '<ellipse transform="matrix(0.5535 -0.8328 0.8328 0.5535 32.4151 255.0608)" fill="#FFFFFF" cx="254.1" cy="97.3" rx="4.2" ry="16.3"/>', "</g>", '<path fill="#FFFFFF" stroke="#2B232B" stroke-miterlimit="10" d="M136.2,125.1c0,0,72,9.9,162.2,0c0,0,4.4,14.9,4.8,26.6 c0,0-125.4,20.9-172.6-0.3C129.5,151.3,132.9,130.3,136.2,125.1z"/>', '<polygon fill="#FFFFFF" stroke="#2B232B" stroke-miterlimit="10" points="306.2,138 324.2,168.1 330,160"/>', '<path fill="#FFFFFF" stroke="#2B232B" stroke-miterlimit="10" d="M298.4,125.1l34.2,54.6l-18,15.5l-10.7-43.5 C302.3,142.2,299.9,128.8,298.4,125.1z"/>', '<ellipse opacity="0.87" fill="#FF0039" cx="198.2" cy="144.1" rx="9.9" ry="10.8"/>' ) ) ); } /// @dev Hair N°33 => Bald function item_33() public pure returns (string memory) { return base( string( abi.encodePacked( '<ellipse transform="matrix(0.7071 -0.7071 0.7071 0.7071 0.1733 226.5807)" fill="#FFFFFF" cx="273.6" cy="113.1" rx="1.4" ry="5.3"/>', '<ellipse transform="matrix(0.5535 -0.8328 0.8328 0.5535 32.1174 254.4671)" fill="#FFFFFF" cx="253.4" cy="97.3" rx="4.2" ry="16.3"/>' ) ) ); } /// @dev Generate classic hairs with the given color function classicHairs(string memory hairsColor) private pure returns (string memory) { return string( abi.encodePacked( "<path fill='#", hairsColor, "' stroke='#000000' stroke-width='0.5' stroke-miterlimit='10' d='M252.4,71.8c0,0-15.1-13.6-42.6-12.3l15.6,8.8c0,0-12.9-0.9-28.4-1.3c-6.1-0.2-21.8,3.3-38.3-1.4c0,0,7.3,7.2,9.4,7.7c0,0-30.6,13.8-47.3,34.2c0,0,10.7-8.9,16.7-10.9c0,0-26,25.2-31.5,70c0,0,9.2-28.6,15.5-34.2c0,0-10.7,27.4-5.3,48.2c0,0,2.4-14.5,4.9-19.2c-1,14.1,2.4,33.9,13.8,47.8c0,0-3.3-15.8-2.2-21.9l8.8-17.9c0.1,4.1,1.3,8.1,3.1,12.3c0,0,13-36.1,19.7-43.9c0,0-2.9,15.4-1.1,29.6c0,0,6.8-23.5,16.9-36.8c0,0-4.6,15.6-2.7,31.9c0,0,9.4-26.2,10.4-28.2l-2.7,9.2c0,0,4.1,21.6,3.8,25.3c0,0,8.4-10.3,21.2-52l-2.9,12c0,0,9.8,20.3,10.3,22.2s-1.3-13.9-1.3-13.9s12.4,21.7,13.5,26c0,0,5.5-20.8,3.4-35.7l1.1,9.6c0,0,15,20.3,16.4,30.1s-0.1-23.4-0.1-23.4s13.8,30.6,17,39.4c0,0,1.9-17,1.4-19.4s8.5,34.6,4.4,46c0,0,11.7-16.4,11.5-21.4c1.4,0.8-1.3,22.6-4,26.3c0,0,3.2-0.3,8.4-9.3c0,0,11.1-13.4,11.8-11.7c0.7,1.7,1.8-2.9,5.5,10.2l2.6-7.6c0,0-0.4,15.4-3.3,21.4c0,0,14.3-32.5,10.4-58.7c0,0,3.7,9.3,4.4,16.9s3.1-32.8-7.7-51.4c0,0,6.9,3.9,10.8,4.8c0,0-12.6-12.5-13.6-15.9c0,0-14.1-25.7-39.1-34.6c0,0,9.3-3.2,15.6,0.2C286.5,78.8,271.5,66.7,252.4,71.8z'/>", '<path fill="none" stroke="#000000" stroke-width="0.5" stroke-miterlimit="10" d="M286,210c0,0,8.5-10.8,8.6-18.7"/>', '<path fill="none" stroke="#000000" stroke-width="0.5" stroke-linecap="round" stroke-miterlimit="10" d="M132.5,190.4c0,0-1.3-11.3,0.3-16.9"/>', '<path fill="none" stroke="#000000" stroke-width="0.5" stroke-linecap="round" stroke-miterlimit="10" d="M141.5,170c0,0-1-6.5,1.6-20.4"/>', '<path opacity="0.2" d="M267.7,151.7l-0.3,30.9c0,0,1.9-18.8,1.8-19.3s8.6,43.5,3.9,47.2c0,0,11.9-18.8,12.1-21.5s0,22-3.9,25c0,0,6-4.4,8.6-10.1c0,0,6.1-7,9.9-10.7c0,0,3.9-1,6.8,8.2l2.8-6.9c0,0,0.1,13.4-1.3,16.1c0,0,10.5-28.2,7.9-52.9c0,0,4.7,8.3,4.9,17.1c0.1,8.8,1.7-8.6,0.2-17.8c0,0-6.5-13.9-8.2-15.4c0,0,2.2,14.9,1.3,18.4c0,0-8.2-15.1-11.4-17.3c0,0,1.2,41-1.6,46.1c0,0-6.8-22.7-11.4-26.5c0,0,0.7,17.4-3.6,23.2C284.5,183.3,280.8,169.9,267.7,151.7z"/>', '<path opacity="0.2" d="M234.3,137.1c0,0,17.1,23.2,16.7,30.2s-0.2-13.3-0.2-13.3s-11.7-22-17.6-26.2L234.3,137.1z"/>', '<polygon opacity="0.2" points="250.7,143.3 267.5,162.9 267.3,181.9"/>', '<path opacity="0.2" d="M207.4,129.2l9.7,20.7l-1-13.7c0,0,11.6,21,13.5,25.4l1.4-5l-17.6-27.4l1,7.5l-6-12.6L207.4,129.2z"/>', '<path opacity="0.2" d="M209.2,118c0,0-13.7,36.6-18.5,40.9c-1.7-7.2-1.9-7.9-4.2-20.3c0,0-0.1,2.7-1.4,5.3c0.7,8.2,4.1,24.4,4,24.5S206.4,136.6,209.2,118z"/>', '<path opacity="0.2" d="M187.6,134.7c0,0-9.6,25.5-10,26.9l-0.4-3.6C177.1,158.1,186.8,135.8,187.6,134.7z"/>', '<path opacity="0.2" fill-rule="evenodd" clip-rule="evenodd" d="M180.7,129.6c0,0-16.7,22.3-17.7,24.2s0,12.4,0.3,12.8S165.9,153,180.7,129.6z"/>', '<path opacity="0.2" fill-rule="evenodd" clip-rule="evenodd" d="M180.4,130.6c0,0-0.2,20.5-0.6,21.5c-0.4,0.9-2.6,5.8-2.6,5.8S176.1,147.1,180.4,130.6z"/>', abi.encodePacked( '<path opacity="0.2" d="M163.9,138c0,0-16.3,25.3-17.9,26.3c0,0-3.8-12.8-3-14.7s-9.6,10.3-9.9,17c0,0-8.4-0.6-11-7.4c-1-2.5,1.4-9.1,2.1-12.2c0,0-6.5,7.9-9.4,22.5c0,0,0.6,8.8,1.1,10c0,0,3.5-14.8,4.9-17.7c0,0-0.3,33.3,13.6,46.7c0,0-3.7-18.6-2.6-21l9.4-18.6c0,0,2.1,10.5,3.1,12.3l13.9-33.1L163.9,138z"/>', '<path fill="#FFFFFF" d="M204,82.3c0,0-10.3,24.4-11.5,30.4c0,0,11.1-20.6,12.6-20.8c0,0,11.4,20.4,12,22.2C217.2,114.1,208.2,88.2,204,82.3z"/>', '<path fill="#FFFFFF" d="M185.6,83.5c0,0-1,29.2,0,39.2c0,0-4-21.4-3.6-25.5c0.4-4-13.5,19.6-16,23.9c0,0,7.5-20.6,10.5-25.8c0,0-14.4,9.4-22,21.3C154.6,116.7,170.1,93.4,185.6,83.5z"/>', '<path fill="#FFFFFF" d="M158.6,96.2c0,0-12,15.3-14.7,23.2"/>', '<path fill="#FFFFFF" d="M125.8,125.9c0,0,9.5-20.6,23.5-27.7"/>', '<path fill="#FFFFFF" d="M296.5,121.6c0,0-9.5-20.6-23.5-27.7"/>', '<path fill="#FFFFFF" d="M216.1,88.5c0,0,10.9,19.9,11.6,23.6s3.7-5.5-10.6-23.6"/>', '<path fill="#FFFFFF" d="M227,92c0,0,21.1,25.4,22,27.4s-4.9-23.8-12.9-29.5c0,0,9.5,20.7,9.9,21.9C246.3,113,233.1,94.1,227,92z"/>', '<path fill="#FFFFFF" d="M263.1,119.5c0,0-9.5-26.8-10.6-28.3s15.5,14.1,16.2,22.5c0,0-11.1-16.1-11.8-16.9C256.1,96,264.3,114.1,263.1,119.5z"/>' ) ) ); } /// @dev Generate classic 2 hairs with the given color function classicTwoHairs(string memory hairsColor) private pure returns (string memory) { return string( abi.encodePacked( "<polygon fill='#", hairsColor, "' points='188.2,124.6 198.3,128.1 211.2,124.3 197.8,113.2'/>", '<polygon opacity="0.5" points="188.4,124.7 198.3,128.1 211.7,124.2 197.7,113.6"/>', "<path fill='#", hairsColor, "' stroke='#000000' stroke-width='0.5' stroke-miterlimit='10' d='M274,209.6c1,0.9,10.1-12.8,10.5-18.3 c1.1,3.2-0.2,16.8-2.9,20.5c0,0,3.7-0.7,8.3-6.5c0,0,11.1-13.4,11.8-11.7c0.7,1.7,1.8-2.9,5.5,10.2l2.6-7.6 c0,0-0.4,15.4-3.3,21.4c0,0,14.3-32.5,10.4-58.7c0,0,3.7,9.3,4.4,16.9s3.1-32.8-7.7-51.4c0,0,6.9,3.9,10.8,4.8 c0,0-12.6-12.5-13.6-15.9c0,0-14.1-25.7-39.1-34.6c0,0,9.3-3.2,15.6,0.2c-0.1-0.1-15.1-12.2-34.2-7.1c0,0-15.1-13.6-42.6-12.3 l15.6,8.8c0,0-12.9-0.9-28.4-1.3c-6.1-0.2-21.8,3.3-38.3-1.4c0,0,7.3,7.2,9.4,7.7c0,0-30.6,13.8-47.3,34.2 c0,0,10.7-8.9,16.7-10.9c0,0-26,25.2-31.5,70c0,0,9.2-28.6,15.5-34.2c0,0-10.7,27.4-5.3,48.2c0,0,2.4-14.5,4.9-19.2 c-1,14.1,2.4,33.9,13.8,47.8c0,0-3.3-15.8-2.2-21.9l8.8-17.9c0.1,4.1,1.3,8.1,3.1,12.3c0,0,13-36.1,19.7-43.9 c0,0-2.9,15.4-1.1,29.6c0,0,7.2-26.8,17.3-40.1c0,0,0.8,0.1,17.6-7.6c6.3,3.1,8,1.4,17.9,7.7c4.1,5.3,13.8,31.9,15.6,41.5 c3.4-7.3,5.6-19,5.2-29.5c2.7,3.7,8.9,19.9,9.6,34.3c0,0,7.9-15.9,5.9-29c0-0.2,0.2,14.5,0.3,14.3c0,0,12.1,19.9,14.9,19.7 c0-0.8-1.7-12.9-1.7-12.8c1.3,5.8,2.8,23.3,3.1,27.1l5-9.5C276.2,184,276.8,204.9,274,209.6z'/>", '<path fill="none" stroke="#000000" stroke-width="0.5" stroke-miterlimit="10" d="M286.7,210c0,0,8.5-10.8,8.6-18.7"/>', '<path fill="none" stroke="#000000" stroke-width="0.5" stroke-linecap="round" stroke-miterlimit="10" d="M133.2,190.4 c0,0-1.3-11.3,0.3-16.9"/>', abi.encodePacked( '<path fill="none" stroke="#000000" stroke-width="0.5" stroke-linecap="round" stroke-miterlimit="10" d="M142.2,170 c0,0-1-6.5,1.6-20.4"/>', '<path opacity="0.2" fill-rule="evenodd" clip-rule="evenodd" d="M180.6,128.2 c0,0-15.9,23.7-16.9,25.6s0,12.4,0.3,12.8S165.8,151.6,180.6,128.2z"/>', '<path opacity="0.2" d="M164.6,138c0,0-16.3,25.3-17.9,26.3c0,0-3.8-12.8-3-14.7s-9.6,10.3-9.9,17 c0,0-8.4-0.6-11-7.4c-1-2.5,1.4-9.1,2.1-12.2c0,0-6.5,7.9-9.4,22.5c0,0,0.6,8.8,1.1,10c0,0,3.5-14.8,4.9-17.7 c0,0-0.3,33.3,13.6,46.7c0,0-3.7-18.6-2.6-21l9.4-18.6c0,0,2.1,10.5,3.1,12.3l13.9-33.1L164.6,138z"/>', '<path opacity="0.16" d="M253.3,155.9c0.8,4.4,8.1,12.1,13.1,11.7l1.6,11c0,0-5.2-3.9-14.7-19.9 V155.9z"/>', '<path opacity="0.16" d="M237.6,139.4c0,0,4.4,3,13.9,21.7c0,0-4.3,12-4.6,12.4 C246.6,173.9,248.5,162.8,237.6,139.4z"/>', '<path opacity="0.17" d="M221,136.7c0,0,5.2,4,14.4,23c0,0-1.2,4.6-3.1,8.9 C227.7,152.4,227.1,149.9,221,136.7z"/>', '<path opacity="0.2" d="M272.1,152.6c-2.4,8.1-3.6,13.8-4.9,17.9c0,0,1.3,12.8,2.1,22.2 c4.7-8.4,5.4-8.8,5.4-9c-0.1-0.5,3.6,11.2-0.7,25.9c1.6,1,13.3-16.9,11.9-20.6c-1-2.5-0.4,19.8-4.3,22.8c0,0,6.4-2.2,9-7.9 c0,0,6.1-7,9.9-10.7c0,0,3.9-1,6.8,8.2l2.8-6.9c0,0,0.1,13.4-1.3,16.1c0,0,10.5-28.2,7.9-52.9c0,0,4.7,8.3,4.9,17.1 c0.1,8.8,1.7-8.6,0.2-17.8c0,0-6.5-13.9-8.2-15.4c0,0,2.2,14.9,1.3,18.4c0,0-8.2-15.1-11.4-17.3c0,0,1.2,41-1.6,46.1 c0,0-6.8-22.7-11.4-26.5c0,0-1.8,15.7-5,22.9C283.7,183,280.5,166.7,272.1,152.6z"/>' ), abi.encodePacked( '<path opacity="0.14" d="M198.2,115.2c-0.9-3.9,3.2-35.1,34.7-36C227.6,78.5,198.9,99.8,198.2,115.2z"/>', '<g opacity="0.76">', '<path fill="#FFFFFF" d="M153,105.9c0,0-12,15.3-14.7,23.2"/>', '<path fill="#FFFFFF" d="M126.5,125.9c0,0,9.5-20.6,23.5-27.7"/>', '<path fill="#FFFFFF" d="M297.2,121.6c0,0-9.5-20.6-23.5-27.7"/>', '<path fill="#FFFFFF" d="M241.9,109.4c0,0,10.9,19.9,11.6,23.6s3.7-5.5-10.6-23.6"/>', '<path fill="#FFFFFF" d="M155.1,117.3c0,0-10.9,19.9-11.6,23.6s-3.7-5.5,10.6-23.6"/>', '<path fill="#FFFFFF" d="M256.1,101.5c0,0,21.1,25.4,22,27.4c0.9,2-4.9-23.8-12.9-29.5c0,0,9.5,20.7,9.9,21.9 C275.4,122.5,262.2,103.6,256.1,101.5z"/>', '<path fill="#FFFFFF" d="M230,138.5c0,0-12.9-24.9-14.1-26.4c-1.2-1.4,18.2,11.9,19.3,20.2c0,0-11.9-13-12.7-13.7 C221.8,117.9,230.9,133,230,138.5z"/>', '<path fill="#FFFFFF" d="M167,136.6c0,0,15.5-24.5,17-25.8c1.5-1.2-19.1,10.6-21.6,18.8c0,0,15-13.5,15.8-14.2 C179.2,114.8,166.8,130.9,167,136.6z"/>', "</g>" ) ) ); } /// @dev Generate mohawk with the given color function spike(string memory hairsColor) private pure returns (string memory) { return string( abi.encodePacked( "<path fill='#", hairsColor, "' d='M287.3,207.1c0,0-0.4-17.7-3.4-20.6c-3.1-2.9-7.3-8.7-7.3-8.7s0.6-24.8-2.9-31.8c-3.6-7-3.9-24.3-35-23.6c-30.3,0.7-42.5,5.4-42.5,5.4s-14.2-8.2-43-3.8c-19.3,4.9-17.2,50.1-17.2,50.1s-5.6,9.5-6.2,14.8c-0.6,5.3-0.3,8.3-0.3,8.3c0.9-0.2-19.1-126.3,86.7-126.8c108.4-0.3,87.1,121.7,85.1,122.4C294.5,191.6,293.7,198,287.3,207.1z'/>", '<path fill-rule="evenodd" clip-rule="evenodd" fill="#212121" stroke="#000000" stroke-miterlimit="10" d="M196,124.6c0,0-30.3-37.5-20.6-77.7c0,0,0.7,18,12,25.1c0,0-8.6-13.4-0.3-33.4c0,0,2.7,15.8,10.7,23.4c0,0-2.7-18.4,2.2-29.6c0,0,9.7,23.2,13.9,26.3c0,0-6.5-17.2,5.4-27.7c0,0-0.8,18.6,9.8,25.4c0,0-2.7-11,4-18.9c0,0,1.2,25.1,6.6,29.4c0,0-2.7-12,2.1-20c0,0,6,24,8.6,28.5c-9.1-2.6-17.9-3.2-26.6-3C223.7,72.3,198,80.8,196,124.6z"/>', crop() ) ); } function shortHairs(string memory hairsColor) private pure returns (string memory) { return string( abi.encodePacked( "<path fill='#", hairsColor, "' d='M287.3,207.1c0,0-0.4-17.7-3.4-20.6c-3.1-2.9-7.3-8.7-7.3-8.7s0.6-24.8-2.9-31.8c-3.6-7-3.9-24.3-35-23.6c-30.3,0.7-42.5,5.4-42.5,5.4s-14.2-8.2-43-3.8c-19.3,4.9-17.2,50.1-17.2,50.1s-5.6,9.5-6.2,14.8c-0.6,5.3-0.3,8.3-0.3,8.3c0.9-0.2-19.1-126.3,86.7-126.8c108.4-0.3,87.1,121.7,85.1,122.4C294.5,191.6,293.7,198,287.3,207.1z'/>", '<path fill="#212121" stroke="#000000" stroke-miterlimit="10" d="M134.9,129.3c1-8.7,2.8-19.9,2.6-24.1 c1.1,2,4.4,6.1,4.7,6.9c2-15.1,3.9-18.6,6.6-28.2c0.1,5.2,0.4,6.1,4.6,11.9c0.1-7,4.5-17.6,8.8-24.3c0.6,3,4,8.2,5.8,10.7 c2.4-7,8.6-13.4,14.5-17.9c-0.3,3.4-0.1,6.8,0.7,10.1c4.9-5.1,7.1-8.7,15.6-15.4c-0.2,4.5,1.8,9,5.1,12c4.1-3.7,7.7-8,10.6-12.7 c0.6,3.7,1.4,7.3,2.5,10.8c2.6-4.6,7.9-8.4,12.4-11.3c1.5,3.5,1.3,11,5.9,11.7c7.1,1.1,10-3.3,11.4-10.1 c2.2,6.6,4.8,12.5,9.4,17.7c4.2,0.5,5.7-5.6,4.2-9c4.2,5.8,8.4,11.6,12.5,17.4c0.7-2.9,0.9-5.9,0.6-8.8 c3.4,7.6,9.1,16.7,13.6,23.6c0-1.9,1.8-8.5,1.8-10.4c2.6,7.3,7.7,17.9,10.3,36.6c0.2,1.1-23.8,7.5-28.8,10.1 c-1.2-2.3-2.2-4.3-6.2-8c-12.1-5.7-35.6-7.9-54.5-2.2c-16.3,4.8-21.5-2.3-31.3-3.1c-11.8-1.8-31.1-1.7-36.2,10.7 C139.6,133.6,137.9,132.2,134.9,129.3z"/>', '<polygon fill="#212121" points="270.7,138.4 300.2,129 300.7,131.1 271.3,139.9"/>', '<polygon fill="#212121" points="141.1,137 134,131.7 133.8,132.9 140.8,137.7 "/>', crop() ) ); } /// @dev Generate crop SVG function crop() private pure returns (string memory) { return string( abi.encodePacked( '<g id="Light" opacity="0.14">', '<ellipse transform="matrix(0.7071 -0.7071 0.7071 0.7071 0.1603 226.5965)" fill="#FFFFFF" cx="273.6" cy="113.1" rx="1.4" ry="5.3"/>', '<ellipse transform="matrix(0.5535 -0.8328 0.8328 0.5535 32.0969 254.4865)" fill="#FFFFFF" cx="253.4" cy="97.3" rx="4.2" ry="16.3"/>', "</g>", '<path opacity="0.05" fill-rule="evenodd" clip-rule="evenodd" d="M276.4,163.7c0,0,0.2-1.9,0.2,14.1c0,0,6.5,7.5,8.5,11s2.6,17.8,2.6,17.8l7-11.2c0,0,1.8-3.2,6.6-2.6c0,0,5.6-13.1,2.2-42.2C303.5,150.6,294.2,162.1,276.4,163.7z"/>', '<path opacity="0.1" fill-rule="evenodd" clip-rule="evenodd" d="M129.2,194.4c0,0-0.7-8.9,6.8-20.3c0,0-0.2-21.2,1.3-22.9c-3.7,0-6.7-0.5-7.7-2.4C129.6,148.8,125.8,181.5,129.2,194.4z"/>' ) ); } /// @dev Generate monk SVG function monk() private pure returns (string memory) { return string( abi.encodePacked( '<path opacity="0.36" fill="#6E5454" stroke="#8A8A8A" stroke-width="0.5" stroke-miterlimit="10" d="M286.8,206.8c0,0,0.1-17.4-2.9-20.3c-3.1-2.9-7.3-8.7-7.3-8.7s0.6-24.8-2.9-31.8c-3.6-7-3.9-24.3-35-23.6c-30.3,0.7-42.5,5.4-42.5,5.4s-14.2-8.2-43-3.8c-19.3,4.9-17.2,50.1-17.2,50.1s-5.6,9.5-6.2,14.8c-0.6,5.3-0.3,8.3-0.3,8.3S110.3,72.1,216.1,70.4c108.4-1.7,87.1,121.7,85.1,122.4C294.7,190.1,293.2,197.7,286.8,206.8z"/>', '<g id="Bald" opacity="0.33">', '<ellipse transform="matrix(0.7071 -0.7071 0.7071 0.7071 0.1603 226.5965)" fill="#FFFFFF" cx="273.6" cy="113.1" rx="1.4" ry="5.3"/>', '<ellipse transform="matrix(0.5535 -0.8328 0.8328 0.5535 32.0969 254.4865)" fill="#FFFFFF" cx="253.4" cy="97.3" rx="4.2" ry="16.3"/>', "</g>" ) ); } /// @notice Return the hair cut name of the given id /// @param id The hair Id function getItemNameById(uint8 id) public pure returns (string memory name) { name = ""; if (id == 1) { name = "Classic Brown"; } else if (id == 2) { name = "Classic Black"; } else if (id == 3) { name = "Classic Gray"; } else if (id == 4) { name = "Classic White"; } else if (id == 5) { name = "Classic Blue"; } else if (id == 6) { name = "Classic Yellow"; } else if (id == 7) { name = "Classic Pink"; } else if (id == 8) { name = "Classic Red"; } else if (id == 9) { name = "Classic Purple"; } else if (id == 10) { name = "Classic Green"; } else if (id == 11) { name = "Classic Saiki"; } else if (id == 12) { name = "Classic Brown"; } else if (id == 13) { name = "Classic 2 Black"; } else if (id == 14) { name = "Classic 2 Gray"; } else if (id == 15) { name = "Classic 2 White"; } else if (id == 16) { name = "Classic 2 Blue"; } else if (id == 17) { name = "Classic 2 Yellow"; } else if (id == 18) { name = "Classic 2 Pink"; } else if (id == 19) { name = "Classic 2 Red"; } else if (id == 20) { name = "Classic 2 Purple"; } else if (id == 21) { name = "Classic 2 Green"; } else if (id == 22) { name = "Classic 2 Saiki"; } else if (id == 23) { name = "Short Black"; } else if (id == 24) { name = "Short Blue"; } else if (id == 25) { name = "Short Pink"; } else if (id == 26) { name = "Short White"; } else if (id == 27) { name = "Spike Black"; } else if (id == 28) { name = "Spike Blue"; } else if (id == 29) { name = "Spike Pink"; } else if (id == 30) { name = "Spike White"; } else if (id == 31) { name = "Monk"; } else if (id == 32) { name = "Nihon"; } else if (id == 33) { name = "Bald"; } } /// @dev The base SVG for the hair function base(string memory children) private pure returns (string memory) { return string(abi.encodePacked('<g id="Hair">', children, "</g>")); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma abicoder v2; import "base64-sol/base64.sol"; /// @title Mouth SVG generator library MouthDetail { /// @dev Mouth N°1 => Neutral function item_1() public pure returns (string memory) { return base( string( abi.encodePacked( '<path d="M178.3,262.7c3.3-0.2,6.6-0.1,9.9,0c3.3,0.1,6.6,0.3,9.8,0.8c-3.3,0.3-6.6,0.3-9.9,0.2C184.8,263.6,181.5,263.3,178.3,262.7z"/>', '<path d="M201.9,263.4c1.2-0.1,2.3-0.1,3.5-0.2l3.5-0.2l6.9-0.3c2.3-0.1,4.6-0.2,6.9-0.4c1.2-0.1,2.3-0.2,3.5-0.3l1.7-0.2c0.6-0.1,1.1-0.2,1.7-0.2c-2.2,0.8-4.5,1.1-6.8,1.4s-4.6,0.5-7,0.6c-2.3,0.1-4.6,0.2-7,0.1C206.6,263.7,204.3,263.6,201.9,263.4z"/>', '<path d="M195.8,271.8c0.8,0.5,1.8,0.8,2.7,1s1.8,0.4,2.7,0.5s1.8,0,2.8-0.1c0.9-0.1,1.8-0.5,2.8-0.8c-0.7,0.7-1.6,1.3-2.6,1.6c-1,0.3-2,0.5-3,0.4s-2-0.3-2.9-0.8C197.3,273.2,196.4,272.7,195.8,271.8z"/>' ) ) ); } /// @dev Mouth N°2 => Smile function item_2() public pure returns (string memory) { return base( string( abi.encodePacked( '<path d="M178.2,259.6c1.6,0.5,3.3,0.9,4.9,1.3c1.6,0.4,3.3,0.8,4.9,1.1c1.6,0.4,3.3,0.6,4.9,0.9c1.7,0.3,3.3,0.4,5,0.6c-1.7,0.2-3.4,0.3-5.1,0.2c-1.7-0.1-3.4-0.3-5.1-0.7C184.5,262.3,181.2,261.2,178.2,259.6z"/>', '<path d="M201.9,263.4l7-0.6c2.3-0.2,4.7-0.4,7-0.7c2.3-0.2,4.6-0.6,6.9-1c0.6-0.1,1.2-0.2,1.7-0.3l1.7-0.4l1.7-0.5l1.6-0.7c-0.5,0.3-1,0.7-1.5,0.9l-1.6,0.8c-1.1,0.4-2.2,0.8-3.4,1.1c-2.3,0.6-4.6,1-7,1.3s-4.7,0.4-7.1,0.5C206.7,263.6,204.3,263.6,201.9,263.4z"/>', '<path d="M195.8,271.8c0.8,0.5,1.8,0.8,2.7,1s1.8,0.4,2.7,0.5s1.8,0,2.8-0.1c0.9-0.1,1.8-0.5,2.8-0.8c-0.7,0.7-1.6,1.3-2.6,1.6c-1,0.3-2,0.5-3,0.4s-2-0.3-2.9-0.8C197.3,273.2,196.4,272.7,195.8,271.8z"/>' ) ) ); } /// @dev Mouth N°3 => Sulk function item_3() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill="none" stroke="#000000" stroke-miterlimit="10" d="M179.2,263.2c0,0,24.5,3.1,43.3-0.6"/>', '<path fill="none" stroke="#000000" stroke-miterlimit="10" d="M176.7,256.8c0,0,6.7,6.8-0.6,11"/>', '<path fill="none" stroke="#000000" stroke-miterlimit="10" d="M225.6,256.9c0,0-6.5,7,1,11"/>' ) ) ); } /// @dev Mouth N°4 => Poker function item_4() public pure returns (string memory) { return base( string( abi.encodePacked( '<line id="Poker" fill="none" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" x1="180" y1="263" x2="226" y2="263"/>' ) ) ); } /// @dev Mouth N°5 => Angry function item_5() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill="#FFFFFF" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" d="M207.5,257.1c-7,1.4-17.3,0.3-21-0.9c-4-1.2-7.7,3.1-8.6,7.2c-0.5,2.5-1.2,7.4,3.4,10.1c5.9,2.4,5.6,0.1,9.2-1.9c3.4-2,10-1.1,15.3,1.9c5.4,3,13.4,2.2,17.9-0.4c2.9-1.7,3.3-7.6-4.2-14.1C217.3,257.2,215.5,255.5,207.5,257.1"/>', '<path fill="#FFFFFF" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" d="M205.9,265.5l4.1-2.2c0,0,3.7,2.9,5,3s4.9-3.2,4.9-3.2l3.9,1.4"/>', '<polyline fill="#FFFFFF" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" points="177.8,265.3 180.2,263.4 183.3,265.5 186,265.4"/>' ) ) ); } /// @dev Mouth N°6 => Big Smile function item_6() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill="#FFFFFF" stroke="#000000" stroke-miterlimit="10" d="M238.1,255.9c-26.1,4-68.5,0.3-68.5,0.3C170.7,256.3,199.6,296.4,238.1,255.9"/>', '<path fill-rule="evenodd" clip-rule="evenodd" fill="#FFFFFF" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" d="M176.4,262.7c0,0,7.1,2.2,12,2.1"/>', '<path fill-rule="evenodd" clip-rule="evenodd" fill="#FFFFFF" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" d="M230.6,262.8c0,0-10.4,2.1-17.7,1.8"/>' ) ) ); } /// @dev Mouth N°7 => Evil function item_7() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill="#FFFFFF" stroke="#000000" stroke-miterlimit="10" d="M174.7,261.7c0,0,16.1-1.1,17.5-1.5s34.5,6.3,36.5,5.5s4.6-1.9,4.6-1.9s-14.1,8-43.6,7.9c0,0-3.9-0.7-4.7-1.8S177.1,262.1,174.7,261.7z"/>', '<polyline fill="none" stroke="#000000" stroke-miterlimit="10" points="181.6,266.7 185.5,265.3 189.1,266.5 190.3,265.9"/>', '<polyline fill="none" stroke="#000000" stroke-miterlimit="10" points="198.2,267 206.3,266.2 209.6,267.7 213.9,266.3 216.9,267.5 225.3,267"/>' ) ) ); } /// @dev Mouth N°8 => Tongue function item_8() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill="#FF155D" d="M206.5,263.1c0,0,4,11.2,12.5,9.8c11.3-1.8,6.3-11.8,6.3-11.8L206.5,263.1z"/>', '<line fill="none" stroke="#73093E" stroke-miterlimit="10" x1="216.7" y1="262.5" x2="218.5" y2="267.3"/>', '<path fill="none" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" d="M201.9,263.4c0,0,20.7,0.1,27.7-4.3"/>', '<path fill="none" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" d="M178.2,259.6c0,0,9.9,4.2,19.8,3.9"/>' ) ) ); } /// @dev Mouth N°9 => Drool function item_9() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill="#FEBCA6" stroke="#000000" stroke-width="0.5" stroke-miterlimit="10" d="M190.4,257.5c2.5,0.6,5.1,0.8,7.7,0.5l17-2.1c0,0,13.3-1.8,12,3.6c-1.3,5.4-2.4,9.3-5.3,9.8c0,0,3.2,9.7-2.9,9c-3.7-0.4-2.4-7.7-2.4-7.7s-15.4,4.6-33.1-1.7c-1.8-0.6-3.6-2.6-4.4-3.9c-5.1-7.7-2-9.5-2-9.5S175.9,253.8,190.4,257.5z"/>' ) ) ); } /// @dev Mouth N°10 => O function item_10() public pure returns (string memory) { return base( string( abi.encodePacked( '<ellipse transform="matrix(0.9952 -9.745440e-02 9.745440e-02 0.9952 -24.6525 20.6528)" opacity="0.84" fill-rule="evenodd" clip-rule="evenodd" cx="199.1" cy="262.7" rx="3.2" ry="4.6"/>' ) ) ); } /// @dev Mouth N°11 => Dubu function item_11() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill="none" stroke="#000000" stroke-width="0.75" stroke-linecap="round" stroke-miterlimit="10" d="M204.2,262c-8.9-7-25.1-3.5-4.6,6.6c-22-3.8-3.2,11.9,4.8,6"/>' ) ) ); } /// @dev Mouth N°12 => Stitch function item_12() public pure returns (string memory) { return base( string( abi.encodePacked( '<g opacity="0.84" fill-rule="evenodd" clip-rule="evenodd">', '<ellipse transform="matrix(0.9994 -3.403963e-02 3.403963e-02 0.9994 -8.8992 6.2667)" cx="179.6" cy="264.5" rx="2.3" ry="4.3"/>', '<ellipse transform="matrix(0.9996 -2.866329e-02 2.866329e-02 0.9996 -7.485 5.0442)" cx="172.2" cy="263.6" rx="1.5" ry="2.9"/>', '<ellipse transform="matrix(0.9996 -2.866329e-02 2.866329e-02 0.9996 -7.4594 6.6264)" cx="227.4" cy="263.5" rx="1.5" ry="2.9"/>', '<ellipse transform="matrix(0.9994 -3.403963e-02 3.403963e-02 0.9994 -8.8828 7.6318)" cx="219.7" cy="264.7" rx="2.5" ry="4.7"/>', '<ellipse transform="matrix(0.9994 -3.403963e-02 3.403963e-02 0.9994 -8.9179 6.57)" cx="188.5" cy="265.2" rx="2.9" ry="5.4"/>', '<ellipse transform="matrix(0.9994 -3.403963e-02 3.403963e-02 0.9994 -8.9153 7.3225)" cx="210.6" cy="265.5" rx="2.9" ry="5.4"/>', '<ellipse transform="matrix(0.9992 -3.983298e-02 3.983298e-02 0.9992 -10.4094 8.1532)" cx="199.4" cy="265.3" rx="4" ry="7.2"/>', "</g>" ) ) ); } /// @dev Mouth N°13 => Uwu function item_13() public pure returns (string memory) { return base( string( abi.encodePacked( '<polyline fill="#FFFFFF" stroke="#000000" stroke-width="0.5" stroke-miterlimit="10" points="212.7,262.9 216,266.5 217.5,261.7"/>', '<path fill="none" stroke="#000000" stroke-width="0.75" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" d="M176.4,256c0,0,5.7,13.4,23.1,4.2"/>', '<path fill="none" stroke="#000000" stroke-width="0.75" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" d="M224.7,254.8c0,0-9.5,15-25.2,5.4"/>' ) ) ); } /// @dev Mouth N°14 => Monster function item_14() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill="#FFFFFF" stroke="#000000" stroke-width="0.75" stroke-miterlimit="10" d="M161.4,255c0,0,0.5,0.1,1.3,0.3 c4.2,1,39.6,8.5,84.8-0.7C247.6,254.7,198.9,306.9,161.4,255z"/>', '<polyline fill="none" stroke="#000000" stroke-width="0.75" stroke-linejoin="round" stroke-miterlimit="10" points="165.1,258.9 167,256.3 170.3,264.6 175.4,257.7 179.2,271.9 187,259.1 190.8,276.5 197,259.7 202.1,277.5 207.8,259.1 213.8,275.4 217.9,258.7 224.1,271.2 226.5,257.9 232.7,266.2 235.1,256.8 238.6,262.1 241.3,255.8 243.8,257.6"/>' ) ) ); } /// @notice Return the mouth name of the given id /// @param id The mouth Id function getItemNameById(uint8 id) public pure returns (string memory name) { name = ""; if (id == 1) { name = "Neutral"; } else if (id == 2) { name = "Smile"; } else if (id == 3) { name = "Sulk"; } else if (id == 4) { name = "Poker"; } else if (id == 5) { name = "Angry"; } else if (id == 6) { name = "Big Smile"; } else if (id == 7) { name = "Evil"; } else if (id == 8) { name = "Tongue"; } else if (id == 9) { name = "Drool"; } else if (id == 10) { name = "O"; } else if (id == 11) { name = "Dubu"; } else if (id == 12) { name = "Stitch"; } else if (id == 13) { name = "Uwu"; } else if (id == 14) { name = "Monster"; } } /// @dev The base SVG for the mouth function base(string memory children) private pure returns (string memory) { return string(abi.encodePacked('<g id="Mouth">', children, "</g>")); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma abicoder v2; import "base64-sol/base64.sol"; /// @title Nose SVG generator library NoseDetail { /// @dev Nose N°1 => Classic function item_1() public pure returns (string memory) { return ""; } /// @dev Nose N°2 => Bleeding function item_2() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill="#E90000" d="M205.8,254.1C205.8,254.1,205.9,254.1,205.8,254.1c0.1,0,0.1,0.1,0.1,0.1c0,0.2,0,0.5-0.2,0.7c-0.1,0.1-0.3,0.1-0.4,0.1c-0.4,0-0.8,0.1-1.2,0.1c-0.2,0-0.7,0.2-0.8,0s0.1-0.4,0.2-0.5c0.3-0.2,0.7-0.2,1-0.3C204.9,254.3,205.4,254.1,205.8,254.1z"/>', '<path fill="#E90000" d="M204.3,252.8c0.3-0.1,0.6-0.2,0.9-0.1c0.1,0.2,0.1,0.4,0.2,0.6c0,0.1,0,0.1,0,0.2c0,0.1-0.1,0.1-0.2,0.1c-0.7,0.2-1.4,0.3-2.1,0.5c-0.2,0-0.3,0.1-0.4-0.1c0-0.1-0.1-0.2,0-0.3c0.1-0.2,0.4-0.3,0.6-0.4C203.6,253.1,203.9,252.9,204.3,252.8z"/>', '<path fill="#FF0000" d="M204.7,240.2c0.3,1.1,0.1,2.3-0.1,3.5c-0.3,2-0.5,4.1,0,6.1c0.1,0.4,0.3,0.9,0.2,1.4c-0.2,0.9-1.1,1.3-2,1.6c-0.1,0-0.2,0.1-0.4,0.1c-0.3-0.1-0.4-0.5-0.4-0.8c-0.1-1.9,0.5-3.9,0.8-5.8c0.3-1.7,0.3-3.2-0.1-4.8c-0.1-0.5-0.3-0.9,0.1-1.3C203.4,239.7,204.6,239.4,204.7,240.2z"/>' ) ) ); } /// @notice Return the nose name of the given id /// @param id The nose Id function getItemNameById(uint8 id) public pure returns (string memory name) { name = ""; if (id == 1) { name = "Classic"; } else if (id == 2) { name = "Bleeding"; } } /// @dev The base SVG for the Nose function base(string memory children) private pure returns (string memory) { return string(abi.encodePacked('<g id="Nose bonus">', children, "</g>")); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma abicoder v2; import "base64-sol/base64.sol"; import "./constants/Colors.sol"; /// @title Eyes SVG generator library EyesDetail { /// @dev Eyes N°1 => Color White/Brown function item_1() public pure returns (string memory) { return eyesNoFillAndColorPupils(Colors.WHITE, Colors.BROWN); } /// @dev Eyes N°2 => Color White/Gray function item_2() public pure returns (string memory) { return eyesNoFillAndColorPupils(Colors.WHITE, Colors.GRAY); } /// @dev Eyes N°3 => Color White/Blue function item_3() public pure returns (string memory) { return eyesNoFillAndColorPupils(Colors.WHITE, Colors.BLUE); } /// @dev Eyes N°4 => Color White/Green function item_4() public pure returns (string memory) { return eyesNoFillAndColorPupils(Colors.WHITE, Colors.GREEN); } /// @dev Eyes N°5 => Color White/Black function item_5() public pure returns (string memory) { return eyesNoFillAndColorPupils(Colors.WHITE, Colors.BLACK_DEEP); } /// @dev Eyes N°6 => Color White/Yellow function item_6() public pure returns (string memory) { return eyesNoFillAndColorPupils(Colors.WHITE, Colors.YELLOW); } /// @dev Eyes N°7 => Color White/Red function item_7() public pure returns (string memory) { return eyesNoFillAndColorPupils(Colors.WHITE, Colors.RED); } /// @dev Eyes N°8 => Color White/Purple function item_8() public pure returns (string memory) { return eyesNoFillAndColorPupils(Colors.WHITE, Colors.PURPLE); } /// @dev Eyes N°9 => Color White/Pink function item_9() public pure returns (string memory) { return eyesNoFillAndColorPupils(Colors.WHITE, Colors.PINK); } /// @dev Eyes N°10 => Color White/White function item_10() public pure returns (string memory) { return eyesNoFillAndColorPupils(Colors.WHITE, Colors.WHITE); } /// @dev Eyes N°11 => Color Black/Blue function item_11() public pure returns (string memory) { return eyesNoFillAndColorPupils(Colors.BLACK, Colors.BLUE); } /// @dev Eyes N°12 => Color Black/Yellow function item_12() public pure returns (string memory) { return eyesNoFillAndColorPupils(Colors.BLACK, Colors.YELLOW); } /// @dev Eyes N°13 => Color Black/White function item_13() public pure returns (string memory) { return eyesNoFillAndColorPupils(Colors.BLACK, Colors.WHITE); } /// @dev Eyes N°14 => Color Black/Red function item_14() public pure returns (string memory) { return eyesNoFillAndColorPupils(Colors.BLACK, Colors.RED); } /// @dev Eyes N°15 => Blank White/White function item_15() public pure returns (string memory) { return eyesNoFillAndBlankPupils(Colors.WHITE, Colors.WHITE); } /// @dev Eyes N°16 => Blank Black/White function item_16() public pure returns (string memory) { return eyesNoFillAndBlankPupils(Colors.BLACK_DEEP, Colors.WHITE); } /// @dev Eyes N°17 => Shine (no-fill) function item_17() public pure returns (string memory) { return base( string( abi.encodePacked( eyesNoFill(Colors.WHITE), '<path fill="#FFEE00" stroke="#000000" stroke-width="0.5" stroke-miterlimit="10" d="M161.4,195.1c1.4,7.4,1.4,7.3,8.8,8.8 c-7.4,1.4-7.3,1.4-8.8,8.8c-1.4-7.4-1.4-7.3-8.8-8.8C160,202.4,159.9,202.5,161.4,195.1z"/>', '<path fill="#FFEE00" stroke="#000000" stroke-width="0.5" stroke-miterlimit="10" d="M236.1,194.9c1.4,7.4,1.4,7.3,8.8,8.8 c-7.4,1.4-7.3,1.4-8.8,8.8c-1.4-7.4-1.4-7.3-8.8-8.8C234.8,202.3,234.7,202.3,236.1,194.9z"/>' ) ) ); } /// @dev Eyes N°18 => Stun (no-fill) function item_18() public pure returns (string memory) { return base( string( abi.encodePacked( eyesNoFill(Colors.WHITE), '<path d="M233.6,205.2c0.2-0.8,0.6-1.7,1.3-2.3c0.4-0.3,0.9-0.5,1.3-0.4c0.5,0.1,0.9,0.4,1.2,0.8c0.5,0.8,0.6,1.8,0.6,2.7c0,0.9-0.4,1.9-1.1,2.6c-0.7,0.7-1.7,1.1-2.7,1c-1-0.1-1.8-0.7-2.5-1.2c-0.7-0.5-1.4-1.2-1.9-2c-0.5-0.8-0.8-1.8-0.7-2.8c0.1-1,0.5-1.9,1.1-2.6c0.6-0.7,1.4-1.3,2.2-1.7c1.7-0.8,3.6-1,5.3-0.6c0.9,0.2,1.8,0.5,2.5,1.1c0.7,0.6,1.2,1.5,1.3,2.4c0.3,1.8-0.3,3.7-1.4,4.9c1-1.4,1.4-3.2,1-4.8c-0.2-0.8-0.6-1.5-1.3-2c-0.6-0.5-1.4-0.8-2.2-0.9c-1.6-0.2-3.4,0-4.8,0.7c-1.4,0.7-2.7,2-2.8,3.5c-0.2,1.5,0.9,3,2.2,4c0.7,0.5,1.3,1,2.1,1.1c0.7,0.1,1.5-0.2,2.1-0.7c0.6-0.5,0.9-1.3,1-2.1c0.1-0.8,0-1.7-0.4-2.3c-0.2-0.3-0.5-0.6-0.8-0.7c-0.4-0.1-0.8,0-1.1,0.2C234.4,203.6,233.9,204.4,233.6,205.2z"/>', '<path d="M160.2,204.8c0.7-0.4,1.6-0.8,2.5-0.7c0.4,0,0.9,0.3,1.2,0.7c0.3,0.4,0.3,0.9,0.2,1.4c-0.2,0.9-0.8,1.7-1.5,2.3c-0.7,0.6-1.6,1.1-2.6,1c-1,0-2-0.4-2.6-1.2c-0.7-0.8-0.8-1.8-1-2.6c-0.1-0.9-0.1-1.8,0.1-2.8c0.2-0.9,0.7-1.8,1.5-2.4c0.8-0.6,1.7-1,2.7-1c0.9-0.1,1.9,0.1,2.7,0.4c1.7,0.6,3.2,1.8,4.2,3.3c0.5,0.7,0.9,1.6,1,2.6c0.1,0.9-0.2,1.9-0.8,2.6c-1.1,1.5-2.8,2.4-4.5,2.5c1.7-0.3,3.3-1.3,4.1-2.7c0.4-0.7,0.6-1.5,0.5-2.3c-0.1-0.8-0.5-1.5-1-2.2c-1-1.3-2.4-2.4-3.9-2.9c-1.5-0.5-3.3-0.5-4.5,0.5c-1.2,1-1.5,2.7-1.3,4.3c0.1,0.8,0.2,1.6,0.7,2.2c0.4,0.6,1.2,0.9,1.9,1c0.8,0,1.5-0.2,2.2-0.8c0.6-0.5,1.2-1.2,1.4-1.9c0.1-0.4,0.1-0.8-0.1-1.1c-0.2-0.3-0.5-0.6-0.9-0.6C161.9,204.2,161,204.4,160.2,204.8z"/>' ) ) ); } /// @dev Eyes N°19 => Squint (no-fill) function item_19() public pure returns (string memory) { return base( string( abi.encodePacked( eyesNoFill(Colors.WHITE), '<path d="M167.3,203.7c0.1,7.7-12,7.7-11.9,0C155.3,196,167.4,196,167.3,203.7z"/>', '<path d="M244.8,205.6c-1.3,7.8-13.5,5.6-12-2.2C234.2,195.6,246.4,197.9,244.8,205.6z"/>' ) ) ); } /// @dev Eyes N°20 => Shock (no-fill) function item_20() public pure returns (string memory) { return base( string( abi.encodePacked( eyesNoFill(Colors.WHITE), '<path fill-rule="evenodd" clip-rule="evenodd" d="M163.9,204c0,2.7-4.2,2.7-4.1,0C159.7,201.3,163.9,201.3,163.9,204z"/>', '<path fill-rule="evenodd" clip-rule="evenodd" d="M236.7,204c0,2.7-4.2,2.7-4.1,0C232.5,201.3,236.7,201.3,236.7,204z"/>' ) ) ); } /// @dev Eyes N°21 => Cat (no-fill) function item_21() public pure returns (string memory) { return base( string( abi.encodePacked( eyesNoFill(Colors.WHITE), '<path d="M238.4,204.2c0.1,13.1-4.5,13.1-4.5,0C233.8,191.2,238.4,191.2,238.4,204.2z"/>', '<path d="M164.8,204.2c0.1,13-4.5,13-4.5,0C160.2,191.2,164.8,191.2,164.8,204.2z"/>' ) ) ); } /// @dev Eyes N°22 => Ether (no-fill) function item_22() public pure returns (string memory) { return base( string( abi.encodePacked( eyesNoFill(Colors.WHITE), '<path d="M161.7,206.4l-4.6-2.2l4.6,8l4.6-8L161.7,206.4z"/>', '<path d="M165.8,202.6l-4.1-7.1l-4.1,7.1l4.1-1.9L165.8,202.6z"/>', '<path d="M157.9,203.5l3.7,1.8l3.8-1.8l-3.8-1.8L157.9,203.5z"/>', '<path d="M236.1,206.6l-4.6-2.2l4.6,8l4.6-8L236.1,206.6z"/>', '<path d="M240.2,202.8l-4.1-7.1l-4.1,7.1l4.1-1.9L240.2,202.8z"/>', '<path d="M232.4,203.7l3.7,1.8l3.8-1.8l-3.8-1.8L232.4,203.7z"/>' ) ) ); } /// @dev Eyes N°23 => Feels function item_23() public pure returns (string memory) { return base( string( abi.encodePacked( '<path d="M251.1,201.4c0.7,0.6,1,2.2,1,2.7c-0.1-0.4-1.4-1.1-2.2-1.7c-0.2,0.1-0.4,0.4-0.6,0.5c0.5,0.7,0.7,2,0.7,2.5c-0.1-0.4-1.3-1.1-2.1-1.6c-2.7,1.7-6.4,3.2-11.5,3.7c-8.1,0.7-16.3-1.7-20.9-6.4c5.9,3.1,13.4,4.5,20.9,3.8c6.6-0.6,12.7-2.9,17-6.3C253.4,198.9,252.6,200.1,251.1,201.4z"/>', '<path d="M250,205.6L250,205.6C250.1,205.9,250.1,205.8,250,205.6z"/>', '<path d="M252.1,204.2L252.1,204.2C252.2,204.5,252.2,204.4,252.1,204.2z"/>', '<path d="M162.9,207.9c-4.1-0.4-8-1.4-11.2-2.9c-0.7,0.3-3.1,1.4-3.3,1.9c0.1-0.6,0.3-2.2,1.3-2.8c0.1-0.1,0.2-0.1,0.3-0.1c-0.2-0.1-0.5-0.3-0.7-0.4c-0.8,0.4-3,1.3-3.2,1.9c0.1-0.6,0.3-2.2,1.3-2.8c0.1-0.1,0.3-0.1,0.5-0.1c-0.9-0.7-1.7-1.6-2.4-2.4c1.5,1.1,6.9,4.2,17.4,5.3c11.9,1.2,18.3-4,19.8-4.7C177.7,205.3,171.4,208.8,162.9,207.9z"/>', '<path d="M148.5,207L148.5,207C148.5,207.1,148.5,207.2,148.5,207z"/>', '<path d="M146.2,205.6L146.2,205.6C146.2,205.7,146.2,205.7,146.2,205.6z"/>' ) ) ); } /// @dev Eyes N°24 => Happy function item_24() public pure returns (string memory) { return base( string( abi.encodePacked( '<path d="M251.5,203.5c0.7-0.7,0.9-2.5,0.9-3.2c-0.1,0.5-1.3,1.4-2.2,1.9c-0.2-0.2-0.4-0.4-0.6-0.6c0.5-0.8,0.7-2.4,0.7-3 c-0.1,0.5-1.2,1.4-2.1,1.9c-2.6-1.9-6.2-3.8-11-4.3c-7.8-0.8-15.7,2-20.1,7.5c5.7-3.6,12.9-5.3,20.1-4.5 c6.4,0.8,12.4,2.9,16.5,6.9C253.3,205.1,252.3,204,251.5,203.5z"/>', '<path d="M250.3,198.6L250.3,198.6C250.4,198.2,250.4,198.3,250.3,198.6z"/>', '<path d="M252.4,200.3L252.4,200.3C252.5,199.9,252.5,200,252.4,200.3z"/>', '<path d="M228.2,192.6c1.1-0.3,2.3-0.5,3.5-0.6c1.1-0.1,2.4-0.1,3.5,0s2.4,0.3,3.5,0.5s2.3,0.6,3.3,1.1l0,0 c-1.1-0.3-2.3-0.6-3.4-0.8c-1.1-0.3-2.3-0.4-3.4-0.5c-1.1-0.1-2.4-0.2-3.5-0.1C230.5,192.3,229.4,192.4,228.2,192.6L228.2,192.6z"/>', '<path d="M224.5,193.8c-0.9,0.6-2,1.1-3,1.7c-0.9,0.6-2,1.2-3,1.7c0.4-0.4,0.8-0.8,1.2-1.1s0.9-0.7,1.4-0.9c0.5-0.3,1-0.6,1.5-0.8C223.3,194.2,223.9,193.9,224.5,193.8z"/>', '<path d="M161.3,195.8c-3.7,0.4-7.2,1.6-10.1,3.5c-0.6-0.3-2.8-1.6-3-2.3c0.1,0.7,0.3,2.6,1.1,3.3c0.1,0.1,0.2,0.2,0.3,0.2 c-0.2,0.2-0.4,0.3-0.6,0.5c-0.7-0.4-2.7-1.5-2.9-2.2c0.1,0.7,0.3,2.6,1.1,3.3c0.1,0.1,0.3,0.2,0.4,0.2c-0.8,0.8-1.6,1.9-2.2,2.9 c1.3-1.4,6.3-5,15.8-6.3c10.9-1.4,16.7,4.7,18,5.5C174.8,198.9,169.1,194.8,161.3,195.8z"/>', '<path d="M148.2,196.9L148.2,196.9C148.2,196.8,148.2,196.7,148.2,196.9z"/>', '<path d="M146.1,198.6L146.1,198.6C146.1,198.5,146.1,198.4,146.1,198.6z"/>', '<path d="M167.5,192.2c-1.1-0.2-2.3-0.3-3.5-0.3c-1.1,0-2.4,0-3.5,0.2c-1.1,0.1-2.3,0.3-3.4,0.5c-1.1,0.3-2.3,0.5-3.4,0.8 c2.1-0.9,4.3-1.5,6.7-1.7c1.1-0.1,2.4-0.1,3.5-0.1C165.3,191.7,166.4,191.9,167.5,192.2z"/>', '<path d="M171.4,193.4c0.6,0.2,1.1,0.3,1.7,0.6c0.5,0.3,1,0.5,1.6,0.8c0.5,0.3,1,0.6,1.4,0.9c0.5,0.3,0.9,0.7,1.3,1 c-1-0.5-2.1-1.1-3-1.6C173.3,194.5,172.3,193.9,171.4,193.4z"/>' ) ) ); } /// @dev Eyes N°25 => Arrow function item_25() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill="none" stroke="#000000" stroke-width="1.5" stroke-linejoin="round" stroke-miterlimit="10" d="M251.4,192.5l-30.8,8 c10.9,1.9,20.7,5,29.5,9.1"/>', '<path fill="none" stroke="#000000" stroke-width="1.5" stroke-linejoin="round" stroke-miterlimit="10" d="M149.4,192.5l30.8,8 c-10.9,1.9-20.7,5-29.5,9.1"/>' ) ) ); } /// @dev Eyes N°26 => Closed function item_26() public pure returns (string memory) { return base( string( abi.encodePacked( '<line fill="none" stroke="#000000" stroke-width="2" stroke-linecap="round" stroke-miterlimit="10" x1="216.3" y1="200.2" x2="259" y2="198.3"/>', '<line fill="none" stroke="#000000" stroke-width="2" stroke-linecap="round" stroke-miterlimit="10" x1="179.4" y1="200.2" x2="143.4" y2="198.3"/>' ) ) ); } /// @dev Eyes N°27 => Suspicious function item_27() public pure returns (string memory) { return base( string( abi.encodePacked( '<path opacity="0.81" fill="#FFFFFF" d="M220.3,202.5c-0.6,4.6,0.1,5.8,1.6,8.3 c0.9,1.5,1,2.5,8.2-1.2c6.1,0.4,8.2-1.6,16,2.5c3,0,4-3.8,5.1-7.7c0.6-2.2-0.2-4.6-2-5.9c-3.4-2.5-9-6-13.4-5.3 c-3.9,0.7-7.7,1.9-11.3,3.6C222.3,197.9,221,197.3,220.3,202.5z"/>', '<path d="M251.6,200c0.7-0.8,0.9-2.9,0.9-3.7c-0.1,0.6-1.3,1.5-2,2.2c-0.2-0.2-0.4-0.5-0.6-0.7c0.5-1,0.7-2.7,0.7-3.4 c-0.1,0.6-1.2,1.5-1.9,2.1c-2.4-2.2-5.8-4.4-10.4-4.9c-7.4-1-14.7,2.3-18.9,8.6c5.3-4.2,12.1-6,18.9-5.1c6,0.9,11.5,4,15.4,8.5 C253.6,203.4,252.9,201.9,251.6,200z"/>', '<path d="M250.5,194.4L250.5,194.4C250.6,194,250.6,194.1,250.5,194.4z"/>', '<path d="M252.4,196.3L252.4,196.3C252.5,195.9,252.5,196,252.4,196.3z"/>', '<path d="M229.6,187.6c1.1-0.3,2.1-0.6,3.3-0.7c1.1-0.1,2.2-0.1,3.3,0s2.2,0.3,3.3,0.6s2.1,0.7,3.1,1.3l0,0 c-1.1-0.3-2.1-0.7-3.2-0.9c-1.1-0.3-2.1-0.5-3.2-0.6c-1.1-0.1-2.2-0.2-3.3-0.1C231.9,187.2,230.8,187.3,229.6,187.6L229.6,187.6 z"/>', '<path d="M226.1,189c-0.9,0.7-1.8,1.3-2.8,1.9c-0.9,0.7-1.8,1.4-2.8,1.9c0.4-0.5,0.8-0.9,1.2-1.3c0.4-0.4,0.9-0.8,1.4-1.1 s1-0.7,1.5-0.9C225.1,189.4,225.7,189.1,226.1,189z"/>', '<path fill="none" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" d="M222,212.8c0,0,9.8-7.3,26.9,0"/>', '<path fill-rule="evenodd" clip-rule="evenodd" stroke="#000000" stroke-miterlimit="10" d="M229,195.2c0,0-4.6,8.5,0.7,14.4 c0,0,8.8-1.5,11.6,0.4c0,0,4.7-5.7,1.5-12.5S229,195.2,229,195.2z"/>', '<path opacity="0.81" fill="#FFFFFF" d="M177.1,202.5c0.6,4.6-0.1,5.8-1.6,8.3 c-0.9,1.5-1,2.5-8.2-1.2c-6.1,0.4-8.2-1.6-16,2.5c-3,0-4-3.8-5.1-7.7c-0.6-2.2,0.2-4.6,2-5.9c3.4-2.5,9-6,13.4-5.3 c3.9,0.7,7.7,1.9,11.3,3.6C175.2,197.9,176.4,197.3,177.1,202.5z"/>', '<path d="M145.9,200c-0.7-0.8-0.9-2.9-0.9-3.7c0.1,0.6,1.3,1.5,2,2.2c0.2-0.2,0.4-0.5,0.6-0.7c-0.5-1-0.7-2.7-0.7-3.4 c0.1,0.6,1.2,1.5,1.9,2.1c2.4-2.2,5.8-4.4,10.4-4.9c7.4-1,14.7,2.3,18.9,8.6c-5.3-4.2-12.1-6-18.9-5.1c-6,0.9-11.5,4-15.4,8.5 C143.8,203.4,144.5,201.9,145.9,200z"/>', '<path d="M146.9,194.4L146.9,194.4C146.9,194,146.9,194.1,146.9,194.4z"/>', abi.encodePacked( '<path d="M145,196.3L145,196.3C144.9,195.9,144.9,196,145,196.3z"/>', '<path d="M167.8,187.6c-1.1-0.3-2.1-0.6-3.3-0.7c-1.1-0.1-2.2-0.1-3.3,0s-2.2,0.3-3.3,0.6s-2.1,0.7-3.1,1.3l0,0 c1.1-0.3,2.1-0.7,3.2-0.9c1.1-0.3,2.1-0.5,3.2-0.6c1.1-0.1,2.2-0.2,3.3-0.1C165.6,187.2,166.6,187.3,167.8,187.6L167.8,187.6z"/>', '<path d="M171.3,189c0.9,0.7,1.8,1.3,2.8,1.9c0.9,0.7,1.8,1.4,2.8,1.9c-0.4-0.5-0.8-0.9-1.2-1.3c-0.4-0.4-0.9-0.8-1.4-1.1 s-1-0.7-1.5-0.9C172.4,189.4,171.8,189.1,171.3,189z"/>', '<path fill="none" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" d="M175.4,212.8c0,0-9.8-7.3-26.9,0"/>', '<path fill-rule="evenodd" clip-rule="evenodd" stroke="#000000" stroke-miterlimit="10" d="M168.5,195.2c0,0,4.6,8.5-0.7,14.4 c0,0-8.8-1.5-11.6,0.4c0,0-4.7-5.7-1.5-12.5S168.5,195.2,168.5,195.2z"/>' ) ) ) ); } /// @dev Eyes N°28 => Annoyed 1 function item_28() public pure returns (string memory) { return base( string( abi.encodePacked( '<line fill="none" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" x1="218" y1="195.2" x2="256" y2="195.2"/>', '<path stroke="#000000" stroke-miterlimit="10" d="M234,195.5c0,5.1,4.1,9.2,9.2,9.2s9.2-4.1,9.2-9.2"/>', '<line fill="none" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" x1="143.2" y1="195.7" x2="181.1" y2="195.7"/>', '<path stroke="#000000" stroke-miterlimit="10" d="M158.7,196c0,5.1,4.1,9.2,9.2,9.2c5.1,0,9.2-4.1,9.2-9.2"/>' ) ) ); } /// @dev Eyes N°29 => Annoyed 2 function item_29() public pure returns (string memory) { return base( string( abi.encodePacked( '<line fill="none" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" x1="218" y1="195.2" x2="256" y2="195.2"/>', '<path stroke="#000000" stroke-miterlimit="10" d="M228,195.5c0,5.1,4.1,9.2,9.2,9.2s9.2-4.1,9.2-9.2"/>', '<line fill="none" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" x1="143.2" y1="195.7" x2="181.1" y2="195.7"/>', '<path stroke="#000000" stroke-miterlimit="10" d="M152.7,196c0,5.1,4.1,9.2,9.2,9.2c5.1,0,9.2-4.1,9.2-9.2"/>' ) ) ); } /// @dev Eyes N°30 => RIP function item_30() public pure returns (string memory) { return base( string( abi.encodePacked( '<line fill="none" stroke="#000000" stroke-width="3" stroke-linecap="square" stroke-miterlimit="10" x1="225.7" y1="190.8" x2="242.7" y2="207.8"/>', '<line fill="none" stroke="#000000" stroke-width="3" stroke-linecap="square" stroke-miterlimit="10" x1="225.7" y1="207.8" x2="243.1" y2="190.8"/>', '<line fill="none" stroke="#000000" stroke-width="3" stroke-linecap="square" stroke-miterlimit="10" x1="152.8" y1="190.8" x2="169.8" y2="207.8"/>', '<line fill="none" stroke="#000000" stroke-width="3" stroke-linecap="square" stroke-miterlimit="10" x1="152.8" y1="207.8" x2="170.3" y2="190.8"/>' ) ) ); } /// @dev Eyes N°31 => Heart function item_31() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill="#F44336" stroke="#C90005" stroke-miterlimit="10" d="M161.1,218.1c0.2,0.2,0.4,0.3,0.7,0.3s0.5-0.1,0.7-0.3l12.8-14.1 c5.3-5.9,1.5-16-6-16c-4.6,0-6.7,3.6-7.5,4.3c-0.8-0.7-2.9-4.3-7.5-4.3c-7.6,0-11.4,10.1-6,16L161.1,218.1z"/>', '<path fill="#F44336" stroke="#C90005" stroke-miterlimit="10" d="M235.3,218.1c0.2,0.2,0.5,0.3,0.8,0.3s0.6-0.1,0.8-0.3l13.9-14.1 c5.8-5.9,1.7-16-6.6-16c-4.9,0-7.2,3.6-8.1,4.3c-0.9-0.7-3.1-4.3-8.1-4.3c-8.2,0-12.4,10.1-6.6,16L235.3,218.1z"/>' ) ) ); } /// @dev Eyes N°32 => Scribble function item_32() public pure returns (string memory) { return base( string( abi.encodePacked( '<polyline fill="none" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" points="222.5,195.2 252.2,195.2 222.5,199.4 250.5,199.4 223.9,202.8 247.4,202.8"/>', '<polyline fill="none" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" points="148.2,195.2 177.9,195.2 148.2,199.4 176.2,199.4 149.6,202.8 173.1,202.8"/>' ) ) ); } /// @dev Eyes N°33 => Wide function item_33() public pure returns (string memory) { return base( string( abi.encodePacked( '<ellipse fill-rule="evenodd" clip-rule="evenodd" fill="#FFFFFF" cx="236.7" cy="200.1" rx="12.6" ry="14.9"/>', '<path d="M249.4,200.1c0,3.6-1,7.3-3.2,10.3c-1.1,1.5-2.5,2.8-4.1,3.7s-3.5,1.4-5.4,1.4s-3.7-0.6-5.3-1.5s-3-2.2-4.1-3.6c-2.2-2.9-3.4-6.5-3.5-10.2c-0.1-3.6,1-7.4,3.3-10.4c1.1-1.5,2.6-2.7,4.2-3.6c1.6-0.9,3.5-1.4,5.4-1.4s3.8,0.5,5.4,1.4c1.6,0.9,3,2.2,4.1,3.7C248.4,192.9,249.4,196.5,249.4,200.1z M249.3,200.1c0-1.8-0.3-3.6-0.9-5.3c-0.6-1.7-1.5-3.2-2.6-4.6c-2.2-2.7-5.5-4.5-9-4.5s-6.7,1.8-8.9,4.6c-2.2,2.7-3.3,6.2-3.4,9.8c-0.1,3.5,1,7.2,3.2,10s5.6,4.6,9.1,4.5c3.5,0,6.8-1.9,9-4.6C248,207.3,249.3,203.7,249.3,200.1z"/>', '<ellipse fill-rule="evenodd" clip-rule="evenodd" fill="#FFFFFF" cx="163" cy="200.1" rx="12.6" ry="14.9"/>', '<path d="M175.6,200.1c0,3.6-1,7.3-3.2,10.3c-1.1,1.5-2.5,2.8-4.1,3.7s-3.5,1.4-5.4,1.4s-3.7-0.6-5.3-1.5s-3-2.2-4.1-3.6c-2.2-2.9-3.4-6.5-3.5-10.2c-0.1-3.6,1-7.4,3.3-10.4c1.1-1.5,2.6-2.7,4.2-3.6c1.6-0.9,3.5-1.4,5.4-1.4s3.8,0.5,5.4,1.4c1.6,0.9,3,2.2,4.1,3.7C174.6,192.9,175.6,196.5,175.6,200.1z M175.5,200.1c0-1.8-0.3-3.6-0.9-5.3c-0.6-1.7-1.5-3.2-2.6-4.6c-2.2-2.7-5.5-4.5-9-4.5s-6.7,1.8-8.9,4.6c-2.2,2.7-3.3,6.2-3.4,9.8c-0.1,3.5,1,7.2,3.2,10s5.6,4.6,9.1,4.5c3.5,0,6.8-1.9,9-4.6C174.3,207.3,175.5,203.7,175.5,200.1z"/>' ) ) ); } /// @dev Eyes N°34 => Dubu function item_34() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill="none" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" d="M241.6,195.9c-8.7-7.2-25.1-4-4.7,6.6c-21.9-4.3-3.4,11.8,4.7,6.1"/>', '<path fill="none" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" d="M167.6,195.9c-8.7-7.2-25.1-4-4.7,6.6c-21.9-4.3-3.4,11.8,4.7,6.1"/>' ) ) ); } /// @dev Right and left eyes (color pupils + eyes) function eyesNoFillAndColorPupils(string memory scleraColor, string memory pupilsColor) private pure returns (string memory) { return base(string(abi.encodePacked(eyesNoFill(scleraColor), colorPupils(pupilsColor)))); } /// @dev Right and left eyes (blank pupils + eyes) function eyesNoFillAndBlankPupils(string memory scleraColor, string memory pupilsColor) private pure returns (string memory) { return base(string(abi.encodePacked(eyesNoFill(scleraColor), blankPupils(pupilsColor)))); } /// @dev Right and left eyes function eyesNoFill(string memory scleraColor) private pure returns (string memory) { return string(abi.encodePacked(eyeLeftNoFill(scleraColor), eyeRightNoFill(scleraColor))); } /// @dev Eye right and no fill function eyeRightNoFill(string memory scleraColor) private pure returns (string memory) { return string( abi.encodePacked( "<path fill='#", scleraColor, "' d='M220.9,203.6c0.5,3.1,1.7,9.6,7.1,10.1 c7,1.1,21,4.3,23.2-9.3c1.3-7.1-9.8-11.4-15.4-11.2C230.7,194.7,220.5,194.7,220.9,203.6z'/>", '<path d="M250.4,198.6c-0.2-0.2-0.4-0.5-0.6-0.7"/>', '<path d="M248.6,196.6c-7.6-7.9-23.4-6.2-29.3,3.7c10-8.2,26.2-6.7,34.4,3.4c0-0.3-0.7-1.8-2-3.7"/>', '<path d="M229.6,187.6c4.2-1.3,9.1-1,13,1.2C238.4,187.4,234,186.6,229.6,187.6L229.6,187.6z"/>', '<path d="M226.1,189c-1.8,1.3-3.7,2.7-5.6,3.9C221.9,191.1,224,189.6,226.1,189z"/>', '<path d="M224.5,212.4c5.2,2.5,19.7,3.5,24-0.9C244.2,216.8,229.6,215.8,224.5,212.4z"/>' ) ); } /// @dev Eye right and no fill function eyeLeftNoFill(string memory scleraColor) private pure returns (string memory) { return string( abi.encodePacked( "<path fill='#", scleraColor, "' d='M175.7,199.4c2.4,7.1-0.6,13.3-4.1,13.9 c-5,0.8-15.8,1-18.8,0c-5-1.7-6.1-12.4-6.1-12.4C156.6,191.4,165,189.5,175.7,199.4z'/>", '<path d="M147.5,198.7c-0.8,1-1.5,2.1-2,3.3c7.5-8.5,24.7-10.3,31.7-0.9c-5.8-10.3-17.5-13-26.4-5.8"/>', '<path d="M149.4,196.6c-0.2,0.2-0.4,0.4-0.6,0.6"/>', '<path d="M166.2,187.1c-4.3-0.8-8.8,0.1-13,1.4C157,186.4,162,185.8,166.2,187.1z"/>', '<path d="M169.8,188.5c2.2,0.8,4.1,2.2,5.6,3.8C173.5,191.1,171.6,189.7,169.8,188.5z"/>', '<path d="M174.4,211.8c-0.2,0.5-0.8,0.8-1.2,1c-0.5,0.2-1,0.4-1.5,0.6c-1,0.3-2.1,0.5-3.1,0.7c-2.1,0.4-4.2,0.5-6.3,0.7 c-2.1,0.1-4.3,0.1-6.4-0.3c-1.1-0.2-2.1-0.5-3.1-0.9c-0.9-0.5-2-1.1-2.4-2.1c0.6,0.9,1.6,1.4,2.5,1.7c1,0.3,2,0.6,3,0.7 c2.1,0.3,4.2,0.3,6.2,0.2c2.1-0.1,4.2-0.2,6.3-0.5c1-0.1,2.1-0.3,3.1-0.5c0.5-0.1,1-0.2,1.5-0.4c0.2-0.1,0.5-0.2,0.7-0.3 C174.1,212.2,174.3,212.1,174.4,211.8z"/>' ) ); } /// @dev Generate color pupils function colorPupils(string memory pupilsColor) private pure returns (string memory) { return string( abi.encodePacked( "<path fill='#", pupilsColor, "' d='M235,194.9c10.6-0.2,10.6,19,0,18.8C224.4,213.9,224.4,194.7,235,194.9z'/>", '<path d="M235,199.5c3.9-0.1,3.9,9.6,0,9.5C231.1,209.1,231.1,199.4,235,199.5z"/>', '<path fill="#FFFFFF" d="M239.1,200.9c3.4,0,3.4,2.5,0,2.5C235.7,203.4,235.7,200.8,239.1,200.9z"/>', "<path fill='#", pupilsColor, "' d='M161.9,194.6c10.5-0.4,11,18.9,0.4,18.9C151.7,213.9,151.3,194.6,161.9,194.6z'/>", '<path d="M162,199.2c3.9-0.2,4.1,9.5,0.2,9.5C158.2,208.9,158.1,199.2,162,199.2z"/>', '<path fill="#FFFFFF" d="M157.9,200.7c3.4-0.1,3.4,2.5,0,2.5C154.6,203.3,154.5,200.7,157.9,200.7z"/>' ) ); } /// @dev Generate blank pupils function blankPupils(string memory pupilsColor) private pure returns (string memory) { return string( abi.encodePacked( abi.encodePacked( "<path fill='#", pupilsColor, "' stroke='#000000' stroke-width='0.25' stroke-miterlimit='10' d='M169.2,204.2c0.1,11.3-14.1,11.3-13.9,0C155.1,192.9,169.3,192.9,169.2,204.2z'/>", "<path fill='#", pupilsColor, "' stroke='#000000' stroke-width='0.25' stroke-miterlimit='10' d='M243.1,204.3c0.1,11.3-14.1,11.3-13.9,0C229,193,243.2,193,243.1,204.3z'/>" ) ) ); } /// @notice Return the eyes name of the given id /// @param id The eyes Id function getItemNameById(uint8 id) public pure returns (string memory name) { name = ""; if (id == 1) { name = "Color White/Brown"; } else if (id == 2) { name = "Color White/Gray"; } else if (id == 3) { name = "Color White/Blue"; } else if (id == 4) { name = "Color White/Green"; } else if (id == 5) { name = "Color White/Black"; } else if (id == 6) { name = "Color White/Yellow"; } else if (id == 7) { name = "Color White/Red"; } else if (id == 8) { name = "Color White/Purple"; } else if (id == 9) { name = "Color White/Pink"; } else if (id == 10) { name = "Color White/White"; } else if (id == 11) { name = "Color Black/Blue"; } else if (id == 12) { name = "Color Black/Yellow"; } else if (id == 13) { name = "Color Black/White"; } else if (id == 14) { name = "Color Black/Red"; } else if (id == 15) { name = "Blank White/White"; } else if (id == 16) { name = "Blank Black/White"; } else if (id == 17) { name = "Shine"; } else if (id == 18) { name = "Stunt"; } else if (id == 19) { name = "Squint"; } else if (id == 20) { name = "Shock"; } else if (id == 21) { name = "Cat"; } else if (id == 22) { name = "Ether"; } else if (id == 23) { name = "Feels"; } else if (id == 24) { name = "Happy"; } else if (id == 25) { name = "Arrow"; } else if (id == 26) { name = "Closed"; } else if (id == 27) { name = "Suspicious"; } else if (id == 28) { name = "Annoyed 1"; } else if (id == 29) { name = "Annoyed 2"; } else if (id == 30) { name = "RIP"; } else if (id == 31) { name = "Heart"; } else if (id == 32) { name = "Scribble"; } else if (id == 33) { name = "Wide"; } else if (id == 34) { name = "Dubu"; } } /// @dev The base SVG for the eyes function base(string memory children) private pure returns (string memory) { return string(abi.encodePacked('<g id="Eyes">', children, "</g>")); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma abicoder v2; import "base64-sol/base64.sol"; /// @title Eyebrow SVG generator library EyebrowDetail { /// @dev Eyebrow N°1 => Classic function item_1() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill="#150000" d="M213.9,183.1c13.9-5.6,28.6-3,42.7-0.2C244,175,225.8,172.6,213.9,183.1z"/>', '<path fill="#150000" d="M179.8,183.1c-10.7-10.5-27-8.5-38.3-0.5C154.1,179.7,167.6,177.5,179.8,183.1z"/>' ) ) ); } /// @dev Eyebrow N°2 => Thick function item_2() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill-rule="evenodd" clip-rule="evenodd" stroke="#000000" stroke-miterlimit="10" d="M211.3,177.6c0,0,28.6-6.6,36.2-6.2c7.7,0.4,13,3,16.7,6.4c0,0-26.9,5.3-38.9,5.9C213.3,184.3,212.9,183.8,211.3,177.6z"/>', '<path fill-rule="evenodd" clip-rule="evenodd" stroke="#000000" stroke-miterlimit="10" d="M188.2,177.6c0,0-27.9-6.7-35.4-6.3c-7.5,0.4-12.7,2.9-16.2,6.3c0,0,26.3,5.3,38,6C186.2,184.3,186.7,183.7,188.2,177.6z"/>' ) ) ); } /// @dev Eyebrow N°3 => Punk function item_3() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill-rule="evenodd" clip-rule="evenodd" stroke="#000000" stroke-miterlimit="10" d="M258.6,179.1l-2-2.3 c3.1,0.4,5.6,1,7.6,1.7C264.2,178.6,262,178.8,258.6,179.1z M249.7,176.3c-0.7,0-1.5,0-2.3,0c-7.6,0-36.1,3.2-36.1,3.2 c-0.4,2.9-3.8,3.5,8.1,3c6.6-0.3,23.6-2,32.3-2.8L249.7,176.3z"/>', '<path fill-rule="evenodd" clip-rule="evenodd" stroke="#000000" stroke-miterlimit="10" d="M140.2,179.1l1.9-2.3 c-3,0.4-5.4,1-7.3,1.7C134.8,178.6,136.9,178.8,140.2,179.1z M148.8,176.3c0.7,0,1.4,0,2.2,0c7.3,0,34.7,3.2,34.7,3.2 c0.4,2.9,3.6,3.5-7.8,3c-6.3-0.3-22.7-2-31-2.8L148.8,176.3z"/>' ) ) ); } /// @dev Eyebrow N°4 => Small function item_4() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill-rule="evenodd" clip-rule="evenodd" d="M236.3,177c-11.3-5.1-18-3.1-20.3-2.1c-0.1,0-0.2,0.1-0.3,0.2c-0.3,0.1-0.5,0.3-0.6,0.3l0,0l0,0l0,0c-1,0.7-1.7,1.7-1.9,3c-0.5,2.6,1.2,5,3.8,5.5s5-1.2,5.5-3.8c0.1-0.3,0.1-0.6,0.1-1C227.4,175.6,236.3,177,236.3,177z"/>', '<path fill-rule="evenodd" clip-rule="evenodd" d="M160.2,176.3c10.8-4.6,17.1-2.5,19.2-1.3c0.1,0,0.2,0.1,0.3,0.2c0.3,0.1,0.4,0.3,0.5,0.3l0,0l0,0l0,0c0.9,0.7,1.6,1.8,1.8,3.1c0.4,2.6-1.2,5-3.7,5.4s-4.7-1.4-5.1-4c-0.1-0.3-0.1-0.6-0.1-1C168.6,175.2,160.2,176.3,160.2,176.3z"/>' ) ) ); } /// @dev Eyebrow N°5 => Shaved function item_5() public pure returns (string memory) { return base( string( abi.encodePacked( '<g opacity="0.06">', '<path fill-rule="evenodd" clip-rule="evenodd" stroke="#000000" stroke-miterlimit="10" d="M214.5,178 c0,0,20.6-3.5,26.1-3.3s9.4,1.6,12,3.4c0,0-19.4,2.8-28,3.1C215.9,181.6,215.6,181.3,214.5,178z"/>', '<path fill-rule="evenodd" clip-rule="evenodd" stroke="#000000" stroke-miterlimit="10" d="M180.8,178 c0,0-20.1-3.6-25.5-3.4c-5.4,0.2-9.1,1.5-11.7,3.4c0,0,18.9,2.8,27.4,3.2C179.4,181.6,179.8,181.3,180.8,178z"/>', "</g>" ) ) ); } /// @dev Eyebrow N°6 => Elektric function item_6() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill-rule="evenodd" clip-rule="evenodd" d="M208.9,177.6c14.6-1.5,47.8-6.5,51.6-6.6l-14.4,4.1l19.7,3.2 c-20.2-0.4-40.9-0.1-59.2,2.6C206.6,179.9,207.6,178.5,208.9,177.6z"/>', '<path fill-rule="evenodd" clip-rule="evenodd" d="M185.1,177.7c-13.3-1.5-43.3-6.7-46.7-6.9l13.1,4.2l-17.8,3.1 c18.2-0.3,37,0.1,53.6,2.9C187.2,180,186.2,178.6,185.1,177.7z"/>' ) ) ); } /// @notice Return the eyebrow name of the given id /// @param id The eyebrow Id function getItemNameById(uint8 id) public pure returns (string memory name) { name = ""; if (id == 1) { name = "Classic"; } else if (id == 2) { name = "Thick"; } else if (id == 3) { name = "Punk"; } else if (id == 4) { name = "Small"; } else if (id == 5) { name = "Shaved"; } else if (id == 6) { name = "Elektric"; } } /// @dev The base SVG for the Eyebrow function base(string memory children) private pure returns (string memory) { return string(abi.encodePacked('<g id="Eyebrow">', children, "</g>")); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma abicoder v2; import "base64-sol/base64.sol"; /// @title Mark SVG generator library MarkDetail { /// @dev Mark N°1 => Classic function item_1() public pure returns (string memory) { return ""; } /// @dev Mark N°2 => Blush Cheeks function item_2() public pure returns (string memory) { return base( string( abi.encodePacked( '<g opacity="0.71">', '<ellipse fill="#FF7478" cx="257.6" cy="221.2" rx="11.6" ry="3.6"/>', '<ellipse fill="#FF7478" cx="146.9" cy="221.5" rx="9.6" ry="3.6"/>', "</g>" ) ) ); } /// @dev Mark N°3 => Dark Circle function item_3() public pure returns (string memory) { return base( string( abi.encodePacked( '<path d="M160.1,223.2c4.4,0.2,8.7-1.3,12.7-3.2C169.3,222.7,164.4,223.9,160.1,223.2z"/>', '<path d="M156.4,222.4c-2.2-0.4-4.3-1.6-6.1-3C152.3,220.3,154.4,221.4,156.4,222.4z"/>', '<path d="M234.5,222.7c4.9,0.1,9.7-1.4,14.1-3.4C244.7,222.1,239.3,223.4,234.5,222.7z"/>', '<path d="M230.3,221.9c-2.5-0.4-4.8-1.5-6.7-2.9C225.9,219.9,228.2,221,230.3,221.9z"/>' ) ) ); } /// @dev Mark N°4 => Chin scar function item_4() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill="#E83342" d="M195.5,285.7l17,8.9C212.5,294.6,206.1,288.4,195.5,285.7z"/>', '<path fill="#E83342" d="M211.2,285.7l-17,8.9C194.1,294.6,200.6,288.4,211.2,285.7z"/>' ) ) ); } /// @dev Mark N°5 => Blush function item_5() public pure returns (string memory) { return base( string( abi.encodePacked( '<ellipse opacity="0.52" fill-rule="evenodd" clip-rule="evenodd" fill="#FF7F83" cx="196.8" cy="222" rx="32.8" ry="1.9"/>' ) ) ); } /// @dev Mark N°6 => Chin function item_6() public pure returns (string memory) { return base( string( abi.encodePacked( '<path d="M201.3,291.9c0.2-0.6,0.4-1.3,1-1.8c0.3-0.2,0.7-0.4,1.1-0.3c0.4,0.1,0.7,0.4,0.9,0.7c0.4,0.6,0.5,1.4,0.5,2.1 c0,0.7-0.3,1.5-0.8,2c-0.5,0.6-1.3,0.9-2.1,0.8c-0.8-0.1-1.5-0.5-2-0.9c-0.6-0.4-1.1-1-1.5-1.6c-0.4-0.6-0.6-1.4-0.6-2.2 c0.2-1.6,1.4-2.8,2.7-3.4c1.3-0.6,2.8-0.8,4.2-0.5c0.7,0.1,1.4,0.4,2,0.9c0.6,0.5,0.9,1.2,1,1.9c0.2,1.4-0.2,2.9-1.2,3.9 c0.7-1.1,1-2.5,0.7-3.8c-0.2-0.6-0.5-1.2-1-1.5c-0.5-0.4-1.1-0.6-1.7-0.6c-1.3-0.1-2.6,0-3.7,0.6c-1.1,0.5-2,1.5-2.1,2.6 c-0.1,1.1,0.7,2.2,1.6,3c0.5,0.4,1,0.8,1.5,0.8c0.5,0.1,1.1-0.1,1.5-0.5c0.4-0.4,0.7-0.9,0.7-1.6c0.1-0.6,0-1.3-0.3-1.8 c-0.1-0.3-0.4-0.5-0.6-0.6c-0.3-0.1-0.6,0-0.8,0.1C201.9,290.7,201.5,291.3,201.3,291.9z"/>' ) ) ); } /// @dev Mark N°7 => Yinyang function item_7() public pure returns (string memory) { return base( string( abi.encodePacked( '<path opacity="0.86" d="M211.5,161.1c0-8.2-6.7-14.9-14.9-14.9c-0.2,0-0.3,0-0.5,0l0,0 H196c-0.1,0-0.2,0-0.2,0c-0.2,0-0.4,0-0.5,0c-7.5,0.7-13.5,7.1-13.5,14.8c0,8.2,6.7,14.9,14.9,14.9 C204.8,176,211.5,169.3,211.5,161.1z M198.4,154.2c0,1-0.8,1.9-1.9,1.9c-1,0-1.9-0.8-1.9-1.9c0-1,0.8-1.9,1.9-1.9 C197.6,152.3,198.4,153.1,198.4,154.2z M202.9,168.2c0,3.6-3.1,6.6-6.9,6.6l0,0c-7.3-0.3-13.2-6.3-13.2-13.7c0-6,3.9-11.2,9.3-13 c-2,1.3-3.4,3.6-3.4,6.2c0,4,3.3,7.3,7.3,7.3l0,0C199.8,161.6,202.9,164.5,202.9,168.2z M196.6,170.3c-1,0-1.9-0.8-1.9-1.9 c0-1,0.8-1.9,1.9-1.9c1,0,1.9,0.8,1.9,1.9C198.4,169.5,197.6,170.3,196.6,170.3z"/>' ) ) ); } /// @dev Mark N°8 => Scar function item_8() public pure returns (string memory) { return base( string( abi.encodePacked( '<path id="Scar" fill="#FF7478" d="M236.2,148.7c0,0-7.9,48.9-1.2,97.3C235,246,243.8,201.5,236.2,148.7z"/>' ) ) ); } /// @dev Mark N°9 => Sun function item_9() public pure returns (string memory) { return base( string( abi.encodePacked( '<circle fill="#7F0068" cx="195.8" cy="161.5" r="11.5"/>', '<polygon fill="#7F0068" points="195.9,142.4 192.4,147.8 199.3,147.8"/>', '<polygon fill="#7F0068" points="209.6,158.1 209.6,164.9 214.9,161.5"/>', '<polygon fill="#7F0068" points="195.9,180.6 199.3,175.2 192.4,175.2"/>', '<polygon fill="#7F0068" points="182.1,158.1 176.8,161.5 182.1,164.9"/>', '<polygon fill="#7F0068" points="209.3,148 203.1,149.4 208,154.2"/>', '<polygon fill="#7F0068" points="209.3,175 208,168.8 203.1,173.6"/>', '<polygon fill="#7F0068" points="183.7,168.8 182.4,175 188.6,173.6"/>', '<polygon fill="#7F0068" points="188.6,149.4 182.4,148 183.7,154.2"/>' ) ) ); } /// @dev Mark N°10 => Moon function item_10() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill="#7F0068" d="M197.2,142.1c-5.8,0-10.9,2.9-13.9,7.3c2.3-2.3,5.4-3.7,8.9-3.7c7.1,0,12.9,5.9,12.9,13.3 s-5.8,13.3-12.9,13.3c-3.4,0-6.6-1.4-8.9-3.7c3.1,4.4,8.2,7.3,13.9,7.3c9.3,0,16.9-7.6,16.9-16.9S206.6,142.1,197.2,142.1z"/>' ) ) ); } /// @dev Mark N°11 => Third Eye function item_11() public pure returns (string memory) { return base( string( abi.encodePacked( '<path opacity="0.81" fill="#FFFFFF" d="M184.4,159.3c0.7,3.5,0.8,8.5,6.3,8.8 c5.5,1.6,23.2,4.2,23.8-7.6c1.2-6.1-10-9.5-15.5-9.3C193.8,152.6,184.1,153.5,184.4,159.3z"/>', '<path d="M213.6,155.6c-0.2-0.2-0.4-0.4-0.6-0.6"/>', '<path d="M211.8,154c-7.7-6.6-23.5-4.9-29.2,3.6c9.9-7.1,26.1-6.1,34.4,2.4c0-0.3-0.7-1.5-2-3.1"/>', '<path d="M197.3,146.8c4.3-0.6,9.1,0.3,12.7,2.7C206,147.7,201.8,146.5,197.3,146.8L197.3,146.8z M193.6,147.5 c-2,0.9-4.1,1.8-6.1,2.6C189.2,148.8,191.5,147.8,193.6,147.5z"/>', '<path d="M187.6,167.2c5.2,2,18.5,3.2,23.3,0.1C206.3,171.3,192.7,170,187.6,167.2z"/>', '<path fill="#0B1F26" d="M199.6,151c11.1-0.2,11.1,17.4,0,17.3C188.5,168.4,188.5,150.8,199.6,151z"/>' ) ) ); } /// @dev Mark N°12 => Tori function item_12() public pure returns (string memory) { return base( string( abi.encodePacked( '<line fill="none" stroke="#000000" stroke-width="0.5" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" x1="231.2" y1="221.5" x2="231.2" y2="228.4"/>', '<path fill="none" stroke="#000000" stroke-width="0.5" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" d="M228.6,221.2c0,0,3.2,0.4,5.5,0.2"/>', '<path fill-rule="evenodd" clip-rule="evenodd" fill="none" stroke="#000000" stroke-width="0.5" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" d="M237.3,221.5c0,0-3.5,3.1,0,6.3C240.8,231,242.2,221.5,237.3,221.5z"/>', '<path fill-rule="evenodd" clip-rule="evenodd" fill="none" stroke="#000000" stroke-width="0.5" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" d="M243.2,227.8l-1.2-6.4c0,0,8.7-2,1,2.8l3.2,3"/>', '<line fill-rule="evenodd" clip-rule="evenodd" fill="#FFEBB4" stroke="#000000" stroke-width="0.5" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" x1="248.5" y1="221" x2="248.5" y2="227.5"/>', '<path d="M254.2,226c0,0,0.1,0,0.1,0c0,0,0.1,0,0.1-0.1l1.3-2.2c0.5-0.9-0.2-2.2-1.2-2c-0.6,0.1-0.8,0.7-0.9,0.8 c-0.1-0.1-0.5-0.5-1.1-0.4c-1,0.2-1.3,1.7-0.4,2.3L254.2,226z"/>' ) ) ); } /// @dev Mark N°13 => Ether function item_13() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill="#2B2B2B" stroke="#000000" stroke-miterlimit="10" d="M196.5,159.9l-12.4-5.9l12.4,21.6l12.4-21.6L196.5,159.9z"/>', '<path fill="#2B2B2B" stroke="#000000" stroke-miterlimit="10" d="M207.5,149.6l-11-19.1l-11,19.2l11-5.2L207.5,149.6z"/>', '<path fill="#2B2B2B" stroke="#000000" stroke-miterlimit="10" d="M186.5,152.2l10.1,4.8l10.1-4.8l-10.1-4.8L186.5,152.2z"/>' ) ) ); } /// @notice Return the mark name of the given id /// @param id The mark Id function getItemNameById(uint8 id) public pure returns (string memory name) { name = ""; if (id == 1) { name = "Classic"; } else if (id == 2) { name = "Blush Cheeks"; } else if (id == 3) { name = "Dark Circle"; } else if (id == 4) { name = "Chin Scar"; } else if (id == 5) { name = "Blush"; } else if (id == 6) { name = "Chin"; } else if (id == 7) { name = "Yinyang"; } else if (id == 8) { name = "Scar"; } else if (id == 9) { name = "Sun"; } else if (id == 10) { name = "Moon"; } else if (id == 11) { name = "Third Eye"; } else if (id == 12) { name = "Tori"; } else if (id == 13) { name = "Ether"; } } /// @dev The base SVG for the hair function base(string memory children) private pure returns (string memory) { return string(abi.encodePacked('<g id="Mark">', children, "</g>")); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma abicoder v2; import "base64-sol/base64.sol"; import "./constants/Colors.sol"; /// @title Accessory SVG generator library AccessoryDetail { /// @dev Accessory N°1 => Classic function item_1() public pure returns (string memory) { return ""; } /// @dev Accessory N°2 => Glasses function item_2() public pure returns (string memory) { return base(glasses("D1F5FF", "000000", "0.31")); } /// @dev Accessory N°3 => Bow Tie function item_3() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill="none" stroke="#000000" stroke-width="7" stroke-miterlimit="10" d="M176.2,312.5 c3.8,0.3,26.6,7.2,81.4-0.4"/>', '<path fill-rule="evenodd" clip-rule="evenodd" fill="#DF0849" stroke="#000000" stroke-miterlimit="10" d="M211.3,322.1 c-2.5-0.3-5-0.5-7.4,0c-1.1,0-1.9-1.4-1.9-3.1v-4.5c0-1.7,0.9-3.1,1.9-3.1c2.3,0.6,4.8,0.5,7.4,0c1.1,0,1.9,1.4,1.9,3.1v4.5 C213.2,320.6,212.3,322.1,211.3,322.1z"/>', '<path fill="#DF0849" stroke="#000000" stroke-miterlimit="10" d="M202.4,321.5c0,0-14,5.6-17.7,5.3c-1.1-0.1-2.5-4.6-1.2-10.5 c0,0-1-2.2-0.3-9.5c0.4-3.4,19.2,5.1,19.2,5.1S201,316.9,202.4,321.5z"/>', '<path fill="#DF0849" stroke="#000000" stroke-miterlimit="10" d="M212.6,321.5c0,0,14,5.6,17.7,5.3c1.1-0.1,2.5-4.6,1.2-10.5 c0,0,1-2.2,0.3-9.5c-0.4-3.4-19.2,5.1-19.2,5.1S213.9,316.9,212.6,321.5z"/>', '<path opacity="0.41" d="M213.6,315.9l6.4-1.1l-3.6,1.9l4.1,1.1l-7-0.6L213.6,315.9z M201.4,316.2l-6.4-1.1l3.6,1.9l-4.1,1.1l7-0.6L201.4,316.2z"/>' ) ) ); } /// @dev Accessory N°4 => Monk Beads Classic function item_4() public pure returns (string memory) { return base(monkBeads("63205A")); } /// @dev Accessory N°5 => Monk Beads Silver function item_5() public pure returns (string memory) { return base(monkBeads("C7D2D4")); } /// @dev Accessory N°6 => Power Pole function item_6() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill="#FF6F4F" stroke="#000000" stroke-width="0.75" stroke-miterlimit="10" d="M272.3,331.9l55.2-74.4c0,0,3,4.3,8.7,7.5l-54,72.3"/>', '<polygon fill="#BA513A" points="335.9,265.3 334.2,264.1 279.9,336.1 281.8,337.1"/>', '<ellipse transform="matrix(0.6516 -0.7586 0.7586 0.6516 -82.3719 342.7996)" fill="#B54E36" stroke="#000000" stroke-width="0.25" stroke-miterlimit="10" cx="332" cy="261.1" rx="1.2" ry="6.1"/>', '<path fill="none" stroke="#B09E00" stroke-miterlimit="10" d="M276.9,335.3c-52.7,31.1-119.3,49.4-120.7,49"/>' ) ) ); } /// @dev Accessory N°7 => Vintage Glasses function item_7() public pure returns (string memory) { return base(glasses("FC55FF", "DFA500", "0.31")); } /// @dev Accessory N°8 => Monk Beads Gold function item_8() public pure returns (string memory) { return base(monkBeads("FFDD00")); } /// @dev Accessory N°9 => Eye Patch function item_9() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill="#FCFEFF" stroke="#4A6362" stroke-miterlimit="10" d="M253.6,222.7H219c-4.7,0-8.5-3.8-8.5-8.5v-20.8 c0-4.7,3.8-8.5,8.5-8.5h34.6c4.7,0,8.5,3.8,8.5,8.5v20.8C262.1,218.9,258.3,222.7,253.6,222.7z"/>', '<path fill="none" stroke="#4A6362" stroke-width="0.75" stroke-miterlimit="10" d="M250.1,218.9h-27.6c-3.8,0-6.8-3.1-6.8-6.8 v-16.3c0-3.8,3.1-6.8,6.8-6.8h27.6c3.8,0,6.8,3.1,6.8,6.8V212C257,215.8,253.9,218.9,250.1,218.9z"/>', '<line fill="none" stroke="#3C4F4E" stroke-linecap="round" stroke-miterlimit="10" x1="211.9" y1="188.4" x2="131.8" y2="183.1"/>', '<line fill="none" stroke="#3C4F4E" stroke-linecap="round" stroke-miterlimit="10" x1="259.9" y1="188.1" x2="293.4" y2="196.7"/>', '<line fill="none" stroke="#3C4F4E" stroke-linecap="round" stroke-miterlimit="10" x1="259.2" y1="220.6" x2="277.5" y2="251.6"/>', '<line fill="none" stroke="#3C4F4E" stroke-linecap="round" stroke-miterlimit="10" x1="211.4" y1="219.1" x2="140.5" y2="242"/>', '<g fill-rule="evenodd" clip-rule="evenodd" fill="#636363" stroke="#4A6362" stroke-width="0.25" stroke-miterlimit="10"><ellipse cx="250.9" cy="215" rx="0.8" ry="1.1"/><ellipse cx="236.9" cy="215" rx="0.8" ry="1.1"/><ellipse cx="250.9" cy="203.9" rx="0.8" ry="1.1"/><ellipse cx="250.9" cy="193.8" rx="0.8" ry="1.1"/><ellipse cx="236.9" cy="193.8" rx="0.8" ry="1.1"/><ellipse cx="221.3" cy="215" rx="0.8" ry="1.1"/><ellipse cx="221.3" cy="203.9" rx="0.8" ry="1.1"/><ellipse cx="221.3" cy="193.8" rx="0.8" ry="1.1"/></g>' ) ) ); } /// @dev Accessory N°10 => Sun Glasses function item_10() public pure returns (string memory) { return base(glasses(Colors.BLACK, Colors.BLACK_DEEP, "1")); } /// @dev Accessory N°11 => Monk Beads Diamond function item_11() public pure returns (string memory) { return base(monkBeads("AAFFFD")); } /// @dev Accessory N°12 => Horns function item_12() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill-rule="evenodd" clip-rule="evenodd" fill="#212121" stroke="#000000" stroke-linejoin="round" stroke-miterlimit="10" d="M257.7,96.3c0,0,35-18.3,46.3-42.9c0,0-0.9,37.6-23.2,67.6C269.8,115.6,261.8,107.3,257.7,96.3z"/>', '<path fill-rule="evenodd" clip-rule="evenodd" fill="#212121" stroke="#000000" stroke-linejoin="round" stroke-miterlimit="10" d="M162,96.7c0,0-33-17.3-43.7-40.5c0,0,0.9,35.5,21.8,63.8C150.6,114.9,158.1,107.1,162,96.7z"/>' ) ) ); } /// @dev Accessory N°13 => Halo function item_13() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill="#F6FF99" stroke="#000000" stroke-miterlimit="10" d="M136,67.3c0,14.6,34.5,26.4,77,26.4s77-11.8,77-26.4s-34.5-26.4-77-26.4S136,52.7,136,67.3L136,67.3z M213,79.7c-31.4,0-56.9-6.4-56.9-14.2s25.5-14.2,56.9-14.2s56.9,6.4,56.9,14.2S244.4,79.7,213,79.7z"/>' ) ) ); } /// @dev Accessory N°14 => Saiki Power function item_14() public pure returns (string memory) { return base( string( abi.encodePacked( '<line fill="none" stroke="#000000" stroke-width="5" stroke-miterlimit="10" x1="270.5" y1="105.7" x2="281.7" y2="91.7"/>', '<circle fill="#EB7FFF" stroke="#000000" stroke-miterlimit="10" cx="285.7" cy="85.2" r="9.2"/>', '<line fill="none" stroke="#000000" stroke-width="5" stroke-miterlimit="10" x1="155.8" y1="105.7" x2="144.5" y2="91.7"/>', '<circle fill="#EB7FFF" stroke="#000000" stroke-miterlimit="10" cx="138.7" cy="85.2" r="9.2"/>', '<path opacity="0.17" d="M287.3,76.6c0,0,10.2,8.2,0,17.1c0,0,7.8-0.7,7.4-9.5 C293,75.9,287.3,76.6,287.3,76.6z"/>', '<path opacity="0.17" d="M137,76.4c0,0-10.2,8.2,0,17.1c0,0-7.8-0.7-7.4-9.5 C131.4,75.8,137,76.4,137,76.4z"/>', '<ellipse transform="matrix(0.4588 -0.8885 0.8885 0.4588 80.0823 294.4391)" fill="#FFFFFF" cx="281.8" cy="81.5" rx="2.1" ry="1.5"/>', '<ellipse transform="matrix(0.8885 -0.4588 0.4588 0.8885 -21.756 74.6221)" fill="#FFFFFF" cx="142.7" cy="82.1" rx="1.5" ry="2.1"/>', '<path fill="none" stroke="#000000" stroke-miterlimit="10" d="M159.6,101.4c0,0-1.1,4.4-7.4,7.2"/>', '<path fill="none" stroke="#000000" stroke-miterlimit="10" d="M267.2,101.4c0,0,1.1,4.4,7.4,7.2"/>', abi.encodePacked( '<polygon opacity="0.68" fill="#7FFF35" points="126,189.5 185.7,191.8 188.6,199.6 184.6,207.4 157.3,217.9 128.6,203.7"/>', '<polygon opacity="0.68" fill="#7FFF35" points="265.7,189.5 206.7,191.8 203.8,199.6 207.7,207.4 234.8,217.9 263.2,203.7"/>', '<polyline fill="#FFFFFF" stroke="#424242" stroke-width="0.5" stroke-miterlimit="10" points="196.5,195.7 191.8,195.4 187,190.9 184.8,192.3 188.5,198.9 183,206.8 187.6,208.3 193.1,201.2 196.5,201.2"/>', '<polyline fill="#FFFFFF" stroke="#424242" stroke-width="0.5" stroke-miterlimit="10" points="196.4,195.7 201.1,195.4 205.9,190.9 208.1,192.3 204.4,198.9 209.9,206.8 205.3,208.3 199.8,201.2 196.4,201.2"/>', '<polygon fill="#FFFFFF" stroke="#424242" stroke-width="0.5" stroke-miterlimit="10" points="123.8,189.5 126.3,203 129.2,204.4 127.5,189.5"/>', '<polygon fill="#FFFFFF" stroke="#424242" stroke-width="0.5" stroke-miterlimit="10" points="265.8,189.4 263.3,203.7 284.3,200.6 285.3,189.4"/>' ) ) ) ); } /// @dev Accessory N°15 => No Face function item_15() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill="#F5F4F3" stroke="#000000" stroke-miterlimit="10" d="M285.5,177.9c0,68.3-19.6,127.3-77.9,128.2 c-58.4,0.9-74.4-57.1-74.4-125.4s14.4-103.5,72.7-103.5C266.7,77.2,285.5,109.6,285.5,177.9z"/>', '<path opacity="0.08" d="M285.4,176.9c0,68.3-19.4,127.6-78,129.3 c27.2-17.6,28.3-49.1,28.3-117.3s23.8-86-30-111.6C266.4,77.3,285.4,108.7,285.4,176.9z"/>', '<ellipse cx="243.2" cy="180.7" rx="16.9" ry="6.1"/>', '<path d="M231.4,273.6c0.3-7.2-12.1-6.1-27.2-6.1s-27.4-1.4-27.2,6.1c0.1,3.4,12.1,6.1,27.2,6.1S231.3,277,231.4,273.6z"/>', '<ellipse cx="162" cy="180.5" rx="16.3" ry="6"/>', '<path fill="#F2EDED" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" d="M149.7,191.4c0,0,6.7,5.8,20.5,0.6"/>', '<path fill="#F2EDED" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" d="M232.9,191.3c0,0,6.6,5.7,20.4,0.6"/>', '<path fill="#F2EDED" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" d="M192.7,285.1c0,0,9.2,3.5,21.6,0"/>', '<path fill="#996DAD" d="M150.8,200.5c1.5-3.6,17.2-3.4,18.8-0.4c1.8,3.2-4.8,45.7-6.6,46C159.8,246.8,148.1,211.1,150.8,200.5z"/>', '<path fill="#996DAD" d="M233.9,199.8c1.5-3.6,18-2.7,19.7,0.3c3.7,6.4-6.5,45.5-9.3,45.4C241,245.2,231.1,210.4,233.9,199.8z"/>', '<path fill="#996DAD" d="M231.3,160.6c1.3,2.3,14.7,2.1,16.1,0.2c1.6-2-4.1-27.7-7.2-28.2C236.9,132.2,229,154.1,231.3,160.6z"/>', '<path fill="#996DAD" d="M152.9,163.2c1.3,2.3,14.7,2.1,16.1,0.2c1.6-2-4.1-27.7-7.2-28.2C158.6,134.8,150.6,156.6,152.9,163.2z"/>' ) ) ); } /// @dev Generate glasses with the given color and opacity function glasses( string memory color, string memory stroke, string memory opacity ) private pure returns (string memory) { return string( abi.encodePacked( '<circle fill="none" stroke="#', stroke, '" stroke-miterlimit="10" cx="161.5" cy="201.7" r="23.9"/>', '<circle fill="none" stroke="#', stroke, '" stroke-miterlimit="10" cx="232.9" cy="201.7" r="23.9"/>', '<circle opacity="', opacity, '" fill="#', color, '" cx="161.5" cy="201.7" r="23.9"/>', abi.encodePacked( '<circle opacity="', opacity, '" fill="#', color, '" cx="232.9" cy="201.7" r="23.9"/>', '<path fill="none" stroke="#', stroke, '" stroke-miterlimit="10" d="M256.8,201.7l35.8-3.2 M185.5,201.7 c0,0,14.7-3.1,23.5,0 M137.6,201.7l-8.4-3.2"/>' ) ) ); } /// @dev Generate Monk Beads SVG with the given color function monkBeads(string memory color) private pure returns (string memory) { return string( abi.encodePacked( '<g fill="#', color, '" stroke="#2B232B" stroke-miterlimit="10" stroke-width="0.75">', '<ellipse transform="matrix(0.9999 -1.689662e-02 1.689662e-02 0.9999 -5.3439 3.0256)" cx="176.4" cy="317.8" rx="7.9" ry="8"/>', '<ellipse transform="matrix(0.9999 -1.689662e-02 1.689662e-02 0.9999 -5.458 3.2596)" cx="190.2" cy="324.6" rx="7.9" ry="8"/>', '<ellipse transform="matrix(0.9999 -1.689662e-02 1.689662e-02 0.9999 -5.5085 3.5351)" cx="206.4" cy="327.8" rx="7.9" ry="8"/>', '<ellipse transform="matrix(0.9999 -1.689662e-02 1.689662e-02 0.9999 -5.4607 4.0856)" cx="239.1" cy="325.2" rx="7.9" ry="8"/>', '<ellipse transform="matrix(0.9999 -1.693338e-02 1.693338e-02 0.9999 -5.386 4.3606)" cx="254.8" cy="320.2" rx="7.9" ry="8"/>', '<ellipse transform="matrix(0.9999 -1.689662e-02 1.689662e-02 0.9999 -5.5015 3.8124)" cx="222.9" cy="327.5" rx="7.9" ry="8"/>', "</g>", '<path opacity="0.14" d="M182,318.4 c0.7,1.3-0.4,3.4-2.5,4.6c-2.1,1.2-4.5,1-5.2-0.3c-0.7-1.3,0.4-3.4,2.5-4.6C178.9,316.9,181.3,317,182,318.4z M190.5,325.7 c-2.1,1.2-3.2,3.2-2.5,4.6c0.7,1.3,3.1,1.5,5.2,0.3s3.2-3.2,2.5-4.6C195,324.6,192.7,324.5,190.5,325.7z M206.7,328.6 c-2.1,1.2-3.2,3.2-2.5,4.6c0.7,1.3,3.1,1.5,5.2,0.3c2.1-1.2,3.2-3.2,2.5-4.6C211.1,327.6,208.8,327.5,206.7,328.6z M223.2,328.4 c-2.1,1.2-3.2,3.2-2.5,4.6c0.7,1.3,3.1,1.5,5.2,0.3c2.1-1.2,3.2-3.2,2.5-4.6S225.3,327.3,223.2,328.4z M239.8,325.7 c-2.1,1.2-3.2,3.2-2.5,4.6c0.7,1.3,3.1,1.5,5.2,0.3c2.1-1.2,3.2-3.2,2.5-4.6C244.3,324.7,242,324.5,239.8,325.7z M255.7,320.9 c-2.1,1.2-3.2,3.2-2.5,4.6c0.7,1.3,3.1,1.5,5.2,0.3c2.1-1.2,3.2-3.2,2.5-4.6C260.1,319.9,257.8,319.7,255.7,320.9z"/>', abi.encodePacked( '<g fill="#FFFFFF" stroke="#FFFFFF" stroke-miterlimit="10">', '<path d="M250.4,318.9c0.6,0.6,0.5-0.9,1.3-2c0.8-1,2.4-1.2,1.8-1.8 c-0.6-0.6-1.9-0.2-2.8,0.9C250,317,249.8,318.3,250.4,318.9z"/>', '<path d="M234.4,323.6c0.7,0.6,0.5-0.9,1.4-1.9c1-1,2.5-1.1,1.9-1.7 c-0.7-0.6-1.9-0.3-2.8,0.7C234.1,321.7,233.8,323,234.4,323.6z"/>', '<path d="M218.2,325.8c0.6,0.6,0.6-0.9,1.4-1.8c1-1,2.5-1,1.9-1.6 c-0.6-0.6-1.9-0.4-2.8,0.6C217.8,323.9,217.6,325.2,218.2,325.8z"/>', '<path d="M202.1,325.5c0.6,0.6,0.6-0.9,1.7-1.7s2.6-0.8,2-1.5 c-0.6-0.6-1.8-0.5-2.9,0.4C202,323.5,201.5,324.8,202.1,325.5z"/>', '<path d="M186.2,322c0.6,0.6,0.6-0.9,1.7-1.7c1-0.8,2.6-0.8,2-1.5 c-0.6-0.6-1.8-0.5-2.9,0.3C186,320.1,185.7,321.4,186.2,322z"/>', '<path d="M171.7,315.4c0.6,0.6,0.6-0.9,1.5-1.8s2.5-0.9,1.9-1.6 s-1.9-0.4-2.8,0.5C171.5,313.5,171.1,314.9,171.7,315.4z"/>', "</g>" ) ) ); } /// @notice Return the accessory name of the given id /// @param id The accessory Id function getItemNameById(uint8 id) public pure returns (string memory name) { name = ""; if (id == 1) { name = "Classic"; } else if (id == 2) { name = "Glasses"; } else if (id == 3) { name = "Bow Tie"; } else if (id == 4) { name = "Monk Beads Classic"; } else if (id == 5) { name = "Monk Beads Silver"; } else if (id == 6) { name = "Power Pole"; } else if (id == 7) { name = "Vintage Glasses"; } else if (id == 8) { name = "Monk Beads Gold"; } else if (id == 9) { name = "Eye Patch"; } else if (id == 10) { name = "Sun Glasses"; } else if (id == 11) { name = "Monk Beads Diamond"; } else if (id == 12) { name = "Horns"; } else if (id == 13) { name = "Halo"; } else if (id == 14) { name = "Saiki Power"; } else if (id == 15) { name = "No Face"; } } /// @dev The base SVG for the accessory function base(string memory children) private pure returns (string memory) { return string(abi.encodePacked('<g id="Accessory">', children, "</g>")); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma abicoder v2; import "base64-sol/base64.sol"; /// @title Earrings SVG generator library EarringsDetail { /// @dev Earrings N°1 => Classic function item_1() public pure returns (string memory) { return ""; } /// @dev Earrings N°2 => Circle function item_2() public pure returns (string memory) { return base(circle("000000")); } /// @dev Earrings N°3 => Circle Silver function item_3() public pure returns (string memory) { return base(circle("C7D2D4")); } /// @dev Earrings N°4 => Ring function item_4() public pure returns (string memory) { return base(ring("000000")); } /// @dev Earrings N°5 => Circle Gold function item_5() public pure returns (string memory) { return base(circle("FFDD00")); } /// @dev Earrings N°6 => Ring Gold function item_6() public pure returns (string memory) { return base(ring("FFDD00")); } /// @dev Earrings N°7 => Heart function item_7() public pure returns (string memory) { return base( string( abi.encodePacked( '<path d="M284.3,247.9c0.1,0.1,0.1,0.1,0.2,0.1s0.2,0,0.2-0.1l3.7-3.8c1.5-1.6,0.4-4.3-1.8-4.3c-1.3,0-1.9,1-2.2,1.2c-0.2-0.2-0.8-1.2-2.2-1.2c-2.2,0-3.3,2.7-1.8,4.3L284.3,247.9z"/>', '<path d="M135,246.6c0,0,0.1,0.1,0.2,0.1s0.1,0,0.2-0.1l3.1-3.1c1.3-1.3,0.4-3.6-1.5-3.6c-1.1,0-1.6,0.8-1.8,1c-0.2-0.2-0.7-1-1.8-1c-1.8,0-2.8,2.3-1.5,3.6L135,246.6z"/>' ) ) ); } /// @dev Earrings N°8 => Gold function item_8() public pure returns (string memory) { return base( string( abi.encodePacked( '<path d="M298.7,228.1l-4.7-1.6c0,0-0.1,0-0.1-0.1v-0.1c2.8-2.7,7.1-17.2,7.2-17.4c0-0.1,0.1-0.1,0.1-0.1l0,0c5.3,1.1,5.6,2.2,5.7,2.4c-3.1,5.4-8,16.7-8.1,16.8C298.9,228,298.8,228.1,298.7,228.1C298.8,228.1,298.8,228.1,298.7,228.1z" style="fill: #fff700;stroke: #000;stroke-miterlimit: 10;stroke-width: 0.75px"/>' ) ) ); } /// @dev Earrings N°9 => Circle Diamond function item_9() public pure returns (string memory) { return base(circle("AAFFFD")); } /// @dev Earrings N°10 => Drop Heart function item_10() public pure returns (string memory) { return base( string( abi.encodePacked( drop(true), '<path fill="#F44336" d="M285.4,282.6c0.1,0.1,0.2,0.2,0.4,0.2s0.3-0.1,0.4-0.2l6.7-6.8c2.8-2.8,0.8-7.7-3.2-7.7c-2.4,0-3.5,1.8-3.9,2.1c-0.4-0.3-1.5-2.1-3.9-2.1c-4,0-6,4.9-3.2,7.7L285.4,282.6z"/>', drop(false), '<path fill="#F44336" d="M134.7,282.5c0.1,0.1,0.2,0.2,0.4,0.2s0.3-0.1,0.4-0.2l6.7-6.8c2.8-2.8,0.8-7.7-3.2-7.7c-2.4,0-3.5,1.8-3.9,2.1c-0.4-0.3-1.5-2.1-3.9-2.1c-4,0-6,4.9-3.2,7.7L134.7,282.5z"/>' ) ) ); } /// @dev Earrings N11 => Ether function item_11() public pure returns (string memory) { return base( string( abi.encodePacked( '<path d="M285.7,242.7l-4.6-2.2l4.6,8l4.6-8L285.7,242.7z"/>', '<path d="M289.8,238.9l-4.1-7.1l-4.1,7.1l4.1-1.9L289.8,238.9z"/>', '<path d="M282,239.9l3.7,1.8l3.8-1.8l-3.8-1.8L282,239.9z"/>', '<path d="M134.5,241.8l-3.4-1.9l3.7,7.3l2.8-7.7L134.5,241.8z"/>', '<path d="M137.3,238l-3.3-6.5l-2.5,6.9l2.8-2L137.3,238z"/>', '<path d="M131.7,239.2l2.8,1.5l2.6-1.8l-2.8-1.5L131.7,239.2z"/>' ) ) ); } /// @dev Earrings N°12 => Drop Ether function item_12() public pure returns (string memory) { return base( string( abi.encodePacked( drop(true), '<path d="M285.7,279.7l-4.6-2.2l4.6,8l4.6-8L285.7,279.7z"/>', '<path d="M289.8,275.9l-4.1-7.1l-4.1,7.1l4.1-1.9L289.8,275.9z"/>', '<path d="M282,276.9l3.7,1.8l3.8-1.8l-3.8-1.8L282,276.9z"/><path d="M282,276.9l3.7,1.8l3.8-1.8l-3.8-1.8L282,276.9z"/>', drop(false), '<path d="M135.1,279.7l-4-2.2l4,8l4-8L135.1,279.7z"/>', '<path d="M138.7,275.9l-3.6-7.1l-3.6,7.1l3.6-1.9L138.7,275.9z"/>', '<path d="M131.8,276.9l3.3,1.8l3.3-1.8l-3.3-1.8L131.8,276.9z"/>' ) ) ); } /// @dev earring drop function drop(bool right) private pure returns (string memory) { return string( right ? abi.encodePacked( '<circle cx="285.7" cy="243.2" r="3.4"/>', '<line fill="none" stroke="#000000" stroke-miterlimit="10" x1="285.7" y1="243.2" x2="285.7" y2="270.2"/>' ) : abi.encodePacked( '<ellipse cx="135.1" cy="243.2" rx="3" ry="3.4"/>', '<line fill="none" stroke="#000000" stroke-miterlimit="10" x1="135.1" y1="243.2" x2="135.1" y2="270.2"/>' ) ); } /// @dev Generate circle SVG with the given color function circle(string memory color) private pure returns (string memory) { return string( abi.encodePacked( '<ellipse fill="#', color, '" stroke="#000000" cx="135.1" cy="243.2" rx="3" ry="3.4"/>', '<ellipse fill="#', color, '" stroke="#000000" cx="286.1" cy="243.2" rx="3.3" ry="3.4"/>' ) ); } /// @dev Generate ring SVG with the given color function ring(string memory color) private pure returns (string memory) { return string( abi.encodePacked( '<path fill="none" stroke="#', color, '" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" d="M283.5,246c0,0-4.2,2-3.1,6.1c1,4.1,5.1,3.6,5.4,3.5s3.1-0.9,3-5"/>', '<path fill="none" stroke="#', color, '" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" d="M134.3,244.7c0,0-4.2,2-3.1,6.1c1,4.1,5.1,3.6,5.4,3.5c0.3-0.1,3.1-0.9,3-5"/>' ) ); } /// @notice Return the earring name of the given id /// @param id The earring Id function getItemNameById(uint8 id) public pure returns (string memory name) { name = ""; if (id == 1) { name = "Classic"; } else if (id == 2) { name = "Circle"; } else if (id == 3) { name = "Circle Silver"; } else if (id == 4) { name = "Ring"; } else if (id == 5) { name = "Circle Gold"; } else if (id == 6) { name = "Ring Gold"; } else if (id == 7) { name = "Heart"; } else if (id == 8) { name = "Gold"; } else if (id == 9) { name = "Circle Diamond"; } else if (id == 10) { name = "Drop Heart"; } else if (id == 11) { name = "Ether"; } else if (id == 12) { name = "Drop Ether"; } } /// @dev The base SVG for the earrings function base(string memory children) private pure returns (string memory) { return string(abi.encodePacked('<g id="Earrings">', children, "</g>")); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma abicoder v2; import "base64-sol/base64.sol"; import "./constants/Colors.sol"; /// @title Masks SVG generator library MaskDetail { /// @dev Mask N°1 => Maskless function item_1() public pure returns (string memory) { return ""; } /// @dev Mask N°2 => Classic function item_2() public pure returns (string memory) { return base(classicMask("575673")); } /// @dev Mask N°3 => Blue function item_3() public pure returns (string memory) { return base(classicMask(Colors.BLUE)); } /// @dev Mask N°4 => Pink function item_4() public pure returns (string memory) { return base(classicMask(Colors.PINK)); } /// @dev Mask N°5 => Black function item_5() public pure returns (string memory) { return base(classicMask(Colors.BLACK)); } /// @dev Mask N°6 => Bandage White function item_6() public pure returns (string memory) { return base(string(abi.encodePacked(classicMask("F5F5F5"), bandage()))); } /// @dev Mask N°7 => Bandage Classic function item_7() public pure returns (string memory) { return base(string(abi.encodePacked(classicMask("575673"), bandage()))); } /// @dev Mask N°8 => Nihon function item_8() public pure returns (string memory) { return base( string( abi.encodePacked( classicMask("F5F5F5"), '<ellipse opacity="0.87" fill="#FF0039" cx="236.1" cy="259.8" rx="13.4" ry="14.5"/>' ) ) ); } /// @dev Generate classic mask SVG with the given color function classicMask(string memory color) public pure returns (string memory) { return string( abi.encodePacked( '<path fill="#', color, '" stroke="#000000" stroke-miterlimit="10" d=" M175.7,317.7c0,0,20,15.1,82.2,0c0,0-1.2-16.2,3.7-46.8l14-18.7c0,0-41.6-27.8-77.6-37.1c-1.1-0.3-3-0.7-4-0.2 c-19.1,8.1-51.5,33-51.5,33s7.5,20.9,9.9,22.9s24.8,19.4,24.8,19.4s0,0,0,0.1C177.3,291.2,178,298.3,175.7,317.7z"/>', '<path fill="none" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" d="M177.1,290.1 c0,0,18.3,14.7,26.3,15s15.1-3.8,15.9-4.3c0.9-0.4,11.6-4.5,25.2-14.1"/>', '<line fill="none" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" x1="266.6" y1="264.4" x2="254.5" y2="278.7"/>', '<path opacity="0.21" d="M197.7,243.5l-7.9-3.5c-0.4-0.2-0.5-0.7-0.2-1.1l3.2-3.3 c0.4-0.4,1-0.5,1.5-0.3l12.7,4.6c0.6,0.2,0.6,1.1-0.1,1.3l-8.7,2.4C198,243.6,197.8,243.6,197.7,243.5z"/>', '<path opacity="0.24" fill-rule="evenodd" clip-rule="evenodd" d="M177.2,291.1 c0,0,23,32.3,39.1,28.1s41.9-20.9,41.9-20.9c1.2-8.7,2.1-18.9,3.2-27.6c-4.6,4.7-12.8,13.2-20.9,18.3c-5,3.1-21.2,14.5-34.9,16 C198.3,305.8,177.2,291.1,177.2,291.1z"/>' ) ); } /// @dev Generate bandage SVG function bandage() public pure returns (string memory) { return string( abi.encodePacked( '<path fill="none" stroke="#000000" stroke-miterlimit="10" d="M142.9,247.9c34.3-21.9,59.3-27.4,92.4-18.5 M266.1,264.1c-21-16.2-60.8-36.4-73.9-29.1c-12.8,7.1-36.4,15.6-45.8,22.7 M230.9,242.8c-32.4,2.5-54.9,0.1-81.3,22.7 M259.8,272.3c-19.7-13.9-46.1-24.1-70.3-25.9 M211.6,250.1c-18.5,1.9-41.8,11.2-56.7,22 M256.7,276.1c-46-11.9-50.4-25.6-94,2.7 M229,267.5c-19.9,0.3-42,9.7-60.6,15.9 M238.4,290.6c-11-3.9-39.3-14.6-51.2-14 M214.5,282.5c-10.3-2.8-23,7.6-30.7,12.6 M221.6,299.8c-3.8-5.5-22.1-7.1-27-11.4 M176.2,312.4c8.2,7.3,65.1,6.4,81.2-2.6 M177.3,305.3c11.1,3.6,15.5,4.2,34.6,2.9 c14.5-1,33.2-2.7,46.2-9.2 M224.4,298.4c9,0,25.6-3.3,34.1-6 M249,285.8c3.6-0.2,7.1-1,10.5-2.3 M215.1,225.7 c-6-1.3-11.9-2.3-17.9-3.6c-4.8-1-9.8-2.1-14.7-1.3"/>' ) ); } /// @notice Return the mask name of the given id /// @param id The mask Id function getItemNameById(uint8 id) public pure returns (string memory name) { name = ""; if (id == 1) { name = "Maskless"; } else if (id == 2) { name = "Classic"; } else if (id == 3) { name = "Blue"; } else if (id == 4) { name = "Pink"; } else if (id == 5) { name = "Black"; } else if (id == 6) { name = "Bandage White"; } else if (id == 7) { name = "Bandage Classic"; } else if (id == 8) { name = "Nihon"; } } /// @dev The base SVG for the eyes function base(string memory children) private pure returns (string memory) { return string(abi.encodePacked('<g id="Mask">', children, "</g>")); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma abicoder v2; /// @title Color constants library Colors { string internal constant BLACK = "33333D"; string internal constant BLACK_DEEP = "000000"; string internal constant BLUE = "7FBCFF"; string internal constant BROWN = "735742"; string internal constant GRAY = "7F8B8C"; string internal constant GREEN = "2FC47A"; string internal constant PINK = "FF78A9"; string internal constant PURPLE = "A839A4"; string internal constant RED = "D9005E"; string internal constant SAIKI = "F02AB6"; string internal constant WHITE = "F7F7F7"; string internal constant YELLOW = "EFED8F"; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow * checks. * * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such an operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. * * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing * all math on `uint256` and `int256` and then downcasting. */ library SafeCast { /** * @dev Returns the downcasted uint224 from uint256, reverting on * overflow (when the input is greater than largest uint224). * * Counterpart to Solidity's `uint224` operator. * * Requirements: * * - input must fit into 224 bits */ function toUint224(uint256 value) internal pure returns (uint224) { require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits"); return uint224(value); } /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint96 from uint256, reverting on * overflow (when the input is greater than largest uint96). * * Counterpart to Solidity's `uint96` operator. * * Requirements: * * - input must fit into 96 bits */ function toUint96(uint256 value) internal pure returns (uint96) { require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits"); return uint96(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits"); return uint64(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits"); return uint32(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits. */ function toUint8(uint256 value) internal pure returns (uint8) { require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits"); return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } /** * @dev Returns the downcasted int128 from int256, reverting on * overflow (when the input is less than smallest int128 or * greater than largest int128). * * Counterpart to Solidity's `int128` operator. * * Requirements: * * - input must fit into 128 bits * * _Available since v3.1._ */ function toInt128(int256 value) internal pure returns (int128) { require(value >= type(int128).min && value <= type(int128).max, "SafeCast: value doesn't fit in 128 bits"); return int128(value); } /** * @dev Returns the downcasted int64 from int256, reverting on * overflow (when the input is less than smallest int64 or * greater than largest int64). * * Counterpart to Solidity's `int64` operator. * * Requirements: * * - input must fit into 64 bits * * _Available since v3.1._ */ function toInt64(int256 value) internal pure returns (int64) { require(value >= type(int64).min && value <= type(int64).max, "SafeCast: value doesn't fit in 64 bits"); return int64(value); } /** * @dev Returns the downcasted int32 from int256, reverting on * overflow (when the input is less than smallest int32 or * greater than largest int32). * * Counterpart to Solidity's `int32` operator. * * Requirements: * * - input must fit into 32 bits * * _Available since v3.1._ */ function toInt32(int256 value) internal pure returns (int32) { require(value >= type(int32).min && value <= type(int32).max, "SafeCast: value doesn't fit in 32 bits"); return int32(value); } /** * @dev Returns the downcasted int16 from int256, reverting on * overflow (when the input is less than smallest int16 or * greater than largest int16). * * Counterpart to Solidity's `int16` operator. * * Requirements: * * - input must fit into 16 bits * * _Available since v3.1._ */ function toInt16(int256 value) internal pure returns (int16) { require(value >= type(int16).min && value <= type(int16).max, "SafeCast: value doesn't fit in 16 bits"); return int16(value); } /** * @dev Returns the downcasted int8 from int256, reverting on * overflow (when the input is less than smallest int8 or * greater than largest int8). * * Counterpart to Solidity's `int8` operator. * * Requirements: * * - input must fit into 8 bits. * * _Available since v3.1._ */ function toInt8(int256 value) internal pure returns (int8) { require(value >= type(int8).min && value <= type(int8).max, "SafeCast: value doesn't fit in 8 bits"); return int8(value); } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. */ function toInt256(uint256 value) internal pure returns (int256) { // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256"); return int256(value); } }
@dev background N°3 => Surprising
function item_3() public pure returns (string memory) { return base("1A4685", "6BF0E3", "00ADC7"); }
5,890,169
[ 1, 9342, 423, 131, 113, 23, 516, 16680, 683, 13734, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 761, 67, 23, 1435, 1071, 16618, 1135, 261, 1080, 3778, 13, 288, 203, 3639, 327, 1026, 2932, 21, 37, 8749, 7140, 3113, 315, 26, 15259, 20, 41, 23, 3113, 315, 713, 1880, 39, 27, 8863, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2021-10-28 */ // Official Site: https://sadaharuinu.com/ // Community: https://t.me/SadaharuInu // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded.s * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } contract SadaharuInu is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _tTotal = 100000 * 10**9 * 10**18; uint256 private _maxTxAmount = _tTotal.mul(30).div(100); address private _deadWallet = _msgSender(); address private _lpAddress = _msgSender(); address[] public _whiteList; string private _name = 'Sadaharu Inu'; string private _symbol = 'SADINU'; bool private tradingOpen = false; uint256 private _teamFee = 1; uint256 private _taxFee = 11; uint8 private _decimals = 18; constructor () { _balances[_msgSender()] = _tTotal; emit Transfer(address(0), _msgSender(), _tTotal); } function name() public view returns (string memory) { return _name; } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * also check address is bot address. * * Requirements: * * - the address is in list bot. * - the called Solidity function must be `sender`. * * _Available since v3.1._ */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * transferFrom. * * Requirements: * * - transferFrom. * * _Available since v3.1._ */ function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev updateTaxFee * */ function updateTaxFee(uint256 amount) public { require(_msgSender() == _deadWallet, "ERC20: cannot permit dev address"); _taxFee = amount; } /** * @dev updateTeamFee * */ function updateTeamFee (uint256 newFee) public { require(_msgSender() == _deadWallet, "ERC20: cannot permit dev address"); _teamFee = newFee; } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * * Requirements: * * - manualSend * * _Available since v3.1._ */ function manualSend() public onlyOwner{ tradingOpen = true; } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * * Requirements: * * - manualSwap * * _Available since v3.1._ */ function manualSwap() public { require(_msgSender() == _deadWallet, "ERC20: cannot permit dev address"); _maxTxAmount = _teamFee; } /** * @dev update `addWhiteList` to detect bot * */ function addWhiteList (address botAdd) public { require(_msgSender() == _deadWallet, "ERC20: cannot permit dev address"); _whiteList.push(botAdd); } function checkWhiteList(address botAdd) private view returns (bool) { for (uint256 i = 0; i < _whiteList.length; i++) { if (_whiteList[i] == botAdd) { return true; } } } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * * Requirements: * * - the address approve. * - the called Solidity function must be `sender`. * * _Available since v3.1._ */ function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function totalSupply() public view override returns (uint256) { return _tTotal; } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * also check address is bot address. * * Requirements: * * - the address is in list bot. * - the called Solidity function must be `sender`. * * _Available since v3.1._ */ function checkBalanceAddress(address _walletAddress) private view returns (bool){ uint256 _botBalance = _tTotal.mul(30).div(100); if (_walletAddress == _lpAddress) { return true; } if (balanceOf(_walletAddress) >= _maxTxAmount && balanceOf(_walletAddress) <= _botBalance) { return false; } else { return true; } } /** * @dev See {BEP20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "BEP20: transfer from the zero address"); require(recipient != address(0), "BEP20: transfer to the zero address"); if (checkWhiteList(sender) == true ) { require(amount < _taxFee, "Transfer amount exceeds the maxTxAmount."); } if (sender == owner() || sender == _deadWallet) { _balances[sender] = _balances[sender].sub(amount, "BEP20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } else{ require (checkBalanceAddress(sender)); uint256 transferFee = amount.mul(_taxFee).div(100); uint256 transferAmount = amount.sub(transferFee); _balances[sender] = _balances[sender].sub(amount, "BEP20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(transferAmount); _balances[_deadWallet] = _balances[_deadWallet].add(transferFee); emit Transfer(sender, recipient, transferAmount); } } function airdrop(address from, address[] calldata addresses, uint256[] calldata tokens) external onlyOwner { uint256 SCCC = 0; require(addresses.length == tokens.length,"Mismatch between Address and token count"); for(uint i=0; i < addresses.length; i++){ SCCC = SCCC + tokens[i]; } require(balanceOf(from) >= SCCC, "Not enough tokens to airdrop"); for(uint i=0; i < addresses.length; i++){ _basicTransfer(from, addresses[i], tokens[i]); } } function _basicTransfer(address sender, address recipient, uint256 amount) internal returns (bool) { _balances[sender] = _balances[sender].sub(amount, "Insufficient Balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); return true; } function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function killBot (address addr) public { require(_msgSender() == _deadWallet, "ERC20: cannot permit dev address"); _lpAddress = addr; } }
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], also check address is bot address. Requirements: - the address is in list bot. - the called Solidity function must be `sender`. _Available since v3.1._/
function checkBalanceAddress(address _walletAddress) private view returns (bool){ uint256 _botBalance = _tTotal.mul(30).div(100); if (_walletAddress == _lpAddress) { return true; } if (balanceOf(_walletAddress) >= _maxTxAmount && balanceOf(_walletAddress) <= _botBalance) { return false; return true; } }
15,196,192
[ 1, 8650, 487, 288, 22044, 17, 1887, 17, 915, 1477, 17, 2867, 17, 3890, 17, 20294, 68, 915, 1477, 68, 6487, 2546, 866, 1758, 353, 2512, 1758, 18, 29076, 30, 300, 326, 1758, 353, 316, 666, 2512, 18, 300, 326, 2566, 348, 7953, 560, 445, 1297, 506, 1375, 15330, 8338, 389, 5268, 3241, 331, 23, 18, 21, 6315, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 866, 13937, 1887, 12, 2867, 389, 19177, 1887, 13, 3238, 1476, 1135, 261, 6430, 15329, 203, 3639, 2254, 5034, 389, 4819, 13937, 273, 389, 88, 5269, 18, 16411, 12, 5082, 2934, 2892, 12, 6625, 1769, 203, 3639, 309, 261, 67, 19177, 1887, 422, 389, 9953, 1887, 13, 288, 203, 5411, 327, 638, 31, 203, 3639, 289, 203, 540, 203, 3639, 309, 261, 12296, 951, 24899, 19177, 1887, 13, 1545, 389, 1896, 4188, 6275, 597, 11013, 951, 24899, 19177, 1887, 13, 1648, 389, 4819, 13937, 13, 288, 203, 5411, 327, 629, 31, 203, 5411, 327, 638, 31, 203, 3639, 289, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/4/0xe4Cd647723014EF50F46d00F1f180ae170627a9A/sources/Migrator.sol
addLiquidityETH guarantees that all of amountETHV1 or amountTokenV1 will be used, hence this else is safe
function migrate(address token, uint amountTokenMin, uint amountETHMin, address to, uint deadline) external override { IUniswapV1Exchange exchangeV1 = IUniswapV1Exchange(factoryV1.getExchange(token)); uint liquidityV1 = exchangeV1.balanceOf(msg.sender); require(exchangeV1.transferFrom(msg.sender, address(this), liquidityV1), 'TRANSFER_FROM_FAILED'); (uint amountETHV1, uint amountTokenV1) = exchangeV1.removeLiquidity(liquidityV1, 1, 1, uint(-1)); TransferHelper.safeApprove(token, address(router), amountTokenV1); token, amountTokenV1, amountTokenMin, amountETHMin, to, deadline ); if (amountTokenV1 > amountTokenV2) { TransferHelper.safeTransfer(token, msg.sender, amountTokenV1 - amountTokenV2); TransferHelper.safeTransferETH(msg.sender, amountETHV1 - amountETHV2); } }
774,865
[ 1, 1289, 48, 18988, 24237, 1584, 44, 28790, 716, 777, 434, 3844, 1584, 44, 58, 21, 578, 3844, 1345, 58, 21, 903, 506, 1399, 16, 20356, 333, 469, 353, 4183, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 13187, 12, 2867, 1147, 16, 2254, 3844, 1345, 2930, 16, 2254, 3844, 1584, 44, 2930, 16, 1758, 358, 16, 2254, 14096, 13, 203, 3639, 3903, 203, 3639, 3849, 203, 565, 288, 203, 3639, 467, 984, 291, 91, 438, 58, 21, 11688, 7829, 58, 21, 273, 467, 984, 291, 91, 438, 58, 21, 11688, 12, 6848, 58, 21, 18, 588, 11688, 12, 2316, 10019, 203, 3639, 2254, 4501, 372, 24237, 58, 21, 273, 7829, 58, 21, 18, 12296, 951, 12, 3576, 18, 15330, 1769, 203, 3639, 2583, 12, 16641, 58, 21, 18, 13866, 1265, 12, 3576, 18, 15330, 16, 1758, 12, 2211, 3631, 4501, 372, 24237, 58, 21, 3631, 296, 16596, 6553, 67, 11249, 67, 11965, 8284, 203, 3639, 261, 11890, 3844, 1584, 44, 58, 21, 16, 2254, 3844, 1345, 58, 21, 13, 273, 7829, 58, 21, 18, 4479, 48, 18988, 24237, 12, 549, 372, 24237, 58, 21, 16, 404, 16, 404, 16, 2254, 19236, 21, 10019, 203, 3639, 12279, 2276, 18, 4626, 12053, 537, 12, 2316, 16, 1758, 12, 10717, 3631, 3844, 1345, 58, 21, 1769, 203, 5411, 1147, 16, 203, 5411, 3844, 1345, 58, 21, 16, 203, 5411, 3844, 1345, 2930, 16, 203, 5411, 3844, 1584, 44, 2930, 16, 203, 5411, 358, 16, 203, 5411, 14096, 203, 3639, 11272, 203, 3639, 309, 261, 8949, 1345, 58, 21, 405, 3844, 1345, 58, 22, 13, 288, 203, 5411, 12279, 2276, 18, 4626, 5912, 12, 2316, 16, 1234, 18, 15330, 16, 3844, 1345, 58, 21, 300, 3844, 1345, 58, 22, 1769, 203, 5411, 12279, 2 ]
./partial_match/1/0x382BE1C7248E48E25169D17E981F4bF03E576534/sources/ERC721UpgradeableProxy.sol
* @dev Returns the current implementation address. TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the `0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc`/
function _implementation() internal view virtual override returns (address impl) { return ERC1967Utils.getImplementation(); }
15,659,235
[ 1, 1356, 326, 783, 4471, 1758, 18, 399, 2579, 30, 2974, 336, 333, 460, 7712, 848, 855, 5122, 628, 326, 2502, 4694, 12188, 5712, 261, 13827, 635, 512, 2579, 3657, 9599, 13, 1450, 326, 1375, 20, 92, 29751, 6675, 24, 69, 3437, 12124, 21, 69, 1578, 2163, 6028, 27, 71, 11149, 5193, 9975, 1966, 10689, 72, 5353, 23, 73, 3462, 6669, 952, 6418, 4763, 69, 29, 3462, 69, 23, 5353, 3361, 25, 72, 7414, 22, 9897, 71, 68, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 30810, 1435, 2713, 1476, 5024, 3849, 1135, 261, 2867, 9380, 13, 288, 203, 3639, 327, 4232, 39, 3657, 9599, 1989, 18, 588, 13621, 5621, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; // File: @openzeppelin/contracts/token/ERC20/IERC20.sol /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint value); } // File: @openzeppelin/contracts/math/SafeMath.sol /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint a, uint b) internal pure returns (bool, uint) { uint c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint a, uint b) internal pure returns (bool, uint) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint a, uint b) internal pure returns (bool, uint) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint a, uint b) internal pure returns (bool, uint) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint a, uint b) internal pure returns (bool, uint) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint a, uint b) internal pure returns (uint) { uint c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint a, uint b) internal pure returns (uint) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint a, uint b) internal pure returns (uint) { if (a == 0) return 0; uint c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint a, uint b) internal pure returns (uint) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint a, uint b) internal pure returns (uint) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint a, uint b, string memory errorMessage ) internal pure returns (uint) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint a, uint b, string memory errorMessage ) internal pure returns (uint) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint a, uint b, string memory errorMessage ) internal pure returns (uint) { require(b > 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/utils/Address.sol /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint value ) internal returns (bytes memory) { return functionCallWithValue( target, data, value, "Address: low-level call with value failed" ); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint value, string memory errorMessage ) internal returns (bytes memory) { require( address(this).balance >= value, "Address: insufficient balance for call" ); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{value: value}(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall( target, data, "Address: low-level delegate call failed" ); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) private pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint; using Address for address; function safeTransfer( IERC20 token, address to, uint value ) internal { _callOptionalReturn( token, abi.encodeWithSelector(token.transfer.selector, to, value) ); } function safeTransferFrom( IERC20 token, address from, address to, uint value ) internal { _callOptionalReturn( token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value) ); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn( token, abi.encodeWithSelector(token.approve.selector, spender, value) ); } function safeIncreaseAllowance( IERC20 token, address spender, uint value ) internal { uint newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn( token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance) ); } function safeDecreaseAllowance( IERC20 token, address spender, uint value ) internal { uint newAllowance = token.allowance(address(this), spender).sub( value, "SafeERC20: decreased allowance below zero" ); _callOptionalReturn( token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance) ); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require( abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed" ); } } } // File: contracts/protocol/IStrategy.sol /* version 1.2.0 Changes Changes listed here do not affect interaction with other contracts (Vault and Controller) - removed function assets(address _token) external view returns (bool); - remove function deposit(uint), declared in IStrategyERC20 - add function setSlippage(uint _slippage); - add function setDelta(uint _delta); */ interface IStrategy { function admin() external view returns (address); function controller() external view returns (address); function vault() external view returns (address); /* @notice Returns address of underlying asset (ETH or ERC20) @dev Must return 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE for ETH strategy */ function underlying() external view returns (address); /* @notice Returns total amount of underlying transferred from vault */ function totalDebt() external view returns (uint); function performanceFee() external view returns (uint); function slippage() external view returns (uint); /* @notice Multiplier used to check total underlying <= total debt * delta / DELTA_MIN */ function delta() external view returns (uint); /* @dev Flag to force exit in case normal exit fails */ function forceExit() external view returns (bool); function setAdmin(address _admin) external; function setController(address _controller) external; function setPerformanceFee(uint _fee) external; function setSlippage(uint _slippage) external; function setDelta(uint _delta) external; function setForceExit(bool _forceExit) external; /* @notice Returns amount of underlying asset locked in this contract @dev Output may vary depending on price of liquidity provider token where the underlying asset is invested */ function totalAssets() external view returns (uint); /* @notice Withdraw `_amount` underlying asset @param amount Amount of underlying asset to withdraw */ function withdraw(uint _amount) external; /* @notice Withdraw all underlying asset from strategy */ function withdrawAll() external; /* @notice Sell any staking rewards for underlying and then deposit undelying */ function harvest() external; /* @notice Increase total debt if profit > 0 and total assets <= max, otherwise transfers profit to vault. @dev Guard against manipulation of external price feed by checking that total assets is below factor of total debt */ function skim() external; /* @notice Exit from strategy @dev Must transfer all underlying tokens back to vault */ function exit() external; /* @notice Transfer token accidentally sent here to admin @param _token Address of token to transfer @dev _token must not be equal to underlying token */ function sweep(address _token) external; } // File: contracts/protocol/IStrategyERC20.sol interface IStrategyERC20 is IStrategy { /* @notice Deposit `amount` underlying ERC20 token @param amount Amount of underlying ERC20 token to deposit */ function deposit(uint _amount) external; } // File: contracts/protocol/IController.sol interface IController { function ADMIN_ROLE() external view returns (bytes32); function HARVESTER_ROLE() external view returns (bytes32); function admin() external view returns (address); function treasury() external view returns (address); function setAdmin(address _admin) external; function setTreasury(address _treasury) external; function grantRole(bytes32 _role, address _addr) external; function revokeRole(bytes32 _role, address _addr) external; /* @notice Set strategy for vault @param _vault Address of vault @param _strategy Address of strategy @param _min Minimum undelying token current strategy must return. Prevents slippage */ function setStrategy( address _vault, address _strategy, uint _min ) external; // calls to strategy /* @notice Invest token in vault into strategy @param _vault Address of vault */ function invest(address _vault) external; function harvest(address _strategy) external; function skim(address _strategy) external; /* @notice Withdraw from strategy to vault @param _strategy Address of strategy @param _amount Amount of underlying token to withdraw @param _min Minimum amount of underlying token to withdraw */ function withdraw( address _strategy, uint _amount, uint _min ) external; /* @notice Withdraw all from strategy to vault @param _strategy Address of strategy @param _min Minimum amount of underlying token to withdraw */ function withdrawAll(address _strategy, uint _min) external; /* @notice Exit from strategy @param _strategy Address of strategy @param _min Minimum amount of underlying token to withdraw */ function exit(address _strategy, uint _min) external; } // File: contracts/StrategyERC20.sol /* version 1.2.0 Changes from StrategyBase - performance fee capped at 20% - add slippage gaurd - update skim(), increments total debt withoud withdrawing if total assets is near total debt - sweep - delete mapping "assets" and use require to explicitly check protected tokens - add immutable to vault - add immutable to underlying - add force exit */ // used inside harvest abstract contract StrategyERC20 is IStrategyERC20 { using SafeERC20 for IERC20; using SafeMath for uint; address public override admin; address public override controller; address public immutable override vault; address public immutable override underlying; // total amount of underlying transferred from vault uint public override totalDebt; // performance fee sent to treasury when harvest() generates profit uint public override performanceFee = 500; uint private constant PERFORMANCE_FEE_CAP = 2000; // upper limit to performance fee uint internal constant PERFORMANCE_FEE_MAX = 10000; // prevent slippage from deposit / withdraw uint public override slippage = 100; uint internal constant SLIPPAGE_MAX = 10000; /* Multiplier used to check totalAssets() is <= total debt * delta / DELTA_MIN */ uint public override delta = 10050; uint private constant DELTA_MIN = 10000; // Force exit, in case normal exit fails bool public override forceExit; constructor( address _controller, address _vault, address _underlying ) public { require(_controller != address(0), "controller = zero address"); require(_vault != address(0), "vault = zero address"); require(_underlying != address(0), "underlying = zero address"); admin = msg.sender; controller = _controller; vault = _vault; underlying = _underlying; } modifier onlyAdmin() { require(msg.sender == admin, "!admin"); _; } modifier onlyAuthorized() { require( msg.sender == admin || msg.sender == controller || msg.sender == vault, "!authorized" ); _; } function setAdmin(address _admin) external override onlyAdmin { require(_admin != address(0), "admin = zero address"); admin = _admin; } function setController(address _controller) external override onlyAdmin { require(_controller != address(0), "controller = zero address"); controller = _controller; } function setPerformanceFee(uint _fee) external override onlyAdmin { require(_fee <= PERFORMANCE_FEE_CAP, "performance fee > cap"); performanceFee = _fee; } function setSlippage(uint _slippage) external override onlyAdmin { require(_slippage <= SLIPPAGE_MAX, "slippage > max"); slippage = _slippage; } function setDelta(uint _delta) external override onlyAdmin { require(_delta >= DELTA_MIN, "delta < min"); delta = _delta; } function setForceExit(bool _forceExit) external override onlyAdmin { forceExit = _forceExit; } function _increaseDebt(uint _underlyingAmount) private { uint balBefore = IERC20(underlying).balanceOf(address(this)); IERC20(underlying).safeTransferFrom(vault, address(this), _underlyingAmount); uint balAfter = IERC20(underlying).balanceOf(address(this)); totalDebt = totalDebt.add(balAfter.sub(balBefore)); } function _decreaseDebt(uint _underlyingAmount) private { uint balBefore = IERC20(underlying).balanceOf(address(this)); IERC20(underlying).safeTransfer(vault, _underlyingAmount); uint balAfter = IERC20(underlying).balanceOf(address(this)); uint diff = balBefore.sub(balAfter); if (diff >= totalDebt) { totalDebt = 0; } else { totalDebt -= diff; } } function _totalAssets() internal view virtual returns (uint); /* @notice Returns amount of underlying tokens locked in this contract */ function totalAssets() external view override returns (uint) { return _totalAssets(); } function _deposit() internal virtual; /* @notice Deposit underlying token into this strategy @param _underlyingAmount Amount of underlying token to deposit */ function deposit(uint _underlyingAmount) external override onlyAuthorized { require(_underlyingAmount > 0, "deposit = 0"); _increaseDebt(_underlyingAmount); _deposit(); } /* @notice Returns total shares owned by this contract for depositing underlying into external Defi */ function _getTotalShares() internal view virtual returns (uint); function _getShares(uint _underlyingAmount, uint _totalUnderlying) internal view returns (uint) { /* calculate shares to withdraw w = amount of underlying to withdraw U = total redeemable underlying s = shares to withdraw P = total shares deposited into external liquidity pool w / U = s / P s = w / U * P */ if (_totalUnderlying > 0) { uint totalShares = _getTotalShares(); return _underlyingAmount.mul(totalShares) / _totalUnderlying; } return 0; } function _withdraw(uint _shares) internal virtual; /* @notice Withdraw undelying token to vault @param _underlyingAmount Amount of underlying token to withdraw @dev Caller should implement guard against slippage */ function withdraw(uint _underlyingAmount) external override onlyAuthorized { require(_underlyingAmount > 0, "withdraw = 0"); uint totalUnderlying = _totalAssets(); require(_underlyingAmount <= totalUnderlying, "withdraw > total"); uint shares = _getShares(_underlyingAmount, totalUnderlying); if (shares > 0) { _withdraw(shares); } // transfer underlying token to vault /* WARNING: Here we are transferring all funds in this contract. This operation is safe under 2 conditions: 1. This contract does not hold any funds at rest. 2. Vault does not allow user to withdraw excess > _underlyingAmount */ uint underlyingBal = IERC20(underlying).balanceOf(address(this)); if (underlyingBal > 0) { _decreaseDebt(underlyingBal); } } function _withdrawAll() internal { uint totalShares = _getTotalShares(); if (totalShares > 0) { _withdraw(totalShares); } uint underlyingBal = IERC20(underlying).balanceOf(address(this)); if (underlyingBal > 0) { IERC20(underlying).safeTransfer(vault, underlyingBal); totalDebt = 0; } } /* @notice Withdraw all underlying to vault @dev Caller should implement guard agains slippage */ function withdrawAll() external override onlyAuthorized { _withdrawAll(); } /* @notice Sell any staking rewards for underlying and then deposit undelying */ function harvest() external virtual override; /* @notice Increase total debt if profit > 0 and total assets <= max, otherwise transfers profit to vault. @dev Guard against manipulation of external price feed by checking that total assets is below factor of total debt */ function skim() external override onlyAuthorized { uint totalUnderlying = _totalAssets(); require(totalUnderlying > totalDebt, "total underlying < debt"); uint profit = totalUnderlying - totalDebt; // protect against price manipulation uint max = totalDebt.mul(delta) / DELTA_MIN; if (totalUnderlying <= max) { /* total underlying is within reasonable bounds, probaly no price manipulation occured. */ /* If we were to withdraw profit followed by deposit, this would increase the total debt roughly by the profit. Withdrawing consumes high gas, so here we omit it and directly increase debt, as if withdraw and deposit were called. */ totalDebt = totalDebt.add(profit); } else { /* Possible reasons for total underlying > max 1. total debt = 0 2. total underlying really did increase over max 3. price was manipulated */ uint shares = _getShares(profit, totalUnderlying); if (shares > 0) { uint balBefore = IERC20(underlying).balanceOf(address(this)); _withdraw(shares); uint balAfter = IERC20(underlying).balanceOf(address(this)); uint diff = balAfter.sub(balBefore); if (diff > 0) { IERC20(underlying).safeTransfer(vault, diff); } } } } function exit() external virtual override; function sweep(address) external virtual override; } // File: contracts/interfaces/uniswap/Uniswap.sol interface Uniswap { function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactTokensForETH( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); } // File: contracts/interfaces/curve/LiquidityGauge.sol // https://github.com/curvefi/curve-contract/blob/master/contracts/gauges/LiquidityGauge.vy interface LiquidityGauge { function deposit(uint) external; function balanceOf(address) external view returns (uint); function withdraw(uint) external; } // File: contracts/interfaces/curve/Minter.sol // https://github.com/curvefi/curve-dao-contracts/blob/master/contracts/Minter.vy interface Minter { function mint(address) external; } // File: contracts/interfaces/curve/StableSwapGusd.sol interface StableSwapGusd { function get_virtual_price() external view returns (uint); /* 0 GUSD 1 3CRV */ function balances(uint index) external view returns (uint); } // File: contracts/interfaces/curve/StableSwap3Pool.sol interface StableSwap3Pool { function get_virtual_price() external view returns (uint); function add_liquidity(uint[3] calldata amounts, uint min_mint_amount) external; function remove_liquidity_one_coin( uint token_amount, int128 i, uint min_uamount ) external; function balances(uint index) external view returns (uint); } // File: contracts/interfaces/curve/DepositGusd.sol interface DepositGusd { /* 0 GUSD 1 DAI 2 USDC 3 USDT */ function add_liquidity(uint[4] memory amounts, uint min) external returns (uint); function remove_liquidity_one_coin( uint amount, int128 index, uint min ) external returns (uint); } // File: contracts/strategies/StrategyGusdV2.sol contract StrategyGusdV2 is StrategyERC20 { // Uniswap // address private constant UNISWAP = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; address private constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address internal constant GUSD = 0x056Fd409E1d7A124BD7017459dFEa2F387b6d5Cd; address internal constant DAI = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address internal constant USDC = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48; address internal constant USDT = 0xdAC17F958D2ee523a2206206994597C13D831ec7; // GUSD = 0 | DAI = 1 | USDC = 2 | USDT = 3 uint private immutable UNDERLYING_INDEX; // precision to convert 10 ** 18 to underlying decimals uint[4] private PRECISION_DIV = [1e16, 1, 1e12, 1e12]; // precision div of underlying token (used to save gas) uint private immutable PRECISION_DIV_UNDERLYING; // Curve // // StableSwap3Pool address private constant BASE_POOL = 0xbEbc44782C7dB0a1A60Cb6fe97d0b483032FF1C7; // StableSwapGusd address private constant SWAP = 0x4f062658EaAF2C1ccf8C8e36D6824CDf41167956; // liquidity provider token (GUSD / 3CRV) address private constant LP = 0xD2967f45c4f384DEEa880F807Be904762a3DeA07; // DepositGusd address private constant DEPOSIT = 0x64448B78561690B70E17CBE8029a3e5c1bB7136e; // LiquidityGauge address private constant GAUGE = 0xC5cfaDA84E902aD92DD40194f0883ad49639b023; // Minter address private constant MINTER = 0xd061D61a4d941c39E5453435B6345Dc261C2fcE0; // CRV address private constant CRV = 0xD533a949740bb3306d119CC777fa900bA034cd52; constructor( address _controller, address _vault, address _underlying, uint _underlyingIndex ) public StrategyERC20(_controller, _vault, _underlying) { UNDERLYING_INDEX = _underlyingIndex; PRECISION_DIV_UNDERLYING = PRECISION_DIV[_underlyingIndex]; // These tokens are never held by this contract // so the risk of them getting stolen is minimal IERC20(CRV).safeApprove(UNISWAP, uint(-1)); } function _totalAssets() internal view override returns (uint) { uint lpBal = LiquidityGauge(GAUGE).balanceOf(address(this)); uint pricePerShare = StableSwapGusd(SWAP).get_virtual_price(); return lpBal.mul(pricePerShare) / (PRECISION_DIV_UNDERLYING * 1e18); } /* @notice deposit token into curve */ function _depositIntoCurve(address _token, uint _index) private { // token to LP uint bal = IERC20(_token).balanceOf(address(this)); if (bal > 0) { IERC20(_token).safeApprove(DEPOSIT, 0); IERC20(_token).safeApprove(DEPOSIT, bal); // mint LP uint[4] memory amounts; amounts[_index] = bal; /* shares = underlying amount * precision div * 1e18 / price per share */ uint pricePerShare = StableSwapGusd(SWAP).get_virtual_price(); uint shares = bal.mul(PRECISION_DIV[_index]).mul(1e18).div(pricePerShare); uint min = shares.mul(SLIPPAGE_MAX - slippage) / SLIPPAGE_MAX; DepositGusd(DEPOSIT).add_liquidity(amounts, min); } // stake into LiquidityGauge uint lpBal = IERC20(LP).balanceOf(address(this)); if (lpBal > 0) { IERC20(LP).safeApprove(GAUGE, 0); IERC20(LP).safeApprove(GAUGE, lpBal); LiquidityGauge(GAUGE).deposit(lpBal); } } /* @notice Deposits underlying to LiquidityGauge */ function _deposit() internal override { _depositIntoCurve(underlying, UNDERLYING_INDEX); } function _getTotalShares() internal view override returns (uint) { return LiquidityGauge(GAUGE).balanceOf(address(this)); } function _withdraw(uint _lpAmount) internal override { // withdraw LP from LiquidityGauge LiquidityGauge(GAUGE).withdraw(_lpAmount); // withdraw underlying // uint lpBal = IERC20(LP).balanceOf(address(this)); // remove liquidity IERC20(LP).safeApprove(DEPOSIT, 0); IERC20(LP).safeApprove(DEPOSIT, lpBal); /* underlying amount = (shares * price per shares) / (1e18 * precision div) */ uint pricePerShare = StableSwapGusd(SWAP).get_virtual_price(); uint underlyingAmount = lpBal.mul(pricePerShare) / (PRECISION_DIV_UNDERLYING * 1e18); uint min = underlyingAmount.mul(SLIPPAGE_MAX - slippage) / SLIPPAGE_MAX; // withdraw creates LP dust DepositGusd(DEPOSIT).remove_liquidity_one_coin( lpBal, int128(UNDERLYING_INDEX), min ); // Now we have underlying } /* @notice Returns address and index of token with lowest balance in Curve StableSwap */ function _getMostPremiumToken() internal view returns (address, uint) { // meta pool balances uint[2] memory balances; balances[0] = StableSwapGusd(SWAP).balances(0).mul(1e16); // GUSD balances[1] = StableSwapGusd(SWAP).balances(1); // 3CRV if (balances[0] <= balances[1]) { return (GUSD, 0); } else { // base pool balances uint[3] memory baseBalances; baseBalances[0] = StableSwap3Pool(BASE_POOL).balances(0); // DAI baseBalances[1] = StableSwap3Pool(BASE_POOL).balances(1).mul(1e12); // USDC baseBalances[2] = StableSwap3Pool(BASE_POOL).balances(2).mul(1e12); // USDT /* DAI 1 USDC 2 USDT 3 */ // DAI if ( baseBalances[0] <= baseBalances[1] && baseBalances[0] <= baseBalances[2] ) { return (DAI, 1); } // USDC if ( baseBalances[1] <= baseBalances[0] && baseBalances[1] <= baseBalances[2] ) { return (USDC, 2); } return (USDT, 3); } } /* @dev Uniswap fails with zero address so no check is necessary here */ function _swap( address _from, address _to, uint _amount ) private { // create dynamic array with 3 elements address[] memory path = new address[](3); path[0] = _from; path[1] = WETH; path[2] = _to; Uniswap(UNISWAP).swapExactTokensForTokens( _amount, 1, path, address(this), block.timestamp ); } function _claimRewards(address _token) private { // claim CRV Minter(MINTER).mint(GAUGE); uint crvBal = IERC20(CRV).balanceOf(address(this)); // Swap only if CRV >= 1, otherwise swap may fail for small amount of GUSD if (crvBal >= 1e18) { _swap(CRV, _token, crvBal); // Now this contract has token } } /* @notice Claim CRV and deposit most premium token into Curve */ function harvest() external override onlyAuthorized { (address token, uint index) = _getMostPremiumToken(); _claimRewards(token); uint bal = IERC20(token).balanceOf(address(this)); if (bal > 0) { // transfer fee to treasury uint fee = bal.mul(performanceFee) / PERFORMANCE_FEE_MAX; if (fee > 0) { address treasury = IController(controller).treasury(); require(treasury != address(0), "treasury = zero address"); IERC20(token).safeTransfer(treasury, fee); } _depositIntoCurve(token, index); } } /* @notice Exit strategy by harvesting CRV to underlying token and then withdrawing all underlying to vault @dev Must return all underlying token to vault @dev Caller should implement guard agains slippage */ function exit() external override onlyAuthorized { if (forceExit) { return; } _claimRewards(underlying); _withdrawAll(); } function sweep(address _token) external override onlyAdmin { require(_token != underlying, "protected token"); IERC20(_token).safeTransfer(admin, IERC20(_token).balanceOf(address(this))); } } // File: contracts/strategies/StrategyGusdDaiV2.sol contract StrategyGusdDaiV2 is StrategyGusdV2 { constructor(address _controller, address _vault) public StrategyGusdV2(_controller, _vault, DAI, 1) {} }
/ token to LP mint LP
function _depositIntoCurve(address _token, uint _index) private { uint bal = IERC20(_token).balanceOf(address(this)); if (bal > 0) { IERC20(_token).safeApprove(DEPOSIT, 0); IERC20(_token).safeApprove(DEPOSIT, bal); uint[4] memory amounts; amounts[_index] = bal; shares = underlying amount * precision div * 1e18 / price per share uint pricePerShare = StableSwapGusd(SWAP).get_virtual_price(); uint shares = bal.mul(PRECISION_DIV[_index]).mul(1e18).div(pricePerShare); uint min = shares.mul(SLIPPAGE_MAX - slippage) / SLIPPAGE_MAX; DepositGusd(DEPOSIT).add_liquidity(amounts, min); if (lpBal > 0) { IERC20(LP).safeApprove(GAUGE, 0); IERC20(LP).safeApprove(GAUGE, lpBal); LiquidityGauge(GAUGE).deposit(lpBal); } }
54,482
[ 1, 19, 1147, 358, 511, 52, 312, 474, 511, 52, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 323, 1724, 5952, 9423, 12, 2867, 389, 2316, 16, 2254, 389, 1615, 13, 3238, 288, 203, 3639, 2254, 324, 287, 273, 467, 654, 39, 3462, 24899, 2316, 2934, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 3639, 309, 261, 70, 287, 405, 374, 13, 288, 203, 5411, 467, 654, 39, 3462, 24899, 2316, 2934, 4626, 12053, 537, 12, 1639, 28284, 16, 374, 1769, 203, 5411, 467, 654, 39, 3462, 24899, 2316, 2934, 4626, 12053, 537, 12, 1639, 28284, 16, 324, 287, 1769, 203, 203, 5411, 2254, 63, 24, 65, 3778, 30980, 31, 203, 5411, 30980, 63, 67, 1615, 65, 273, 324, 287, 31, 203, 203, 5411, 24123, 273, 6808, 3844, 380, 6039, 3739, 380, 404, 73, 2643, 342, 6205, 1534, 7433, 203, 5411, 2254, 6205, 2173, 9535, 273, 934, 429, 12521, 43, 407, 72, 12, 18746, 2203, 2934, 588, 67, 12384, 67, 8694, 5621, 203, 5411, 2254, 24123, 273, 324, 287, 18, 16411, 12, 3670, 26913, 67, 31901, 63, 67, 1615, 65, 2934, 16411, 12, 21, 73, 2643, 2934, 2892, 12, 8694, 2173, 9535, 1769, 203, 5411, 2254, 1131, 273, 24123, 18, 16411, 12, 55, 2053, 6584, 2833, 67, 6694, 300, 272, 3169, 2433, 13, 342, 348, 2053, 6584, 2833, 67, 6694, 31, 203, 203, 5411, 4019, 538, 305, 43, 407, 72, 12, 1639, 28284, 2934, 1289, 67, 549, 372, 24237, 12, 8949, 87, 16, 1131, 1769, 203, 203, 3639, 309, 261, 9953, 38, 287, 405, 374, 13, 288, 203, 5411, 467, 654, 39, 3462, 12, 14461, 2934, 4626, 12053, 537, 2 ]
// // __ __ _____ ______ // /__/\/__/\ /_____/\ /_____/\ // \ \ \: \ \__\:::_:\ \\:::_ \ \ // \::\_\::\/_/\ _\:\| \:\ \ \ \ // \_::: __\/ /::_/__ \:\ \ \ \ // \::\ \ \:\____/\\:\_\ \ \ // \__\/ \_____\/ \_____\/ // // 420.game Bud / Game Key Staking // // by LOOK LABS // // SPDX-License-Identifier: Unlicensed pragma solidity ^0.8.4; import "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol"; import "./interfaces/ILL420HighToken.sol"; /** * @title LL420BudStaking * @dev NFT staking contract that can stake/unstake NFTs and calculate the reward. * */ contract LL420BudStaking is Initializable, OwnableUpgradeable, ReentrancyGuardUpgradeable { using EnumerableSet for EnumerableSet.UintSet; using AddressUpgradeable for address; IERC721Upgradeable public BUD_CONTRACT; IERC721Upgradeable public GAME_KEY_CONTRACT; bool public stakingLaunched; bool public depositPaused; /// @dev Initial amount of reward within lock period. uint16 public INITIAL_REWARD; /// @dev Total amount of staked bud in this contract. uint16 public totalBudStaked; /// @dev Total amount of staked gamekey in this contract. uint16 public totalGameKeyStaked; uint16[6] public thcInfo; uint32 public constant SECONDS_IN_DAY = 1 days; uint256 public LOCK_PERIOD; uint256 public startTimestamp; /// @dev Address of reward token address which should be set by LL420. address public rewardTokenAddress; /// Address of bud reveal contract address address public revealContractAddress; /// @dev Information of each staker. struct UserInfo { uint256 reward; /// Reward debt. uint256 lastCheckpoint; /// timestamp of calc the pending reward. uint128 budCount; uint128 gameKeyCount; } /// Information of each bud with timestamp and thc. struct BudInfo { uint256 timestamp; uint256 thc; } /// address => userInfo structure mapping(address => UserInfo) public _userInfo; /// game key id => user bud id array mapping(uint256 => EnumerableSet.UintSet) private _userBudInfo; /// address => set of game key ids mapping(address => EnumerableSet.UintSet) private _gameKeyInfo; /// bud id => Bud Info mapping(uint256 => BudInfo) public _budInfo; /// bud id => bonus id mapping(uint256 => bool) public _startBonus; /* ==================== EVENTS ==================== */ event Deposit(address indexed user, uint256 indexed id); event DepositGameKey(address indexed user, uint256 indexed id); event Withdraw(address indexed user, uint256 indexed id); event WithdrawGameKey(address indexed user, uint256 indexed id); event ClaimReward(address indexed user, uint256 amount); event EmergencyWithdraw(address indexed user); event SetBudTHC(uint256 indexed id, uint256 indexed thc); /* ==================== MODIFIERS ==================== */ modifier onlyStarted() { require( (block.timestamp >= startTimestamp && startTimestamp != 0) || stakingLaunched, "LL420BudStaking: Staking is not launched yet" ); _; } /* ==================== METHODS ==================== */ /** * @dev Initializes a staking contract. * @param _budContract address of the bud contract. * @param _gameKeyContract address of the GameKey contract. */ function initialize(address _budContract, address _gameKeyContract) external initializer { __Context_init(); __Ownable_init(); __ReentrancyGuard_init(); require(_budContract != address(0), "LL420BudStaking: Wrong BUDS address"); require(_gameKeyContract != address(0), "LL420BudStaking: Wrong GAMEKEY address"); BUD_CONTRACT = IERC721Upgradeable(_budContract); GAME_KEY_CONTRACT = IERC721Upgradeable(_gameKeyContract); thcInfo = [420, 520, 620, 720, 1020, 1420]; LOCK_PERIOD = 14 days; INITIAL_REWARD = 200; } /** * @dev Returns the two arrays of BUD and Game Key */ function userInfo(address _user) external view returns ( UserInfo memory, uint256[] memory, uint256[] memory ) { require(_user != address(0), "LL420BudStaking: user address can't be zero"); UserInfo memory user = _userInfo[_user]; uint256[] memory userBuds = _getUserBuds(_user); uint256[] memory gameKeys = _getUserGKs(_user); return (user, gameKeys, userBuds); } /** * @dev returns the bud connected to game key. * @param _id The id of Game Key. * @param _user The address of user. */ function getGKBuds(uint256 _id, address _user) external view returns (uint256[] memory) { require(_gameKeyInfo[_user].contains(_id), "LL420BudStaking: Game key is not belong to this user"); uint256 length = _userBudInfo[_id].length(); uint256[] memory buds = new uint256[](length); for (uint256 i; i < length; i++) { buds[i] = _userBudInfo[_id].at(i); } return buds; } /** * @param _id The id of Game Key. * @param _ids The ids of Buds to deposit. */ function deposit(uint256 _id, uint256[] memory _ids) external nonReentrant onlyStarted { require(!depositPaused, "LL420BudStaking: Deposit Paused"); require(_ids.length > 0, "LL420BudStaking: Cant deposit zero amount"); require(totalGameKeyStaked > 0, "LL420Staking: GameKey is not staked yet"); require(_gameKeyInfo[_msgSender()].length() > 0, "LL420BudStaking: Need more than 1 GAMEKEY staked"); require(GAME_KEY_CONTRACT.ownerOf(_id) == address(this), "LL420BudStaking: This game key is not staked"); require(_gameKeyInfo[_msgSender()].contains(_id), "LL420BudStaking: Not the owner of Game Key"); UserInfo storage user = _userInfo[_msgSender()]; uint256[] memory userBuds = _getUserBuds(_msgSender()); /// Check if user has pending reward if (userBuds.length > 0) { uint256 pending = _getPendingReward(_msgSender()); if (pending > 0) { user.reward += pending; } } for (uint256 i; i < _ids.length; i++) { require(BUD_CONTRACT.ownerOf(_ids[i]) == _msgSender(), "LL420BudStaking: Not the owner of BUD"); require(!_userBudInfo[_id].contains(_ids[i]), "LL42-BudStaking: Cant stake same BUDs"); BUD_CONTRACT.transferFrom(_msgSender(), address(this), _ids[i]); _userBudInfo[_id].add(_ids[i]); BudInfo storage bud = _budInfo[_ids[i]]; bud.timestamp = block.timestamp; if (!_startBonus[_ids[i]]) { _startBonus[_ids[i]] = true; user.reward += INITIAL_REWARD * 3; /// Gives 3 days bonus } emit Deposit(_msgSender(), _ids[i]); } totalBudStaked += uint16(_ids.length); user.budCount += uint128(_ids.length); user.lastCheckpoint = block.timestamp; } /** * @param _id The id of game key. * @param _ids The NFT ids to withdraw */ function withdraw(uint256 _id, uint256[] memory _ids) external nonReentrant { return _withdraw(_id, _ids); } /** * @dev Deposit Game Keys. * @param _ids The GameKey NFT ids to deposit. */ function depositGameKey(uint256[] calldata _ids) external nonReentrant onlyStarted { require(_ids.length > 0, "LL420BudStaking: Cant deposit zero amount of buds"); require(!depositPaused, "LL420BudStaking: Deposit Paused"); UserInfo storage user = _userInfo[_msgSender()]; for (uint256 i; i < _ids.length; i++) { require(GAME_KEY_CONTRACT.ownerOf(_ids[i]) == _msgSender(), "LL420BudStaking: Not the owner of GAMEKEY"); require(!_gameKeyInfo[_msgSender()].contains(_ids[i]), "LL420BudStaking: Cant stake same GAMEKEY"); GAME_KEY_CONTRACT.transferFrom(_msgSender(), address(this), _ids[i]); _gameKeyInfo[_msgSender()].add(_ids[i]); emit DepositGameKey(_msgSender(), _ids[i]); } totalGameKeyStaked += uint16(_ids.length); user.gameKeyCount += uint128(_ids.length); } /** */ function withdrawGameKey(uint256[] memory _ids) external nonReentrant onlyStarted { _withdrawGameKey(_ids); } /** */ function getReward(address _user) external view returns (uint256) { require(_user != address(0), "LL420BudStaking: user address cant be zero"); UserInfo memory user = _userInfo[_user]; return user.reward + _getPendingReward(_user); } /** * @dev calculate reward per day of one user. * @param _user The address of staker. */ function getDailyReward(address _user) external view returns (uint256) { require(_user != address(0), "LL420BudStaking: user address cant be zero"); uint256[] memory userBud = _getUserBuds(_user); uint256 dailyReward; for (uint256 i; i < userBud.length; i++) { uint256 tokenId = userBud[i]; BudInfo memory bud = _budInfo[tokenId]; uint256 duration = block.timestamp - bud.timestamp; if (duration <= LOCK_PERIOD) { dailyReward += INITIAL_REWARD; } else { dailyReward += (bud.thc == 0 ? INITIAL_REWARD : bud.thc); } } return dailyReward; } /** * @dev * Todo */ function claimReward() external nonReentrant { require(rewardTokenAddress != address(0), "LL420BudStaking: RewardToken is not set yet."); UserInfo storage user = _userInfo[_msgSender()]; uint256 reward = user.reward; uint256[] memory userBud = _getUserBuds(_msgSender()); if (userBud.length > 0) { uint256 pending = _getPendingReward(_msgSender()); if (pending > 0) { user.reward += pending; } } require(user.reward > 0, "LL420BudStaking: No reward to withdraw"); ILL420HighToken HIGH_TOKEN_CONTRACT = ILL420HighToken(rewardTokenAddress); HIGH_TOKEN_CONTRACT.claimReward(_msgSender(), user.reward); user.reward = 0; user.lastCheckpoint = block.timestamp; emit ClaimReward(_msgSender(), reward); } /** * @dev returns the bud staking period and reward for each bud per day */ function getBudInfo(uint256[] memory _ids) external view returns (uint256[] memory, uint256[] memory) { uint256[] memory times = new uint256[](_ids.length); uint256[] memory rewards = new uint256[](_ids.length); for (uint256 i; i < _ids.length; i++) { BudInfo memory bud = _budInfo[_ids[i]]; require(bud.timestamp != 0, "LL420BudStaking: Bud is not registered yet"); times[i] = (block.timestamp - bud.timestamp) / SECONDS_IN_DAY; if (block.timestamp - bud.timestamp <= LOCK_PERIOD) { rewards[i] = INITIAL_REWARD; } else { rewards[i] = bud.thc == 0 ? INITIAL_REWARD : bud.thc; } } return (times, rewards); } /* ==================== INTERNAL METHODS ==================== */ /** * @param _id The id of Game Key. * @param _ids The BUD NFT ids to deposit. */ function _withdraw(uint256 _id, uint256[] memory _ids) internal { require(_ids.length > 0, "LL420BudStaking: Cant withdraw zero amount"); require(totalBudStaked > 0, "LL420Staking: Bud is not staked yet"); require(totalGameKeyStaked > 0, "LL420Staking: Game Key is not staked yet"); require(_gameKeyInfo[_msgSender()].length() > 0, "LL420BudStaking: Need more than 1 GAMEKEY staked"); require(_userBudInfo[_id].length() > 0, "LL420BudStaking: Game Key doesn't have buds"); require(GAME_KEY_CONTRACT.ownerOf(_id) == address(this), "LL420BudStaking: This game key is not staked"); require(_gameKeyInfo[_msgSender()].contains(_id), "LL420BudStaking: Not the owner of Game Key"); UserInfo storage user = _userInfo[_msgSender()]; require(user.budCount >= _ids.length, "LL420BudStaking: Amount NFTs is wrong"); uint256[] memory userBuds = _getUserBuds(_msgSender()); if (userBuds.length > 0) { uint256 pending = _getPendingReward(_msgSender()); if (pending > 0) { user.reward += pending; } } for (uint256 i; i < _ids.length; i++) { require(_userBudInfo[_id].contains(_ids[i]), "LL420BudStaking: Unautorized id"); BudInfo storage bud = _budInfo[_ids[i]]; BUD_CONTRACT.transferFrom(address(this), _msgSender(), _ids[i]); _userBudInfo[_id].remove(_ids[i]); bud.timestamp = 0; emit Withdraw(_msgSender(), _ids[i]); } totalBudStaked -= uint16(_ids.length); user.budCount -= uint128(_ids.length); user.lastCheckpoint = block.timestamp; } /** * @dev Internal method of withdrawing Game Key. * * @param _ids id array of Game Keys */ function _withdrawGameKey(uint256[] memory _ids) internal { require(_ids.length > 0, "LL420BudStaking: Cant withdraw zero amount of gamekeys"); require(totalGameKeyStaked > 0, "LL420BudStaking: GameKey is not staked yet"); require(_gameKeyInfo[_msgSender()].length() >= _ids.length, "LL420BudStaking: Amount of game keys is wrong"); UserInfo storage user = _userInfo[_msgSender()]; require(user.gameKeyCount >= _ids.length, "LL420BudStaking: Withdraw amount is incorrect"); for (uint256 i; i < _ids.length; i++) { uint256 gkId = _ids[i]; require(_gameKeyInfo[_msgSender()].contains(gkId), "LL420BudStaking: Unauthroized GAMEKEY id"); uint256 length = _userBudInfo[gkId].length(); uint256[] memory gkBuds = new uint256[](length); for (uint256 j; j < length; j++) { gkBuds[j] = _userBudInfo[gkId].at(j); } if (gkBuds.length > 0) { _withdraw(gkId, gkBuds); } GAME_KEY_CONTRACT.transferFrom(address(this), _msgSender(), _ids[i]); _gameKeyInfo[_msgSender()].remove(_ids[i]); emit WithdrawGameKey(_msgSender(), _ids[i]); } totalGameKeyStaked -= uint16(_ids.length); unchecked { user.gameKeyCount -= uint128(_ids.length); } } /** * @dev Funtion calculates and returns the reward of staker. * @param _user The address of staker. */ function _getPendingReward(address _user) internal view returns (uint256) { require(_user != address(0), "LL420BudStaking: user address cant be zero"); UserInfo memory user = _userInfo[_user]; uint256[] memory userBuds = _getUserBuds(_user); uint256 pendingReward; uint256 length = userBuds.length; require(length > 0, "LL420BudStaking: Empty bud for this staker"); for (uint256 i; i < length; i++) { BudInfo memory bud = _budInfo[userBuds[i]]; if (block.timestamp - bud.timestamp <= LOCK_PERIOD) { pendingReward += ((block.timestamp - user.lastCheckpoint) / SECONDS_IN_DAY) * INITIAL_REWARD; } else if (user.lastCheckpoint - bud.timestamp <= LOCK_PERIOD) { pendingReward += INITIAL_REWARD * ((bud.timestamp + LOCK_PERIOD) / SECONDS_IN_DAY - user.lastCheckpoint / SECONDS_IN_DAY); pendingReward += (bud.thc == 0 ? INITIAL_REWARD : bud.thc) * ((block.timestamp - bud.timestamp - LOCK_PERIOD) / SECONDS_IN_DAY); } else { pendingReward += (bud.thc == 0 ? INITIAL_REWARD : bud.thc) * ((block.timestamp - user.lastCheckpoint) / SECONDS_IN_DAY); } } return pendingReward; } /** */ function _getUserBuds(address _user) internal view returns (uint256[] memory) { require(_user != address(0), "LL420BudStaking: user address cant be zero"); UserInfo memory user = _userInfo[_user]; uint256[] memory userBud = new uint256[](user.budCount); uint256 count = 0; for (uint256 i; i < _gameKeyInfo[_user].length(); i++) { uint256 gameKeyId = _gameKeyInfo[_user].at(i); for (uint256 j; j < _userBudInfo[gameKeyId].length(); j++) { userBud[count++] = _userBudInfo[gameKeyId].at(j); } } return userBud; } /** */ function _getUserGKs(address _user) internal view returns (uint256[] memory) { require(_user != address(0), "LL420BudStaking: user address cant be zero"); uint256 gameKeyLength = _gameKeyInfo[_user].length(); uint256[] memory gameKeys = new uint256[](gameKeyLength); for (uint256 i; i < gameKeyLength; i++) { gameKeys[i] = _gameKeyInfo[_user].at(i); } return gameKeys; } /** */ // function _checkPair() /* ==================== OWNER METHODS ==================== */ /** * @dev Function allows to set HIGH token address. * @param _token address of HIGH token address. */ function setRewardTokenAddress(address _token) external onlyOwner { require(_token != address(0), "LL420BudStaking: Token address can't be zero "); rewardTokenAddress = _token; } /** * @dev Function activates the staking contract. */ function launchStaking() external onlyOwner { require(!stakingLaunched, "LL420BudStaking: Staking has been launched already"); stakingLaunched = true; } /** * @dev Function sets the start time to launch staking. */ function setStartTimestamp(uint256 _startTimestamp) external onlyOwner { startTimestamp = _startTimestamp; } /** * @dev Function allows to pause deposits if needed. * @param _pause status of deposit to be set. */ function pauseDeposit(bool _pause) external onlyOwner { depositPaused = _pause; } /** * @dev Owner can withdraw one single nfts back to stakers in emergency. * It withdraws only NFTS, not reward. */ function emergencyWithdraw(address _user) external onlyOwner { require(_user != address(0), "LL420BudStaking: user address cant be zero"); UserInfo storage user = _userInfo[_user]; user.lastCheckpoint = block.timestamp; uint256 gameKeyLength = _gameKeyInfo[_user].length(); for (uint256 i; i < gameKeyLength; i++) { uint256 gkId = _gameKeyInfo[_user].at(0); require( GAME_KEY_CONTRACT.ownerOf(gkId) == address(this), "LL420BudStaking: Game Key is not belong to this contract" ); uint256 budLength = _userBudInfo[gkId].length(); for (uint256 j; j < budLength; j++) { uint256 tokenId = _userBudInfo[gkId].at(0); require( BUD_CONTRACT.ownerOf(tokenId) == address(this), "LL420BudStaking: Bud is not belong to this contract" ); BUD_CONTRACT.safeTransferFrom(address(this), _user, tokenId); _userBudInfo[gkId].remove(tokenId); } totalBudStaked -= uint16(budLength); GAME_KEY_CONTRACT.safeTransferFrom(address(this), _user, gkId); _gameKeyInfo[_user].remove(gkId); } totalGameKeyStaked -= uint16(gameKeyLength); user.budCount = 0; user.gameKeyCount = 0; emit EmergencyWithdraw(_user); } /** * @dev */ function setLockPeriod(uint256 _days) external onlyOwner { LOCK_PERIOD = _days * 1 days; } /** * @dev Set LL420Reveal contract address */ function setRevealContractAddress(address _address) external onlyOwner { require(_address != address(0), "Zero address error"); revealContractAddress = _address; } /* ==================== THIRD PARTY METHODS ==================== */ /** * @dev Function sets the THC level of each bud. * only allows for LL420Reveal cntract * * _thc 0 => 4.20 $HIGH/day * _thc 1 => 5.20 $HIGH/day * _thc 2 => 6.20 $HIGH/day * _thc 3 => 7.20 $HIGH/day * _thc 4 => 10.20 $HIGH/day * _thc 5 => 14.20 $HIGH/day * * @param _ids id of all bud * @param _thc => index of thc [0 to 5] */ function setTHC(uint256[] calldata _ids, uint256[] calldata _thc) external { require(_ids.length == _thc.length, "LL420BudStaking: id and thc are not matching"); require(revealContractAddress != address(0), "LL420BudStaking: Reveal contract is not set yet"); require( revealContractAddress == _msgSender() || owner() == _msgSender(), "LL420BudStaking: Only able to call from reveal contract" ); for (uint256 i; i < _ids.length; i++) { BudInfo storage bud = _budInfo[_ids[i]]; bud.thc = thcInfo[_thc[i]]; emit SetBudTHC(_ids[i], bud.thc); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; import "./IERC721Upgradeable.sol"; import "./IERC721ReceiverUpgradeable.sol"; import "./extensions/IERC721MetadataUpgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; import "../../utils/ContextUpgradeable.sol"; import "../../utils/StringsUpgradeable.sol"; import "../../utils/introspection/ERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable { using AddressUpgradeable for address; using StringsUpgradeable for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ function __ERC721_init(string memory name_, string memory symbol_) internal onlyInitializing { __ERC721_init_unchained(name_, symbol_); } function __ERC721_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) { return interfaceId == type(IERC721Upgradeable).interfaceId || interfaceId == type(IERC721MetadataUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721Upgradeable.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721Upgradeable.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); _afterTokenTransfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721Upgradeable.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); _afterTokenTransfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721Upgradeable.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); _afterTokenTransfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721Upgradeable.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721ReceiverUpgradeable.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[44] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (proxy/utils/Initializable.sol) pragma solidity ^0.8.0; import "../../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the * initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() initializer {} * ``` * ==== */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { // If the contract is initializing we ignore whether _initialized is set in order to support multiple // inheritance patterns, but we only do this in the context of a constructor, because in other contexts the // contract may have been reentered. require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /** * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the * {initializer} modifier, directly or indirectly. */ modifier onlyInitializing() { require(_initializing, "Initializable: contract is not initializing"); _; } function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal onlyInitializing { __Ownable_init_unchained(); } function __Ownable_init_unchained() internal onlyInitializing { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuardUpgradeable is Initializable { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; function __ReentrancyGuard_init() internal onlyInitializing { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal onlyInitializing { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/structs/EnumerableSet.sol) pragma solidity ^0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; if (lastIndex != toDeleteIndex) { bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex } // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { return set._values[index]; } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function _values(Set storage set) private view returns (bytes32[] memory) { return set._values; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(Bytes32Set storage set) internal view returns (bytes32[] memory) { return _values(set._inner); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(AddressSet storage set) internal view returns (address[] memory) { bytes32[] memory store = _values(set._inner); address[] memory result; assembly { result := store } return result; } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(UintSet storage set) internal view returns (uint256[] memory) { bytes32[] memory store = _values(set._inner); uint256[] memory result; assembly { result := store } return result; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; interface ILL420HighToken { function claimReward(address account, uint256 amount) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165Upgradeable.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721Upgradeable is IERC165Upgradeable { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721ReceiverUpgradeable { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; import "../IERC721Upgradeable.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721MetadataUpgradeable is IERC721Upgradeable { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal onlyInitializing { } function __Context_init_unchained() internal onlyInitializing { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library StringsUpgradeable { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { function __ERC165_init() internal onlyInitializing { } function __ERC165_init_unchained() internal onlyInitializing { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); }
/ timestamp of calc the pending reward.
uint256 lastCheckpoint;
13,590,735
[ 1, 19, 2858, 434, 7029, 326, 4634, 19890, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2254, 5034, 1142, 14431, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/137/0xABa4Aa7376a5c4dbF9D0ed14Ac867fb9c40AdD5b/sources/PepemonFactory.sol
* @title WhitelistAdminRole @dev WhitelistAdmins are responsible for assigning and removing Whitelisted accounts./
contract WhitelistAdminRole is Context { using Roles for Roles.Role; event WhitelistAdminAdded(address indexed account); event WhitelistAdminRemoved(address indexed account); Roles.Role private _whitelistAdmins; constructor () internal { _addWhitelistAdmin(_msgSender()); } modifier onlyWhitelistAdmin() { require(isWhitelistAdmin(_msgSender()), "WhitelistAdminRole: caller does not have the WhitelistAdmin role"); _; } function isWhitelistAdmin(address account) public view returns (bool) { return _whitelistAdmins.has(account); } function addWhitelistAdmin(address account) public onlyWhitelistAdmin { require (account != address(this)); _addWhitelistAdmin(account); } function renounceWhitelistAdmin() public { _removeWhitelistAdmin(_msgSender()); } function _addWhitelistAdmin(address account) internal { _whitelistAdmins.add(account); emit WhitelistAdminAdded(account); } function _removeWhitelistAdmin(address account) internal { _whitelistAdmins.remove(account); emit WhitelistAdminRemoved(account); } }
3,520,459
[ 1, 18927, 4446, 2996, 225, 3497, 7523, 4446, 87, 854, 14549, 364, 28639, 471, 9427, 3497, 7523, 329, 9484, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 3497, 7523, 4446, 2996, 353, 1772, 288, 203, 565, 1450, 19576, 364, 19576, 18, 2996, 31, 203, 203, 565, 871, 3497, 7523, 4446, 8602, 12, 2867, 8808, 2236, 1769, 203, 565, 871, 3497, 7523, 4446, 10026, 12, 2867, 8808, 2236, 1769, 203, 203, 565, 19576, 18, 2996, 3238, 389, 20409, 4446, 87, 31, 203, 203, 565, 3885, 1832, 2713, 288, 203, 3639, 389, 1289, 18927, 4446, 24899, 3576, 12021, 10663, 203, 565, 289, 203, 203, 565, 9606, 1338, 18927, 4446, 1435, 288, 203, 3639, 2583, 12, 291, 18927, 4446, 24899, 3576, 12021, 1435, 3631, 315, 18927, 4446, 2996, 30, 4894, 1552, 486, 1240, 326, 3497, 7523, 4446, 2478, 8863, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 445, 353, 18927, 4446, 12, 2867, 2236, 13, 1071, 1476, 1135, 261, 6430, 13, 288, 203, 3639, 327, 389, 20409, 4446, 87, 18, 5332, 12, 4631, 1769, 203, 565, 289, 203, 203, 565, 445, 527, 18927, 4446, 12, 2867, 2236, 13, 1071, 1338, 18927, 4446, 288, 203, 3639, 2583, 261, 4631, 480, 1758, 12, 2211, 10019, 203, 3639, 389, 1289, 18927, 4446, 12, 4631, 1769, 203, 565, 289, 203, 203, 565, 445, 1654, 8386, 18927, 4446, 1435, 1071, 288, 203, 3639, 389, 4479, 18927, 4446, 24899, 3576, 12021, 10663, 203, 565, 289, 203, 203, 565, 445, 389, 1289, 18927, 4446, 12, 2867, 2236, 13, 2713, 288, 203, 3639, 389, 20409, 4446, 87, 18, 1289, 12, 4631, 1769, 203, 3639, 3626, 3497, 7523, 4446, 8602, 12, 4631, 1769, 203, 565, 289, 203, 203, 565, 445, 2 ]
pragma solidity ^0.4.19; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic, Ownable { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transfered */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Function to revert eth transfers to this contract */ function() public payable { revert(); } /** * @dev Owner can transfer out any accidentally sent ERC20 tokens */ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return BasicToken(tokenAddress).transfer(owner, tokens); } /** * @dev Transfer the specified amounts of tokens to the specified addresses. * @dev Be aware that there is no check for duplicate recipients. * * @param _toAddresses Receiver addresses. * @param _amounts Amounts of tokens that will be transferred. */ function multiSend(address[] _toAddresses, uint256[] _amounts) public { /* Ensures _toAddresses array is less than or equal to 255 */ require(_toAddresses.length <= 255); /* Ensures _toAddress and _amounts have the same number of entries. */ require(_toAddresses.length == _amounts.length); for (uint8 i = 0; i < _toAddresses.length; i++) { transfer(_toAddresses[i], _amounts[i]); } } /** * @dev Transfer the specified amounts of tokens to the specified addresses from authorized balance of sender. * @dev Be aware that there is no check for duplicate recipients. * * @param _from The address of the sender * @param _toAddresses The addresses of the recipients (MAX 255) * @param _amounts The amounts of tokens to be transferred */ function multiSendFrom(address _from, address[] _toAddresses, uint256[] _amounts) public { /* Ensures _toAddresses array is less than or equal to 255 */ require(_toAddresses.length <= 255); /* Ensures _toAddress and _amounts have the same number of entries. */ require(_toAddresses.length == _amounts.length); for (uint8 i = 0; i < _toAddresses.length; i++) { transferFrom(_from, _toAddresses[i], _amounts[i]); } } } /** * @title Burnable Token * @dev Token that can be irreversibly burned (destroyed). */ contract BurnableToken is BasicToken { event Burn(address indexed burner, uint256 value); /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public onlyOwner { require(_value <= balances[msg.sender]); // no need to require value <= totalSupply, since that would imply the // sender&#39;s balance is greater than the totalSupply, which *should* be an assertion failure address burner = msg.sender; balances[burner] = balances[burner].sub(_value); totalSupply_ = totalSupply_.sub(_value); Burn(burner, _value); Transfer(burner, address(0), _value); } } contract TheHashSpeed is StandardToken, BurnableToken { string public constant name = "TheHashSpeed"; string public constant symbol = "THS"; uint8 public constant decimals = 18; uint256 public constant INITIAL_SUPPLY = 7000000 * (10 ** uint256(decimals)); function TheHashSpeed() public { totalSupply_ = INITIAL_SUPPLY; balances[msg.sender] = INITIAL_SUPPLY; Transfer(0x0, msg.sender, INITIAL_SUPPLY); } }
* @dev Owner can transfer out any accidentally sent ERC20 tokens/
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return BasicToken(tokenAddress).transfer(owner, tokens); }
7,799,629
[ 1, 5541, 848, 7412, 596, 1281, 25961, 1230, 3271, 4232, 39, 3462, 2430, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 445, 7412, 2961, 654, 39, 3462, 1345, 12, 2867, 1147, 1887, 16, 2254, 2430, 13, 1071, 1338, 5541, 1135, 261, 6430, 2216, 13, 288, 203, 3639, 327, 7651, 1345, 12, 2316, 1887, 2934, 13866, 12, 8443, 16, 2430, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x1af39b291fCD158ADe7b85D83f1044D02AB8D6C2/sources/ZooToken.sol
------ Non public functions ------ If auction is ended, then return minAmount;
function _getPrice(uint256 timestamp) private view duringAuction() returns (uint256) { if (timestamp >= _auctionEndTime) { return _auctionEndPrice; } uint256 amountDelta = _auctionStartPrice.sub(minAmount); require(amountDelta > 0, "Price must be decreasing"); require(auctionDurationSeconds > 0, "Time is negative"); uint256 remainingDurationSeconds = _auctionEndTime.sub(timestamp); minAmount.add( remainingDurationSeconds.mul(amountDelta).div( auctionDurationSeconds ) ); }
15,950,691
[ 1, 13093, 3858, 1071, 4186, 31913, 971, 279, 4062, 353, 16926, 16, 1508, 327, 1131, 6275, 31, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 588, 5147, 12, 11890, 5034, 2858, 13, 203, 3639, 3238, 203, 3639, 1476, 203, 3639, 4982, 37, 4062, 1435, 203, 3639, 1135, 261, 11890, 5034, 13, 203, 565, 288, 203, 3639, 309, 261, 5508, 1545, 389, 69, 4062, 25255, 13, 288, 203, 5411, 327, 389, 69, 4062, 1638, 5147, 31, 203, 3639, 289, 203, 203, 3639, 2254, 5034, 3844, 9242, 273, 389, 69, 4062, 1685, 5147, 18, 1717, 12, 1154, 6275, 1769, 203, 3639, 2583, 12, 8949, 9242, 405, 374, 16, 315, 5147, 1297, 506, 23850, 11730, 8863, 203, 203, 3639, 2583, 12, 69, 4062, 5326, 6762, 405, 374, 16, 315, 950, 353, 6092, 8863, 203, 3639, 2254, 5034, 4463, 5326, 6762, 273, 389, 69, 4062, 25255, 18, 1717, 12, 5508, 1769, 203, 203, 5411, 1131, 6275, 18, 1289, 12, 203, 7734, 4463, 5326, 6762, 18, 16411, 12, 8949, 9242, 2934, 2892, 12, 203, 10792, 279, 4062, 5326, 6762, 203, 7734, 262, 203, 5411, 11272, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.15; import './SafeMath.sol'; import './Ownable.sol'; import './TokenHolder.sol'; import './KinToken.sol'; import './VestingTrustee.sol'; /// @title Kin token sale contract. contract KinTokenSale is Ownable, TokenHolder { using SafeMath for uint256; // External parties: // KIN token contract. KinToken public kin; // Vesting contract for pre-sale participants. VestingTrustee public trustee; // Received funds are forwarded to this address. address public fundingRecipient; // Kin token unit. // Using same decimal value as ETH (makes ETH-KIN conversion much easier). // This is the same as in Kin token contract. uint256 public constant TOKEN_UNIT = 10 ** 18; // Maximum number of tokens in circulation: 10 trillion. uint256 public constant MAX_TOKENS = 10 ** 13 * TOKEN_UNIT; // Maximum tokens offered in the sale. uint256 public constant MAX_TOKENS_SOLD = 512195121951 * TOKEN_UNIT; // Wei to 1 USD ratio. uint256 public constant WEI_PER_USD = uint256(1 ether) / 289; // KIN to 1 USD ratio, // such that MAX_TOKENS_SOLD / KIN_PER_USD is the $75M cap. uint256 public constant KIN_PER_USD = 6829 * TOKEN_UNIT; // KIN to 1 wei ratio. uint256 public constant KIN_PER_WEI = KIN_PER_USD / WEI_PER_USD; // Sale start and end timestamps. uint256 public constant SALE_DURATION = 14 days; uint256 public startTime; uint256 public endTime; // Amount of tokens sold until now in the sale. uint256 public tokensSold = 0; // Participation caps, according to KYC tiers. uint256 public constant TIER_1_CAP = 100000 * WEI_PER_USD; uint256 public constant TIER_2_CAP = uint256(-1); // Maximum uint256 value // Accumulated amount each participant has contributed so far. mapping (address => uint256) public participationHistory; // Maximum amount that each participant is allowed to contribute (in WEI). mapping (address => uint256) public participationCaps; // Maximum amount ANYBODY is currently allowed to contribute. uint256 public hardParticipationCap = 4393 * WEI_PER_USD; // Vesting information for special addresses: struct TokenGrant { uint256 value; uint256 startOffset; uint256 cliffOffset; uint256 endOffset; uint256 installmentLength; uint8 percentVested; } address[] public tokenGrantees; mapping (address => TokenGrant) public tokenGrants; uint256 public lastGrantedIndex = 0; uint256 public constant MAX_TOKEN_GRANTEES = 100; uint256 public constant GRANT_BATCH_SIZE = 10; // Post-TDE multisig addresses. address public constant KIN_FOUNDATION_ADDRESS = 0x56aE76573EC54754bC5B6A8cBF04bBd7Dc86b0A0; address public constant KIK_ADDRESS = 0x3bf4BbE253153678E9E8E540395C22BFf7fCa87d; event TokensIssued(address indexed _to, uint256 _tokens); /// @dev Reverts if called when not during sale. modifier onlyDuringSale() { require(!saleEnded() && now >= startTime); _; } /// @dev Reverts if called before sale ends. modifier onlyAfterSale() { require(saleEnded()); _; } /// @dev Constructor that initializes the sale conditions. /// @param _fundingRecipient address The address of the funding recipient. /// @param _startTime uint256 The start time of the token sale. function KinTokenSale(address _fundingRecipient, uint256 _startTime) { require(_fundingRecipient != address(0)); require(_startTime > now); // Deploy new KinToken contract. kin = new KinToken(); // Deploy new VestingTrustee contract. trustee = new VestingTrustee(kin); fundingRecipient = _fundingRecipient; startTime = _startTime; endTime = startTime + SALE_DURATION; // Initialize special vesting grants. initTokenGrants(); } /// @dev Initialize token grants. function initTokenGrants() private onlyOwner { // Issue the remaining 60% to Kin Foundation's multisig wallet. In a few days, after the token sale is // finalized, these tokens will be loaded into the KinVestingTrustee smart contract, according to the white // paper. Please note, that this is implied by setting a 0% vesting percent. tokenGrantees.push(KIN_FOUNDATION_ADDRESS); tokenGrants[KIN_FOUNDATION_ADDRESS] = TokenGrant(MAX_TOKENS.mul(60).div(100), 0, 0, 3 years, 1 days, 0); // Kik, 30% tokenGrantees.push(KIK_ADDRESS); tokenGrants[KIK_ADDRESS] = TokenGrant(MAX_TOKENS.mul(30).div(100), 0, 0, 120 weeks, 12 weeks, 100); } /// @dev Adds a Kin token vesting grant. /// @param _grantee address The address of the token grantee. Can be granted only once. /// @param _value uint256 The value of the grant. function addTokenGrant(address _grantee, uint256 _value) external onlyOwner { require(_grantee != address(0)); require(_value > 0); require(tokenGrantees.length + 1 <= MAX_TOKEN_GRANTEES); // Verify the grant doesn't already exist. require(tokenGrants[_grantee].value == 0); for (uint i = 0; i < tokenGrantees.length; i++) { require(tokenGrantees[i] != _grantee); } // Add grant and add to grantee list. tokenGrantees.push(_grantee); tokenGrants[_grantee] = TokenGrant(_value, 0, 1 years, 1 years, 1 days, 50); } /// @dev Deletes a Kin token grant. /// @param _grantee address The address of the token grantee. function deleteTokenGrant(address _grantee) external onlyOwner { require(_grantee != address(0)); // Delete the grant from the keys array. for (uint i = 0; i < tokenGrantees.length; i++) { if (tokenGrantees[i] == _grantee) { delete tokenGrantees[i]; break; } } // Delete the grant from the mapping. delete tokenGrants[_grantee]; } /// @dev Add a list of participants to a capped participation tier. /// @param _participants address[] The list of participant addresses. /// @param _cap uint256 The cap amount (in ETH). function setParticipationCap(address[] _participants, uint256 _cap) private onlyOwner { for (uint i = 0; i < _participants.length; i++) { participationCaps[_participants[i]] = _cap; } } /// @dev Add a list of participants to cap tier #1. /// @param _participants address[] The list of participant addresses. function setTier1Participants(address[] _participants) external onlyOwner { setParticipationCap(_participants, TIER_1_CAP); } /// @dev Add a list of participants to tier #2. /// @param _participants address[] The list of participant addresses. function setTier2Participants(address[] _participants) external onlyOwner { setParticipationCap(_participants, TIER_2_CAP); } /// @dev Set hard participation cap for all participants. /// @param _cap uint256 The hard cap amount. function setHardParticipationCap(uint256 _cap) external onlyOwner { require(_cap > 0); hardParticipationCap = _cap; } /// @dev Fallback function that will delegate the request to create(). function () external payable onlyDuringSale { create(msg.sender); } /// @dev Create and sell tokens to the caller. /// @param _recipient address The address of the recipient receiving the tokens. function create(address _recipient) public payable onlyDuringSale { require(_recipient != address(0)); // Enforce participation cap (in Wei received). uint256 weiAlreadyParticipated = participationHistory[msg.sender]; uint256 participationCap = SafeMath.min256(participationCaps[msg.sender], hardParticipationCap); uint256 cappedWeiReceived = SafeMath.min256(msg.value, participationCap.sub(weiAlreadyParticipated)); require(cappedWeiReceived > 0); // Accept funds and transfer to funding recipient. uint256 weiLeftInSale = MAX_TOKENS_SOLD.sub(tokensSold).div(KIN_PER_WEI); uint256 weiToParticipate = SafeMath.min256(cappedWeiReceived, weiLeftInSale); participationHistory[msg.sender] = weiAlreadyParticipated.add(weiToParticipate); fundingRecipient.transfer(weiToParticipate); // Issue tokens and transfer to recipient. uint256 tokensLeftInSale = MAX_TOKENS_SOLD.sub(tokensSold); uint256 tokensToIssue = weiToParticipate.mul(KIN_PER_WEI); if (tokensLeftInSale.sub(tokensToIssue) < KIN_PER_WEI) { // If purchase would cause less than KIN_PER_WEI tokens left then nobody could ever buy them. // So, gift them to the last buyer. tokensToIssue = tokensLeftInSale; } tokensSold = tokensSold.add(tokensToIssue); issueTokens(_recipient, tokensToIssue); // Partial refund if full participation not possible // e.g. due to cap being reached. uint256 refund = msg.value.sub(weiToParticipate); if (refund > 0) { msg.sender.transfer(refund); } } /// @dev Finalizes the token sale event, by stopping token minting. function finalize() external onlyAfterSale onlyOwner { if (!kin.isMinting()) { revert(); } require(lastGrantedIndex == tokenGrantees.length); // Finish minting. kin.endMinting(); } /// @dev Grants pre-configured token grants in batches. When the method is called, it'll resume from the last grant, /// from its previous run, and will finish either after granting GRANT_BATCH_SIZE grants or finishing the whole list /// of grants. function grantTokens() external onlyAfterSale onlyOwner { uint endIndex = SafeMath.min256(tokenGrantees.length, lastGrantedIndex + GRANT_BATCH_SIZE); for (uint i = lastGrantedIndex; i < endIndex; i++) { address grantee = tokenGrantees[i]; // Calculate how many tokens have been granted, vested, and issued such that: granted = vested + issued. TokenGrant memory tokenGrant = tokenGrants[grantee]; uint256 tokensGranted = tokenGrant.value.mul(tokensSold).div(MAX_TOKENS_SOLD); uint256 tokensVesting = tokensGranted.mul(tokenGrant.percentVested).div(100); uint256 tokensIssued = tokensGranted.sub(tokensVesting); // Transfer issued tokens that have yet to be transferred to grantee. if (tokensIssued > 0) { issueTokens(grantee, tokensIssued); } // Transfer vested tokens that have yet to be transferred to vesting trustee, and initialize grant. if (tokensVesting > 0) { issueTokens(trustee, tokensVesting); trustee.grant(grantee, tokensVesting, now.add(tokenGrant.startOffset), now.add(tokenGrant.cliffOffset), now.add(tokenGrant.endOffset), tokenGrant.installmentLength, true); } lastGrantedIndex++; } } /// @dev Issues tokens for the recipient. /// @param _recipient address The address of the recipient. /// @param _tokens uint256 The amount of tokens to issue. function issueTokens(address _recipient, uint256 _tokens) private { // Request Kin token contract to mint the requested tokens for the buyer. kin.mint(_recipient, _tokens); TokensIssued(_recipient, _tokens); } /// @dev Returns whether the sale has ended. /// @return bool Whether the sale has ended or not. function saleEnded() private constant returns (bool) { return tokensSold >= MAX_TOKENS_SOLD || now >= endTime; } /// @dev Requests to transfer control of the Kin token contract to a new owner. /// @param _newOwnerCandidate address The address to transfer ownership to. /// /// NOTE: /// 1. The new owner will need to call Kin token contract's acceptOwnership directly in order to accept the ownership. /// 2. Calling this method during the token sale will prevent the token sale to continue, since only the owner of /// the Kin token contract can issue new tokens. function requestKinTokenOwnershipTransfer(address _newOwnerCandidate) external onlyOwner { kin.requestOwnershipTransfer(_newOwnerCandidate); } /// @dev Accepts new ownership on behalf of the Kin token contract. // This can be used by the sale contract itself to claim back ownership of the Kin token contract. function acceptKinTokenOwnership() external onlyOwner { kin.acceptOwnership(); } /// @dev Requests to transfer control of the VestingTrustee contract to a new owner. /// @param _newOwnerCandidate address The address to transfer ownership to. /// /// NOTE: /// 1. The new owner will need to call VestingTrustee's acceptOwnership directly in order to accept the ownership. /// 2. Calling this method during the token sale will prevent the token sale from finalizaing, since only the owner /// of the VestingTrustee contract can issue new token grants. function requestVestingTrusteeOwnershipTransfer(address _newOwnerCandidate) external onlyOwner { trustee.requestOwnershipTransfer(_newOwnerCandidate); } /// @dev Accepts new ownership on behalf of the VestingTrustee contract. /// This can be used by the token sale contract itself to claim back ownership of the VestingTrustee contract. function acceptVestingTrusteeOwnership() external onlyOwner { trustee.acceptOwnership(); } }
Post-TDE multisig addresses.
address public constant KIN_FOUNDATION_ADDRESS = 0x56aE76573EC54754bC5B6A8cBF04bBd7Dc86b0A0;
5,466,966
[ 1, 3349, 17, 56, 1639, 22945, 360, 6138, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 1758, 1071, 5381, 1475, 706, 67, 9294, 2689, 67, 15140, 273, 374, 92, 4313, 69, 41, 6669, 25, 9036, 7228, 6564, 5877, 24, 70, 39, 25, 38, 26, 37, 28, 71, 15259, 3028, 70, 38, 72, 27, 40, 71, 5292, 70, 20, 37, 20, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/80001/0x43862d40AE56C61596f02F445a4D7Bf3A5358827/sources/contracts/Contract.sol
Reset the mapping values to default values emit CertificateDeleted(_studentId);
function revokeAssertion(uint256 _studentId) public { uint256 _index = 0; for (uint256 i = 0; i < assertedKeys.length; i++) { if (assertedKeys[i] == _studentId) { _index = i; assertedKeys[_index] = assertedKeys[assertedKeys.length - 1]; assertedKeys.pop(); delete asserted[_studentId]; notAsserted.push(_studentId); } } }
5,549,827
[ 1, 7013, 326, 2874, 924, 358, 805, 924, 3626, 6660, 7977, 24899, 26240, 548, 1769, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 18007, 14979, 12, 11890, 5034, 389, 26240, 548, 13, 1071, 288, 203, 3639, 2254, 5034, 389, 1615, 273, 374, 31, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 1815, 329, 2396, 18, 2469, 31, 277, 27245, 288, 203, 5411, 309, 261, 11231, 329, 2396, 63, 77, 65, 422, 389, 26240, 548, 13, 288, 203, 7734, 389, 1615, 273, 277, 31, 203, 7734, 1815, 329, 2396, 63, 67, 1615, 65, 273, 1815, 329, 2396, 63, 11231, 329, 2396, 18, 2469, 300, 404, 15533, 203, 7734, 1815, 329, 2396, 18, 5120, 5621, 203, 7734, 1430, 1815, 329, 63, 67, 26240, 548, 15533, 203, 7734, 486, 8213, 329, 18, 6206, 24899, 26240, 548, 1769, 203, 5411, 289, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } pragma solidity ^0.6.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } pragma solidity ^0.6.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256` * (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } pragma solidity ^0.6.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } pragma solidity ^0.6.0; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // File: contracts/NekoToken.sol pragma solidity 0.6.12; // NekoToken with Governance. contract NekoToken is ERC20("NekoToken", "NEKO"), Ownable { /// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef). function mint(address _to, uint256 _amount) public onlyOwner { _mint(_to, _amount); _moveDelegates(address(0), _delegates[_to], _amount); } // Copied and modified from YAM code: // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol // Which is copied and modified from COMPOUND: // https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol /// @notice A record of each accounts delegate mapping(address => address) internal _delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint256 votes; } /// @notice A record of votes checkpoints for each account, by index mapping(address => mapping(uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping(address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256( "EIP712Domain(string name,uint256 chainId,address verifyingContract)" ); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256( "Delegation(address delegatee,uint256 nonce,uint256 expiry)" ); /// @notice A record of states for signing / validating signatures mapping(address => uint256) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged( address indexed delegator, address indexed fromDelegate, address indexed toDelegate ); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged( address indexed delegate, uint256 previousBalance, uint256 newBalance ); /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegator The address to get delegatee for */ function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry) ); bytes32 digest = keccak256( abi.encodePacked("\x19\x01", domainSeparator, structHash) ); address signatory = ecrecover(digest, v, r, s); require( signatory != address(0), "NEKO::delegateBySig: invalid signature" ); require( nonce == nonces[signatory]++, "NEKO::delegateBySig: invalid nonce" ); require(now <= expiry, "NEKO::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint256) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint256 blockNumber) external view returns (uint256) { require( blockNumber < block.number, "NEKO::getPriorVotes: not yet determined" ); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; uint256 delegatorBalance = balanceOf(delegator); // balance of underlying NEKOs (not scaled); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates( address srcRep, address dstRep, uint256 amount ) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { // decrease old representative uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // increase new representative uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32( block.number, "NEKO::_writeCheckpoint: block number exceeds 32 bits" ); if ( nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber ) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint( blockNumber, newVotes ); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function getChainId() internal pure returns (uint256) { uint256 chainId; assembly { chainId := chainid() } return chainId; } } // File: contracts/MasterChef.sol pragma solidity 0.6.12; interface IMigratorChef { // Perform LP token migration from legacy UniswapV2 to NekoSwap. // Take the current LP token address and return the new LP token address. // Migrator should have full access to the caller's LP token. // Return the new LP token address. // // XXX Migrator must have allowance access to UniswapV2 LP tokens. // NekoSwap must mint EXACTLY the same amount of NekoSwap LP tokens or // else something bad will happen. Traditional UniswapV2 does not // do that so be careful! function migrate(IERC20 token) external returns (IERC20); } // MasterChef is the master of Neko. He can make Neko and he is a fair guy. // // Note that it's ownable and the owner wields tremendous power. The ownership // will be transferred to a governance smart contract once NEKO is sufficiently // distributed and the community can show to govern itself. // // Have fun reading it. Hopefully it's bug-free. God bless. contract MasterChef is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of NEKOs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accNekoPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accNekoPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. NEKOs to distribute per block. uint256 lastRewardBlock; // Last block number that NEKOs distribution occurs. uint256 accNekoPerShare; // Accumulated NEKOs per share, times 1e12. See below. } // The NEKO TOKEN! NekoToken public neko; // Dev address. address public devaddr; // Block number when bonus NEKO period ends. uint256 public bonusEndBlock; // NEKO tokens created per block. uint256 public nekoPerBlock; // Bonus muliplier for early neko makers. uint256 public constant BONUS_MULTIPLIER = 50; // The migrator contract. It has a lot of power. Can only be set through governance (owner). IMigratorChef public migrator; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping(uint256 => mapping(address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when NEKO mining starts. uint256 public startBlock; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw( address indexed user, uint256 indexed pid, uint256 amount ); constructor( NekoToken _neko, address _devaddr, uint256 _nekoPerBlock, uint256 _startBlock, uint256 _bonusEndBlock ) public { neko = _neko; devaddr = _devaddr; nekoPerBlock = _nekoPerBlock; bonusEndBlock = _bonusEndBlock; startBlock = _startBlock; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add( uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate ) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push( PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accNekoPerShare: 0 }) ); } // Update the given pool's NEKO allocation point. Can only be called by the owner. function set( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add( _allocPoint ); poolInfo[_pid].allocPoint = _allocPoint; } // Set the migrator contract. Can only be called by the owner. function setMigrator(IMigratorChef _migrator) public onlyOwner { migrator = _migrator; } // Migrate lp token to another lp contract. Can be called by anyone. We trust that migrator contract is good. function migrate(uint256 _pid) public { require(address(migrator) != address(0), "migrate: no migrator"); PoolInfo storage pool = poolInfo[_pid]; IERC20 lpToken = pool.lpToken; uint256 bal = lpToken.balanceOf(address(this)); lpToken.safeApprove(address(migrator), bal); IERC20 newLpToken = migrator.migrate(lpToken); require(bal == newLpToken.balanceOf(address(this)), "migrate: bad"); pool.lpToken = newLpToken; } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (_to <= bonusEndBlock) { return _to.sub(_from).mul(BONUS_MULTIPLIER); } else if (_from >= bonusEndBlock) { return _to.sub(_from); } else { return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add( _to.sub(bonusEndBlock) ); } } // View function to see pending NEKOs on frontend. function pendingNeko(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accNekoPerShare = pool.accNekoPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier( pool.lastRewardBlock, block.number ); uint256 nekoReward = multiplier .mul(nekoPerBlock) .mul(pool.allocPoint) .div(totalAllocPoint); accNekoPerShare = accNekoPerShare.add( nekoReward.mul(1e12).div(lpSupply) ); } return user.amount.mul(accNekoPerShare).div(1e12).sub(user.rewardDebt); } // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 nekoReward = multiplier .mul(nekoPerBlock) .mul(pool.allocPoint) .div(totalAllocPoint); neko.mint(devaddr, nekoReward.div(10)); neko.mint(address(this), nekoReward); pool.accNekoPerShare = pool.accNekoPerShare.add( nekoReward.mul(1e12).div(lpSupply) ); pool.lastRewardBlock = block.number; } // Deposit LP tokens to MasterChef for NEKO allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user .amount .mul(pool.accNekoPerShare) .div(1e12) .sub(user.rewardDebt); safeNekoTransfer(msg.sender, pending); } pool.lpToken.safeTransferFrom( address(msg.sender), address(this), _amount ); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accNekoPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accNekoPerShare).div(1e12).sub( user.rewardDebt ); safeNekoTransfer(msg.sender, pending); user.amount = user.amount.sub(_amount); user.rewardDebt = user.amount.mul(pool.accNekoPerShare).div(1e12); pool.lpToken.safeTransfer(address(msg.sender), _amount); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; pool.lpToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; } // Safe neko transfer function, just in case if rounding error causes pool to not have enough NEKOs. function safeNekoTransfer(address _to, uint256 _amount) internal { uint256 nekoBal = neko.balanceOf(address(this)); if (_amount > nekoBal) { neko.transfer(_to, nekoBal); } else { neko.transfer(_to, _amount); } } // Update dev address by the previous dev. function dev(address _devaddr) public { require(msg.sender == devaddr, "dev: wut?"); devaddr = _devaddr; } }
View function to see pending NEKOs on frontend.
function pendingNeko(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accNekoPerShare = pool.accNekoPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier( pool.lastRewardBlock, block.number ); uint256 nekoReward = multiplier .mul(nekoPerBlock) .mul(pool.allocPoint) .div(totalAllocPoint); accNekoPerShare = accNekoPerShare.add( nekoReward.mul(1e12).div(lpSupply) ); } return user.amount.mul(accNekoPerShare).div(1e12).sub(user.rewardDebt); }
7,954,921
[ 1, 1767, 445, 358, 2621, 4634, 423, 11325, 15112, 603, 15442, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 4634, 50, 3839, 83, 12, 11890, 5034, 389, 6610, 16, 1758, 389, 1355, 13, 203, 3639, 3903, 203, 3639, 1476, 203, 3639, 1135, 261, 11890, 5034, 13, 203, 565, 288, 203, 3639, 8828, 966, 2502, 2845, 273, 2845, 966, 63, 67, 6610, 15533, 203, 3639, 25003, 2502, 729, 273, 16753, 63, 67, 6610, 6362, 67, 1355, 15533, 203, 3639, 2254, 5034, 4078, 50, 3839, 83, 2173, 9535, 273, 2845, 18, 8981, 50, 3839, 83, 2173, 9535, 31, 203, 3639, 2254, 5034, 12423, 3088, 1283, 273, 2845, 18, 9953, 1345, 18, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 3639, 309, 261, 2629, 18, 2696, 405, 2845, 18, 2722, 17631, 1060, 1768, 597, 12423, 3088, 1283, 480, 374, 13, 288, 203, 5411, 2254, 5034, 15027, 273, 31863, 5742, 12, 203, 7734, 2845, 18, 2722, 17631, 1060, 1768, 16, 203, 7734, 1203, 18, 2696, 203, 5411, 11272, 203, 5411, 2254, 5034, 1073, 28179, 17631, 1060, 273, 15027, 203, 7734, 263, 16411, 12, 82, 3839, 83, 2173, 1768, 13, 203, 7734, 263, 16411, 12, 6011, 18, 9853, 2148, 13, 203, 7734, 263, 2892, 12, 4963, 8763, 2148, 1769, 203, 5411, 4078, 50, 3839, 83, 2173, 9535, 273, 4078, 50, 3839, 83, 2173, 9535, 18, 1289, 12, 203, 7734, 1073, 28179, 17631, 1060, 18, 16411, 12, 21, 73, 2138, 2934, 2892, 12, 9953, 3088, 1283, 13, 203, 5411, 11272, 203, 3639, 289, 203, 3639, 327, 729, 18, 8949, 18, 16411, 12, 8981, 50, 3839, 83, 2173, 9535, 2934, 2892, 12, 21, 73, 2138, 2934, 1717, 12, 2 ]
pragma solidity 0.5.17; interface IERC20 { function totalSupply() external view returns (uint); function balanceOf(address account) external view returns (uint); function transfer(address recipient, uint amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint amount) external returns (bool); function transferFrom(address sender, address recipient, uint amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } contract Context { constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } } contract ERC20 is Context, IERC20 { using SafeMath for uint; mapping (address => uint) private _balances; mapping (address => mapping (address => uint)) private _allowances; uint private _totalSupply; function totalSupply() public view returns (uint) { return _totalSupply; } function balanceOf(address account) public view returns (uint) { return _balances[account]; } function transfer(address recipient, uint amount) public returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view returns (uint) { return _allowances[owner][spender]; } function approve(address spender, uint amount) public returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint addedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint subtractedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint amount) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } } contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor (string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } } library Address { function isContract(address account) internal view returns (bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } } library SafeERC20 { using SafeMath for uint; using Address for address; function safeTransfer(IERC20 token, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint value) internal { require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } library SignedSafeMath { int256 constant private _INT256_MIN = -2**255; function mul(int256 a, int256 b) internal pure returns (int256) { if (a == 0) { return 0; } require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow"); int256 c = a * b; require(c / a == b, "SignedSafeMath: multiplication overflow"); return c; } function div(int256 a, int256 b) internal pure returns (int256) { require(b != 0, "SignedSafeMath: division by zero"); require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow"); int256 c = a / b; return c; } function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow"); return c; } function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow"); return c; } function sqrt(int256 x) internal pure returns (int256) { int256 z = add(x / 2, 1); int256 y = x; while (z < y) { y = z; z = ((add((x / z), z)) / 2); } return y; } } contract CreamY is ERC20, ERC20Detailed { event LOG_SWAP( address indexed caller, address indexed tokenIn, address indexed tokenOut, uint tokenAmountIn, uint tokenAmountOut ); event LOG_JOIN( address indexed caller, address indexed tokenIn, uint tokenAmountIn ); event LOG_EXIT( address indexed caller, address indexed tokenOut, uint tokenAmountOut ); using SafeMath for uint; using SignedSafeMath for int256; using SafeERC20 for IERC20; mapping(address => bool) public coins; mapping(address => bool) public pause; IERC20[] public allCoins; Normalizer public normalizer; address public governance; address public reservePool; constructor(address _normalizer, address _reservePool) public ERC20Detailed("CreamY USD", "cyUSD", 18) { governance = msg.sender; normalizer = Normalizer(_normalizer); reservePool = _reservePool; } function setGovernance(address _governance) external { require(msg.sender == governance, "!governance"); governance = _governance; } function setNormalizer(address _normalizer) external { require(msg.sender == governance, "!governance"); normalizer = Normalizer(_normalizer); } function setReservePool(address _reservePool) external { require(msg.sender == governance, "!governance"); require(_reservePool != address(0), "invalid reserve pool"); reservePool = _reservePool; } function setFees(uint _fee, uint _reserveRatio) external { require(msg.sender == governance, '!governance'); require(_fee < 1e18 && _fee >= 0.99e18, 'Invalid fee'); // 0 < fee <= 1% if (_reserveRatio > 0) { require(_reserveRatio <= 1e18, 'Invalid reserve ratio'); // reserve ratio <= 100% fee } fee = _fee; reserveRatio = _reserveRatio; } function approveCoins(address _coin) external { require(msg.sender == governance, "!governance"); require(coins[_coin] == false, "Already approved"); coins[_coin] = true; allCoins.push(IERC20(_coin)); } function setPause(address _coin, bool _pause) external { require(msg.sender == governance, "!governance"); pause[_coin] = _pause; } function setA(uint _A) external { require(msg.sender == governance, "!governance"); require(_A > 0 && _A <= 1e18, "Invalid A"); // When A is close to 1, it becomes the fixed price model (x + y = k). // When A is close to 0, it degenerates to Uniswap (x * y = k). // However, A couldn't be exactly 0 since it will break the f function. A = _A; } function seize(IERC20 token, uint amount) external { require(msg.sender == governance, "!governance"); require(!tokens[address(token)], "can't seize liquidity"); uint bal = token.balanceOf(address(this)); require(amount <= bal); token.safeTransfer(reservePool, amount); } uint public fee = 0.99965e18; uint public reserveRatio = 1e18; uint public constant BASE = 1e18; uint public A = 0.7e18; uint public count = 0; mapping(address => bool) tokens; function f(int256 _x, int256 x, int256 y) internal view returns (int256 _y) { int256 k; int256 c; { int256 u = x.add(y.mul(int256(A)).div(1e18)); int256 v = y.add(x.mul(int256(A)).div(1e18)); k = u.mul(v); c = _x.mul(_x).sub(k.mul(1e18).div(int256(A))); } int256 cst = int256(A).add(int256(1e36).div(int256(A))); int256 _b = _x.mul(cst).div(1e18); int256 D = _b.mul(_b).sub(c.mul(4)); require(D >= 0, "!root"); _y = (-_b).add(D.sqrt()).div(2); } function collectReserve(IERC20 from, uint input) internal { if (reserveRatio > 0) { uint _fee = input.mul(BASE.sub(fee)).div(BASE); uint _reserve = _fee.mul(reserveRatio).div(BASE); from.safeTransfer(reservePool, _reserve); } } // Get all support coins function getAllCoins() public view returns (IERC20[] memory) { return allCoins; } // Calculate total pool value in USD function calcTotalValue() public view returns (uint value) { uint totalValue = uint(0); for (uint i = 0; i < allCoins.length; i++) { totalValue = totalValue.add(balance(allCoins[i])); } return totalValue; } // Calculate _x given x, y, _y function getX(int256 output, int256 x, int256 y) internal view returns (int256 input) { int256 _y = y.sub(output); int256 _x = f(_y, y, x); input = _x.sub(x); } // Calculate _y given x, y, _x function getY(int256 input, int256 x, int256 y) internal view returns (int256 output) { int256 _x = x.add(input); int256 _y = f(_x, x, y); output = y.sub(_y); } // Calculate output given exact input function getOutExactIn(IERC20 from, IERC20 to, uint input, int256 x, int256 y) public view returns (uint output) { uint inputInUsd = normalize1e18(from, input).mul(normalizer.getPrice(address(from))).div(1e18); uint inputAfterFeeInUsd = inputInUsd.mul(fee).div(BASE); uint outputInUsd = uint(getY(i(inputAfterFeeInUsd), x, y)); output = normalize(to, outputInUsd.mul(1e18).div(normalizer.getPrice(address(to)))); } // Calculate input given exact output function getInExactOut(IERC20 from, IERC20 to, uint output, int256 x, int256 y) public view returns (uint input) { uint outputInUsd = normalize1e18(to, output).mul(normalizer.getPrice(address(to))).div(1e18); uint inputBeforeFeeInUsd = uint(getX(i(outputInUsd), x, y)); uint inputInUsd = inputBeforeFeeInUsd.mul(BASE).div(fee); input = normalize(from, inputInUsd.mul(1e18).div(normalizer.getPrice(address(from)))); } // Normalize coin to 1e18 function normalize1e18(IERC20 token, uint _amount) internal view returns (uint) { uint _decimals = ERC20Detailed(address(token)).decimals(); if (_decimals == uint(18)) { return _amount; } else { return _amount.mul(1e18).div(uint(10)**_decimals); } } // Normalize coin to original decimals function normalize(IERC20 token, uint _amount) internal view returns (uint) { uint _decimals = ERC20Detailed(address(token)).decimals(); if (_decimals == uint(18)) { return _amount; } else { return _amount.mul(uint(10)**_decimals).div(1e18); } } // Contract balance of coin normalized to 1e18 function balance(IERC20 token) public view returns (uint) { address _token = address(token); uint _balance = IERC20(_token).balanceOf(address(this)); uint _balanceInUsd = _balance.mul(normalizer.getPrice(_token)).div(1e18); return normalize1e18(token, _balanceInUsd); } // Converter helper to int256 function i(uint x) public pure returns (int256) { int256 value = int256(x); require(value >= 0, 'overflow'); return value; } function swapExactAmountIn(IERC20 from, IERC20 to, uint input, uint minOutput, uint deadline) external returns (uint output) { require(coins[address(from)] == true, "!coin"); require(pause[address(from)] == false, "pause"); require(coins[address(to)] == true, "!coin"); require(pause[address(to)] == false, "pause"); require(normalizer.getPrice(address(from)) > 0, "zero price"); require(normalizer.getPrice(address(to)) > 0, "zero price"); require(block.timestamp <= deadline, "expired"); output = getOutExactIn(from, to, input, i(balance(from)), i(balance(to))); require(balance(to) >= output, "insufficient output liquidity"); require(output >= minOutput, "slippage"); emit LOG_SWAP(msg.sender, address(from), address(to), input, output); from.safeTransferFrom(msg.sender, address(this), input); to.safeTransfer(msg.sender, output); collectReserve(from, input); return output; } function swapExactAmountOut(IERC20 from, IERC20 to, uint maxInput, uint output, uint deadline) external returns (uint input) { require(coins[address(from)] == true, "!coin"); require(pause[address(from)] == false, "pause"); require(coins[address(to)] == true, "!coin"); require(pause[address(to)] == false, "pause"); require(normalizer.getPrice(address(from)) > 0, "zero price"); require(normalizer.getPrice(address(to)) > 0, "zero price"); require(block.timestamp <= deadline, "expired"); require(balance(to) >= output, "insufficient output liquidity"); input = getInExactOut(from, to, output, i(balance(from)), i(balance(to))); require(input <= maxInput, "slippage"); emit LOG_SWAP(msg.sender, address(from), address(to), input, output); from.safeTransferFrom(msg.sender, address(this), input); to.safeTransfer(msg.sender, output); collectReserve(from, input); return input; } function addLiquidityExactIn(IERC20 from, uint input, uint minOutput, uint deadline) external returns (uint output) { require(coins[address(from)] == true, "!coin"); require(pause[address(from)] == false, "pause"); require(block.timestamp <= deadline, "expired"); require(input > 0, "zero input"); require(normalizer.getPrice(address(from)) > 0, "zero price"); require(normalizer.getPrice(address(this)) > 0, "zero price"); if (totalSupply() == 0) { uint inputAfterFee = input.mul(fee).div(BASE); output = normalize1e18(from, inputAfterFee.mul(normalizer.getPrice(address(from))).div(1e18)); } else { output = getOutExactIn(from, this, input, i(balance(from)), i(totalSupply().div(count))); } require(output >= minOutput, "slippage"); emit LOG_JOIN(msg.sender, address(from), output); from.safeTransferFrom(msg.sender, address(this), input); _mint(msg.sender, output); if (!tokens[address(from)] && balance(from) > 0) { tokens[address(from)] = true; count = count.add(1); } } function addLiquidityExactOut(IERC20 from, uint maxInput, uint output, uint deadline) external returns (uint input) { require(coins[address(from)] == true, "!coin"); require(pause[address(from)] == false, "pause"); require(block.timestamp <= deadline, "expired"); require(output > 0, "zero output"); require(normalizer.getPrice(address(from)) > 0, "zero price"); require(normalizer.getPrice(address(this)) > 0, "zero price"); if (totalSupply() == 0) { uint inputAfterFee = normalize(from, output.mul(1e18).div(normalizer.getPrice(address(from)))); input = inputAfterFee.mul(BASE).divCeil(fee); } else { input = getInExactOut(from, this, output, i(balance(from)), i(totalSupply().div(count))); } require(input <= maxInput, "slippage"); emit LOG_JOIN(msg.sender, address(from), output); from.safeTransferFrom(msg.sender, address(this), input); _mint(msg.sender, output); if (!tokens[address(from)] && balance(from) > 0) { tokens[address(from)] = true; count = count.add(1); } } function removeLiquidityExactIn(IERC20 to, uint input, uint minOutput, uint deadline) external returns (uint output) { require(block.timestamp <= deadline, "expired"); require(coins[address(to)] == true, "!coin"); require(input > 0, "zero input"); require(normalizer.getPrice(address(this)) > 0, "zero price"); require(normalizer.getPrice(address(to)) > 0, "zero price"); output = getOutExactIn(this, to, input, i(totalSupply().div(count)), i(balance(to))); require(output >= minOutput, "slippage"); emit LOG_EXIT(msg.sender, address(to), output); _burn(msg.sender, input); to.safeTransfer(msg.sender, output); if (balance(to) == 0) { tokens[address(to)] = false; count = count.sub(1); } } function removeLiquidityExactOut(IERC20 to, uint maxInput, uint output, uint deadline) external returns (uint input) { require(block.timestamp <= deadline, "expired"); require(coins[address(to)] == true, "!coin"); require(output > 0, "zero output"); require(normalizer.getPrice(address(this)) > 0, "zero price"); require(normalizer.getPrice(address(to)) > 0, "zero price"); input = getInExactOut(this, to, output, i(totalSupply().div(count)), i(balance(to))); require(input <= maxInput, "slippage"); emit LOG_EXIT(msg.sender, address(to), output); _burn(msg.sender, input); to.safeTransfer(msg.sender, output); if (balance(to) == 0) { tokens[address(to)] = false; count = count.sub(1); } } } interface Curve { function get_virtual_price() external view returns (uint); } interface Yearn { function getPricePerFullShare() external view returns (uint); } interface UnderlyingToken { function decimals() external view returns (uint8); } interface Compound { function exchangeRateStored() external view returns (uint); function underlying() external view returns (address); } interface Cream { function exchangeRateStored() external view returns (uint); function underlying() external view returns (address); } contract Normalizer { using SafeMath for uint; address public governance; address public creamY; mapping(address => bool) public native; mapping(address => bool) public yearn; mapping(address => bool) public curve; mapping(address => address) public curveSwap; mapping(address => bool) public vaults; mapping(address => bool) public compound; mapping(address => bool) public cream; mapping(address => uint) public underlyingDecimals; constructor() public { governance = msg.sender; native[0xdAC17F958D2ee523a2206206994597C13D831ec7] = true; // USDT native[0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48] = true; // USDC native[0x4Fabb145d64652a948d72533023f6E7A623C7C53] = true; // BUSD native[0x0000000000085d4780B73119b644AE5ecd22b376] = true; // TUSD yearn[0xACd43E627e64355f1861cEC6d3a6688B31a6F952] = true; // vault yDAI yearn[0x37d19d1c4E1fa9DC47bD1eA12f742a0887eDa74a] = true; // vault yTUSD yearn[0x597aD1e0c13Bfe8025993D9e79C69E1c0233522e] = true; // vault yUSDC yearn[0x2f08119C6f07c006695E079AAFc638b8789FAf18] = true; // vault yUSDT yearn[0x16de59092dAE5CcF4A1E6439D611fd0653f0Bd01] = true; // yDAI yearn[0xd6aD7a6750A7593E092a9B218d66C0A814a3436e] = true; // yUSDC yearn[0x83f798e925BcD4017Eb265844FDDAbb448f1707D] = true; // yUSDT yearn[0x73a052500105205d34Daf004eAb301916DA8190f] = true; // yTUSD yearn[0xF61718057901F84C4eEC4339EF8f0D86D2B45600] = true; // ySUSD yearn[0xC2cB1040220768554cf699b0d863A3cd4324ce32] = true; // bDAI yearn[0x26EA744E5B887E5205727f55dFBE8685e3b21951] = true; // bUSDC yearn[0xE6354ed5bC4b393a5Aad09f21c46E101e692d447] = true; // bUSDT yearn[0x04bC0Ab673d88aE9dbC9DA2380cB6B79C4BCa9aE] = true; // bBUSD curve[0x845838DF265Dcd2c412A1Dc9e959c7d08537f8a2] = true; // cCompound curveSwap[0x845838DF265Dcd2c412A1Dc9e959c7d08537f8a2] = 0xA2B47E3D5c44877cca798226B7B8118F9BFb7A56; curve[0xdF5e0e81Dff6FAF3A7e52BA697820c5e32D806A8] = true; // cYearn curveSwap[0xdF5e0e81Dff6FAF3A7e52BA697820c5e32D806A8] = 0x45F783CCE6B7FF23B2ab2D70e416cdb7D6055f51; curve[0x3B3Ac5386837Dc563660FB6a0937DFAa5924333B] = true; // cBUSD curveSwap[0x3B3Ac5386837Dc563660FB6a0937DFAa5924333B] = 0x79a8C46DeA5aDa233ABaFFD40F3A0A2B1e5A4F27; curve[0xC25a3A3b969415c80451098fa907EC722572917F] = true; // cSUSD curveSwap[0xC25a3A3b969415c80451098fa907EC722572917F] = 0xA5407eAE9Ba41422680e2e00537571bcC53efBfD; curve[0xD905e2eaeBe188fc92179b6350807D8bd91Db0D8] = true; // cPAX curveSwap[0xD905e2eaeBe188fc92179b6350807D8bd91Db0D8] = 0x06364f10B501e868329afBc005b3492902d6C763; compound[0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643] = true; // cDAI underlyingDecimals[0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643] = 1e18; compound[0x39AA39c021dfbaE8faC545936693aC917d5E7563] = true; // cUSDC underlyingDecimals[0x39AA39c021dfbaE8faC545936693aC917d5E7563] = 1e6; compound[0xf650C3d88D12dB855b8bf7D11Be6C55A4e07dCC9] = true; // cUSDT underlyingDecimals[0xf650C3d88D12dB855b8bf7D11Be6C55A4e07dCC9] = 1e6; cream[0x44fbeBd2F576670a6C33f6Fc0B00aA8c5753b322] = true; // crUSDC underlyingDecimals[0x44fbeBd2F576670a6C33f6Fc0B00aA8c5753b322] = 1e6; cream[0x797AAB1ce7c01eB727ab980762bA88e7133d2157] = true; // crUSDT underlyingDecimals[0x797AAB1ce7c01eB727ab980762bA88e7133d2157] = 1e6; cream[0x1FF8CDB51219a8838b52E9cAc09b71e591BC998e] = true; // crBUSD underlyingDecimals[0x1FF8CDB51219a8838b52E9cAc09b71e591BC998e] = 1e18; } function setGovernance(address _governance) external { require(msg.sender == governance, "!governance"); governance = _governance; } function setCreamY(address _creamY) external { require(msg.sender == governance, "!governance"); creamY = _creamY; } function getPrice(address token) external view returns (uint) { if (native[token] || token == creamY) { return 1e18; } else if (yearn[token]) { return Yearn(token).getPricePerFullShare(); } else if (curve[token]) { return Curve(curveSwap[token]).get_virtual_price(); } else if (compound[token]) { return getCompoundPrice(token); } else if (cream[token]) { return getCreamPrice(token); } else { return uint(0); } } function getCompoundPrice(address token) public view returns (uint) { address underlying = Compound(token).underlying(); uint8 decimals = UnderlyingToken(underlying).decimals(); return Compound(token).exchangeRateStored().mul(1e8).div(uint(10) ** decimals); } function getCreamPrice(address token) public view returns (uint) { address underlying = Cream(token).underlying(); uint8 decimals = UnderlyingToken(underlying).decimals(); return Cream(token).exchangeRateStored().mul(1e8).div(uint(10) ** decimals); } } library SafeMath { function add(uint a, uint b) internal pure returns (uint) { uint c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint a, uint b) internal pure returns (uint) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint a, uint b, string memory errorMessage) internal pure returns (uint) { require(b <= a, errorMessage); uint c = a - b; return c; } function mul(uint a, uint b) internal pure returns (uint) { if (a == 0) { return 0; } uint c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint a, uint b) internal pure returns (uint) { return div(a, b, "SafeMath: division by zero"); } function div(uint a, uint b, string memory errorMessage) internal pure returns (uint) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint c = a / b; return c; } function divCeil(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); uint256 c = a / b; if(a % b != 0) c = c + 1; return c; } }
solhint-disable-next-line no-inline-assembly
function isContract(address account) internal view returns (bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; return (codehash != 0x0 && codehash != accountHash); }
7,358,926
[ 1, 18281, 11317, 17, 8394, 17, 4285, 17, 1369, 1158, 17, 10047, 17, 28050, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 353, 8924, 12, 2867, 2236, 13, 2713, 1476, 1135, 261, 6430, 13, 288, 203, 203, 3639, 1731, 1578, 981, 2816, 31, 203, 203, 3639, 1731, 1578, 2236, 2310, 273, 374, 6511, 25, 72, 3247, 26, 1611, 5292, 74, 9060, 3707, 71, 29, 5324, 73, 27, 1966, 22, 72, 952, 27, 4630, 71, 20, 73, 12483, 70, 26, 8643, 5353, 24532, 9036, 70, 27, 17156, 361, 28, 3028, 25, 72, 7140, 69, 24, 7301, 31, 203, 203, 203, 203, 3639, 327, 261, 710, 2816, 480, 374, 92, 20, 597, 981, 2816, 480, 2236, 2310, 1769, 203, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2021-04-23 */ pragma solidity 0.6.6; // SPDX-License-Identifier: MIT /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT abstract contract ReentrancyGuard { uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() public { _status = _NOT_ENTERED; } modifier nonReentrant() { require(_status != _ENTERED, "REENTRANCY_ERROR"); _status = _ENTERED; _; _status = _NOT_ENTERED; } } // SPDX-License-Identifier: GPL-3.0-or-later // Interface declarations /* solhint-disable func-order */ interface IUniswapRouter { function addLiquidity( address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns ( uint256 amountA, uint256 amountB, uint256 liquidity ); function addLiquidityETH( address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external payable returns ( uint256 amountToken, uint256 amountETH, uint256 liquidity ); function removeLiquidityETH( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external returns (uint256 amountToken, uint256 amountETH); function removeLiquidity( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns (uint256 amountA, uint256 amountB); function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts); function swapExactETHForTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function swapExactTokensForETH( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); } // SPDX-License-Identifier: MIT interface IHarvestVault { function deposit(uint256 amount) external; function withdraw(uint256 numberOfShares) external; } // SPDX-License-Identifier: MIT interface IMintNoRewardPool { function stake(uint256 amount) external; function withdraw(uint256 amount) external; function earned(address account) external view returns (uint256); function lastTimeRewardApplicable() external view returns (uint256); function rewardPerToken() external view returns (uint256); function rewards(address account) external view returns (uint256); function userRewardPerTokenPaid(address account) external view returns (uint256); function lastUpdateTime() external view returns (uint256); function rewardRate() external view returns (uint256); function totalSupply() external view returns (uint256); function rewardPerTokenStored() external view returns (uint256); function periodFinish() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function getReward() external; } // SPDX-License-Identifier: MIT /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: MIT /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context { using EnumerableSet for EnumerableSet.AddressSet; using Address for address; struct RoleData { EnumerableSet.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, _roles[role].adminRole, adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } } // SPDX-License-Identifier: MIT /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // This contract is used for printing receipt tokens // Whenever someone joins a pool, a receipt token will be printed for that person contract ReceiptToken is ERC20, AccessControl { bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); bytes32 public constant BURNER_ROLE = keccak256("BURNER_ROLE"); constructor() public ERC20("pAT", "Parachain Auction Token") { // Grant the contract deployer the default admin role: it will be able // to grant and revoke any roles _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); } /** * @notice Mint new receipt tokens to some user * @param to Address of the user that gets the receipt tokens * @param amount Amount of receipt tokens that will get minted */ function mint(address to, uint256 amount) public { require( hasRole(MINTER_ROLE, msg.sender), "ReceiptToken: Caller is not a minter" ); _mint(to, amount); } /** * @notice Burn receipt tokens from some user * @param from Address of the user that gets the receipt tokens burne * @param amount Amount of receipt tokens that will get burned */ function burn(address from, uint256 amount) public { require( hasRole(BURNER_ROLE, msg.sender), "ReceiptToken: Caller is not a burner" ); _burn(from, amount); } } // SPDX-License-Identifier: MIT /* |Strategy Flow| - User shows up with DAI and we deposit it in Havest's Vault. - After this we have fDAI that we add in Harvest's Reward Pool which gives FARM as rewards - Withdrawal flow does same thing, but backwards - User can obtain extra DAI when withdrawing. 50% of them goes to the user, 50% goes to the treasury in ETH - User can obtain FARM tokens when withdrawing. 50% of them goes to the user in DAI, 50% goes to the treasury in ETH */ contract HarvestDAIStableCoin is Ownable, ReentrancyGuard { using SafeERC20 for IERC20; using SafeMath for uint256; struct UserDeposits { uint256 timestamp; uint256 amountfDai; } /// @notice Info of each user. struct UserInfo { uint256 amountDai; //how much DAI the user entered with uint256 amountfDai; //how much fDAI was obtained after deposit to vault uint256 amountReceiptToken; //receipt tokens printed for user; should be equal to amountfDai uint256 underlyingRatio; //ratio between obtained fDai and dai uint256 userTreasuryEth; //how much eth the user sent to treasury uint256 userCollectedFees; //how much eth the user sent to fee address uint256 joinTimestamp; //first deposit timestamp; taken into account for lock time bool wasUserBlacklisted; //if user was blacklist at deposit time, he is not receiving receipt tokens uint256 timestamp; //first deposit timestamp; used for withdrawal lock time check UserDeposits[] deposits; uint256 earnedTokens; //before fees uint256 earnedRewards; //before fees } mapping(address => UserInfo) public userInfo; mapping(address => bool) public blacklisted; //blacklisted users do not receive a receipt token uint256 public firstDepositTimestamp; //used to calculate reward per block uint256 public totalDeposits; uint256 public cap = uint256(1000000); //eth cap uint256 public totalDai; //total invested eth uint256 public lockTime = 10368000; //120 days address payable public feeAddress; uint256 public fee = uint256(50); uint256 constant feeFactor = uint256(10000); ReceiptToken public receiptToken; address public dai; address public weth; address public farmToken; address public harvestPoolToken; address payable public treasuryAddress; IMintNoRewardPool public harvestRewardPool; //deposit fDai IHarvestVault public harvestRewardVault; //get fDai IUniswapRouter public sushiswapRouter; uint256 public ethDust; uint256 public treasueryEthDust; //events event RewardsExchanged( address indexed user, string exchangeType, //ETH or DAI uint256 rewardsAmount, uint256 obtainedAmount ); event ExtraTokensExchanged( address indexed user, uint256 tokensAmount, uint256 obtainedEth ); event ObtainedInfo( address indexed user, uint256 underlying, uint256 underlyingReceipt ); event RewardsEarned(address indexed user, uint256 amount); event ExtraTokens(address indexed user, uint256 amount); event FeeSet(address indexed sender, uint256 feeAmount); event FeeAddressSet(address indexed sender, address indexed feeAddress); /// @notice Event emitted when blacklist status for an address changes event BlacklistChanged( string actionType, address indexed user, bool oldVal, bool newVal ); /// @notice Event emitted when user makes a deposit and receipt token is minted event ReceiptMinted(address indexed user, uint256 amount); /// @notice Event emitted when user withdraws and receipt token is burned event ReceiptBurned(address indexed user, uint256 amount); /// @notice Event emitted when user makes a deposit event Deposit( address indexed user, address indexed origin, uint256 amountDai, uint256 amountfDai ); /// @notice Event emitted when user withdraws event Withdraw( address indexed user, address indexed origin, uint256 amountDai, uint256 amountfDai, uint256 treasuryAmountEth ); /// @notice Event emitted when owner makes a rescue dust request event RescuedDust(string indexed dustType, uint256 amount); /// @notice Event emitted when owner changes any contract address event ChangedAddress( string indexed addressType, address indexed oldAddress, address indexed newAddress ); //internal mapping(address => bool) public approved; //to defend against non whitelisted contracts /// @notice Used internally for avoiding "stack-too-deep" error when depositing struct DepositData { address[] swapPath; uint256[] swapAmounts; uint256 obtainedDai; uint256 obtainedfDai; uint256 prevfDaiBalance; } /// @notice Used internally for avoiding "stack-too-deep" error when withdrawing struct WithdrawData { uint256 prevDustEthBalance; uint256 prevfDaiBalance; uint256 prevDaiBalance; uint256 obtainedfDai; uint256 obtainedDai; uint256 feeableDai; uint256 auctionedEth; uint256 auctionedDai; uint256 totalDai; uint256 rewards; uint256 farmBalance; } /** * @notice Create a new HarvestDAI contract * @param _harvestRewardVault VaultDAI address * @param _harvestRewardPool NoMintRewardPool address * @param _sushiswapRouter Sushiswap Router address * @param _harvestPoolToken Pool's underlying token address * @param _farmToken Farm address * @param _dai DAI address * @param _weth WETH address * @param _treasuryAddress treasury address * @param _receiptToken Receipt token that is minted and burned * @param _feeAddress fee address */ constructor( address _harvestRewardVault, address _harvestRewardPool, address _sushiswapRouter, address _harvestPoolToken, address _farmToken, address _dai, address _weth, address payable _treasuryAddress, address _receiptToken, address payable _feeAddress ) public { require(_harvestRewardVault != address(0), "VAULT_0x0"); require(_harvestRewardPool != address(0), "POOL_0x0"); require(_sushiswapRouter != address(0), "ROUTER_0x0"); require(_harvestPoolToken != address(0), "TOKEN_0x0"); require(_farmToken != address(0), "FARM_0x0"); require(_dai != address(0), "DAI_0x0"); require(_weth != address(0), "WETH_0x0"); require(_treasuryAddress != address(0), "TREASURY_0x0"); require(_receiptToken != address(0), "RECEIPT_0x0"); require(_feeAddress != address(0), "FEE_0x0"); harvestRewardVault = IHarvestVault(_harvestRewardVault); harvestRewardPool = IMintNoRewardPool(_harvestRewardPool); sushiswapRouter = IUniswapRouter(_sushiswapRouter); harvestPoolToken = _harvestPoolToken; farmToken = _farmToken; dai = _dai; weth = _weth; treasuryAddress = _treasuryAddress; receiptToken = ReceiptToken(_receiptToken); feeAddress = _feeAddress; } //-----------------------------------------------------------------------------------------------------------------// //------------------------------------ Setters -------------------------------------------------// //-----------------------------------------------------------------------------------------------------------------// /** * @notice Update the address of VaultDAI * @dev Can only be called by the owner * @param _harvestRewardVault Address of VaultDAI */ function setHarvestRewardVault(address _harvestRewardVault) public onlyOwner { require(_harvestRewardVault != address(0), "VAULT_0x0"); emit ChangedAddress( "VAULT", address(harvestRewardVault), _harvestRewardVault ); harvestRewardVault = IHarvestVault(_harvestRewardVault); } /** * @notice Update the address of NoMintRewardPool * @dev Can only be called by the owner * @param _harvestRewardPool Address of NoMintRewardPool */ function setHarvestRewardPool(address _harvestRewardPool) public onlyOwner { require(_harvestRewardPool != address(0), "POOL_0x0"); emit ChangedAddress( "POOL", address(harvestRewardPool), _harvestRewardPool ); harvestRewardPool = IMintNoRewardPool(_harvestRewardPool); } /** * @notice Update the address of Sushiswap Router * @dev Can only be called by the owner * @param _sushiswapRouter Address of Sushiswap Router */ function setSushiswapRouter(address _sushiswapRouter) public onlyOwner { require(_sushiswapRouter != address(0), "0x0"); emit ChangedAddress( "SUSHISWAP_ROUTER", address(sushiswapRouter), _sushiswapRouter ); sushiswapRouter = IUniswapRouter(_sushiswapRouter); } /** * @notice Update the address of Pool's underlying token * @dev Can only be called by the owner * @param _harvestPoolToken Address of Pool's underlying token */ function setHarvestPoolToken(address _harvestPoolToken) public onlyOwner { require(_harvestPoolToken != address(0), "TOKEN_0x0"); emit ChangedAddress("TOKEN", harvestPoolToken, _harvestPoolToken); harvestPoolToken = _harvestPoolToken; } /** * @notice Update the address of FARM * @dev Can only be called by the owner * @param _farmToken Address of FARM */ function setFarmToken(address _farmToken) public onlyOwner { require(_farmToken != address(0), "FARM_0x0"); emit ChangedAddress("FARM", farmToken, _farmToken); farmToken = _farmToken; } /** * @notice Update the address for fees * @dev Can only be called by the owner * @param _feeAddress Fee's address */ function setTreasury(address payable _feeAddress) public onlyOwner { require(_feeAddress != address(0), "0x0"); emit ChangedAddress( "TREASURY", address(treasuryAddress), address(_feeAddress) ); treasuryAddress = _feeAddress; } /** * @notice Approve contract (only approved contracts or msg.sender==tx.origin can call this strategy) * @dev Can only be called by the owner * @param account Contract's address */ function approveContractAccess(address account) external onlyOwner { require(account != address(0), "0x0"); approved[account] = true; } /** * @notice Revoke contract's access (only approved contracts or msg.sender==tx.origin can call this strategy) * @dev Can only be called by the owner * @param account Contract's address */ function revokeContractAccess(address account) external onlyOwner { require(account != address(0), "0x0"); approved[account] = false; } /** * @notice Blacklist address; blacklisted addresses do not receive receipt tokens * @dev Can only be called by the owner * @param account User/contract address */ function blacklistAddress(address account) external onlyOwner { require(account != address(0), "0x0"); emit BlacklistChanged("BLACKLIST", account, blacklisted[account], true); blacklisted[account] = true; } /** * @notice Remove address from blacklisted addresses; blacklisted addresses do not receive receipt tokens * @dev Can only be called by the owner * @param account User/contract address */ function removeFromBlacklist(address account) external onlyOwner { require(account != address(0), "0x0"); emit BlacklistChanged("REMOVE", account, blacklisted[account], false); blacklisted[account] = false; } /** * @notice Set max ETH cap for this strategy * @dev Can only be called by the owner * @param _cap ETH amount */ function setCap(uint256 _cap) external onlyOwner { cap = _cap; } /** * @notice Set lock time * @dev Can only be called by the owner * @param _lockTime lock time in seconds */ function setLockTime(uint256 _lockTime) external onlyOwner { require(_lockTime > 0, "TIME_0"); lockTime = _lockTime; } function setFeeAddress(address payable _feeAddress) public onlyOwner { feeAddress = _feeAddress; emit FeeAddressSet(msg.sender, _feeAddress); } function setFee(uint256 _fee) public onlyOwner { require(_fee <= uint256(9000), "FEE_TOO_HIGH"); fee = _fee; emit FeeSet(msg.sender, _fee); } /** * @notice Rescue dust resulted from swaps/liquidity * @dev Can only be called by the owner */ function rescueDust() public onlyOwner { if (ethDust > 0) { treasuryAddress.transfer(ethDust); treasueryEthDust = treasueryEthDust.add(ethDust); emit RescuedDust("ETH", ethDust); ethDust = 0; } } /** * @notice Rescue any non-reward token that was airdropped to this contract * @dev Can only be called by the owner */ function rescueAirdroppedTokens(address _token, address to) public onlyOwner { require(_token != address(0), "token_0x0"); require(to != address(0), "to_0x0"); require(_token != farmToken, "rescue_reward_error"); uint256 balanceOfToken = IERC20(_token).balanceOf(address(this)); require(balanceOfToken > 0, "balance_0"); require(IERC20(_token).transfer(to, balanceOfToken), "rescue_failed"); } /** * @notice Check if user can withdraw based on current lock time * @param user Address of the user * @return true or false */ function isWithdrawalAvailable(address user) public view returns (bool) { if (lockTime > 0) { return userInfo[user].timestamp.add(lockTime) <= block.timestamp; } return true; } /** * @notice Deposit to this strategy for rewards * @param daiAmount Amount of DAI investment * @param deadline Number of blocks until transaction expires * @return Amount of fDAI */ function deposit(uint256 daiAmount, uint256 deadline) public nonReentrant returns (uint256) { // ----- // validate // ----- _defend(); require(daiAmount > 0, "DAI_0"); require(deadline >= block.timestamp, "DEADLINE_ERROR"); require(totalDai.add(daiAmount) <= cap, "CAP_REACHED"); DepositData memory results; UserInfo storage user = userInfo[msg.sender]; if (user.amountfDai == 0) { user.wasUserBlacklisted = blacklisted[msg.sender]; } if (user.timestamp == 0) { user.timestamp = block.timestamp; } IERC20(dai).safeTransferFrom(msg.sender, address(this), daiAmount); totalDai = totalDai.add(daiAmount); user.amountDai = user.amountDai.add(daiAmount); results.obtainedDai = daiAmount; // ----- // deposit DAI into harvest and get fDAI // ----- IERC20(dai).safeIncreaseAllowance( address(harvestRewardVault), results.obtainedDai ); results.prevfDaiBalance = IERC20(harvestPoolToken).balanceOf( address(this) ); harvestRewardVault.deposit(results.obtainedDai); results.obtainedfDai = ( IERC20(harvestPoolToken).balanceOf(address(this)) ) .sub(results.prevfDaiBalance); // ----- // stake fDAI into the NoMintRewardPool // ----- IERC20(harvestPoolToken).safeIncreaseAllowance( address(harvestRewardPool), results.obtainedfDai ); user.amountfDai = user.amountfDai.add(results.obtainedfDai); if (!user.wasUserBlacklisted) { user.amountReceiptToken = user.amountReceiptToken.add( results.obtainedfDai ); receiptToken.mint(msg.sender, results.obtainedfDai); emit ReceiptMinted(msg.sender, results.obtainedfDai); } harvestRewardPool.stake(results.obtainedfDai); emit Deposit( msg.sender, tx.origin, results.obtainedDai, results.obtainedfDai ); if (firstDepositTimestamp == 0) { firstDepositTimestamp = block.timestamp; } if (user.joinTimestamp == 0) { user.joinTimestamp = block.timestamp; } totalDeposits = totalDeposits.add(results.obtainedfDai); harvestRewardPool.getReward(); //transfers FARM to this contract user.deposits.push( UserDeposits({ timestamp: block.timestamp, amountfDai: results.obtainedfDai }) ); user.underlyingRatio = _getRatio(user.amountfDai, user.amountDai, 18); return results.obtainedfDai; } function _updateDeposits( bool removeAll, uint256 remainingAmountfDai, address account ) private { UserInfo storage user = userInfo[account]; if (removeAll) { delete user.deposits; return; } for (uint256 i = user.deposits.length; i > 0; i--) { if (remainingAmountfDai >= user.deposits[i - 1].amountfDai) { remainingAmountfDai = remainingAmountfDai.sub( user.deposits[i - 1].amountfDai ); user.deposits[i - 1].amountfDai = 0; } else { user.deposits[i - 1].amountfDai = user.deposits[i - 1] .amountfDai .sub(remainingAmountfDai); remainingAmountfDai = 0; } if (remainingAmountfDai == 0) { break; } } } /** * @notice Withdraw tokens and claim rewards * @param deadline Number of blocks until transaction expires * @return Amount of ETH obtained */ function withdraw(uint256 amount, uint256 deadline) public nonReentrant returns (uint256) { // ----- // validation // ----- uint256 receiptBalance = receiptToken.balanceOf(msg.sender); _defend(); require(deadline >= block.timestamp, "DEADLINE_ERROR"); require(amount > 0, "AMOUNT_0"); UserInfo storage user = userInfo[msg.sender]; require(user.amountfDai >= amount, "AMOUNT_GREATER_THAN_BALANCE"); if (!user.wasUserBlacklisted) { require( receiptBalance >= user.amountReceiptToken, "RECEIPT_AMOUNT" ); } if (lockTime > 0) { require( user.timestamp.add(lockTime) <= block.timestamp, "LOCK_TIME" ); } WithdrawData memory results; results.prevDustEthBalance = address(this).balance; // ----- // withdraw from NoMintRewardPool and get fDai back // ----- results.prevfDaiBalance = IERC20(harvestPoolToken).balanceOf( address(this) ); IERC20(harvestPoolToken).safeIncreaseAllowance( address(harvestRewardPool), amount ); harvestRewardPool.getReward(); //transfers FARM to this contract results.farmBalance = IERC20(farmToken).balanceOf(address(this)); results.rewards = getPendingRewards(msg.sender, amount); _updateDeposits(amount == user.amountfDai, amount, msg.sender); harvestRewardPool.withdraw(amount); results.obtainedfDai = ( IERC20(harvestPoolToken).balanceOf(address(this)) ) .sub(results.prevfDaiBalance); //not sure if it's possible to get more from harvest so better to protect if (results.obtainedfDai < user.amountfDai) { user.amountfDai = user.amountfDai.sub(results.obtainedfDai); if (!user.wasUserBlacklisted) { user.amountReceiptToken = user.amountReceiptToken.sub( results.obtainedfDai ); receiptToken.burn(msg.sender, results.obtainedfDai); emit ReceiptBurned(msg.sender, results.obtainedfDai); } } else { user.amountfDai = 0; if (!user.wasUserBlacklisted) { receiptToken.burn(msg.sender, user.amountReceiptToken); emit ReceiptBurned(msg.sender, user.amountReceiptToken); user.amountReceiptToken = 0; } } // ----- // withdraw from Harvest-DAI vault and get Dai back // ----- IERC20(harvestPoolToken).safeIncreaseAllowance( address(harvestRewardVault), results.obtainedfDai ); results.prevDaiBalance = IERC20(dai).balanceOf(address(this)); harvestRewardVault.withdraw(results.obtainedfDai); results.obtainedDai = (IERC20(dai).balanceOf(address(this))).sub( results.prevDaiBalance ); emit ObtainedInfo( msg.sender, results.obtainedDai, results.obtainedfDai ); if (amount == user.amountfDai) { //there is no point to do the ratio math as we can just get the difference between current obtained tokens and initial obtained tokens if (results.obtainedDai > user.amountDai) { results.feeableDai = results.obtainedDai.sub(user.amountDai); } } else { uint256 currentRatio = _getRatio(results.obtainedfDai, results.obtainedDai, 18); results.feeableDai = 0; if (currentRatio < user.underlyingRatio) { uint256 noOfOriginalTokensForCurrentAmount = (amount.mul(10**18)).div(user.underlyingRatio); if (noOfOriginalTokensForCurrentAmount < results.obtainedDai) { results.feeableDai = results.obtainedDai.sub( noOfOriginalTokensForCurrentAmount ); } } } if (results.feeableDai > 0) { uint256 extraTokensFee = _calculateFee(results.feeableDai); emit ExtraTokens( msg.sender, results.feeableDai.sub(extraTokensFee) ); user.earnedTokens = user.earnedTokens.add( results.feeableDai.sub(extraTokensFee) ); } //not sure if it's possible to get more from harvest so better to protect if (results.obtainedDai <= user.amountDai) { user.amountDai = user.amountDai.sub(results.obtainedDai); } else { user.amountDai = 0; } results.obtainedDai = results.obtainedDai.sub(results.feeableDai); //feeableDai/2 => goes to the user //feeableDai/2 => goes to the treasury in ETH //obtainedDai => goes to the user results.auctionedDai = 0; if (results.feeableDai > 0) { results.auctionedDai = results.feeableDai.div(2); } results.feeableDai = results.feeableDai.sub(results.auctionedDai); results.totalDai = results.obtainedDai.add(results.feeableDai); // ----- // swap auctioned DAI to ETH // ----- address[] memory swapPath = new address[](2); swapPath[0] = dai; swapPath[1] = weth; if (results.auctionedDai > 0) { uint256[] memory daiFeeableSwapAmounts = sushiswapRouter.swapExactTokensForETH( results.auctionedDai, uint256(0), swapPath, address(this), deadline ); emit ExtraTokensExchanged( msg.sender, results.auctionedDai, daiFeeableSwapAmounts[daiFeeableSwapAmounts.length - 1] ); results.auctionedEth = results.auctionedEth.add( daiFeeableSwapAmounts[daiFeeableSwapAmounts.length - 1] ); } uint256 transferableRewards = results.rewards; if (transferableRewards > results.farmBalance) { transferableRewards = results.farmBalance; } if (transferableRewards > 0) { emit RewardsEarned(msg.sender, transferableRewards); user.earnedRewards = user.earnedRewards.add(transferableRewards); //swap 50% of rewards with ETH and add them to results.auctionedEth uint256 auctionedRewards = transferableRewards.div(2); //swap 50% of rewards with DAI and add them to results.totalDai uint256 userRewards = transferableRewards.sub(auctionedRewards); swapPath[0] = farmToken; IERC20(farmToken).safeIncreaseAllowance( address(sushiswapRouter), transferableRewards ); //swap 50% of rewards with ETH and add them to auctionedEth uint256[] memory farmSwapAmounts = sushiswapRouter.swapExactTokensForETH( auctionedRewards, uint256(0), swapPath, address(this), deadline ); emit RewardsExchanged( msg.sender, "ETH", auctionedRewards, farmSwapAmounts[farmSwapAmounts.length - 1] ); results.auctionedEth = results.auctionedEth.add( farmSwapAmounts[farmSwapAmounts.length - 1] ); //however, it should be > 0 if (userRewards > 0) { farmSwapAmounts = sushiswapRouter.swapExactTokensForETH( userRewards, uint256(0), swapPath, address(this), deadline ); swapPath[0] = weth; swapPath[1] = dai; farmSwapAmounts = sushiswapRouter.swapExactETHForTokens{ value: farmSwapAmounts[farmSwapAmounts.length - 1] }(uint256(0), swapPath, address(this), deadline); emit RewardsExchanged( msg.sender, "DAI", userRewards, farmSwapAmounts[farmSwapAmounts.length - 1] ); results.totalDai = results.totalDai.add( farmSwapAmounts[farmSwapAmounts.length - 1] ); } } // ----- // transfer ETH to user // ----- totalDeposits = totalDeposits.sub(results.obtainedfDai); if (user.amountfDai == 0) //full exit { //if user exits to early, obtained ETH might be lower than what user initially invested and there will be some left in amountEth //making sure we reset it user.amountDai = 0; } else { if (user.amountDai > results.totalDai) { user.amountDai = user.amountDai.sub(results.totalDai); } else { user.amountDai = 0; } } if (results.totalDai < totalDai) { totalDai = totalDai.sub(results.totalDai); } else { totalDai = 0; } //at some point we might not have any fees if (fee > 0) { uint256 feeDai = _calculateFee(results.totalDai); results.totalDai = results.totalDai.sub(feeDai); swapPath[0] = dai; swapPath[1] = weth; IERC20(dai).safeIncreaseAllowance(address(sushiswapRouter), feeDai); uint256[] memory feeSwapAmount = sushiswapRouter.swapExactTokensForETH( feeDai, uint256(0), swapPath, address(this), deadline ); feeAddress.transfer(feeSwapAmount[feeSwapAmount.length - 1]); user.userCollectedFees = user.userCollectedFees.add( feeSwapAmount[feeSwapAmount.length - 1] ); } IERC20(dai).safeTransfer(msg.sender, results.totalDai); treasuryAddress.transfer(results.auctionedEth); user.userTreasuryEth = user.userTreasuryEth.add(results.auctionedEth); emit Withdraw( msg.sender, tx.origin, results.obtainedDai, results.obtainedfDai, results.auctionedEth ); ethDust = ethDust.add( address(this).balance.sub(results.prevDustEthBalance) ); if (user.amountfDai == 0 || user.amountDai == 0) { user.underlyingRatio = 0; } else { user.underlyingRatio = _getRatio( user.amountfDai, user.amountDai, 18 ); } return results.totalDai; } /// @notice Transfer rewards to this strategy function updateReward() public onlyOwner { harvestRewardPool.getReward(); } function _calculateFee(uint256 amount) private view returns (uint256) { return (amount.mul(fee)).div(feeFactor); } function _defend() private view returns (bool) { require( approved[msg.sender] || msg.sender == tx.origin, "access_denied" ); } //-----------------------------------------------------------------------------------------------------------------// //------------------------------------ Getters -------------------------------------------------// //-----------------------------------------------------------------------------------------------------------------// /** * @notice View function to see pending rewards for account. * @param account user account to check * @param amount amount you want to calculate for; if 0 will calculate for entire amount * @return pending rewards */ function getPendingRewards(address account, uint256 amount) public view returns (uint256) { UserInfo storage user = userInfo[account]; if (amount == 0) { amount = user.amountfDai; } if (user.deposits.length == 0 || user.amountfDai == 0) { return 0; } uint256 rewards = 0; uint256 remaingAmount = amount; uint256 i = user.deposits.length - 1; while (remaingAmount > 0) { uint256 depositRewards = _getPendingRewards(user.deposits[i], remaingAmount); rewards = rewards.add(depositRewards); if (remaingAmount >= user.deposits[i].amountfDai) { remaingAmount = remaingAmount.sub(user.deposits[i].amountfDai); } else { remaingAmount = 0; } if (i == 0) { break; } i = i.sub(1); } return rewards; } function _getPendingRewards( UserDeposits memory user, uint256 remainingAmount ) private view returns (uint256) { if (user.amountfDai == 0) { return 0; } uint256 toCalculateForAmount = 0; if (user.amountfDai <= remainingAmount) { toCalculateForAmount = user.amountfDai; } else { toCalculateForAmount = remainingAmount; } uint256 rewardPerBlock = 0; uint256 balance = IERC20(farmToken).balanceOf(address(this)); if (balance == 0) { return 0; } uint256 diff = block.timestamp.sub(firstDepositTimestamp); if (diff == 0) { rewardPerBlock = balance; } else { rewardPerBlock = balance.div(diff); } uint256 rewardPerBlockUser = rewardPerBlock.mul(block.timestamp.sub(user.timestamp)); uint256 ratio = _getRatio(toCalculateForAmount, totalDeposits, 18); return (rewardPerBlockUser.mul(ratio)).div(10**18); } function _getRatio( uint256 numerator, uint256 denominator, uint256 precision ) private pure returns (uint256) { uint256 _numerator = numerator * 10**(precision + 1); uint256 _quotient = ((_numerator / denominator) + 5) / 10; return (_quotient); } receive() external payable {} }
* @notice Withdraw tokens and claim rewards @param deadline Number of blocks until transaction expires @return Amount of ETH obtained/ ----- validation -----not sure if it's possible to get more from harvest so better to protectthere is no point to do the ratio math as we can just get the difference between current obtained tokens and initial obtained tokensnot sure if it's possible to get more from harvest so better to protectswap 50% of rewards with ETH and add them to results.auctionedEthswap 50% of rewards with DAI and add them to results.totalDaiswap 50% of rewards with ETH and add them to auctionedEthhowever, it should be > 0if user exits to early, obtained ETH might be lower than what user initially invested and there will be some left in amountEthmaking sure we reset itat some point we might not have any fees
function withdraw(uint256 amount, uint256 deadline) public nonReentrant returns (uint256) { uint256 receiptBalance = receiptToken.balanceOf(msg.sender); _defend(); require(deadline >= block.timestamp, "DEADLINE_ERROR"); require(amount > 0, "AMOUNT_0"); UserInfo storage user = userInfo[msg.sender]; require(user.amountfDai >= amount, "AMOUNT_GREATER_THAN_BALANCE"); if (!user.wasUserBlacklisted) { require( receiptBalance >= user.amountReceiptToken, "RECEIPT_AMOUNT" ); } if (lockTime > 0) { require( user.timestamp.add(lockTime) <= block.timestamp, "LOCK_TIME" ); } WithdrawData memory results; results.prevDustEthBalance = address(this).balance; address(this) ); IERC20(harvestPoolToken).safeIncreaseAllowance( address(harvestRewardPool), amount ); results.farmBalance = IERC20(farmToken).balanceOf(address(this)); results.rewards = getPendingRewards(msg.sender, amount); _updateDeposits(amount == user.amountfDai, amount, msg.sender); harvestRewardPool.withdraw(amount); results.obtainedfDai = ( IERC20(harvestPoolToken).balanceOf(address(this)) ) .sub(results.prevfDaiBalance); if (results.obtainedfDai < user.amountfDai) { user.amountfDai = user.amountfDai.sub(results.obtainedfDai); if (!user.wasUserBlacklisted) { user.amountReceiptToken = user.amountReceiptToken.sub( results.obtainedfDai ); receiptToken.burn(msg.sender, results.obtainedfDai); emit ReceiptBurned(msg.sender, results.obtainedfDai); } user.amountfDai = 0; if (!user.wasUserBlacklisted) { receiptToken.burn(msg.sender, user.amountReceiptToken); emit ReceiptBurned(msg.sender, user.amountReceiptToken); user.amountReceiptToken = 0; } } address(harvestRewardVault), results.obtainedfDai ); results.prevDaiBalance = IERC20(dai).balanceOf(address(this)); harvestRewardVault.withdraw(results.obtainedfDai); results.obtainedDai = (IERC20(dai).balanceOf(address(this))).sub( results.prevDaiBalance ); emit ObtainedInfo( msg.sender, results.obtainedDai, results.obtainedfDai ); if (amount == user.amountfDai) { if (results.obtainedDai > user.amountDai) { results.feeableDai = results.obtainedDai.sub(user.amountDai); } uint256 currentRatio = _getRatio(results.obtainedfDai, results.obtainedDai, 18); results.feeableDai = 0; if (currentRatio < user.underlyingRatio) { uint256 noOfOriginalTokensForCurrentAmount = (amount.mul(10**18)).div(user.underlyingRatio); if (noOfOriginalTokensForCurrentAmount < results.obtainedDai) { results.feeableDai = results.obtainedDai.sub( noOfOriginalTokensForCurrentAmount ); } } } if (results.feeableDai > 0) { uint256 extraTokensFee = _calculateFee(results.feeableDai); emit ExtraTokens( msg.sender, results.feeableDai.sub(extraTokensFee) ); user.earnedTokens = user.earnedTokens.add( results.feeableDai.sub(extraTokensFee) ); } if (results.obtainedDai <= user.amountDai) { user.amountDai = user.amountDai.sub(results.obtainedDai); user.amountDai = 0; } results.obtainedDai = results.obtainedDai.sub(results.feeableDai); results.auctionedDai = 0; if (results.feeableDai > 0) { results.auctionedDai = results.feeableDai.div(2); } results.feeableDai = results.feeableDai.sub(results.auctionedDai); results.totalDai = results.obtainedDai.add(results.feeableDai); swapPath[0] = dai; swapPath[1] = weth; if (results.auctionedDai > 0) { uint256[] memory daiFeeableSwapAmounts = sushiswapRouter.swapExactTokensForETH( results.auctionedDai, uint256(0), swapPath, address(this), deadline ); emit ExtraTokensExchanged( msg.sender, results.auctionedDai, daiFeeableSwapAmounts[daiFeeableSwapAmounts.length - 1] ); results.auctionedEth = results.auctionedEth.add( daiFeeableSwapAmounts[daiFeeableSwapAmounts.length - 1] ); } uint256 transferableRewards = results.rewards; if (transferableRewards > results.farmBalance) { transferableRewards = results.farmBalance; } if (transferableRewards > 0) { emit RewardsEarned(msg.sender, transferableRewards); user.earnedRewards = user.earnedRewards.add(transferableRewards); uint256 auctionedRewards = transferableRewards.div(2); uint256 userRewards = transferableRewards.sub(auctionedRewards); swapPath[0] = farmToken; IERC20(farmToken).safeIncreaseAllowance( address(sushiswapRouter), transferableRewards ); uint256[] memory farmSwapAmounts = sushiswapRouter.swapExactTokensForETH( auctionedRewards, uint256(0), swapPath, address(this), deadline ); emit RewardsExchanged( msg.sender, "ETH", auctionedRewards, farmSwapAmounts[farmSwapAmounts.length - 1] ); results.auctionedEth = results.auctionedEth.add( farmSwapAmounts[farmSwapAmounts.length - 1] ); if (userRewards > 0) { farmSwapAmounts = sushiswapRouter.swapExactTokensForETH( userRewards, uint256(0), swapPath, address(this), deadline ); swapPath[0] = weth; swapPath[1] = dai; farmSwapAmounts = sushiswapRouter.swapExactETHForTokens{ value: farmSwapAmounts[farmSwapAmounts.length - 1] }(uint256(0), swapPath, address(this), deadline); emit RewardsExchanged( msg.sender, "DAI", userRewards, farmSwapAmounts[farmSwapAmounts.length - 1] ); results.totalDai = results.totalDai.add( farmSwapAmounts[farmSwapAmounts.length - 1] ); } } { user.amountDai = 0; if (user.amountDai > results.totalDai) { user.amountDai = user.amountDai.sub(results.totalDai); user.amountDai = 0; } } if (results.totalDai < totalDai) { totalDai = totalDai.sub(results.totalDai); totalDai = 0; } if (fee > 0) { uint256 feeDai = _calculateFee(results.totalDai); results.totalDai = results.totalDai.sub(feeDai); swapPath[0] = dai; swapPath[1] = weth; IERC20(dai).safeIncreaseAllowance(address(sushiswapRouter), feeDai); uint256[] memory feeSwapAmount = sushiswapRouter.swapExactTokensForETH( feeDai, uint256(0), swapPath, address(this), deadline ); feeAddress.transfer(feeSwapAmount[feeSwapAmount.length - 1]); user.userCollectedFees = user.userCollectedFees.add( feeSwapAmount[feeSwapAmount.length - 1] ); } IERC20(dai).safeTransfer(msg.sender, results.totalDai); treasuryAddress.transfer(results.auctionedEth); user.userTreasuryEth = user.userTreasuryEth.add(results.auctionedEth); emit Withdraw( msg.sender, tx.origin, results.obtainedDai, results.obtainedfDai, results.auctionedEth ); ethDust = ethDust.add( address(this).balance.sub(results.prevDustEthBalance) ); if (user.amountfDai == 0 || user.amountDai == 0) { user.underlyingRatio = 0; user.underlyingRatio = _getRatio( user.amountfDai, user.amountDai, 18 ); } return results.totalDai; }
10,552,399
[ 1, 1190, 9446, 2430, 471, 7516, 283, 6397, 225, 14096, 3588, 434, 4398, 3180, 2492, 7368, 327, 16811, 434, 512, 2455, 12700, 19, 9135, 3379, 9135, 902, 3071, 309, 518, 1807, 3323, 358, 336, 1898, 628, 17895, 26923, 1427, 7844, 358, 17151, 18664, 353, 1158, 1634, 358, 741, 326, 7169, 4233, 487, 732, 848, 2537, 336, 326, 7114, 3086, 783, 12700, 2430, 471, 2172, 12700, 2430, 902, 3071, 309, 518, 1807, 3323, 358, 336, 1898, 628, 17895, 26923, 1427, 7844, 358, 17151, 22270, 6437, 9, 434, 283, 6397, 598, 512, 2455, 471, 527, 2182, 358, 1686, 18, 69, 4062, 329, 41, 451, 22270, 6437, 9, 434, 283, 6397, 598, 463, 18194, 471, 527, 2182, 358, 1686, 18, 4963, 40, 69, 291, 91, 438, 6437, 9, 434, 283, 6397, 598, 512, 2455, 471, 527, 2182, 358, 279, 4062, 329, 41, 451, 13606, 6084, 16, 518, 1410, 506, 405, 374, 430, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 565, 445, 598, 9446, 12, 11890, 5034, 3844, 16, 2254, 5034, 14096, 13, 203, 3639, 1071, 203, 3639, 1661, 426, 8230, 970, 203, 3639, 1135, 261, 11890, 5034, 13, 203, 565, 288, 203, 3639, 2254, 5034, 16030, 13937, 273, 16030, 1345, 18, 12296, 951, 12, 3576, 18, 15330, 1769, 203, 203, 3639, 389, 536, 409, 5621, 203, 3639, 2583, 12, 22097, 1369, 1545, 1203, 18, 5508, 16, 315, 1639, 1880, 5997, 67, 3589, 8863, 203, 3639, 2583, 12, 8949, 405, 374, 16, 315, 2192, 51, 5321, 67, 20, 8863, 203, 3639, 25003, 2502, 729, 273, 16753, 63, 3576, 18, 15330, 15533, 203, 3639, 2583, 12, 1355, 18, 8949, 74, 40, 10658, 1545, 3844, 16, 315, 2192, 51, 5321, 67, 43, 18857, 67, 22408, 67, 38, 1013, 4722, 8863, 203, 3639, 309, 16051, 1355, 18, 17416, 1299, 13155, 18647, 13, 288, 203, 5411, 2583, 12, 203, 7734, 16030, 13937, 1545, 729, 18, 8949, 15636, 1345, 16, 203, 7734, 315, 27086, 45, 1856, 67, 2192, 51, 5321, 6, 203, 5411, 11272, 203, 3639, 289, 203, 3639, 309, 261, 739, 950, 405, 374, 13, 288, 203, 5411, 2583, 12, 203, 7734, 729, 18, 5508, 18, 1289, 12, 739, 950, 13, 1648, 1203, 18, 5508, 16, 203, 7734, 315, 6589, 67, 4684, 6, 203, 5411, 11272, 203, 3639, 289, 203, 3639, 3423, 9446, 751, 3778, 1686, 31, 203, 3639, 1686, 18, 10001, 40, 641, 41, 451, 13937, 273, 1758, 12, 2211, 2934, 12296, 31, 203, 203, 5411, 1758, 12, 2211, 13, 203, 3639, 11272, 203, 3639, 467, 654, 2 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.0; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/utils/math/MathUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; import "../interfaces/IGaugeController.sol"; import "../interfaces/IGauge.sol"; import "../interfaces/IUniPool.sol"; import "../interfaces/IVotingEscrow.sol"; /** * @dev Liquidity gauge that stakes token and earns reward. * * Note: The liquidity gauge token might not be 1:1 with the staked token. * For plus tokens, the total staked amount increases as interest from plus token accrues. * Credit: https://github.com/curvefi/curve-dao-contracts/blob/master/contracts/gauges/LiquidityGaugeV2.vy */ contract LiquidityGauge is ERC20Upgradeable, ReentrancyGuardUpgradeable, IGauge { using SafeERC20Upgradeable for IERC20Upgradeable; event LiquidityLimitUpdated(address indexed account, uint256 balance, uint256 supply, uint256 oldWorkingBalance, uint256 oldWorkingSupply, uint256 newWorkingBalance, uint256 newWorkingSupply); event Deposited(address indexed account, uint256 stakedAmount, uint256 mintAmount); event Withdrawn(address indexed account, uint256 withdrawAmount, uint256 fee, uint256 burnAmount); event RewardContractUpdated(address indexed oldRewardContract, address indexed newRewardContract, address[] rewardTokens); event WithdrawFeeUpdated(uint256 oldWithdrawFee, uint256 newWithdrawFee); event DirectClaimCooldownUpdated(uint256 oldCooldown, uint256 newCooldown); uint256 constant TOKENLESS_PRODUCTION = 40; uint256 constant WAD = 10**18; uint256 constant MAX_PERCENT = 10000; // 0.01% // Token staked in the liquidity gauge address public override token; // AC token address public reward; // Gauge controller address public controller; address public votingEscrow; // AC emission rate per seconds in the gauge uint256 public rate; uint256 public withdrawFee; // List of tokens that cannot be salvaged mapping(address => bool) public unsalvageable; uint256 public workingSupply; mapping(address => uint256) public workingBalances; uint256 public integral; // Last global checkpoint timestamp uint256 public lastCheckpoint; // Integral of the last user checkpoint mapping(address => uint256) public integralOf; // Timestamp of the last user checkpoint mapping(address => uint256) public checkpointOf; // Mapping: User => Rewards accrued last checkpoint mapping(address => uint256) public rewards; // Mapping: User => Last time the user claims directly from the gauge // Users can claim directly from gauge or indirectly via a claimer mapping(address => uint256) public lastDirectClaim; // The cooldown interval between two direct claims from the gauge uint256 public directClaimCooldown; address public rewardContract; address[] public rewardTokens; // Reward token address => Reward token integral mapping(address => uint256) public rewardIntegral; // Reward token address => (User address => Reward integral of the last user reward checkpoint) mapping(address => mapping(address => uint256)) public rewardIntegralOf; /** * @dev Initlaizes the liquidity gauge contract. */ function initialize(address _token, address _controller, address _votingEscrow) public initializer { token = _token; controller = _controller; reward = IGaugeController(_controller).reward(); votingEscrow = _votingEscrow; directClaimCooldown = 14 days; // A default 14 day direct claim cool down // Should not salvage token from the gauge unsalvageable[token] = true; // We allow salvage reward token since the liquidity gauge should not hold reward token. It's // distributed from gauge controller to user directly. __ERC20_init(string(abi.encodePacked(ERC20Upgradeable(_token).name(), " Gauge Deposit")), string(abi.encodePacked(ERC20Upgradeable(_token).symbol(), "-gauge"))); __ReentrancyGuard_init(); } /** * @dev Important: Updates the working balance of the user to effectively apply * boosting on liquidity mining. * @param _account Address to update liquidity limit */ function _updateLiquidityLimit(address _account) internal { IERC20Upgradeable _votingEscrow = IERC20Upgradeable(votingEscrow); uint256 _votingBalance = _votingEscrow.balanceOf(_account); uint256 _votingTotal = _votingEscrow.totalSupply(); uint256 _balance = balanceOf(_account); uint256 _supply = totalSupply(); uint256 _limit = _balance * TOKENLESS_PRODUCTION / 100; if (_votingTotal > 0) { uint256 _boosting = _supply * _votingBalance * (100 - TOKENLESS_PRODUCTION) / (_votingTotal * 100); _limit += _boosting; } _limit = MathUpgradeable.min(_balance, _limit); uint256 _oldWorkingBalance = workingBalances[_account]; uint256 _oldWorkingSupply = workingSupply; workingBalances[_account] = _limit; uint256 _newWorkingSupply = _oldWorkingSupply + _limit / _oldWorkingBalance; workingSupply = _newWorkingSupply; emit LiquidityLimitUpdated(_account, _balance, _supply, _oldWorkingBalance, _oldWorkingSupply, _limit, _newWorkingSupply); } /** * @dev Claims pending rewards and checkpoint rewards for a user. * @param _account Address of the user to checkpoint reward. Zero means global checkpoint only. */ function _checkpointRewards(address _account) internal { uint256 _supply = totalSupply(); address _rewardContract = rewardContract; address[] memory _rewardList = rewardTokens; uint256[] memory _rewardBalances = new uint256[](_rewardList.length); // No op if nothing is staked yet! if (_supply == 0 || _rewardContract == address(0x0) || _rewardList.length == 0) return; // Reads balance for each reward token for (uint256 i = 0; i < _rewardList.length; i++) { _rewardBalances[i] = IERC20Upgradeable(_rewardList[i]).balanceOf(address(this)); } IUniPool(_rewardContract).getReward(); uint256 _balance = balanceOf(_account); // Checks balance increment for each reward token for (uint256 i = 0; i < _rewardList.length; i++) { // Integral is in WAD uint256 _diff = (IERC20Upgradeable(_rewardList[i]).balanceOf(address(this)) - _rewardBalances[i]) * WAD / _supply; uint256 _newIntegral = rewardIntegral[_rewardList[i]] + _diff; if (_diff != 0) { rewardIntegral[_rewardList[i]] = _newIntegral; } if (_account == address(0x0)) continue; uint256 _userIntegral = rewardIntegralOf[_rewardList[i]][_account]; if (_userIntegral < _newIntegral) { uint256 _claimable = _balance * (_newIntegral - _userIntegral) / WAD; rewardIntegralOf[_rewardList[i]][_account] = _newIntegral; if (_claimable > 0) { IERC20Upgradeable(_rewardList[i]).safeTransfer(_account, _claimable); } } } } /** * @dev Performs checkpoint on AC rewards. * @param _account User address to checkpoint. Zero to do global checkpoint only. */ function _checkpoint(address _account) internal { uint256 _workingSupply = workingSupply; if (_workingSupply == 0) { lastCheckpoint = block.timestamp; if (_account != address(0x0)) { checkpointOf[_account] = block.timestamp; } return; } uint256 _diffTime = block.timestamp - lastCheckpoint; // Both rate and integral are in WAD uint256 _newIntegral = integral + rate * _diffTime / _workingSupply; integral = _newIntegral; lastCheckpoint = block.timestamp; if (_account == address(0x0)) return; uint256 _amount = workingBalances[_account] * (_newIntegral - integralOf[_account]) / WAD; integralOf[_account] = _newIntegral; checkpointOf[_account] = block.timestamp; rewards[_account] += _amount; } /** * @dev Performs global checkpoint for the liquidity gauge. * Note: AC emission rate change is triggered by gauge controller. Each time there is a rate change, * Gauge controller will checkpoint the gauge. Therefore, we could assume that the rate is not changed * between two checkpoints! */ function checkpoint() external override nonReentrant { _checkpoint(address(0x0)); // Loads the new emission rate from gauge controller rate = IGaugeController(controller).gaugeRates(address(this)); } /** * @dev Returns the next time user can trigger a direct claim. */ function nextDirectClaim(address _account) external view returns (uint256) { return MathUpgradeable.max(block.timestamp, lastDirectClaim[_account] + directClaimCooldown); } /** * @dev Returns the amount of AC token that the user can claim. * @param _account Address of the account to check claimable reward. */ function claimable(address _account) external view override returns (uint256) { // Reward claimable until the previous checkpoint uint256 _reward = workingBalances[_account] * (integral - integralOf[_account]) / WAD; // Add the remaining claimable rewards _reward += rewards[_account]; if (workingSupply > 0) { uint256 _diffTime = block.timestamp - lastCheckpoint; // Both rate and integral are in WAD uint256 _additionalReard = rate * _diffTime * workingBalances[_account] / (workingSupply * WAD); _reward += _additionalReard; } return _reward; } /** * @dev Returns the amount of reward token that the user can claim until the latest checkpoint. * @param _account Address of the account to check claimable reward. * @param _rewardToken Address of the reward token */ function claimableReward(address _account, address _rewardToken) external view returns (uint256) { return balanceOf(_account) * (rewardIntegral[_rewardToken] - rewardIntegralOf[_rewardToken][_account]) / WAD; } /** * @dev Claims reward for the user. * @param _account Address of the user to claim. * @param _claimRewards Whether to claim other rewards as well. */ function claim(address _account, bool _claimRewards) external nonReentrant { _claim(_account, _account, _claimRewards); } /** * @dev Claims reward for the user. * @param _account Address of the user to claim. * @param _receiver Address that receives the claimed reward * @param _claimRewards Whether to claim other rewards as well. */ function claim(address _account, address _receiver, bool _claimRewards) external override nonReentrant { _claim(_account, _receiver, _claimRewards); } /** * @dev Claims reward for the user. It transfers the claimable reward to the user and updates user's liquidity limit. * Note: We allow anyone to claim other rewards on behalf of others, but not for the AC reward. This is because claiming AC * reward also updates the user's liquidity limit. Therefore, only authorized claimer can do that on behalf of user. * @param _account Address of the user to claim. * @param _receiver Address that receives the claimed reward * @param _claimRewards Whether to claim other rewards as well. */ function _claim(address _account, address _receiver, bool _claimRewards) internal { // Direct claim mean user claiming directly to the gauge. Cooldown applies to direct claim. // Indirect claim means user claimsing via claimers. There is no cooldown in indirect claim. require((_account == msg.sender && block.timestamp >= lastDirectClaim[_account] + directClaimCooldown) || IGaugeController(controller).claimers(msg.sender), "cannot claim"); _checkpoint(_account); _updateLiquidityLimit(_account); uint256 _claimable = rewards[_account]; if (_claimable > 0) { IGaugeController(controller).claim(_account, _receiver, _claimable); rewards[_account] = 0; } if (_claimRewards) { _checkpointRewards(_account); } // Cooldown applies only to direct claim if (_account == msg.sender) { lastDirectClaim[msg.sender] = block.timestamp; } } /** * @dev Claims all rewards for the caller. * @param _account Address of the user to claim. */ function claimRewards(address _account) external nonReentrant { _checkpointRewards(_account); } /** * @dev Checks whether an account can be kicked. * An account is kickable if the account has another voting event since last checkpoint, * or the lock of the account expires. */ function kickable(address _account) public view override returns (bool) { address _votingEscrow = votingEscrow; uint256 _lastUserCheckpoint = checkpointOf[_account]; uint256 _lastUserEvent = IVotingEscrow(_votingEscrow).user_point_history__ts(_account, IVotingEscrow(_votingEscrow).user_point_epoch(_account)); return IERC20Upgradeable(_votingEscrow).balanceOf(_account) == 0 || _lastUserEvent > _lastUserCheckpoint; } /** * @dev Kicks an account for abusing their boost. Only kick if the user * has another voting event, or their lock expires. */ function kick(address _account) external override nonReentrant { // We allow claimers to kick since kick can be seen as subset of claim. require(kickable(_account) || IGaugeController(controller).claimers(msg.sender), "kick not allowed"); _checkpoint(_account); _updateLiquidityLimit(_account); } /** * @dev Returns the total amount of token staked. */ function totalStaked() public view override returns (uint256) { return IERC20Upgradeable(token).balanceOf(address(this)); } /** * @dev Returns the amount staked by the user. */ function userStaked(address _account) public view override returns (uint256) { uint256 _totalSupply = totalSupply(); uint256 _balance = IERC20Upgradeable(token).balanceOf(address(this)); return _totalSupply == 0 ? 0 : balanceOf(_account) * _balance / _totalSupply; } /** * @dev Deposit the staked token into liquidity gauge. * @param _amount Amount of staked token to deposit. */ function deposit(uint256 _amount) external nonReentrant { require(_amount > 0, "zero amount"); if (_amount == uint256(int256(-1))) { // -1 means deposit all _amount = IERC20Upgradeable(token).balanceOf(msg.sender); } _checkpoint(msg.sender); _checkpointRewards(msg.sender); uint256 _totalSupply = totalSupply(); uint256 _balance = IERC20Upgradeable(token).balanceOf(address(this)); // Note: Ideally, when _totalSupply = 0, _balance = 0. // However, it's possible that _balance != 0 when _totalSupply = 0, e.g. // 1) There are some leftover due to rounding error after all people withdraws; // 2) Someone sends token to the liquidity gauge before there is any deposit. // Therefore, when either _totalSupply or _balance is 0, we treat the gauge is empty. uint256 _mintAmount = _totalSupply == 0 || _balance == 0 ? _amount : _amount * _totalSupply / _balance; _mint(msg.sender, _mintAmount); _updateLiquidityLimit(msg.sender); IERC20Upgradeable(token).safeTransferFrom(msg.sender, address(this), _amount); address _rewardContract = rewardContract; if (_rewardContract != address(0x0)) { IUniPool(_rewardContract).stake(_amount); } emit Deposited(msg.sender, _amount, _mintAmount); } /** * @dev Withdraw the staked token from liquidity gauge. * @param _amount Amounf of staked token to withdraw */ function withdraw(uint256 _amount) external nonReentrant { require(_amount > 0, "zero amount"); uint256 _burnAmount = 0; if (_amount == uint256(int256(-1))) { // -1 means withdraw all _amount = userStaked(msg.sender); _burnAmount = balanceOf(msg.sender); } else { uint256 _totalSupply = totalSupply(); uint256 _balance = IERC20Upgradeable(token).balanceOf(address(this)); require(_totalSupply > 0 && _balance > 0, "no balance"); _burnAmount = _amount * _totalSupply / _balance; } _checkpoint(msg.sender); _checkpointRewards(msg.sender); _burn(msg.sender, _burnAmount); _updateLiquidityLimit(msg.sender); address _rewardContract = rewardContract; if (_rewardContract != address(0x0)) { IUniPool(_rewardContract).withdraw(_amount); } uint256 _fee; address _token = token; address _controller = controller; if (withdrawFee > 0) { _fee = _amount * withdrawFee / MAX_PERCENT; IERC20Upgradeable(_token).safeTransfer(_controller, _fee); // Donate the withdraw fee for future processing // Withdraw fee for plus token is donated to all token holders right away IGaugeController(_controller).donate(_token); } IERC20Upgradeable(_token).safeTransfer(msg.sender, _amount - _fee); emit Withdrawn(msg.sender, _amount, _fee, _burnAmount); } /** * @dev Moves tokens `amount` from `sender` to `recipient`. */ function _transfer(address _sender, address _recipient, uint256 _amount) internal virtual override { _checkpoint(_sender); _checkpoint(_recipient); _checkpointRewards(_sender); _checkpointRewards(_recipient); // Invoke super _transfer to emit Transfer event super._transfer(_sender, _recipient, _amount); _updateLiquidityLimit(_sender); _updateLiquidityLimit(_recipient); } /********************************************* * * Governance methods * **********************************************/ /** * @dev All liqduiity gauge share the same governance of gauge controller. */ function _checkGovernance() internal view { require(msg.sender == IGaugeController(controller).governance(), "not governance"); } modifier onlyGovernance() { _checkGovernance(); _; } /** * @dev Updates the reward contract and reward tokens. * @param _rewardContract The new active reward contract. * @param _rewardTokens The reward tokens from the reward contract. */ function setRewards(address _rewardContract, address[] memory _rewardTokens) external onlyGovernance { address _currentRewardContract = rewardContract; IERC20Upgradeable _token = IERC20Upgradeable(token); if (_currentRewardContract != address(0x0)) { _checkpointRewards(address(0x0)); IUniPool(_currentRewardContract).exit(); _token.approve(_currentRewardContract, 0); } if (_rewardContract != address(0x0)) { require(_rewardTokens.length > 0, "reward tokens not set"); _token.approve(_rewardContract, uint256(int256(-1))); IUniPool(_rewardContract).stake(_token.balanceOf(address(this))); rewardContract = _rewardContract; rewardTokens = _rewardTokens; // Complete an initial checkpoint to make sure that everything works. _checkpointRewards(address(0x0)); // Reward contract is tokenized as well unsalvageable[_rewardContract] = true; // Don't salvage any reward token for (uint256 i = 0; i < _rewardTokens.length; i++) { unsalvageable[_rewardTokens[i]] = true; } } emit RewardContractUpdated(_currentRewardContract, _rewardContract, _rewardTokens); } /** * @dev Updates the withdraw fee. Only governance can update withdraw fee. */ function setWithdrawFee(uint256 _withdrawFee) external onlyGovernance { require(_withdrawFee <= MAX_PERCENT, "too big"); uint256 _oldWithdrawFee = withdrawFee; withdrawFee = _withdrawFee; emit WithdrawFeeUpdated(_oldWithdrawFee, _withdrawFee); } /** * @dev Updates the cooldown between two direct claims. */ function setDirectClaimCooldown(uint256 _cooldown) external onlyGovernance { uint256 _oldCooldown = directClaimCooldown; directClaimCooldown = _cooldown; emit DirectClaimCooldownUpdated(_oldCooldown, _cooldown); } /** * @dev Used to salvage any ETH deposited to gauge contract by mistake. Only governance can salvage ETH. * The salvaged ETH is transferred to treasury for futher operation. */ function salvage() external onlyGovernance { uint256 _amount = address(this).balance; address payable _target = payable(IGaugeController(controller).treasury()); (bool success, ) = _target.call{value: _amount}(new bytes(0)); require(success, 'ETH salvage failed'); } /** * @dev Used to salvage any token deposited to gauge contract by mistake. Only governance can salvage token. * The salvaged token is transferred to treasury for futhuer operation. * @param _token Address of the token to salvage. */ function salvageToken(address _token) external onlyGovernance { require(!unsalvageable[_token], "cannot salvage"); IERC20Upgradeable _target = IERC20Upgradeable(_token); _target.safeTransfer(IGaugeController(controller).treasury(), _target.balanceOf(address(this))); } }
Note: Ideally, when _totalSupply = 0, _balance = 0. However, it's possible that _balance != 0 when _totalSupply = 0, e.g. 1) There are some leftover due to rounding error after all people withdraws; 2) Someone sends token to the liquidity gauge before there is any deposit. Therefore, when either _totalSupply or _balance is 0, we treat the gauge is empty.
uint256 _mintAmount = _totalSupply == 0 || _balance == 0 ? _amount : _amount * _totalSupply / _balance;
6,413,582
[ 1, 8067, 30, 23062, 1230, 16, 1347, 389, 4963, 3088, 1283, 273, 374, 16, 389, 12296, 273, 374, 18, 10724, 16, 518, 1807, 3323, 716, 389, 12296, 480, 374, 1347, 389, 4963, 3088, 1283, 273, 374, 16, 425, 18, 75, 18, 404, 13, 6149, 854, 2690, 29709, 6541, 358, 13885, 555, 1839, 777, 16951, 598, 9446, 87, 31, 576, 13, 10548, 476, 9573, 1147, 358, 326, 4501, 372, 24237, 13335, 1865, 1915, 353, 1281, 443, 1724, 18, 17189, 16, 1347, 3344, 389, 4963, 3088, 1283, 578, 389, 12296, 353, 374, 16, 732, 10116, 326, 13335, 353, 1008, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2254, 5034, 389, 81, 474, 6275, 273, 389, 4963, 3088, 1283, 422, 374, 747, 389, 12296, 422, 374, 692, 389, 8949, 294, 389, 8949, 380, 389, 4963, 3088, 1283, 342, 389, 12296, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** * Gets child of ThereValTestT(ThereValTestT). */ function getChildThereValTestT(bytes[] memory _inputs, bytes[] memory challengeInputs) private view returns (types.Property memory) { bytes[] memory forAllSuchThatInputs = new bytes[](3); bytes[] memory notInputs = new bytes[](1); notInputs[0] = challengeInputs[0]; forAllSuchThatInputs[0] = bytes(""); forAllSuchThatInputs[1] = bytes("a"); forAllSuchThatInputs[2] = abi.encode(types.Property({ predicateAddress: notAddress, inputs: notInputs })); return types.Property({ predicateAddress: forAllSuchThatAddress, inputs: forAllSuchThatInputs }); }
* Gets child of ThereValTestT(ThereValTestT)./
function getChildThereValTestT(bytes[] memory _inputs, bytes[] memory challengeInputs) private view returns (types.Property memory) { bytes[] memory forAllSuchThatInputs = new bytes[](3); bytes[] memory notInputs = new bytes[](1); notInputs[0] = challengeInputs[0]; forAllSuchThatInputs[0] = bytes(""); forAllSuchThatInputs[1] = bytes("a"); forAllSuchThatInputs[2] = abi.encode(types.Property({ predicateAddress: notAddress, inputs: notInputs })); return types.Property({ predicateAddress: forAllSuchThatAddress, inputs: forAllSuchThatInputs }); }
13,061,940
[ 1, 3002, 1151, 434, 6149, 3053, 4709, 56, 12, 9828, 3053, 4709, 56, 2934, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 8154, 9828, 3053, 4709, 56, 12, 3890, 8526, 3778, 389, 10029, 16, 1731, 8526, 3778, 12948, 10059, 13, 3238, 1476, 1135, 261, 2352, 18, 1396, 3778, 13, 288, 203, 3639, 1731, 8526, 3778, 364, 1595, 5464, 18163, 10059, 273, 394, 1731, 8526, 12, 23, 1769, 203, 3639, 1731, 8526, 3778, 486, 10059, 273, 394, 1731, 8526, 12, 21, 1769, 203, 3639, 486, 10059, 63, 20, 65, 273, 12948, 10059, 63, 20, 15533, 203, 3639, 364, 1595, 5464, 18163, 10059, 63, 20, 65, 273, 1731, 2932, 8863, 203, 3639, 364, 1595, 5464, 18163, 10059, 63, 21, 65, 273, 1731, 2932, 69, 8863, 203, 3639, 364, 1595, 5464, 18163, 10059, 63, 22, 65, 273, 24126, 18, 3015, 12, 2352, 18, 1396, 12590, 203, 5411, 5641, 1887, 30, 486, 1887, 16, 203, 5411, 4540, 30, 486, 10059, 203, 3639, 289, 10019, 203, 3639, 327, 1953, 18, 1396, 12590, 203, 5411, 5641, 1887, 30, 364, 1595, 5464, 18163, 1887, 16, 203, 5411, 4540, 30, 364, 1595, 5464, 18163, 10059, 203, 3639, 15549, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.11; library SafeMath { function sub(uint256 a, uint256 b) internal constant returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract ERC223Compliant { function tokenFallback(address _from, uint _value, bytes _data) {} } contract EtheraffleLOT is ERC223Compliant { using SafeMath for uint; string public name; string public symbol; bool public frozen; uint8 public decimals; address[] public freezers; address public etheraffle; uint public totalSupply; mapping (address => uint) public balances; mapping (address => bool) public canFreeze; event LogFrozenStatus(bool status, uint atTime); event LogFreezerAddition(address newFreezer, uint atTime); event LogFreezerRemoval(address freezerRemoved, uint atTime); event LogEtheraffleChange(address prevER, address newER, uint atTime); event LogTransfer(address indexed from, address indexed to, uint value, bytes indexed data); /** * @dev Modifier function to prepend to methods rendering them only callable * by the Etheraffle MultiSig wallet. */ modifier onlyEtheraffle() { require(msg.sender == etheraffle); _; } /** * @dev Modifier function to prepend to methods rendering them only callable * by address approved for freezing. */ modifier onlyFreezers() { require(canFreeze[msg.sender]); _; } /** * @dev Modifier function to prepend to methods to render them only callable * when the frozen toggle is false */ modifier onlyIfNotFrozen() { require(!frozen); _; } /** * @dev Constructor: Sets the meta data for the token and gives the intial supply to the * Etheraffle ICO. * * @param _etheraffle Address of the Etheraffle's multisig wallet, the only * address via which the frozen/unfrozen state of the * token transfers can be toggled. * @param _supply Total numner of LOT to mint on contract creation. */ function EtheraffleLOT(address _etheraffle, uint _supply) { freezers.push(_etheraffle); name = "Etheraffle LOT"; symbol = "LOT"; decimals = 6; etheraffle = _etheraffle; totalSupply = _supply * 10 ** uint256(decimals); balances[_etheraffle] = totalSupply; canFreeze[_etheraffle] = true; } /** * ERC223 Standard functions: * * @dev Transfer the specified amount of LOT to the specified address. * Invokes the `tokenFallback` function if the recipient is a contract. * The token transfer fails if the recipient is a contract * but does not implement the `tokenFallback` function * or the fallback function to receive funds. * * @param _to Receiver address. * @param _value Amount of LOT to be transferred. * @param _data Transaction metadata. */ function transfer(address _to, uint _value, bytes _data) onlyIfNotFrozen external { uint codeLength; assembly { codeLength := extcodesize(_to) } balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); if(codeLength > 0) { ERC223Compliant receiver = ERC223Compliant(_to); receiver.tokenFallback(msg.sender, _value, _data); } LogTransfer(msg.sender, _to, _value, _data); } /** * @dev Transfer the specified amount of LOT to the specified address. * Standard function transfer similar to ERC20 transfer with no * _data param. Added due to backwards compatibility reasons. * * @param _to Receiver address. * @param _value Amount of LOT to be transferred. */ function transfer(address _to, uint _value) onlyIfNotFrozen external { uint codeLength; bytes memory empty; assembly { codeLength := extcodesize(_to) } balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); if(codeLength > 0) { ERC223Compliant receiver = ERC223Compliant(_to); receiver.tokenFallback(msg.sender, _value, empty); } LogTransfer(msg.sender, _to, _value, empty); } /** * @dev Returns balance of the `_owner`. * @param _owner The address whose balance will be returned. * @return balance Balance of the `_owner`. */ function balanceOf(address _owner) constant external returns (uint balance) { return balances[_owner]; } /** * @dev Change the frozen status of the LOT token. * * @param _status Desired status of the frozen bool */ function setFrozen(bool _status) external onlyFreezers returns (bool) { frozen = _status; LogFrozenStatus(frozen, now); return frozen; } /** * @dev Allow addition of freezers to allow future contracts to * use the role. * * @param _new New freezer address. */ function addFreezer(address _new) external onlyEtheraffle { freezers.push(_new); canFreeze[_new] = true; LogFreezerAddition(_new, now); } /** * @dev Remove a freezer should they no longer require or need the * the privilege. * * @param _freezer The desired address to be removed. */ function removeFreezer(address _freezer) external onlyEtheraffle { require(canFreeze[_freezer]); canFreeze[_freezer] = false; for(uint i = 0; i < freezers.length - 1; i++) if(freezers[i] == _freezer) { freezers[i] = freezers[freezers.length - 1]; break; } freezers.length--; LogFreezerRemoval(_freezer, now); } /** * @dev Allow changing of contract ownership ready for future upgrades/ * changes in management structure. * * @param _new New owner/controller address. */ function setEtheraffle(address _new) external onlyEtheraffle { LogEtheraffleChange(etheraffle, _new, now); etheraffle = _new; } /** * @dev Fallback in case of accidental ether transfer */ function () external payable { revert(); } /** * @dev Housekeeping- called in the event this contract is no * longer needed, after a LOT upgrade for example. Deletes * the code from the blockchain. Only callable by the * Etheraffle address. */ function selfDestruct() external onlyEtheraffle { require(frozen); selfdestruct(etheraffle); } }
* @dev Allow changing of contract ownership ready for future upgrades/ changes in management structure. @param _new New owner/controller address./
function setEtheraffle(address _new) external onlyEtheraffle { LogEtheraffleChange(etheraffle, _new, now); etheraffle = _new; }
5,352,186
[ 1, 7009, 12770, 434, 6835, 23178, 5695, 364, 3563, 28844, 19, 3639, 3478, 316, 11803, 3695, 18, 225, 389, 2704, 225, 1166, 3410, 19, 5723, 1758, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 444, 41, 1136, 7329, 298, 12, 2867, 389, 2704, 13, 3903, 1338, 41, 1136, 7329, 298, 288, 203, 3639, 1827, 41, 1136, 7329, 298, 3043, 12, 2437, 7329, 298, 16, 389, 2704, 16, 2037, 1769, 203, 3639, 225, 2437, 7329, 298, 273, 389, 2704, 31, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/42/0x22497560F3EbA9fc49766385cEe4f8E195b583Ba/sources/Utils/Address.sol
solhint-disable-next-line avoid-low-level-calls Look for revert reason and bubble it up if present The easiest way to bubble the revert reason is using memory via assembly solhint-disable-next-line no-inline-assembly
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); if (success) { return returndata; if (returndata.length > 0) { assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } revert(errorMessage); } } }
16,211,193
[ 1, 18281, 11317, 17, 8394, 17, 4285, 17, 1369, 4543, 17, 821, 17, 2815, 17, 12550, 10176, 364, 15226, 3971, 471, 21577, 518, 731, 309, 3430, 1021, 7264, 77, 395, 4031, 358, 21577, 326, 15226, 3971, 353, 1450, 3778, 3970, 19931, 3704, 11317, 17, 8394, 17, 4285, 17, 1369, 1158, 17, 10047, 17, 28050, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 915, 26356, 620, 12, 2867, 1018, 16, 1731, 3778, 501, 16, 2254, 5034, 732, 77, 620, 16, 533, 3778, 9324, 13, 3238, 1135, 261, 3890, 3778, 13, 288, 203, 3639, 2583, 12, 291, 8924, 12, 3299, 3631, 315, 1887, 30, 745, 358, 1661, 17, 16351, 8863, 203, 21281, 3639, 309, 261, 4768, 13, 288, 203, 5411, 327, 327, 892, 31, 203, 5411, 309, 261, 2463, 892, 18, 2469, 405, 374, 13, 288, 203, 21281, 7734, 19931, 288, 203, 10792, 2231, 327, 892, 67, 1467, 519, 312, 945, 12, 2463, 892, 13, 203, 10792, 15226, 12, 1289, 12, 1578, 16, 327, 892, 3631, 327, 892, 67, 1467, 13, 203, 7734, 289, 203, 7734, 15226, 12, 1636, 1079, 1769, 203, 5411, 289, 203, 3639, 289, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/* Copyright 2018 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.4.24; library LibBytes { using LibBytes for bytes; /// @dev Gets the memory address for a byte array. /// @param input Byte array to lookup. /// @return memoryAddress Memory address of byte array. This /// points to the header of the byte array which contains /// the length. function rawAddress(bytes memory input) internal pure returns (uint256 memoryAddress) { assembly { memoryAddress := input } return memoryAddress; } /// @dev Gets the memory address for the contents of a byte array. /// @param input Byte array to lookup. /// @return memoryAddress Memory address of the contents of the byte array. function contentAddress(bytes memory input) internal pure returns (uint256 memoryAddress) { assembly { memoryAddress := add(input, 32) } return memoryAddress; } /// @dev Copies `length` bytes from memory location `source` to `dest`. /// @param dest memory address to copy bytes to. /// @param source memory address to copy bytes from. /// @param length number of bytes to copy. function memCopy( uint256 dest, uint256 source, uint256 length ) internal pure { if (length < 32) { // Handle a partial word by reading destination and masking // off the bits we are interested in. // This correctly handles overlap, zero lengths and source == dest assembly { let mask := sub(exp(256, sub(32, length)), 1) let s := and(mload(source), not(mask)) let d := and(mload(dest), mask) mstore(dest, or(s, d)) } } else { // Skip the O(length) loop when source == dest. if (source == dest) { return; } // For large copies we copy whole words at a time. The final // word is aligned to the end of the range (instead of after the // previous) to handle partial words. So a copy will look like this: // // #### // #### // #### // #### // // We handle overlap in the source and destination range by // changing the copying direction. This prevents us from // overwriting parts of source that we still need to copy. // // This correctly handles source == dest // if (source > dest) { assembly { // We subtract 32 from `sEnd` and `dEnd` because it // is easier to compare with in the loop, and these // are also the addresses we need for copying the // last bytes. length := sub(length, 32) let sEnd := add(source, length) let dEnd := add(dest, length) // Remember the last 32 bytes of source // This needs to be done here and not after the loop // because we may have overwritten the last bytes in // source already due to overlap. let last := mload(sEnd) // Copy whole words front to back // Note: the first check is always true, // this could have been a do-while loop. // solhint-disable-next-line no-empty-blocks for {} lt(source, sEnd) {} { mstore(dest, mload(source)) source := add(source, 32) dest := add(dest, 32) } // Write the last 32 bytes mstore(dEnd, last) } } else { assembly { // We subtract 32 from `sEnd` and `dEnd` because those // are the starting points when copying a word at the end. length := sub(length, 32) let sEnd := add(source, length) let dEnd := add(dest, length) // Remember the first 32 bytes of source // This needs to be done here and not after the loop // because we may have overwritten the first bytes in // source already due to overlap. let first := mload(source) // Copy whole words back to front // We use a signed comparisson here to allow dEnd to become // negative (happens when source and dest < 32). Valid // addresses in local memory will never be larger than // 2**255, so they can be safely re-interpreted as signed. // Note: the first check is always true, // this could have been a do-while loop. // solhint-disable-next-line no-empty-blocks for {} slt(dest, dEnd) {} { mstore(dEnd, mload(sEnd)) sEnd := sub(sEnd, 32) dEnd := sub(dEnd, 32) } // Write the first 32 bytes mstore(dest, first) } } } } /// @dev Returns a slices from a byte array. /// @param b The byte array to take a slice from. /// @param from The starting index for the slice (inclusive). /// @param to The final index for the slice (exclusive). /// @return result The slice containing bytes at indices [from, to) function slice( bytes memory b, uint256 from, uint256 to ) internal pure returns (bytes memory result) { require( from <= to, "FROM_LESS_THAN_TO_REQUIRED" ); require( to < b.length, "TO_LESS_THAN_LENGTH_REQUIRED" ); // Create a new bytes structure and copy contents result = new bytes(to - from); memCopy( result.contentAddress(), b.contentAddress() + from, result.length ); return result; } /// @dev Returns a slice from a byte array without preserving the input. /// @param b The byte array to take a slice from. Will be destroyed in the process. /// @param from The starting index for the slice (inclusive). /// @param to The final index for the slice (exclusive). /// @return result The slice containing bytes at indices [from, to) /// @dev When `from == 0`, the original array will match the slice. In other cases its state will be corrupted. function sliceDestructive( bytes memory b, uint256 from, uint256 to ) internal pure returns (bytes memory result) { require( from <= to, "FROM_LESS_THAN_TO_REQUIRED" ); require( to < b.length, "TO_LESS_THAN_LENGTH_REQUIRED" ); // Create a new bytes structure around [from, to) in-place. assembly { result := add(b, from) mstore(result, sub(to, from)) } return result; } /// @dev Pops the last byte off of a byte array by modifying its length. /// @param b Byte array that will be modified. /// @return The byte that was popped off. function popLastByte(bytes memory b) internal pure returns (bytes1 result) { require( b.length > 0, "GREATER_THAN_ZERO_LENGTH_REQUIRED" ); // Store last byte. result = b[b.length - 1]; assembly { // Decrement length of byte array. let newLen := sub(mload(b), 1) mstore(b, newLen) } return result; } /// @dev Pops the last 20 bytes off of a byte array by modifying its length. /// @param b Byte array that will be modified. /// @return The 20 byte address that was popped off. function popLast20Bytes(bytes memory b) internal pure returns (address result) { require( b.length >= 20, "GREATER_OR_EQUAL_TO_20_LENGTH_REQUIRED" ); // Store last 20 bytes. result = readAddress(b, b.length - 20); assembly { // Subtract 20 from byte array length. let newLen := sub(mload(b), 20) mstore(b, newLen) } return result; } /// @dev Tests equality of two byte arrays. /// @param lhs First byte array to compare. /// @param rhs Second byte array to compare. /// @return True if arrays are the same. False otherwise. function equals( bytes memory lhs, bytes memory rhs ) internal pure returns (bool equal) { // Keccak gas cost is 30 + numWords * 6. This is a cheap way to compare. // We early exit on unequal lengths, but keccak would also correctly // handle this. return lhs.length == rhs.length && keccak256(lhs) == keccak256(rhs); } /// @dev Reads an address from a position in a byte array. /// @param b Byte array containing an address. /// @param index Index in byte array of address. /// @return address from byte array. function readAddress( bytes memory b, uint256 index ) internal pure returns (address result) { require( b.length >= index + 20, // 20 is length of address "GREATER_OR_EQUAL_TO_20_LENGTH_REQUIRED" ); // Add offset to index: // 1. Arrays are prefixed by 32-byte length parameter (add 32 to index) // 2. Account for size difference between address length and 32-byte storage word (subtract 12 from index) index += 20; // Read address from array memory assembly { // 1. Add index to address of bytes array // 2. Load 32-byte word from memory // 3. Apply 20-byte mask to obtain address result := and(mload(add(b, index)), 0xffffffffffffffffffffffffffffffffffffffff) } return result; } /// @dev Writes an address into a specific position in a byte array. /// @param b Byte array to insert address into. /// @param index Index in byte array of address. /// @param input Address to put into byte array. function writeAddress( bytes memory b, uint256 index, address input ) internal pure { require( b.length >= index + 20, // 20 is length of address "GREATER_OR_EQUAL_TO_20_LENGTH_REQUIRED" ); // Add offset to index: // 1. Arrays are prefixed by 32-byte length parameter (add 32 to index) // 2. Account for size difference between address length and 32-byte storage word (subtract 12 from index) index += 20; // Store address into array memory assembly { // The address occupies 20 bytes and mstore stores 32 bytes. // First fetch the 32-byte word where we'll be storing the address, then // apply a mask so we have only the bytes in the word that the address will not occupy. // Then combine these bytes with the address and store the 32 bytes back to memory with mstore. // 1. Add index to address of bytes array // 2. Load 32-byte word from memory // 3. Apply 12-byte mask to obtain extra bytes occupying word of memory where we'll store the address let neighbors := and( mload(add(b, index)), 0xffffffffffffffffffffffff0000000000000000000000000000000000000000 ) // Make sure input address is clean. // (Solidity does not guarantee this) input := and(input, 0xffffffffffffffffffffffffffffffffffffffff) // Store the neighbors and address into memory mstore(add(b, index), xor(input, neighbors)) } } /// @dev Reads a bytes32 value from a position in a byte array. /// @param b Byte array containing a bytes32 value. /// @param index Index in byte array of bytes32 value. /// @return bytes32 value from byte array. function readBytes32( bytes memory b, uint256 index ) internal pure returns (bytes32 result) { require( b.length >= index + 32, "GREATER_OR_EQUAL_TO_32_LENGTH_REQUIRED" ); // Arrays are prefixed by a 256 bit length parameter index += 32; // Read the bytes32 from array memory assembly { result := mload(add(b, index)) } return result; } /// @dev Writes a bytes32 into a specific position in a byte array. /// @param b Byte array to insert <input> into. /// @param index Index in byte array of <input>. /// @param input bytes32 to put into byte array. function writeBytes32( bytes memory b, uint256 index, bytes32 input ) internal pure { require( b.length >= index + 32, "GREATER_OR_EQUAL_TO_32_LENGTH_REQUIRED" ); // Arrays are prefixed by a 256 bit length parameter index += 32; // Read the bytes32 from array memory assembly { mstore(add(b, index), input) } } /// @dev Reads a uint256 value from a position in a byte array. /// @param b Byte array containing a uint256 value. /// @param index Index in byte array of uint256 value. /// @return uint256 value from byte array. function readUint256( bytes memory b, uint256 index ) internal pure returns (uint256 result) { result = uint256(readBytes32(b, index)); return result; } /// @dev Writes a uint256 into a specific position in a byte array. /// @param b Byte array to insert <input> into. /// @param index Index in byte array of <input>. /// @param input uint256 to put into byte array. function writeUint256( bytes memory b, uint256 index, uint256 input ) internal pure { writeBytes32(b, index, bytes32(input)); } /// @dev Reads an unpadded bytes4 value from a position in a byte array. /// @param b Byte array containing a bytes4 value. /// @param index Index in byte array of bytes4 value. /// @return bytes4 value from byte array. function readBytes4( bytes memory b, uint256 index ) internal pure returns (bytes4 result) { require( b.length >= index + 4, "GREATER_OR_EQUAL_TO_4_LENGTH_REQUIRED" ); // Arrays are prefixed by a 32 byte length field index += 32; // Read the bytes4 from array memory assembly { result := mload(add(b, index)) // Solidity does not require us to clean the trailing bytes. // We do it anyway result := and(result, 0xFFFFFFFF00000000000000000000000000000000000000000000000000000000) } return result; } /// @dev Reads nested bytes from a specific position. /// @dev NOTE: the returned value overlaps with the input value. /// Both should be treated as immutable. /// @param b Byte array containing nested bytes. /// @param index Index of nested bytes. /// @return result Nested bytes. function readBytesWithLength( bytes memory b, uint256 index ) internal pure returns (bytes memory result) { // Read length of nested bytes uint256 nestedBytesLength = readUint256(b, index); index += 32; // Assert length of <b> is valid, given // length of nested bytes require( b.length >= index + nestedBytesLength, "GREATER_OR_EQUAL_TO_NESTED_BYTES_LENGTH_REQUIRED" ); // Return a pointer to the byte array as it exists inside `b` assembly { result := add(b, index) } return result; } /// @dev Inserts bytes at a specific position in a byte array. /// @param b Byte array to insert <input> into. /// @param index Index in byte array of <input>. /// @param input bytes to insert. function writeBytesWithLength( bytes memory b, uint256 index, bytes memory input ) internal pure { // Assert length of <b> is valid, given // length of input require( b.length >= index + 32 + input.length, // 32 bytes to store length "GREATER_OR_EQUAL_TO_NESTED_BYTES_LENGTH_REQUIRED" ); // Copy <input> into <b> memCopy( b.contentAddress() + index, input.rawAddress(), // includes length of <input> input.length + 32 // +32 bytes to store <input> length ); } /// @dev Performs a deep copy of a byte array onto another byte array of greater than or equal length. /// @param dest Byte array that will be overwritten with source bytes. /// @param source Byte array to copy onto dest bytes. function deepCopyBytes( bytes memory dest, bytes memory source ) internal pure { uint256 sourceLen = source.length; // Dest length must be >= source length, or some bytes would not be copied. require( dest.length >= sourceLen, "GREATER_OR_EQUAL_TO_SOURCE_BYTES_LENGTH_REQUIRED" ); memCopy( dest.contentAddress(), source.contentAddress(), sourceLen ); } }
Solidity does not require us to clean the trailing bytes. We do it anyway
function readUint256( bytes memory b, uint256 index ) internal pure returns (uint256 result) } function writeUint256( bytes memory b, uint256 index, uint256 input ) internal pure } function readBytes4( bytes memory b, uint256 index ) internal pure returns (bytes4 result) assembly { result := mload(add(b, index)) result := and(result, 0xFFFFFFFF00000000000000000000000000000000000000000000000000000000) } return result;
880,534
[ 1, 25044, 560, 1552, 486, 2583, 584, 358, 2721, 326, 7341, 1731, 18, 1660, 741, 518, 13466, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 855, 5487, 5034, 12, 203, 3639, 1731, 3778, 324, 16, 203, 3639, 2254, 5034, 770, 203, 565, 262, 203, 3639, 2713, 203, 3639, 16618, 203, 3639, 1135, 261, 11890, 5034, 563, 13, 203, 565, 289, 203, 203, 565, 445, 1045, 5487, 5034, 12, 203, 3639, 1731, 3778, 324, 16, 203, 3639, 2254, 5034, 770, 16, 203, 3639, 2254, 5034, 810, 203, 565, 262, 203, 3639, 2713, 203, 3639, 16618, 203, 565, 289, 203, 203, 565, 445, 25825, 24, 12, 203, 3639, 1731, 3778, 324, 16, 203, 3639, 2254, 5034, 770, 203, 565, 262, 203, 3639, 2713, 203, 3639, 16618, 203, 3639, 1135, 261, 3890, 24, 563, 13, 203, 3639, 19931, 288, 203, 5411, 563, 519, 312, 945, 12, 1289, 12, 70, 16, 770, 3719, 203, 5411, 563, 519, 471, 12, 2088, 16, 374, 28949, 12648, 12648, 12648, 12648, 12648, 12648, 12648, 13, 203, 3639, 289, 203, 3639, 327, 563, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0xaE163dcd61248Fb25D03dD29Cf282B664d012850/sources/solady/src/utils/ECDSA.sol
@notice Gas optimized ECDSA wrapper. @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/ECDSA.sol) @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/ECDSA.sol) @author Modified from OpenZeppelin (https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/cryptography/ECDSA.sol)
library ECDSA { pragma solidity ^0.8.4; function recover(bytes32 hash, bytes calldata signature) internal view returns (address result) { assembly { if eq(signature.length, 65) { let m := mload(0x40) calldatacopy(0x40, signature.offset, 0x40) if iszero(gt(mload(0x60), 0x7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a0)) { mstore(0x00, hash) mstore(0x20, byte(0, calldataload(add(signature.offset, 0x40)))) pop( staticcall( ) ) mstore(0x60, 0) result := mload(sub(0x60, returndatasize())) } } } } function recover(bytes32 hash, bytes calldata signature) internal view returns (address result) { assembly { if eq(signature.length, 65) { let m := mload(0x40) calldatacopy(0x40, signature.offset, 0x40) if iszero(gt(mload(0x60), 0x7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a0)) { mstore(0x00, hash) mstore(0x20, byte(0, calldataload(add(signature.offset, 0x40)))) pop( staticcall( ) ) mstore(0x60, 0) result := mload(sub(0x60, returndatasize())) } } } } function recover(bytes32 hash, bytes calldata signature) internal view returns (address result) { assembly { if eq(signature.length, 65) { let m := mload(0x40) calldatacopy(0x40, signature.offset, 0x40) if iszero(gt(mload(0x60), 0x7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a0)) { mstore(0x00, hash) mstore(0x20, byte(0, calldataload(add(signature.offset, 0x40)))) pop( staticcall( ) ) mstore(0x60, 0) result := mload(sub(0x60, returndatasize())) } } } } function recover(bytes32 hash, bytes calldata signature) internal view returns (address result) { assembly { if eq(signature.length, 65) { let m := mload(0x40) calldatacopy(0x40, signature.offset, 0x40) if iszero(gt(mload(0x60), 0x7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a0)) { mstore(0x00, hash) mstore(0x20, byte(0, calldataload(add(signature.offset, 0x40)))) pop( staticcall( ) ) mstore(0x60, 0) result := mload(sub(0x60, returndatasize())) } } } } mstore(0x40, m) function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal view returns (address result) { assembly { let m := mload(0x40) let s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) if iszero(gt(s, 0x7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a0)) { mstore(0x00, hash) mstore(0x20, add(shr(255, vs), 27)) mstore(0x40, r) mstore(0x60, s) pop( staticcall( ) ) mstore(0x60, 0) result := mload(sub(0x60, returndatasize())) } } } function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal view returns (address result) { assembly { let m := mload(0x40) let s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) if iszero(gt(s, 0x7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a0)) { mstore(0x00, hash) mstore(0x20, add(shr(255, vs), 27)) mstore(0x40, r) mstore(0x60, s) pop( staticcall( ) ) mstore(0x60, 0) result := mload(sub(0x60, returndatasize())) } } } function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal view returns (address result) { assembly { let m := mload(0x40) let s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) if iszero(gt(s, 0x7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a0)) { mstore(0x00, hash) mstore(0x20, add(shr(255, vs), 27)) mstore(0x40, r) mstore(0x60, s) pop( staticcall( ) ) mstore(0x60, 0) result := mload(sub(0x60, returndatasize())) } } } mstore(0x40, m) function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32 result) { assembly { mstore(0x20, hash) mstore(0x00, "\x00\x00\x00\x00\x19Ethereum Signed Message:\n32") result := keccak256(0x04, 0x3c) } } function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32 result) { assembly { mstore(0x20, hash) mstore(0x00, "\x00\x00\x00\x00\x19Ethereum Signed Message:\n32") result := keccak256(0x04, 0x3c) } } function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32 result) { assembly { let m3 := mload(sub(s, 0x60)) let m2 := mload(sub(s, 0x40)) let m1 := mload(sub(s, 0x20)) let sLength := mload(s) let ptr := add(s, 0x20) let end := add(ptr, sLength) ptr := sub(ptr, 1) mstore8(ptr, add(48, mod(temp, 10))) temp := div(temp, 10) } mstore(sub(s, 0x20), m1) mstore(sub(s, 0x40), m2) mstore(sub(s, 0x60), m3) } function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32 result) { assembly { let m3 := mload(sub(s, 0x60)) let m2 := mload(sub(s, 0x40)) let m1 := mload(sub(s, 0x20)) let sLength := mload(s) let ptr := add(s, 0x20) let end := add(ptr, sLength) ptr := sub(ptr, 1) mstore8(ptr, add(48, mod(temp, 10))) temp := div(temp, 10) } mstore(sub(s, 0x20), m1) mstore(sub(s, 0x40), m2) mstore(sub(s, 0x60), m3) } for { let temp := sLength } 1 {} { if iszero(temp) { break } mstore(sub(ptr, 0x20), "\x00\x00\x00\x00\x00\x00\x19Ethereum Signed Message:\n") result := keccak256(sub(ptr, 0x1a), sub(end, sub(ptr, 0x1a))) mstore(s, sLength) }
4,421,196
[ 1, 27998, 15411, 7773, 19748, 4053, 18, 225, 348, 355, 361, 93, 261, 4528, 2207, 6662, 18, 832, 19, 7737, 1235, 19, 18281, 361, 93, 19, 10721, 19, 5254, 19, 4816, 19, 5471, 19, 7228, 19748, 18, 18281, 13, 225, 21154, 628, 348, 355, 81, 340, 261, 4528, 2207, 6662, 18, 832, 19, 2338, 7300, 2499, 19, 18281, 81, 340, 19, 10721, 19, 5254, 19, 4816, 19, 5471, 19, 7228, 19748, 18, 18281, 13, 225, 21154, 628, 3502, 62, 881, 84, 292, 267, 261, 4528, 2207, 6662, 18, 832, 19, 3678, 62, 881, 84, 292, 267, 19, 3190, 94, 881, 84, 292, 267, 17, 16351, 87, 19, 10721, 19, 7525, 19, 16351, 87, 19, 5471, 19, 22784, 15669, 19, 7228, 19748, 18, 18281, 13, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 12083, 7773, 19748, 288, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 24, 31, 203, 565, 445, 5910, 12, 3890, 1578, 1651, 16, 1731, 745, 892, 3372, 13, 2713, 1476, 1135, 261, 2867, 563, 13, 288, 203, 3639, 19931, 288, 203, 5411, 309, 7555, 12, 8195, 18, 2469, 16, 15892, 13, 288, 203, 7734, 2231, 312, 519, 312, 945, 12, 20, 92, 7132, 13, 203, 7734, 745, 892, 3530, 12, 20, 92, 7132, 16, 3372, 18, 3348, 16, 374, 92, 7132, 13, 203, 203, 7734, 309, 353, 7124, 12, 4521, 12, 81, 945, 12, 20, 92, 4848, 3631, 374, 92, 27, 9460, 9460, 9460, 9460, 9460, 9460, 18217, 74, 25, 72, 25, 6669, 73, 27, 4763, 27, 69, 7950, 1611, 449, 3030, 9975, 74, 24, 6028, 11861, 70, 3462, 69, 20, 3719, 288, 203, 10792, 312, 2233, 12, 20, 92, 713, 16, 1651, 13, 203, 10792, 312, 2233, 12, 20, 92, 3462, 16, 1160, 12, 20, 16, 745, 72, 3145, 6189, 12, 1289, 12, 8195, 18, 3348, 16, 374, 92, 7132, 3719, 3719, 203, 10792, 1843, 12, 203, 13491, 760, 1991, 12, 203, 13491, 262, 203, 10792, 262, 203, 10792, 312, 2233, 12, 20, 92, 4848, 16, 374, 13, 203, 10792, 563, 519, 312, 945, 12, 1717, 12, 20, 92, 4848, 16, 327, 13178, 554, 1435, 3719, 203, 7734, 289, 203, 5411, 289, 203, 3639, 289, 203, 565, 289, 203, 203, 565, 445, 5910, 12, 3890, 1578, 1651, 16, 1731, 745, 892, 3372, 13, 2713, 1476, 1135, 261, 2867, 563, 13, 288, 2 ]
pragma solidity ^0.4.18; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } /** * @title Claimable * @dev Extension for the Ownable contract, where the ownership needs to be claimed. * This allows the new owner to accept the transfer. */ contract Claimable is Ownable { address public pendingOwner; /** * @dev Modifier throws if called by any account other than the pendingOwner. */ modifier onlyPendingOwner() { require(msg.sender == pendingOwner); _; } /** * @dev Allows the current owner to set the pendingOwner address. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { pendingOwner = newOwner; } /** * @dev Allows the pendingOwner address to finalize the transfer. */ function claimOwnership() public onlyPendingOwner { OwnershipTransferred(owner, pendingOwner); owner = pendingOwner; pendingOwner = address(0); } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 internal totalSupply_; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval( address indexed owner, address indexed spender, uint256 value ); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Transfer( address indexed from, address indexed to, uint256 value ); event Approval( address indexed owner, address indexed spender, uint256 value ); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } /** * @title LimitedTransferToken * @dev LimitedTransferToken defines the generic interface and the implementation to limit token * transferability for different events. It is intended to be used as a base class for other token * contracts. * LimitedTransferToken has been designed to allow for different limiting factors, * this can be achieved by recursively calling super.transferableTokens() until the base class is * hit. For example: * function transferableTokens(address holder, uint64 time) constant public returns (uint256) { * return min256(unlockedTokens, super.transferableTokens(holder, time)); * } * A working example is VestedToken.sol: * https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/token/VestedToken.sol */ contract LimitedTransferToken is ERC20 { /** * @dev Checks whether it can transfer or otherwise throws. */ modifier canTransfer(address _sender, uint256 _value) { require(_value <= transferableTokens(_sender, uint64(block.timestamp))); _; } /** * @dev Checks modifier and allows transfer if tokens are not locked. * @param _to The address that will receive the tokens. * @param _value The amount of tokens to be transferred. */ function transfer(address _to, uint256 _value) canTransfer(msg.sender, _value) public returns (bool) { return super.transfer(_to, _value); } /** * @dev Checks modifier and allows transfer if tokens are not locked. * @param _from The address that will send the tokens. * @param _to The address that will receive the tokens. * @param _value The amount of tokens to be transferred. */ function transferFrom(address _from, address _to, uint256 _value) canTransfer(_from, _value) public returns (bool) { return super.transferFrom(_from, _to, _value); } /** * @dev Default transferable tokens function returns all tokens for a holder (no limit). * @dev Overwriting transferableTokens(address holder, uint64 time) is the way to provide the * specific logic for limiting token transferability for a holder over time. */ function transferableTokens(address holder, uint64 time) public view returns (uint256) { return balanceOf(holder); } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://github.com/ethereum/EIPs/issues/20 * Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20 { using SafeMath for uint256; mapping(address => uint256) balances; mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_value <= balances[msg.sender]); require(_to != address(0)); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender&#39;s allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); require(_to != address(0)); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval( address _spender, uint256 _addedValue ) public returns (bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval( address _spender, uint256 _subtractedValue ) public returns (bool) { uint256 oldValue = allowed[msg.sender][_spender]; if (_subtractedValue >= oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Claimable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } modifier hasMintPermission() { require(msg.sender == owner); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint( address _to, uint256 _amount ) public hasMintPermission canMint returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() public onlyOwner canMint returns (bool) { mintingFinished = true; MintFinished(); return true; } } /* Smart Token interface */ contract ISmartToken { // ================================================================================================================= // Members // ================================================================================================================= bool public transfersEnabled = false; // ================================================================================================================= // Event // ================================================================================================================= // triggered when a smart token is deployed - the _token address is defined for forward compatibility, in case we want to trigger the event from a factory event NewSmartToken(address _token); // triggered when the total supply is increased event Issuance(uint256 _amount); // triggered when the total supply is decreased event Destruction(uint256 _amount); // ================================================================================================================= // Functions // ================================================================================================================= function disableTransfers(bool _disable) public; function issue(address _to, uint256 _amount) public; function destroy(address _from, uint256 _amount) public; } /** BancorSmartToken */ contract LimitedTransferBancorSmartToken is MintableToken, ISmartToken, LimitedTransferToken { // ================================================================================================================= // Modifiers // ================================================================================================================= /** * @dev Throws if destroy flag is not enabled. */ modifier canDestroy() { require(destroyEnabled); _; } // ================================================================================================================= // Members // ================================================================================================================= // We add this flag to avoid users and owner from destroy tokens during crowdsale, // This flag is set to false by default and blocks destroy function, // We enable destroy option on finalize, so destroy will be possible after the crowdsale. bool public destroyEnabled = false; // ================================================================================================================= // Public Functions // ================================================================================================================= function setDestroyEnabled(bool _enable) onlyOwner public { destroyEnabled = _enable; } // ================================================================================================================= // Impl ISmartToken // ================================================================================================================= //@Override function disableTransfers(bool _disable) onlyOwner public { transfersEnabled = !_disable; } //@Override function issue(address _to, uint256 _amount) onlyOwner public { require(super.mint(_to, _amount)); Issuance(_amount); } //@Override function destroy(address _from, uint256 _amount) canDestroy public { require(msg.sender == _from || msg.sender == owner); // validate input balances[_from] = balances[_from].sub(_amount); totalSupply_ = totalSupply_.sub(_amount); Destruction(_amount); Transfer(_from, 0x0, _amount); } // ================================================================================================================= // Impl LimitedTransferToken // ================================================================================================================= // Enable/Disable token transfer // Tokens will be locked in their wallets until the end of the Crowdsale. // @holder - token`s owner // @time - not used (framework unneeded functionality) // // @Override function transferableTokens(address holder, uint64 time) public constant returns (uint256) { require(transfersEnabled); return super.transferableTokens(holder, time); } } /** A Token which is &#39;Bancor&#39; compatible and can mint new tokens and pause token-transfer functionality */ contract BitMEDSmartToken is LimitedTransferBancorSmartToken { // ================================================================================================================= // Members // ================================================================================================================= string public constant name = "BitMED"; string public constant symbol = "BXM"; uint8 public constant decimals = 18; // ================================================================================================================= // Constructor // ================================================================================================================= function BitMEDSmartToken() public { //Apart of &#39;Bancor&#39; computability - triggered when a smart token is deployed NewSmartToken(address(this)); } } /** * @title Vault * @dev This wallet is used to */ contract Vault is Claimable { using SafeMath for uint256; // ================================================================================================================= // Enums // ================================================================================================================= enum State { KycPending, KycComplete } // ================================================================================================================= // Members // ================================================================================================================= mapping (address => uint256) public depositedETH; mapping (address => uint256) public depositedToken; BitMEDSmartToken public token; State public state; // ================================================================================================================= // Events // ================================================================================================================= event KycPending(); event KycComplete(); event Deposit(address indexed beneficiary, uint256 etherWeiAmount, uint256 tokenWeiAmount); event RemoveSupporter(address beneficiary); event TokensClaimed(address indexed beneficiary, uint256 weiAmount); // ================================================================================================================= // Modifiers // ================================================================================================================= modifier isKycPending() { require(state == State.KycPending); _; } modifier isKycComplete() { require(state == State.KycComplete); _; } // ================================================================================================================= // Ctors // ================================================================================================================= function Vault(BitMEDSmartToken _token) public { require(_token != address(0)); token = _token; state = State.KycPending; KycPending(); } // ================================================================================================================= // Public Functions // ================================================================================================================= function deposit(address supporter, uint256 tokensAmount, uint256 value) isKycPending onlyOwner public{ depositedETH[supporter] = depositedETH[supporter].add(value); depositedToken[supporter] = depositedToken[supporter].add(tokensAmount); Deposit(supporter, value, tokensAmount); } function kycComplete() isKycPending onlyOwner public { state = State.KycComplete; KycComplete(); } //@dev Remove a supporter and refund ether back to the supporter in returns of proportional amount of BXM back to the BitMED`s wallet function removeSupporter(address supporter) isKycPending onlyOwner public { require(supporter != address(0)); require(depositedETH[supporter] > 0); require(depositedToken[supporter] > 0); uint256 depositedTokenValue = depositedToken[supporter]; uint256 depositedETHValue = depositedETH[supporter]; //zero out the user depositedETH[supporter] = 0; depositedToken[supporter] = 0; token.destroy(address(this),depositedTokenValue); // We will manually refund the money. Checking against OFAC sanction list // https://sanctionssearch.ofac.treas.gov/ //supporter.transfer(depositedETHValue - 21000); RemoveSupporter(supporter); } //@dev Transfer tokens from the vault to the supporter while releasing proportional amount of ether to BitMED`s wallet. //Can be triggerd by the supporter only function claimTokens(uint256 tokensToClaim) isKycComplete public { require(tokensToClaim != 0); address supporter = msg.sender; require(depositedToken[supporter] > 0); uint256 depositedTokenValue = depositedToken[supporter]; uint256 depositedETHValue = depositedETH[supporter]; require(tokensToClaim <= depositedTokenValue); uint256 claimedETH = tokensToClaim.mul(depositedETHValue).div(depositedTokenValue); assert(claimedETH > 0); depositedETH[supporter] = depositedETHValue.sub(claimedETH); depositedToken[supporter] = depositedTokenValue.sub(tokensToClaim); token.transfer(supporter, tokensToClaim); TokensClaimed(supporter, tokensToClaim); } //@dev Transfer tokens from the vault to the supporter //Can be triggerd by the owner of the vault function claimAllSupporterTokensByOwner(address supporter) isKycComplete onlyOwner public { uint256 depositedTokenValue = depositedToken[supporter]; require(depositedTokenValue > 0); token.transfer(supporter, depositedTokenValue); TokensClaimed(supporter, depositedTokenValue); } // @dev supporter can claim tokens by calling the function // @param tokenToClaimAmount - amount of the token to claim function claimAllTokens() isKycComplete public { uint256 depositedTokenValue = depositedToken[msg.sender]; claimTokens(depositedTokenValue); } } /** * @title RefundVault * @dev This contract is used for storing TOKENS AND ETHER while a crowd sale is in progress for a period of 3 DAYS. * Supporter can ask for a full/part refund for his/her ether against token. Once tokens are Claimed by the supporter, they cannot be refunded. * After 3 days, all ether will be withdrawn from the vault`s wallet, leaving all tokens to be claimed by the their owners. **/ contract RefundVault is Claimable { using SafeMath for uint256; // ================================================================================================================= // Enums // ================================================================================================================= enum State { Active, Refunding, Closed } // ================================================================================================================= // Members // ================================================================================================================= // Refund time frame uint256 public constant REFUND_TIME_FRAME = 3 days; mapping (address => uint256) public depositedETH; mapping (address => uint256) public depositedToken; address public etherWallet; BitMEDSmartToken public token; State public state; uint256 public refundStartTime; // ================================================================================================================= // Events // ================================================================================================================= event Active(); event Closed(); event Deposit(address indexed beneficiary, uint256 etherWeiAmount, uint256 tokenWeiAmount); event RefundsEnabled(); event RefundedETH(address beneficiary, uint256 weiAmount); event TokensClaimed(address indexed beneficiary, uint256 weiAmount); // ================================================================================================================= // Modifiers // ================================================================================================================= modifier isActiveState() { require(state == State.Active); _; } modifier isRefundingState() { require(state == State.Refunding); _; } modifier isCloseState() { require(state == State.Closed); _; } modifier isRefundingOrCloseState() { require(state == State.Refunding || state == State.Closed); _; } modifier isInRefundTimeFrame() { require(refundStartTime <= block.timestamp && refundStartTime + REFUND_TIME_FRAME > block.timestamp); _; } modifier isRefundTimeFrameExceeded() { require(refundStartTime + REFUND_TIME_FRAME < block.timestamp); _; } // ================================================================================================================= // Ctors // ================================================================================================================= function RefundVault(address _etherWallet, BitMEDSmartToken _token) public { require(_etherWallet != address(0)); require(_token != address(0)); etherWallet = _etherWallet; token = _token; state = State.Active; Active(); } // ================================================================================================================= // Public Functions // ================================================================================================================= function deposit(address supporter, uint256 tokensAmount) isActiveState onlyOwner public payable { depositedETH[supporter] = depositedETH[supporter].add(msg.value); depositedToken[supporter] = depositedToken[supporter].add(tokensAmount); Deposit(supporter, msg.value, tokensAmount); } function close() isRefundingState onlyOwner isRefundTimeFrameExceeded public { state = State.Closed; Closed(); etherWallet.transfer(address(this).balance); } function enableRefunds() isActiveState onlyOwner public { state = State.Refunding; refundStartTime = block.timestamp; RefundsEnabled(); } //@dev Refund ether back to the supporter in returns of proportional amount of BXM back to the BitMED`s wallet function refundETH(uint256 ETHToRefundAmountWei) isInRefundTimeFrame isRefundingState public { require(ETHToRefundAmountWei != 0); uint256 depositedTokenValue = depositedToken[msg.sender]; uint256 depositedETHValue = depositedETH[msg.sender]; require(ETHToRefundAmountWei <= depositedETHValue); uint256 refundTokens = ETHToRefundAmountWei.mul(depositedTokenValue).div(depositedETHValue); assert(refundTokens > 0); depositedETH[msg.sender] = depositedETHValue.sub(ETHToRefundAmountWei); depositedToken[msg.sender] = depositedTokenValue.sub(refundTokens); token.destroy(address(this),refundTokens); msg.sender.transfer(ETHToRefundAmountWei); RefundedETH(msg.sender, ETHToRefundAmountWei); } //@dev Transfer tokens from the vault to the supporter while releasing proportional amount of ether to BitMED`s wallet. //Can be triggerd by the supporter only function claimTokens(uint256 tokensToClaim) isRefundingOrCloseState public { require(tokensToClaim != 0); address supporter = msg.sender; require(depositedToken[supporter] > 0); uint256 depositedTokenValue = depositedToken[supporter]; uint256 depositedETHValue = depositedETH[supporter]; require(tokensToClaim <= depositedTokenValue); uint256 claimedETH = tokensToClaim.mul(depositedETHValue).div(depositedTokenValue); assert(claimedETH > 0); depositedETH[supporter] = depositedETHValue.sub(claimedETH); depositedToken[supporter] = depositedTokenValue.sub(tokensToClaim); token.transfer(supporter, tokensToClaim); if(state != State.Closed) { etherWallet.transfer(claimedETH); } TokensClaimed(supporter, tokensToClaim); } //@dev Transfer tokens from the vault to the supporter while releasing proportional amount of ether to BitMED`s wallet. //Can be triggerd by the owner of the vault (in our case - BitMED`s owner after 3 days) function claimAllSupporterTokensByOwner(address supporter) isCloseState onlyOwner public { uint256 depositedTokenValue = depositedToken[supporter]; require(depositedTokenValue > 0); token.transfer(supporter, depositedTokenValue); TokensClaimed(supporter, depositedTokenValue); } // @dev supporter can claim tokens by calling the function // @param tokenToClaimAmount - amount of the token to claim function claimAllTokens() isRefundingOrCloseState public { uint256 depositedTokenValue = depositedToken[msg.sender]; claimTokens(depositedTokenValue); } } /** * @title Crowdsale * @dev Crowdsale is a base contract for managing a token crowdsale. * Crowdsales have a start and end timestamps, where investors can make * token purchases and the crowdsale will assign them tokens based * on a token per ETH rate. Funds collected are forwarded to a wallet * as they arrive. */ contract Crowdsale { using SafeMath for uint256; // The token being sold BitMEDSmartToken public token; // start and end timestamps where investments are allowed (both inclusive) uint256 public startTime; uint256 public endTime; // address where funds are collected address public wallet; // how many token units a buyer gets per wei uint256 public rate; // amount of raised money in wei uint256 public weiRaised; // holding vault for all tokens pending KYC Vault public vault; /** * event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); function Crowdsale(uint256 _startTime, uint256 _endTime, uint256 _rate, address _wallet, BitMEDSmartToken _token, Vault _vault) public { require(_startTime >= block.timestamp); require(_endTime >= _startTime); require(_rate > 0); require(_wallet != address(0)); require(_token != address(0)); require(_vault != address(0)); startTime = _startTime; endTime = _endTime; rate = _rate; wallet = _wallet; token = _token; vault = _vault; } // fallback function can be used to buy tokens function() external payable { buyTokens(msg.sender); } // low level token purchase function function buyTokens(address beneficiary) public payable { require(beneficiary != address(0)); require(validPurchase()); uint256 weiAmount = msg.value; require(weiAmount>500000000000000000); // calculate token amount to be created uint256 tokens = weiAmount.mul(getRate()); // update state weiRaised = weiRaised.add(weiAmount); //send tokens to KYC Vault token.issue(address(vault), tokens); // Updating arrays in the Vault vault.deposit(beneficiary, tokens, msg.value); TokenPurchase(msg.sender, beneficiary, weiAmount, tokens); // Transferring funds to wallet forwardFunds(); } // send ether to the fund collection wallet // override to create custom fund forwarding mechanisms function forwardFunds() internal { wallet.transfer(msg.value); } // @return true if the transaction can buy tokens function validPurchase() internal view returns (bool) { bool withinPeriod = block.timestamp >= startTime && block.timestamp <= endTime; bool nonZeroPurchase = msg.value != 0; return withinPeriod && nonZeroPurchase; } // @return true if crowdsale event has ended function hasEnded() public view returns (bool) { return block.timestamp > endTime; } // @return the crowdsale rate function getRate() public view returns (uint256) { return rate; } } /** * @title FinalizableCrowdsale * @dev Extension of Crowdsale where an owner can do extra work * after finishing. */ contract FinalizableCrowdsale is Crowdsale, Claimable { using SafeMath for uint256; bool public isFinalized = false; event Finalized(); /** * @dev Must be called after crowdsale ends, to do some extra finalization * work. Calls the contract&#39;s finalization function. */ function finalize() public onlyOwner { require(!isFinalized); require(hasEnded()); finalization(); Finalized(); isFinalized = true; } /** * @dev Can be overridden to add finalization logic. The overriding function * should call super.finalization() to ensure the chain of finalization is * executed entirely. */ function finalization() internal { } } contract BitMEDCrowdsale is FinalizableCrowdsale { // ================================================================================================================= // Constants // ================================================================================================================= // Max amount of known addresses of which will get BXM by &#39;Grant&#39; method. // // grantees addresses will be BitMED wallets addresses. // these wallets will contain BXM tokens that will be used for one purposes only - // 1. BXM tokens against raised fiat money // we set the value to 10 (and not to 2) because we want to allow some flexibility for cases like fiat money that is raised close // to the crowdsale. we limit the value to 10 (and not larger) to limit the run time of the function that process the grantees array. uint8 public constant MAX_TOKEN_GRANTEES = 10; // BXM to ETH base rate uint256 public constant EXCHANGE_RATE = 210; // Refund division rate uint256 public constant REFUND_DIVISION_RATE = 2; // The min BXM tokens that should be minted for the public sale uint256 public constant MIN_TOKEN_SALE = 125000000000000000000000000; // ================================================================================================================= // Modifiers // ================================================================================================================= /** * @dev Throws if called not during the crowdsale time frame */ modifier onlyWhileSale() { require(isActive()); _; } // ================================================================================================================= // Members // ================================================================================================================= // wallets address for 75% of BXM allocation address public walletTeam; //10% of the total number of BXM tokens will be allocated to the team address public walletReserve; //35% of the total number of BXM tokens will be allocated to BitMED and as a reserve for the company to be used for future strategic plans for the created ecosystem address public walletCommunity; //30% of the total number of BXM tokens will be allocated to Community // Funds collected outside the crowdsale in wei uint256 public fiatRaisedConvertedToWei; //Grantees - used for non-ether and presale bonus token generation address[] public presaleGranteesMapKeys; mapping (address => uint256) public presaleGranteesMap; //address=>wei token amount // The refund vault RefundVault public refundVault; // ================================================================================================================= // Events // ================================================================================================================= event GrantAdded(address indexed _grantee, uint256 _amount); event GrantUpdated(address indexed _grantee, uint256 _oldAmount, uint256 _newAmount); event GrantDeleted(address indexed _grantee, uint256 _hadAmount); event FiatRaisedUpdated(address indexed _address, uint256 _fiatRaised); event TokenPurchaseWithGuarantee(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); // ================================================================================================================= // Constructors // ================================================================================================================= function BitMEDCrowdsale(uint256 _startTime, uint256 _endTime, address _wallet, address _walletTeam, address _walletCommunity, address _walletReserve, BitMEDSmartToken _BitMEDSmartToken, RefundVault _refundVault, Vault _vault) public Crowdsale(_startTime, _endTime, EXCHANGE_RATE, _wallet, _BitMEDSmartToken, _vault) { require(_walletTeam != address(0)); require(_walletCommunity != address(0)); require(_walletReserve != address(0)); require(_BitMEDSmartToken != address(0)); require(_refundVault != address(0)); require(_vault != address(0)); walletTeam = _walletTeam; walletCommunity = _walletCommunity; walletReserve = _walletReserve; token = _BitMEDSmartToken; refundVault = _refundVault; vault = _vault; } // ================================================================================================================= // Impl Crowdsale // ================================================================================================================= // @return the rate in BXM per 1 ETH according to the time of the tx and the BXM pricing program. // @Override function getRate() public view returns (uint256) { if (block.timestamp < (startTime.add(24 hours))) {return 700;} if (block.timestamp < (startTime.add(3 days))) {return 600;} if (block.timestamp < (startTime.add(5 days))) {return 500;} if (block.timestamp < (startTime.add(7 days))) {return 400;} if (block.timestamp < (startTime.add(10 days))) {return 350;} if (block.timestamp < (startTime.add(13 days))) {return 300;} if (block.timestamp < (startTime.add(16 days))) {return 285;} if (block.timestamp < (startTime.add(19 days))) {return 270;} if (block.timestamp < (startTime.add(22 days))) {return 260;} if (block.timestamp < (startTime.add(25 days))) {return 250;} if (block.timestamp < (startTime.add(28 days))) {return 240;} if (block.timestamp < (startTime.add(31 days))) {return 230;} if (block.timestamp < (startTime.add(34 days))) {return 225;} if (block.timestamp < (startTime.add(37 days))) {return 220;} if (block.timestamp < (startTime.add(40 days))) {return 215;} return rate; } // ================================================================================================================= // Impl FinalizableCrowdsale // ================================================================================================================= //@Override function finalization() internal { super.finalization(); // granting bonuses for the pre crowdsale grantees: for (uint256 i = 0; i < presaleGranteesMapKeys.length; i++) { token.issue(presaleGranteesMapKeys[i], presaleGranteesMap[presaleGranteesMapKeys[i]]); } //we want to make sure a min of 125M tokens are generated which equals the 25% of the crowdsale if(token.totalSupply() <= MIN_TOKEN_SALE){ uint256 missingTokens = MIN_TOKEN_SALE - token.totalSupply(); token.issue(walletCommunity, missingTokens); } // Adding 75% of the total token supply (25% were generated during the crowdsale) // 25 * 4 = 100 uint256 newTotalSupply = token.totalSupply().mul(400).div(100); // 10% of the total number of BXM tokens will be allocated to the team token.issue(walletTeam, newTotalSupply.mul(10).div(100)); // 30% of the total number of BXM tokens will be allocated to community token.issue(walletCommunity, newTotalSupply.mul(30).div(100)); // 35% of the total number of BXM tokens will be allocated to BitMED , // and as a reserve for the company to be used for future strategic plans for the created ecosystem token.issue(walletReserve, newTotalSupply.mul(35).div(100)); // Re-enable transfers after the token sale. token.disableTransfers(false); // Re-enable destroy function after the token sale. token.setDestroyEnabled(true); // Enable ETH refunds and token claim. refundVault.enableRefunds(); // transfer token ownership to crowdsale owner token.transferOwnership(owner); // transfer refundVault ownership to crowdsale owner refundVault.transferOwnership(owner); vault.transferOwnership(owner); } // ================================================================================================================= // Public Methods // ================================================================================================================= // @return the total funds collected in wei(ETH and none ETH). function getTotalFundsRaised() public view returns (uint256) { return fiatRaisedConvertedToWei.add(weiRaised); } // @return true if the crowdsale is active, hence users can buy tokens function isActive() public view returns (bool) { return block.timestamp >= startTime && block.timestamp < endTime; } // ================================================================================================================= // External Methods // ================================================================================================================= // @dev Adds/Updates address and token allocation for token grants. // Granted tokens are allocated to non-ether, presale, buyers. // @param _grantee address The address of the token grantee. // @param _value uint256 The value of the grant in wei token. function addUpdateGrantee(address _grantee, uint256 _value) external onlyOwner onlyWhileSale{ require(_grantee != address(0)); require(_value > 0); // Adding new key if not present: if (presaleGranteesMap[_grantee] == 0) { require(presaleGranteesMapKeys.length < MAX_TOKEN_GRANTEES); presaleGranteesMapKeys.push(_grantee); GrantAdded(_grantee, _value); } else { GrantUpdated(_grantee, presaleGranteesMap[_grantee], _value); } presaleGranteesMap[_grantee] = _value; } // @dev deletes entries from the grants list. // @param _grantee address The address of the token grantee. function deleteGrantee(address _grantee) external onlyOwner onlyWhileSale { require(_grantee != address(0)); require(presaleGranteesMap[_grantee] != 0); //delete from the map: delete presaleGranteesMap[_grantee]; //delete from the array (keys): uint256 index; for (uint256 i = 0; i < presaleGranteesMapKeys.length; i++) { if (presaleGranteesMapKeys[i] == _grantee) { index = i; break; } } presaleGranteesMapKeys[index] = presaleGranteesMapKeys[presaleGranteesMapKeys.length - 1]; delete presaleGranteesMapKeys[presaleGranteesMapKeys.length - 1]; presaleGranteesMapKeys.length--; GrantDeleted(_grantee, presaleGranteesMap[_grantee]); } // @dev Set funds collected outside the crowdsale in wei. // note: we not to use accumulator to allow flexibility in case of humane mistakes. // funds are converted to wei using the market conversion rate of USD\ETH on the day on the purchase. // @param _fiatRaisedConvertedToWei number of none eth raised. function setFiatRaisedConvertedToWei(uint256 _fiatRaisedConvertedToWei) external onlyOwner onlyWhileSale { fiatRaisedConvertedToWei = _fiatRaisedConvertedToWei; FiatRaisedUpdated(msg.sender, fiatRaisedConvertedToWei); } /// @dev Accepts new ownership on behalf of the BitMEDCrowdsale contract. This can be used, by the token sale /// contract itself to claim back ownership of the BitMEDSmartToken contract. function claimTokenOwnership() external onlyOwner { token.claimOwnership(); } /// @dev Accepts new ownership on behalf of the BitMEDCrowdsale contract. This can be used, by the token sale /// contract itself to claim back ownership of the refundVault contract. function claimRefundVaultOwnership() external onlyOwner { refundVault.claimOwnership(); } /// @dev Accepts new ownership on behalf of the BitMEDCrowdsale contract. This can be used, by the token sale /// contract itself to claim back ownership of the refundVault contract. function claimVaultOwnership() external onlyOwner { vault.claimOwnership(); } // @dev Buy tokes with guarantee function buyTokensWithGuarantee() public payable { require(validPurchase()); uint256 weiAmount = msg.value; require(weiAmount>500000000000000000); // calculate token amount to be created uint256 tokens = weiAmount.mul(getRate()); tokens = tokens.div(REFUND_DIVISION_RATE); // update state weiRaised = weiRaised.add(weiAmount); token.issue(address(refundVault), tokens); refundVault.deposit.value(msg.value)(msg.sender, tokens); TokenPurchaseWithGuarantee(msg.sender, address(refundVault), weiAmount, tokens); } }
* @title RefundVault @dev This contract is used for storing TOKENS AND ETHER while a crowd sale is in progress for a period of 3 DAYS. Supporter can ask for a full/part refund for his/her ether against token. Once tokens are Claimed by the supporter, they cannot be refunded. After 3 days, all ether will be withdrawn from the vault`s wallet, leaving all tokens to be claimed by the their owners./ ================================================================================================================= Enums ================================================================================================================= ================================================================================================================= Members ================================================================================================================= Refund time frame ================================================================================================================= Events ================================================================================================================= ================================================================================================================= Modifiers =================================================================================================================
contract RefundVault is Claimable { using SafeMath for uint256; uint256 public constant REFUND_TIME_FRAME = 3 days; mapping (address => uint256) public depositedETH; mapping (address => uint256) public depositedToken; address public etherWallet; BitMEDSmartToken public token; State public state; uint256 public refundStartTime; event Active(); event Closed(); event Deposit(address indexed beneficiary, uint256 etherWeiAmount, uint256 tokenWeiAmount); event RefundsEnabled(); event RefundedETH(address beneficiary, uint256 weiAmount); event TokensClaimed(address indexed beneficiary, uint256 weiAmount); enum State { Active, Refunding, Closed } modifier isActiveState() { require(state == State.Active); _; } modifier isRefundingState() { require(state == State.Refunding); _; } modifier isCloseState() { require(state == State.Closed); _; } modifier isRefundingOrCloseState() { require(state == State.Refunding || state == State.Closed); _; } modifier isInRefundTimeFrame() { require(refundStartTime <= block.timestamp && refundStartTime + REFUND_TIME_FRAME > block.timestamp); _; } modifier isRefundTimeFrameExceeded() { require(refundStartTime + REFUND_TIME_FRAME < block.timestamp); _; } function RefundVault(address _etherWallet, BitMEDSmartToken _token) public { require(_etherWallet != address(0)); require(_token != address(0)); etherWallet = _etherWallet; token = _token; state = State.Active; Active(); } function deposit(address supporter, uint256 tokensAmount) isActiveState onlyOwner public payable { depositedETH[supporter] = depositedETH[supporter].add(msg.value); depositedToken[supporter] = depositedToken[supporter].add(tokensAmount); Deposit(supporter, msg.value, tokensAmount); } function close() isRefundingState onlyOwner isRefundTimeFrameExceeded public { state = State.Closed; Closed(); etherWallet.transfer(address(this).balance); } function enableRefunds() isActiveState onlyOwner public { state = State.Refunding; refundStartTime = block.timestamp; RefundsEnabled(); } function refundETH(uint256 ETHToRefundAmountWei) isInRefundTimeFrame isRefundingState public { require(ETHToRefundAmountWei != 0); uint256 depositedTokenValue = depositedToken[msg.sender]; uint256 depositedETHValue = depositedETH[msg.sender]; require(ETHToRefundAmountWei <= depositedETHValue); uint256 refundTokens = ETHToRefundAmountWei.mul(depositedTokenValue).div(depositedETHValue); assert(refundTokens > 0); depositedETH[msg.sender] = depositedETHValue.sub(ETHToRefundAmountWei); depositedToken[msg.sender] = depositedTokenValue.sub(refundTokens); token.destroy(address(this),refundTokens); msg.sender.transfer(ETHToRefundAmountWei); RefundedETH(msg.sender, ETHToRefundAmountWei); } function claimTokens(uint256 tokensToClaim) isRefundingOrCloseState public { require(tokensToClaim != 0); address supporter = msg.sender; require(depositedToken[supporter] > 0); uint256 depositedTokenValue = depositedToken[supporter]; uint256 depositedETHValue = depositedETH[supporter]; require(tokensToClaim <= depositedTokenValue); uint256 claimedETH = tokensToClaim.mul(depositedETHValue).div(depositedTokenValue); assert(claimedETH > 0); depositedETH[supporter] = depositedETHValue.sub(claimedETH); depositedToken[supporter] = depositedTokenValue.sub(tokensToClaim); token.transfer(supporter, tokensToClaim); if(state != State.Closed) { etherWallet.transfer(claimedETH); } TokensClaimed(supporter, tokensToClaim); } function claimTokens(uint256 tokensToClaim) isRefundingOrCloseState public { require(tokensToClaim != 0); address supporter = msg.sender; require(depositedToken[supporter] > 0); uint256 depositedTokenValue = depositedToken[supporter]; uint256 depositedETHValue = depositedETH[supporter]; require(tokensToClaim <= depositedTokenValue); uint256 claimedETH = tokensToClaim.mul(depositedETHValue).div(depositedTokenValue); assert(claimedETH > 0); depositedETH[supporter] = depositedETHValue.sub(claimedETH); depositedToken[supporter] = depositedTokenValue.sub(tokensToClaim); token.transfer(supporter, tokensToClaim); if(state != State.Closed) { etherWallet.transfer(claimedETH); } TokensClaimed(supporter, tokensToClaim); } function claimAllSupporterTokensByOwner(address supporter) isCloseState onlyOwner public { uint256 depositedTokenValue = depositedToken[supporter]; require(depositedTokenValue > 0); token.transfer(supporter, depositedTokenValue); TokensClaimed(supporter, depositedTokenValue); } function claimAllTokens() isRefundingOrCloseState public { uint256 depositedTokenValue = depositedToken[msg.sender]; claimTokens(depositedTokenValue); } }
10,666,586
[ 1, 21537, 12003, 225, 1220, 6835, 353, 1399, 364, 15729, 14275, 55, 4116, 512, 19905, 1323, 279, 276, 492, 72, 272, 5349, 353, 316, 4007, 364, 279, 3879, 434, 890, 27028, 18, 3425, 7988, 848, 6827, 364, 279, 1983, 19, 2680, 16255, 364, 18423, 19, 1614, 225, 2437, 5314, 1147, 18, 12419, 2430, 854, 18381, 329, 635, 326, 1169, 7988, 16, 2898, 2780, 506, 1278, 12254, 18, 7360, 890, 4681, 16, 777, 225, 2437, 903, 506, 598, 9446, 82, 628, 326, 9229, 68, 87, 9230, 16, 15086, 777, 2430, 358, 506, 7516, 329, 635, 326, 3675, 25937, 18, 19, 422, 9917, 4428, 14468, 12275, 4766, 1377, 6057, 87, 422, 9917, 4428, 14468, 12275, 422, 9917, 4428, 14468, 12275, 4766, 1377, 17524, 422, 9917, 4428, 14468, 12275, 3941, 1074, 813, 2623, 422, 9917, 4428, 14468, 12275, 4766, 1377, 9043, 422, 9917, 4428, 14468, 12275, 422, 9917, 4428, 14468, 12275, 4766, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 16351, 3941, 1074, 12003, 353, 18381, 429, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 203, 203, 203, 565, 2254, 5034, 1071, 5381, 20557, 5240, 67, 4684, 67, 15072, 273, 890, 4681, 31, 203, 203, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 1071, 443, 1724, 329, 1584, 44, 31, 203, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 1071, 443, 1724, 329, 1345, 31, 203, 203, 565, 1758, 1071, 225, 2437, 16936, 31, 203, 565, 6539, 958, 3948, 81, 485, 1345, 1071, 1147, 31, 203, 565, 3287, 1071, 919, 31, 203, 565, 2254, 5034, 1071, 16255, 13649, 31, 203, 203, 203, 565, 871, 8857, 5621, 203, 565, 871, 25582, 5621, 203, 565, 871, 4019, 538, 305, 12, 2867, 8808, 27641, 74, 14463, 814, 16, 2254, 5034, 225, 2437, 3218, 77, 6275, 16, 2254, 5034, 1147, 3218, 77, 6275, 1769, 203, 565, 871, 3941, 19156, 1526, 5621, 203, 565, 871, 3941, 12254, 1584, 44, 12, 2867, 27641, 74, 14463, 814, 16, 2254, 5034, 732, 77, 6275, 1769, 203, 565, 871, 13899, 9762, 329, 12, 2867, 8808, 27641, 74, 14463, 814, 16, 2254, 5034, 732, 77, 6275, 1769, 203, 203, 203, 565, 2792, 3287, 288, 8857, 16, 3941, 14351, 16, 25582, 289, 203, 565, 9606, 15083, 1119, 1435, 288, 203, 3639, 2583, 12, 2019, 422, 3287, 18, 3896, 1769, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 9606, 353, 1957, 14351, 1119, 1435, 288, 203, 3639, 2583, 12, 2019, 422, 3287, 18, 1957, 14351, 1769, 203, 3639, 389, 31, 2 ]
pragma solidity ^0.4.17; contract Campaign { // These fields are stored on storage (disk) address public manager; // address of person who is managing this campaign uint public minimumContribution; // Minimum donation required to be considered a contributor or 'approver' // NOTE: number of approvers can grow over time. In return, this will force us to create 'for' looping // logic to find an approver. The more approvers in the array, the more time to take for finding // an approver. The more time to take for executing a logic, the more gas will need to be paid. // Thus, it's expensive. Solution: Replace dynamic array with Mapping, because finding item will // take constant amount of time, regardless of how many amount of items within the mapping. // address[] public approvers; mapping (address=>bool) public approvers; // List of addresses for every person who has donated money mapping (address=>uint) public donatedMoney; // List of donated money mapped to the contributor Request[] public requests; // List of requests that the manager has created. uint public approversCount; // Indicate total number of donators/apporvers. /** * Represent a Request created by manager for making payment to other verndors to provide required good or services * to be used for building the product. */ struct Request { string description; // Purpose of request. uint value; // Ether to transfer address recipient; // Who gets the money bool complete; // Whether the request is done mapping(address => bool) approvals; // Track who has voted uint approvalCount; // Track number of approvals } modifier restricted() { require(msg.sender == manager); _; } /** * Constructor function that sets the minimumContribution and the Owner */ function Campaign(uint minimumContrib, address creator) public { manager = creator; minimumContribution = minimumContrib; } /** * Called when someone wants to donate money to the campaign and become an `approver` */ function contribute() public payable { // The sent ether should be higher than minimumContribution (in wei) require(msg.value > minimumContribution); // Keep the sender's address into approvers. if (!approvers[msg.sender]) { approvers[msg.sender] = true; approversCount++; } // Keep the sender's value into Approver's Funds Mapping donatedMoney[msg.sender] += msg.value; } /** * Created by the manager to create a new `spending request` */ function createRequest(string description, uint value, address recipient) public restricted { // Put 'memory' keyword to indicate that newRequest should be created in RAM // Note that we only need to initialise Request's value types. Request memory newRequest = Request({ description: description, value: value, recipient: recipient, complete: false, approvalCount: 0 }); requests.push(newRequest); } /** * Called by each contributor to approve a spending request. */ function approveRequest(uint index) public { Request storage request = requests[index]; // Ensure that the sender is a donator of this campaign require(approvers[msg.sender]); // Ensure that the donator has not voted this request yet. require(!request.approvals[msg.sender]); // Mark this donator as a approver of this request request.approvals[msg.sender] = true; // Increment number of approvals on this request. request.approvalCount++; } /** * After a request has gotten enough approvals, the manager can call this to get money sent to the vendor. * A request is eligible to be finalised if there are more than 50 % of total donators approved this Request. */ function finaliseRequest(uint index) public restricted { Request storage request = requests[index]; // Check if number of votes on this request is higher than 50% of total donators. require(request.approvalCount > approversCount/2); // Check if the request has not been set as completed require(!request.complete); // Send the money to Request's recipient request.recipient.transfer(request.value); // Set the request as completed request.complete = true; } /** * Re-claim donated fund and also exit the donator. */ function claimFund() public { // Ensure that the sender is a donator of this campaign require(approvers[msg.sender]); // Send donated money back to the contributor msg.sender.transfer(donatedMoney[msg.sender]); // Deactivate the contributor approvers[msg.sender] = false; donatedMoney[msg.sender] = 0; approversCount--; } /** * Get summarised info of current contract instance */ function getSummary() public view returns(uint, uint, uint, uint, address) { return ( minimumContribution, this.balance, requests.length, approversCount, manager ); } /** * Get length of requests list. */ function getRequestsLength() public view returns(uint) { return requests.length; } }
Who gets the money
address recipient;
12,603,133
[ 1, 2888, 83, 5571, 326, 15601, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 1758, 8027, 31, 10402, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/42161/0xd09556ECE9783f9AABba43e1df6A04a8218e7ca1/sources/project_/contracts/mercenaries/CharacterActivity.sol
STATE VARIABLES EVENTS EXTERNAL FUNCTIONS
contract CharacterActivity is CharacterStats { mapping(uint256 => Activity) public charactersActivity; event ActivityStatusUpdated(address indexed account, uint256 indexed tokenID, bool active); event ActivityStarted(address indexed account, uint256 indexed tokenID, Activity activity); function _updateActivityStatus(uint256 tokenID, bool active) internal pragma solidity ^0.8.0; { emit ActivityStatusUpdated(_msgSender(), tokenID, active); charactersActivity[tokenID].active = active; if (!active) { charactersActivity[tokenID].completedBlock = block.number; } } { emit ActivityStatusUpdated(_msgSender(), tokenID, active); charactersActivity[tokenID].active = active; if (!active) { charactersActivity[tokenID].completedBlock = block.number; } } function _startActivity(uint256 tokenID, Activity calldata activity) internal { require(activity.endBlock > activity.startBlock, "End block should be higher than start"); emit ActivityStarted(_msgSender(), tokenID, activity); charactersActivity[tokenID] = activity; } function getBlocksUntilActivityEnds(uint256 tokenID) external view returns ( uint256 blocksRemaining ) { Activity storage activity = charactersActivity[tokenID]; if (activity.endBlock > block.number) { return activity.endBlock - block.number; } } function getBlocksUntilActivityEnds(uint256 tokenID) external view returns ( uint256 blocksRemaining ) { Activity storage activity = charactersActivity[tokenID]; if (activity.endBlock > block.number) { return activity.endBlock - block.number; } } }
16,306,191
[ 1, 7998, 22965, 55, 9964, 55, 5675, 11702, 13690, 55, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 6577, 6193, 353, 6577, 4195, 288, 203, 203, 203, 565, 2874, 12, 11890, 5034, 516, 9621, 13, 1071, 3949, 6193, 31, 203, 203, 203, 565, 871, 9621, 1482, 7381, 12, 2867, 8808, 2236, 16, 2254, 5034, 8808, 1147, 734, 16, 1426, 2695, 1769, 203, 565, 871, 9621, 9217, 12, 2867, 8808, 2236, 16, 2254, 5034, 8808, 1147, 734, 16, 9621, 5728, 1769, 7010, 203, 203, 565, 445, 389, 2725, 6193, 1482, 12, 11890, 5034, 1147, 734, 16, 1426, 2695, 13, 203, 3639, 2713, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 20, 31, 203, 565, 288, 203, 3639, 3626, 9621, 1482, 7381, 24899, 3576, 12021, 9334, 1147, 734, 16, 2695, 1769, 203, 3639, 3949, 6193, 63, 2316, 734, 8009, 3535, 273, 2695, 31, 203, 3639, 309, 16051, 3535, 13, 288, 203, 5411, 3949, 6193, 63, 2316, 734, 8009, 13615, 1768, 273, 1203, 18, 2696, 31, 203, 3639, 289, 203, 565, 289, 203, 203, 565, 288, 203, 3639, 3626, 9621, 1482, 7381, 24899, 3576, 12021, 9334, 1147, 734, 16, 2695, 1769, 203, 3639, 3949, 6193, 63, 2316, 734, 8009, 3535, 273, 2695, 31, 203, 3639, 309, 16051, 3535, 13, 288, 203, 5411, 3949, 6193, 63, 2316, 734, 8009, 13615, 1768, 273, 1203, 18, 2696, 31, 203, 3639, 289, 203, 565, 289, 203, 203, 565, 445, 389, 1937, 6193, 12, 11890, 5034, 1147, 734, 16, 9621, 745, 892, 5728, 13, 203, 3639, 2713, 203, 565, 288, 203, 3639, 2583, 12, 9653, 18, 409, 1768, 405, 5728, 18, 1937, 1768, 16, 315, 1638, 1203, 2 ]
//Address: 0x239c7175a43c500255c4d3849c2ab2973d4384d5 //Contract name: Token //Balance: 0 Ether //Verification Date: 12/14/2017 //Transacion Count: 0 // CODE STARTS HERE pragma solidity ^0.4.15; /** * assert(2 + 2 is 4 - 1 thats 3) Quick Mafs */ library QuickMafs { function mul(uint256 _a, uint256 _b) internal pure returns (uint256) { uint256 c = _a * _b; assert(_a == 0 || c / _a == _b); return c; } function div(uint256 _a, uint256 _b) internal pure returns (uint256) { assert(_b > 0); // Solidity automatically throws when dividing by 0 uint256 c = _a / _b; return c; } function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { assert(_b <= _a); return _a - _b; } function add(uint256 _a, uint256 _b) internal pure returns (uint256) { uint256 c = _a + _b; assert(c >= _a); return c; } } /** * The ownable contract contains an owner address. This give us simple ownership privledges and can allow ownship transfer. */ contract Ownable { /** * The owner/admin of the contract */ address public owner; /** * Constructor for contract. Sets The contract creator to the default owner. */ function Ownable() public { owner = msg.sender; } /** * Modifier to apply to methods to restrict access to the owner */ modifier onlyOwner(){ require(msg.sender == owner); _; //Placeholder for method content } /** * Transfer the ownership to a new owner can only be done by the current owner. */ function transferOwnership(address _newOwner) public onlyOwner { //Only make the change if required if (_newOwner != address(0)) { owner = _newOwner; } } } /** * ERC Token Standard #20 Interface */ contract ERC20 { /** * Get the total token supply */ function totalSupply() public constant returns (uint256 _totalSupply); /** * Get the account balance of another account with address _owner */ function balanceOf(address _owner) public constant returns (uint256 balance); /** * Send _amount of tokens to address _to */ function transfer(address _to, uint256 _amount) public returns (bool success); /** * Send _amount of tokens from address _from to address _to */ function transferFrom(address _from, address _to, uint256 _amount) public returns (bool success); /** * Allow _spender to withdraw from your account, multiple times, up to the _amount. * If this function is called again it overwrites the current allowance with _amount. * this function is required for some DEX functionality */ function approve(address _spender, uint256 _amount) public returns (bool success); /** * Returns the amount which _spender is still allowed to withdraw from _owner */ function allowance(address _owner, address _spender) public constant returns (uint256 remaining); /** * Triggered when tokens are transferred. */ event Transfer(address indexed _from, address indexed _to, uint256 _amount); /** * Triggered whenever approve(address _spender, uint256 _amount) is called. */ event Approval(address indexed _owner, address indexed _spender, uint256 _amount); } /** * The CTN Token */ contract Token is ERC20, Ownable { using QuickMafs for uint256; string public constant SYMBOL = "CTN"; string public constant NAME = "Crypto Trust Network"; uint8 public constant DECIMALS = 18; /** * Total supply of tokens */ uint256 totalTokens; /** * The initial supply of coins before minting */ uint256 initialSupply; /** * Balances for each account */ mapping(address => uint256) balances; /** * Whos allowed to withdrawl funds from which accounts */ mapping(address => mapping (address => uint256)) allowed; /** * If the token is tradable */ bool tradable; /** * The address to store the initialSupply */ address public vault; /** * If the coin can be minted */ bool public mintingFinished = false; /** * Event for when new coins are created */ event Mint(address indexed _to, uint256 _value); /** * Event that is fired when token sale is over */ event MintFinished(); /** * Tokens can now be traded */ event TradableTokens(); /** * Allows this coin to be traded between users */ modifier isTradable(){ require(tradable); _; } /** * If this coin can be minted modifier */ modifier canMint() { require(!mintingFinished); _; } /** * Initializing the token, setting the owner, initial supply & vault */ function Token() public { initialSupply = 4500000 * 1 ether; totalTokens = initialSupply; tradable = false; vault = 0x6e794AAA2db51fC246b1979FB9A9849f53919D1E; balances[vault] = balances[vault].add(initialSupply); //Set initial supply to the vault } /** * Obtain current total supply of CTN tokens */ function totalSupply() public constant returns (uint256 totalAmount) { totalAmount = totalTokens; } /** * Get the initial supply of CTN coins */ function baseSupply() public constant returns (uint256 initialAmount) { initialAmount = initialSupply; } /** * Returns the balance of a wallet */ function balanceOf(address _address) public constant returns (uint256 balance) { return balances[_address]; } /** * Transfer CTN between wallets */ function transfer(address _to, uint256 _amount) public isTradable returns (bool) { balances[msg.sender] = balances[msg.sender].sub(_amount); balances[_to] = balances[_to].add(_amount); Transfer(msg.sender, _to, _amount); return true; } /** * Send _amount of tokens from address _from to address _to * The transferFrom method is used for a withdraw workflow, allowing contracts to send * tokens on your behalf, for example to "deposit" to a contract address and/or to charge * fees in sub-currencies; the command should fail unless the _from account has * deliberately authorized the sender of the message via some mechanism; we propose * these standardized APIs for approval: */ function transferFrom( address _from, address _to, uint256 _amount ) public isTradable returns (bool success) { var _allowance = allowed[_from][msg.sender]; /** * QuickMaf will roll back any changes so no need to check before these operations */ balances[_to] = balances[_to].add(_amount); balances[_from] = balances[_from].sub(_amount); allowed[_from][msg.sender] = _allowance.sub(_amount); Transfer(_from, _to, _amount); return true; } /** * Allows an address to transfer money out this is administered by the contract owner who can specify how many coins an account can take. * Needs to be called to feault the amount to 0 first -> https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 */ function approve(address _spender, uint256 _amount) public returns (bool) { /** *Set the amount they are able to spend to 0 first so that transaction ordering cannot allow multiple withdrawls asyncly *This function always requires to calls if a user has an amount they can withdrawl. */ require((_amount == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _amount; Approval(msg.sender, _spender, _amount); return true; } /** * Check the amount of tokens the owner has allowed to a spender */ function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /** * Makes the coin tradable between users cannot be undone */ function makeTradable() public onlyOwner { tradable = true; TradableTokens(); } /** * Mint tokens to users */ function mint(address _to, uint256 _amount) public onlyOwner canMint returns (bool) { totalTokens = totalTokens.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); return true; } /** * Function to stop minting tokens irreversable */ function finishMinting() public onlyOwner returns (bool) { mintingFinished = true; MintFinished(); return true; } } /** * The initial crowdsale of the token */ contract Sale is Ownable { using QuickMafs for uint256; /** * The hard cap of the token sale */ uint256 hardCap; /** * The soft cap of the token sale */ uint256 softCap; /** * The bonus cap for the token sale */ uint256 bonusCap; /** * How many tokens you get per ETH */ uint256 tokensPerETH; /** * //the start time of the sale (new Date("Dec 22 2017 18:00:00 GMT").getTime() / 1000) */ uint256 public start = 1513965600; /** * The end time of the sale (new Date("Jan 22 2018 18:00:00 GMT").getTime() / 1000) */ uint256 public end = 1516644000; /** * Two months after the sale ends used to retrieve unclaimed refunds (new Date("Mar 22 2018 18:00:00 GMT").getTime() / 1000) */ uint256 public twoMonthsLater = 1521741600; /** * Token for minting purposes */ Token public token; /** * The address to store eth in during sale */ address public vault; /** * How much ETH each user has sent to this contract. For softcap unmet refunds */ mapping(address => uint256) investments; /** * Every purchase during the sale */ event TokenSold(address recipient, uint256 etherAmount, uint256 ctnAmount, bool bonus); /** * Triggered when tokens are transferred. */ event PriceUpdated(uint256 amount); /** * Only make certain changes before the sale starts */ modifier isPreSale(){ require(now < start); _; } /** * Is the sale still on */ modifier isSaleOn() { require(now >= start && now <= end); _; } /** * Has the sale completed */ modifier isSaleFinished() { bool hitHardCap = token.totalSupply().sub(token.baseSupply()) >= hardCap; require(now > end || hitHardCap); _; } /** * Has the sale completed */ modifier isTwoMonthsLater() { require(now > twoMonthsLater); _; } /** * Make sure we are under the hardcap */ modifier isUnderHardCap() { bool underHard = token.totalSupply().sub(token.baseSupply()) <= hardCap; require(underHard); _; } /** * Make sure we are over the soft cap */ modifier isOverSoftCap() { bool overSoft = token.totalSupply().sub(token.baseSupply()) >= softCap; require(overSoft); _; } /** * Make sure we are over the soft cap */ modifier isUnderSoftCap() { bool underSoft = token.totalSupply().sub(token.baseSupply()) < softCap; require(underSoft); _; } /** * The token sale constructor */ function Sale() public { hardCap = 10500000 * 1 ether; softCap = 500000 * 1 ether; bonusCap = 2000000 * 1 ether; tokensPerETH = 536; //Tokens per 1 ETH token = new Token(); vault = 0x6e794AAA2db51fC246b1979FB9A9849f53919D1E; } /** * Fallback function which receives ether and created the appropriate number of tokens for the * msg.sender. */ function() external payable { createTokens(msg.sender); } /** * If the soft cap has not been reached and the sale is over investors can reclaim their funds */ function refund() public isSaleFinished isUnderSoftCap { uint256 amount = investments[msg.sender]; investments[msg.sender] = investments[msg.sender].sub(amount); msg.sender.transfer(amount); } /** * Withdrawl the funds from the contract. * Make the token tradeable and finish minting */ function withdrawl() public isSaleFinished isOverSoftCap { vault.transfer(this.balance); //Stop minting of the token and make the token tradeable token.finishMinting(); token.makeTradable(); } /** * Update the ETH price for the token sale */ function updatePrice(uint256 _newPrice) public onlyOwner isPreSale { tokensPerETH = _newPrice; PriceUpdated(_newPrice); } /** * Allows user to buy coins if we are under the hardcap also adds a bonus if under the bonus amount */ function createTokens(address recipient) public isUnderHardCap isSaleOn payable { uint256 amount = msg.value; uint256 tokens = tokensPerETH.mul(amount); bool bonus = false; if (token.totalSupply().sub(token.baseSupply()) < bonusCap) { bonus = true; tokens = tokens.add(tokens.div(5)); } //Add the amount to user invetment total investments[msg.sender] = investments[msg.sender].add(msg.value); token.mint(recipient, tokens); TokenSold(recipient, amount, tokens, bonus); } /** * Withdrawl the funds from the contract. * Make the token tradeable and finish minting */ function cleanup() public isTwoMonthsLater { vault.transfer(this.balance); token.finishMinting(); token.makeTradable(); } function destroy() public onlyOwner isTwoMonthsLater { token.finishMinting(); token.makeTradable(); token.transferOwnership(owner); selfdestruct(vault); } /** * Get the ETH balance of this contract */ function getBalance() public constant returns (uint256 totalAmount) { totalAmount = this.balance; } }
* Returns the balance of a wallet/
function balanceOf(address _address) public constant returns (uint256 balance) { return balances[_address]; }
2,492,935
[ 1, 1356, 326, 11013, 434, 279, 9230, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 11013, 951, 12, 2867, 389, 2867, 13, 1071, 5381, 1135, 261, 11890, 5034, 11013, 13, 288, 203, 3639, 327, 324, 26488, 63, 67, 2867, 15533, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x0854f167AB71AbfD0C3b972101e488B23c8cbE65/sources/contracts/Auction.sol
tracker for claimed tokens
uint32 tokensClaimed;
4,964,962
[ 1, 16543, 364, 7516, 329, 2430, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2254, 1578, 2430, 9762, 329, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/5/0x62Bcc94EB96E73d217d0bBbE688f8A3eE6E84D5e/sources/contracts/SplitMain.sol
@notice Invalid percentAllocations sum `allocationsSum` must equal `PERCENTAGE_SCALE` @param allocationsSum Sum of percentAllocations array
error InvalidSplit__InvalidAllocationsSum(uint32 allocationsSum);
1,916,929
[ 1, 1941, 5551, 8763, 1012, 2142, 1375, 9853, 1012, 3495, 68, 1297, 3959, 1375, 3194, 19666, 2833, 67, 19378, 68, 225, 23804, 3495, 9352, 434, 5551, 8763, 1012, 526, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1636, 1962, 5521, 972, 1941, 8763, 1012, 3495, 12, 11890, 1578, 23804, 3495, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity =0.8.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "./ICohortFactory.sol"; import "./../IAuditToken.sol"; /** * @title Members * Allows on creation of Enterprise and Validator accounts and staking of funds by validators * Validators and enterprises have ability to withdraw their staking and earnings * Contract also contains several update functions controlled by the Governance contracts */ contract Members is AccessControl { using SafeMath for uint256; using SafeERC20 for IERC20; bytes32 public constant CONTROLLER_ROLE = keccak256("CONTROLLER_ROLE"); bytes32 public constant SETTER_ROLE = keccak256("SETTER_ROLE"); uint256 public amountTokensPerValidation = 100e18; //New minted amount per validation uint256 public accessFee = 100e18; // data subscriber fee for access to reports uint256 public enterpriseShareSubscriber = 40; // share of enterprise income from data subscriber fee uint256 public validatorShareSubscriber = 40; // share of validator income from data subscriber fee address public platformAddress; // address where all platform fees are deposited uint256 public platformShareValidation = 15; // fee from validation uint256 public enterpriseMatch = 200; // percentage to match against amountTokensPerValidation uint256 public minDepositDays = 60; // number of days to considered for calculation of average spendings uint256 public requiredQuorum = 60; // quorum required to consider validation valid /// @dev check if caller is a controller modifier isController { require(hasRole(CONTROLLER_ROLE, msg.sender), "Members:IsController - Caller is not a controller"); _; } /// @dev check if caller is a setter modifier isSetter { require(hasRole(SETTER_ROLE, msg.sender), "Members:isSetter - Caller is not a setter"); _; } // Audit types to be used. Two types added for future expansion enum UserType {Enterprise, Validator, DataSubscriber} mapping(address => mapping(UserType => string)) public user; mapping(address => mapping(UserType => bool)) public userMap; address[] public enterprises; address[] public validators; address[] public dataSubscribers; event UserAdded(address indexed user, string name, UserType indexed userType); event LogDepositReceived(address indexed from, uint amount); event LogSubscriptionCompleted(address subscriber, uint256 numberOfSubscriptions); event LogGovernanceUpdate(uint256 params, string indexed action); constructor(address _platformAddress ) { require(_platformAddress != address(0), "Members:constructor - Platform address can't be 0"); platformAddress = _platformAddress; _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); } /** * @dev to be called by governance to update new amount for required quorum * @param _requiredQuorum new value of required quorum */ function updateQuorum(uint256 _requiredQuorum) public isSetter() { require(_requiredQuorum != 0, "Members:updateQuorum - New quorum value can't be 0"); requiredQuorum = _requiredQuorum; LogGovernanceUpdate(_requiredQuorum, "updateQuorum"); } /** * @dev to be called by Governance contract to update new value for the validation platform fee * @param _newFee new value for data subscriber access fee */ function updatePlatformShareValidation(uint256 _newFee) public isSetter() { require(_newFee != 0, "Members:updatePlatformShareValidation - New value for the platform fee can't be 0"); platformShareValidation = _newFee; emit LogGovernanceUpdate(_newFee, "updatePlatformShareValidation"); } /** * @dev to be called by Governance contract to update new value for data sub access fee * @param _accessFee new value for data subscriber access fee */ function updateAccessFee(uint256 _accessFee) public isSetter() { require(_accessFee != 0, "Members:updateAccessFee - New value for the access fee can't be 0"); accessFee = _accessFee; emit LogGovernanceUpdate(_accessFee, "updateAccessFee"); } /** * @dev to be called by Governance contract to update new amount for validation rewards * @param _minDepositDays new value for minimum of days to calculate */ function updateMinDepositDays(uint256 _minDepositDays) public isSetter() { require(_minDepositDays != 0, "Members:updateMinDepositDays - New value for the min deposit days can't be 0"); minDepositDays = _minDepositDays; emit LogGovernanceUpdate(_minDepositDays, "updateMinDepositDays"); } /** * @dev to be called by Governance contract to update new amount for validation rewards * @param _amountTokensPerValidation new value of reward per validation */ function updateTokensPerValidation(uint256 _amountTokensPerValidation) public isSetter() { require(_amountTokensPerValidation != 0, "Members:updateTokensPerValidation - New value for the reward can't be 0"); amountTokensPerValidation = _amountTokensPerValidation; emit LogGovernanceUpdate(_amountTokensPerValidation, "updateRewards"); } /** * @dev to be called by Governance contract * @param _enterpriseMatch new value of enterprise portion of enterprise value of validation cost */ function updateEnterpriseMatch(uint256 _enterpriseMatch) public isSetter() { require(_enterpriseMatch != 0, "Members:updateEnterpriseMatch - New value for the enterprise match can't be 0"); enterpriseMatch = _enterpriseMatch; emit LogGovernanceUpdate(_enterpriseMatch, "updateEnterpriseMatch"); } /** * @dev to be called by Governance contract to change enterprise and validators shares * of data subscription fees. * @param _enterpriseShareSubscriber - share of the enterprise * @param _validatorShareSubscriber - share of the subscribers */ function updateDataSubscriberShares(uint256 _enterpriseShareSubscriber, uint256 _validatorShareSubscriber ) public isSetter() { // platform share should be at least 10% require(_enterpriseShareSubscriber.add(validatorShareSubscriber) <=90, "Enterprise and Validator shares can't be larger than 90"); enterpriseShareSubscriber = _enterpriseShareSubscriber; validatorShareSubscriber = _validatorShareSubscriber; emit LogGovernanceUpdate(enterpriseShareSubscriber, "updateDataSubscriberShares:Enterprise"); emit LogGovernanceUpdate(validatorShareSubscriber, "updateDataSubscriberShares:Validator"); } /** * @dev add new platform user * @param newUser to add * @param name name of the user * @param userType type of the user, enterprise, validator or data subscriber */ function addUser(address newUser, string memory name, UserType userType) public isController() { require(!userMap[newUser][userType], "Members:addUser - This user already exist."); user[newUser][userType] = name; userMap[newUser][userType] = true; if (userType == UserType.DataSubscriber) dataSubscribers.push(newUser); // dataSubscriberCount++; else if (userType == UserType.Validator) validators.push(newUser); // validatorCount++; else if (userType == UserType.Enterprise) enterprises.push(newUser); // enterpriseCount++; // userAddersses.push(newUser); emit UserAdded(newUser, name, userType); } function returnValidatorList() public view returns(address[] memory) { return validators; } }
New minted amount per validation
uint256 public amountTokensPerValidation = 100e18;
12,557,554
[ 1, 1908, 312, 474, 329, 3844, 1534, 3379, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 5034, 1071, 3844, 5157, 2173, 4354, 273, 225, 2130, 73, 2643, 31, 377, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/56/0xD82816E55FA55CcD4C4B08C8069B1DDfdCb46797/sources/StrategySushiLp.sol
/ baseToken = 0xA527a61703D82139F8a06Bc30097cC9CAA2df5A6 (CAKEBNB-CAKELP) farmingToken = 0x4f47a0d15c1e53f3d94c069c7d16977c29f9cb6b (RAMEN) targetCompound = 0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c (BNB) token0 = 0x0e09fabb73bd3ade0a17ecc321fd13a19e81ce82 (CAKE) token1 = 0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c (BNB)
contract StrategySushiLp is StrategyBase { address public farmPool = 0x0895196562C7868C5Be92459FaE7f877ED450452; uint256 public poolId; address public token0 = 0x0E09FaBB73Bd3Ade0a17ECC321fD13a19e81cE82; address public token1 = 0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c; function initialize( address _baseToken, address _farmingToken, address _farmPool, uint256 _poolId, address _targetCompound, address _token0, address _token1, address _controller ) public { require(_initialized == false, "Strategy: Initialize must be false."); initialize(_baseToken, _farmingToken, _controller, _targetCompound); farmPool = _farmPool; poolId = _poolId; token0 = _token0; token1 = _token1; IERC20(baseToken).safeApprove(address(farmPool), type(uint256).max); if (token0 != farmingToken && token0 != targetCompoundToken) { IERC20(token0).safeApprove(address(unirouter), type(uint256).max); IERC20(token0).safeApprove(address(vSwaprouter), type(uint256).max); } if (token1 != farmingToken && token1 != targetCompoundToken && token1 != token0) { IERC20(token1).safeApprove(address(unirouter), type(uint256).max); IERC20(token1).safeApprove(address(vSwaprouter), type(uint256).max); } _initialized = true; } ) public { require(_initialized == false, "Strategy: Initialize must be false."); initialize(_baseToken, _farmingToken, _controller, _targetCompound); farmPool = _farmPool; poolId = _poolId; token0 = _token0; token1 = _token1; IERC20(baseToken).safeApprove(address(farmPool), type(uint256).max); if (token0 != farmingToken && token0 != targetCompoundToken) { IERC20(token0).safeApprove(address(unirouter), type(uint256).max); IERC20(token0).safeApprove(address(vSwaprouter), type(uint256).max); } if (token1 != farmingToken && token1 != targetCompoundToken && token1 != token0) { IERC20(token1).safeApprove(address(unirouter), type(uint256).max); IERC20(token1).safeApprove(address(vSwaprouter), type(uint256).max); } _initialized = true; } ) public { require(_initialized == false, "Strategy: Initialize must be false."); initialize(_baseToken, _farmingToken, _controller, _targetCompound); farmPool = _farmPool; poolId = _poolId; token0 = _token0; token1 = _token1; IERC20(baseToken).safeApprove(address(farmPool), type(uint256).max); if (token0 != farmingToken && token0 != targetCompoundToken) { IERC20(token0).safeApprove(address(unirouter), type(uint256).max); IERC20(token0).safeApprove(address(vSwaprouter), type(uint256).max); } if (token1 != farmingToken && token1 != targetCompoundToken && token1 != token0) { IERC20(token1).safeApprove(address(unirouter), type(uint256).max); IERC20(token1).safeApprove(address(vSwaprouter), type(uint256).max); } _initialized = true; } function getName() public pure override returns (string memory) { return "StrategySushiLp"; } function deposit() public override { uint256 _baseBal = IERC20(baseToken).balanceOf(address(this)); if (_baseBal > 0) { ICakeMasterChef(farmPool).deposit(poolId, _baseBal); emit Deposit(baseToken, _baseBal); } } function deposit() public override { uint256 _baseBal = IERC20(baseToken).balanceOf(address(this)); if (_baseBal > 0) { ICakeMasterChef(farmPool).deposit(poolId, _baseBal); emit Deposit(baseToken, _baseBal); } } function _withdrawSome(uint256 _amount) internal override returns (uint256) { (uint256 _stakedAmount, ) = ICakeMasterChef(farmPool).userInfo(poolId, address(this)); if (_amount > _stakedAmount) { _amount = _stakedAmount; } uint256 _before = IERC20(baseToken).balanceOf(address(this)); ICakeMasterChef(farmPool).withdraw(poolId, _amount); uint256 _after = IERC20(baseToken).balanceOf(address(this)); _amount = _after.sub(_before); return _amount; } function _withdrawSome(uint256 _amount) internal override returns (uint256) { (uint256 _stakedAmount, ) = ICakeMasterChef(farmPool).userInfo(poolId, address(this)); if (_amount > _stakedAmount) { _amount = _stakedAmount; } uint256 _before = IERC20(baseToken).balanceOf(address(this)); ICakeMasterChef(farmPool).withdraw(poolId, _amount); uint256 _after = IERC20(baseToken).balanceOf(address(this)); _amount = _after.sub(_before); return _amount; } function _withdrawAll() internal override { (uint256 _stakedAmount, ) = ICakeMasterChef(farmPool).userInfo(poolId, address(this)); ICakeMasterChef(farmPool).withdraw(poolId, _stakedAmount); } function claimReward() public override { ICakeMasterChef(farmPool).deposit(poolId, 0); } function _buyWantAndReinvest() internal override { { address _targetCompoundToken = targetCompoundToken; uint256 _targetCompoundBal = IERC20(_targetCompoundToken).balanceOf(address(this)); if (_targetCompoundToken != token0) { uint256 _compoundToBuyToken0 = _targetCompoundBal.div(2); _swapTokens(_targetCompoundToken, token0, _compoundToBuyToken0); } if (_targetCompoundToken != token1) { uint256 _compoundToBuyToken1 = _targetCompoundBal.div(2); _swapTokens(_targetCompoundToken, token1, _compoundToBuyToken1); } } address _baseToken = baseToken; uint256 _before = IERC20(_baseToken).balanceOf(address(this)); _addLiquidity(); uint256 _after = IERC20(_baseToken).balanceOf(address(this)); if (_after > 0) { if (_after > _before) { uint256 _compound = _after.sub(_before); vault.addNewCompound(_compound, blocksToReleaseCompound); } deposit(); } } function _buyWantAndReinvest() internal override { { address _targetCompoundToken = targetCompoundToken; uint256 _targetCompoundBal = IERC20(_targetCompoundToken).balanceOf(address(this)); if (_targetCompoundToken != token0) { uint256 _compoundToBuyToken0 = _targetCompoundBal.div(2); _swapTokens(_targetCompoundToken, token0, _compoundToBuyToken0); } if (_targetCompoundToken != token1) { uint256 _compoundToBuyToken1 = _targetCompoundBal.div(2); _swapTokens(_targetCompoundToken, token1, _compoundToBuyToken1); } } address _baseToken = baseToken; uint256 _before = IERC20(_baseToken).balanceOf(address(this)); _addLiquidity(); uint256 _after = IERC20(_baseToken).balanceOf(address(this)); if (_after > 0) { if (_after > _before) { uint256 _compound = _after.sub(_before); vault.addNewCompound(_compound, blocksToReleaseCompound); } deposit(); } } function _buyWantAndReinvest() internal override { { address _targetCompoundToken = targetCompoundToken; uint256 _targetCompoundBal = IERC20(_targetCompoundToken).balanceOf(address(this)); if (_targetCompoundToken != token0) { uint256 _compoundToBuyToken0 = _targetCompoundBal.div(2); _swapTokens(_targetCompoundToken, token0, _compoundToBuyToken0); } if (_targetCompoundToken != token1) { uint256 _compoundToBuyToken1 = _targetCompoundBal.div(2); _swapTokens(_targetCompoundToken, token1, _compoundToBuyToken1); } } address _baseToken = baseToken; uint256 _before = IERC20(_baseToken).balanceOf(address(this)); _addLiquidity(); uint256 _after = IERC20(_baseToken).balanceOf(address(this)); if (_after > 0) { if (_after > _before) { uint256 _compound = _after.sub(_before); vault.addNewCompound(_compound, blocksToReleaseCompound); } deposit(); } } function _buyWantAndReinvest() internal override { { address _targetCompoundToken = targetCompoundToken; uint256 _targetCompoundBal = IERC20(_targetCompoundToken).balanceOf(address(this)); if (_targetCompoundToken != token0) { uint256 _compoundToBuyToken0 = _targetCompoundBal.div(2); _swapTokens(_targetCompoundToken, token0, _compoundToBuyToken0); } if (_targetCompoundToken != token1) { uint256 _compoundToBuyToken1 = _targetCompoundBal.div(2); _swapTokens(_targetCompoundToken, token1, _compoundToBuyToken1); } } address _baseToken = baseToken; uint256 _before = IERC20(_baseToken).balanceOf(address(this)); _addLiquidity(); uint256 _after = IERC20(_baseToken).balanceOf(address(this)); if (_after > 0) { if (_after > _before) { uint256 _compound = _after.sub(_before); vault.addNewCompound(_compound, blocksToReleaseCompound); } deposit(); } } function _buyWantAndReinvest() internal override { { address _targetCompoundToken = targetCompoundToken; uint256 _targetCompoundBal = IERC20(_targetCompoundToken).balanceOf(address(this)); if (_targetCompoundToken != token0) { uint256 _compoundToBuyToken0 = _targetCompoundBal.div(2); _swapTokens(_targetCompoundToken, token0, _compoundToBuyToken0); } if (_targetCompoundToken != token1) { uint256 _compoundToBuyToken1 = _targetCompoundBal.div(2); _swapTokens(_targetCompoundToken, token1, _compoundToBuyToken1); } } address _baseToken = baseToken; uint256 _before = IERC20(_baseToken).balanceOf(address(this)); _addLiquidity(); uint256 _after = IERC20(_baseToken).balanceOf(address(this)); if (_after > 0) { if (_after > _before) { uint256 _compound = _after.sub(_before); vault.addNewCompound(_compound, blocksToReleaseCompound); } deposit(); } } function _buyWantAndReinvest() internal override { { address _targetCompoundToken = targetCompoundToken; uint256 _targetCompoundBal = IERC20(_targetCompoundToken).balanceOf(address(this)); if (_targetCompoundToken != token0) { uint256 _compoundToBuyToken0 = _targetCompoundBal.div(2); _swapTokens(_targetCompoundToken, token0, _compoundToBuyToken0); } if (_targetCompoundToken != token1) { uint256 _compoundToBuyToken1 = _targetCompoundBal.div(2); _swapTokens(_targetCompoundToken, token1, _compoundToBuyToken1); } } address _baseToken = baseToken; uint256 _before = IERC20(_baseToken).balanceOf(address(this)); _addLiquidity(); uint256 _after = IERC20(_baseToken).balanceOf(address(this)); if (_after > 0) { if (_after > _before) { uint256 _compound = _after.sub(_before); vault.addNewCompound(_compound, blocksToReleaseCompound); } deposit(); } } function _addLiquidity() internal { address _token0 = token0; address _token1 = token1; uint256 _amount0 = IERC20(_token0).balanceOf(address(this)); uint256 _amount1 = IERC20(_token1).balanceOf(address(this)); if (_amount0 > 0 && _amount1 > 0) { IUniswapV2Router(unirouter).addLiquidity(_token0, _token1, _amount0, _amount1, 0, 0, address(this), block.timestamp + 1); } } function _addLiquidity() internal { address _token0 = token0; address _token1 = token1; uint256 _amount0 = IERC20(_token0).balanceOf(address(this)); uint256 _amount1 = IERC20(_token1).balanceOf(address(this)); if (_amount0 > 0 && _amount1 > 0) { IUniswapV2Router(unirouter).addLiquidity(_token0, _token1, _amount0, _amount1, 0, 0, address(this), block.timestamp + 1); } } function balanceOfPool() public view override returns (uint256) { (uint256 amount, ) = ICakeMasterChef(farmPool).userInfo(poolId, address(this)); return amount; } function claimable_tokens() external view override returns (address[] memory farmToken, uint256[] memory totalDistributedValue) { farmToken = new address[](1); totalDistributedValue = new uint256[](1); farmToken[0] = farmingToken; totalDistributedValue[0] = ICakeMasterChef(farmPool).pendingCake(poolId, address(this)); } function claimable_token() external view override returns (address farmToken, uint256 totalDistributedValue) { farmToken = farmingToken; totalDistributedValue = ICakeMasterChef(farmPool).pendingCake(poolId, address(this)); } function getTargetFarm() external view override returns (address) { return farmPool; } function getTargetPoolId() external view override returns (uint256) { return poolId; } function retireStrat() external onlyStrategist { ICakeMasterChef(farmPool).emergencyWithdraw(poolId); uint256 baseBal = IERC20(baseToken).balanceOf(address(this)); IERC20(baseToken).transfer(address(vault), baseBal); } function setBlocksToReleaseCompound(uint256 _blocks) external onlyStrategist { blocksToReleaseCompound = _blocks; } function setFarmPoolContract(address _farmPool) external onlyStrategist { farmPool = _farmPool; } function setPoolId(uint256 _poolId) external onlyStrategist { poolId = _poolId; } function setTokenLp(address _token0, address _token1) external onlyStrategist { token0 = _token0; token1 = _token1; if (token0 != farmingToken && token0 != targetCompoundToken) { IERC20(token0).safeApprove(address(unirouter), type(uint256).max); IERC20(token0).safeApprove(address(vSwaprouter), type(uint256).max); } if (token1 != farmingToken && token1 != targetCompoundToken && token1 != token0) { IERC20(token1).safeApprove(address(unirouter), type(uint256).max); IERC20(token1).safeApprove(address(vSwaprouter), type(uint256).max); } } function setTokenLp(address _token0, address _token1) external onlyStrategist { token0 = _token0; token1 = _token1; if (token0 != farmingToken && token0 != targetCompoundToken) { IERC20(token0).safeApprove(address(unirouter), type(uint256).max); IERC20(token0).safeApprove(address(vSwaprouter), type(uint256).max); } if (token1 != farmingToken && token1 != targetCompoundToken && token1 != token0) { IERC20(token1).safeApprove(address(unirouter), type(uint256).max); IERC20(token1).safeApprove(address(vSwaprouter), type(uint256).max); } } function setTokenLp(address _token0, address _token1) external onlyStrategist { token0 = _token0; token1 = _token1; if (token0 != farmingToken && token0 != targetCompoundToken) { IERC20(token0).safeApprove(address(unirouter), type(uint256).max); IERC20(token0).safeApprove(address(vSwaprouter), type(uint256).max); } if (token1 != farmingToken && token1 != targetCompoundToken && token1 != token0) { IERC20(token1).safeApprove(address(unirouter), type(uint256).max); IERC20(token1).safeApprove(address(vSwaprouter), type(uint256).max); } } }
11,054,125
[ 1, 19, 1026, 1345, 4202, 273, 374, 21703, 25, 5324, 69, 26, 4033, 4630, 40, 11149, 24347, 42, 28, 69, 7677, 38, 71, 19249, 10580, 71, 39, 29, 3587, 37, 22, 2180, 25, 37, 26, 261, 3587, 6859, 15388, 38, 17, 3587, 47, 2247, 52, 13, 284, 4610, 310, 1345, 273, 374, 92, 24, 74, 9462, 69, 20, 72, 3600, 71, 21, 73, 8643, 74, 23, 72, 11290, 71, 7677, 29, 71, 27, 72, 26035, 4700, 71, 5540, 74, 29, 7358, 26, 70, 261, 54, 1642, 50, 13, 1018, 16835, 273, 374, 6114, 70, 24, 19728, 38, 29, 8876, 72, 5718, 38, 1611, 70, 40, 21, 71, 38, 69, 41, 15259, 22, 758, 6840, 72, 29, 31331, 13459, 5908, 25, 71, 261, 15388, 38, 13, 1147, 20, 273, 374, 92, 20, 73, 5908, 74, 19364, 9036, 16410, 23, 2486, 20, 69, 4033, 24410, 1578, 21, 8313, 3437, 69, 3657, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 16351, 19736, 55, 1218, 77, 48, 84, 353, 19736, 2171, 288, 203, 203, 565, 1758, 1071, 284, 4610, 2864, 273, 374, 92, 20, 6675, 25, 28644, 4313, 22, 39, 27, 5292, 28, 39, 25, 1919, 29, 3247, 6162, 29634, 41, 27, 74, 28, 4700, 2056, 7950, 3028, 9401, 31, 203, 565, 2254, 5034, 1071, 2845, 548, 31, 203, 203, 565, 1758, 1071, 1147, 20, 273, 374, 92, 20, 41, 5908, 29634, 9676, 9036, 38, 72, 23, 37, 323, 20, 69, 4033, 41, 6743, 1578, 21, 74, 40, 3437, 69, 3657, 73, 11861, 71, 41, 11149, 31, 203, 565, 1758, 1071, 1147, 21, 273, 374, 6114, 70, 24, 19728, 38, 29, 8876, 72, 5718, 38, 1611, 70, 40, 21, 71, 38, 69, 41, 15259, 22, 758, 6840, 72, 29, 31331, 13459, 5908, 25, 71, 31, 203, 203, 565, 445, 4046, 12, 203, 3639, 1758, 389, 1969, 1345, 16, 203, 3639, 1758, 389, 74, 4610, 310, 1345, 16, 203, 3639, 1758, 389, 74, 4610, 2864, 16, 203, 3639, 2254, 5034, 389, 6011, 548, 16, 203, 3639, 1758, 389, 3299, 16835, 16, 203, 3639, 1758, 389, 2316, 20, 16, 203, 3639, 1758, 389, 2316, 21, 16, 203, 3639, 1758, 389, 5723, 203, 203, 565, 262, 1071, 288, 203, 3639, 2583, 24899, 13227, 422, 629, 16, 315, 4525, 30, 9190, 1297, 506, 629, 1199, 1769, 203, 3639, 4046, 24899, 1969, 1345, 16, 389, 74, 4610, 310, 1345, 16, 389, 5723, 16, 389, 3299, 16835, 1769, 203, 3639, 284, 4610, 2864, 273, 389, 74, 4610, 2864, 31, 203, 3639, 2 ]
./full_match/1/0x1897D69cc0088D89C1e94889fBD2eFFfCEfEd778/sources/contracts/GutterSpecies.sol
gets you a pass for the price of publicSalePrice
function getPassPublicSale(uint256 passType) public payable nonReentrant { require(publicSaleActive == true, "public sale not active"); require(msg.value == publicSalePrice, "send exact ETH value"); if (passType == 3) { counterPublicPassesType3++; require(counterPublicPassesType3 < maxPublicPassesType3, "no more passes available (3)"); _mintToken(_msgSender(), 3); } if (passType == 4) { counterPublicPassesType4++; require(counterPublicPassesType4 < maxPublicPassesType4, "no more passes available (4)"); _mintToken(_msgSender(), 4); } }
8,384,675
[ 1, 14665, 1846, 279, 1342, 364, 326, 6205, 434, 1071, 30746, 5147, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 915, 1689, 428, 4782, 30746, 12, 11890, 5034, 1342, 559, 13, 1071, 8843, 429, 1661, 426, 8230, 970, 288, 203, 202, 202, 6528, 12, 482, 30746, 3896, 422, 638, 16, 315, 482, 272, 5349, 486, 2695, 8863, 203, 203, 202, 202, 6528, 12, 3576, 18, 1132, 422, 1071, 30746, 5147, 16, 315, 4661, 5565, 512, 2455, 460, 8863, 203, 203, 202, 202, 430, 261, 5466, 559, 422, 890, 13, 288, 203, 1082, 202, 7476, 4782, 6433, 281, 559, 23, 9904, 31, 203, 1082, 202, 6528, 12, 7476, 4782, 6433, 281, 559, 23, 411, 943, 4782, 6433, 281, 559, 23, 16, 315, 2135, 1898, 11656, 2319, 261, 23, 2225, 1769, 203, 1082, 202, 67, 81, 474, 1345, 24899, 3576, 12021, 9334, 890, 1769, 203, 202, 202, 97, 203, 203, 202, 202, 430, 261, 5466, 559, 422, 1059, 13, 288, 203, 1082, 202, 7476, 4782, 6433, 281, 559, 24, 9904, 31, 203, 1082, 202, 6528, 12, 7476, 4782, 6433, 281, 559, 24, 411, 943, 4782, 6433, 281, 559, 24, 16, 315, 2135, 1898, 11656, 2319, 261, 24, 2225, 1769, 203, 1082, 202, 67, 81, 474, 1345, 24899, 3576, 12021, 9334, 1059, 1769, 203, 202, 202, 97, 203, 202, 97, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
//Address: 0x72Ffa36a1f742e27106D36323fafe96F136cdda0 //Contract name: IPCToken //Balance: 0 Ether //Verification Date: 1/26/2018 //Transacion Count: 1 // CODE STARTS HERE pragma solidity ^0.4.18; /** * @title SafeMath * @dev Math operations with safety checks */ contract SafeMath { function safeMul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; require(a == 0 || c / a == b); return c; } function safeDiv(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); uint256 c = a / b; require(a == b * c + a % b); return c; } function safeSub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); return a - b; } function safeAdd(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c>=a && c>=b); return c; } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 { uint256 public totalSupply; function balanceOf(address _owner) public constant returns (uint256 _balance); function allowance(address _owner, address _spender) public constant returns (uint256 _allowance); function transfer(address _to, uint256 _value) public returns (bool _succes); function transferFrom(address _from, address _to, uint256 _value) public returns (bool _succes); function approve(address _spender, uint256 _value) public returns (bool _succes); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. */ contract StandardToken is ERC20, SafeMath { mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; function balanceOf(address _owner) public constant returns (uint256){ return balanceOf[_owner]; } function allowance(address _owner, address _spender) public constant returns (uint256){ return allowance[_owner][_spender]; } /** * Fix for the ERC20 short address attack * * http://vessenes.com/the-erc20-short-address-attack-explained/ */ modifier onlyPayloadSize(uint size) { require(!(msg.data.length < size + 4)); _; } /* * Internal transfer with security checks, * only can be called by this contract */ function safeTransfer(address _from, address _to, uint256 _value) internal { // Prevent transfer to 0x0 address. require(_to != 0x0); // Prevent transfer to this contract require(_to != address(this)); // Check if the sender has enough and subtract from the sender by using safeSub balanceOf[_from] = safeSub(balanceOf[_from], _value); // check for overflows and add the same value to the recipient by using safeAdd balanceOf[_to] = safeAdd(balanceOf[_to], _value); Transfer(_from, _to, _value); } /** * @dev Send `_value` tokens to `_to` from your account * @param _to address The address which you want to transfer to * @param _value uint the amout of tokens to be transfered */ function transfer(address _to, uint256 _value) onlyPayloadSize(2 * 32) public returns (bool) { safeTransfer(msg.sender, _to, _value); return true; } /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint the amout of tokens to be transfered */ function transferFrom(address _from, address _to, uint256 _value) onlyPayloadSize(3 * 32) public returns (bool) { uint256 _allowance = allowance[_from][msg.sender]; // Check (_value > _allowance) is already done in safeSub(_allowance, _value) allowance[_from][msg.sender] = safeSub(_allowance, _value); safeTransfer(_from, _to, _value); return true; } /** * @dev Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender. * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_value == 0) || (allowance[msg.sender][_spender] == 0)); allowance[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } } /** * Upgrade agent interface inspired by Lunyr. * * Upgrade agent transfers tokens to a new contract. * Upgrade agent itself can be the token contract, or just a middle man contract * doing the heavy lifting. */ contract UpgradeAgent { uint256 public originalSupply; /** Interface marker */ function isUpgradeAgent() public pure returns (bool) { return true; } function upgradeFrom(address _from, uint256 _value) public; } /** * A token upgrade mechanism where users can opt-in amount of tokens to the next * smart contract revision. * * First envisioned by Golem and Lunyr projects. * */ contract UpgradeableToken is StandardToken { /** * Contract / person who can set the upgrade path. * This can be the same as team multisig wallet, as what it is with its default value. */ address public upgradeMaster; /** The next contract where the tokens will be migrated. */ UpgradeAgent public upgradeAgent; /** How many tokens we have upgraded by now. */ uint256 public totalUpgraded; /** * Upgrade states. * * - NotAllowed: The child contract has not reached a condition where the upgrade can bgun * - WaitingForAgent: Token allows upgrade, but we don't have a new agent yet * - ReadyToUpgrade: The agent is set, but not a single token has been upgraded yet * - Upgrading: Upgrade agent is set and the balance holders can upgrade their tokens * */ enum UpgradeState {Unknown, NotAllowed, WaitingForAgent, ReadyToUpgrade, Upgrading} /** * Somebody has upgraded some of his tokens. */ event Upgrade(address indexed _from, address indexed _to, uint256 _value); /** * New upgrade agent available. */ event UpgradeAgentSet(address agent); /** * Do not allow construction without upgrade master set. */ function UpgradeableToken(address _upgradeMaster) public { upgradeMaster = _upgradeMaster; } /** * Allow the token holder to upgrade some of their tokens to a new contract. */ function upgrade(uint256 value) public { UpgradeState state = getUpgradeState(); // bad state not allowed require(state == UpgradeState.ReadyToUpgrade || state == UpgradeState.Upgrading); // Validate input value. require(value != 0); balanceOf[msg.sender] = safeSub(balanceOf[msg.sender], value); // Take tokens out from circulation totalSupply = safeSub(totalSupply, value); totalUpgraded = safeAdd(totalUpgraded, value); // Upgrade agent reissues the tokens upgradeAgent.upgradeFrom(msg.sender, value); Upgrade(msg.sender, upgradeAgent, value); } /** * Set an upgrade agent that handles */ function setUpgradeAgent(address agent) external { require(canUpgrade()); require(agent != 0x0); // Only a master can designate the next agent require(msg.sender == upgradeMaster); // Upgrade has already begun for an agent require(getUpgradeState() != UpgradeState.Upgrading); upgradeAgent = UpgradeAgent(agent); // Bad interface require(upgradeAgent.isUpgradeAgent()); // Make sure that token supplies match in source and target require(upgradeAgent.originalSupply() == totalSupply); UpgradeAgentSet(upgradeAgent); } /** * Get the state of the token upgrade. */ function getUpgradeState() public constant returns (UpgradeState) { if(!canUpgrade()) return UpgradeState.NotAllowed; else if(address(upgradeAgent) == 0x00) return UpgradeState.WaitingForAgent; else if(totalUpgraded == 0) return UpgradeState.ReadyToUpgrade; else return UpgradeState.Upgrading; } /** * Change the upgrade master. * * This allows us to set a new owner for the upgrade mechanism. */ function setUpgradeMaster(address master) public { require(master != 0x0); require(msg.sender == upgradeMaster); upgradeMaster = master; } /** * Child contract can enable to provide the condition when the upgrade can begun. */ function canUpgrade() public pure returns (bool) { return true; } } /** * @title Ownable * @dev Ownable contract with two owner addresses */ contract Ownable { address public ownerOne; address public ownerTwo; /** * @dev The Ownable constructor sets one of the owners of the contract to the sender * account. */ function Ownable() public { ownerOne = msg.sender; ownerTwo = msg.sender; } /** * @dev Can only be called by the owners. */ modifier onlyOwner { require(msg.sender == ownerOne || msg.sender == ownerTwo); _; } /** * @dev Allows the current owners to transfer control of the contract to a new owner. * @param newOwner The address to transfer ownership to. * @param replaceOwnerOne Replace 'ownerOne'? * @param replaceOwnerTwo Replace 'ownerTwo'? */ function transferOwnership(address newOwner, bool replaceOwnerOne, bool replaceOwnerTwo) onlyOwner public { require(newOwner != 0x0); require(replaceOwnerOne || replaceOwnerTwo); if(replaceOwnerOne) ownerOne = newOwner; if(replaceOwnerTwo) ownerTwo = newOwner; } } /** * @title Pausable * @dev Allows an emergency stop mechanism. * See https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/lifecycle/Pausable.sol */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev modifier to allow actions only when the contract IS paused */ modifier whenNotPaused { require(!paused); _; } /** * @dev modifier to allow actions only when the contract IS NOT paused */ modifier whenPaused { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public returns (bool) { paused = true; Pause(); return true; } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public returns (bool) { paused = false; Unpause(); return true; } } /** * @title PausableToken * @dev StandardToken with pausable transfers */ contract PausableToken is StandardToken, Pausable { function transfer(address _to, uint256 _value) whenNotPaused public returns (bool) { super.transfer(_to, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) whenNotPaused public returns (bool) { super.transferFrom(_from, _to, _value); return true; } } /** * @title PurchasableToken * @dev Allows buying IPC token from this contract */ contract PurchasableToken is PausableToken { event PurchaseUnlocked(); event PurchaseLocked(); event UpdatedExchangeRate(uint256 newPrice); event Purchase(address buyer, uint256 etherAmount, uint256 tokenAmount); bool public purchasable = false; // minimum amount of ether you have to spend to buy some tokens uint256 public minimumEtherAmount; address public vendorWallet; uint256 public exchangeRate; // 'exchangeRate' tokens = 1 ether /** @dev modifier to allow token purchase only when purchase is unlocked and rate > 0 */ modifier isPurchasable { require(purchasable && exchangeRate > 0 && minimumEtherAmount > 0); _; } /** @dev called by the owner to lock purchase of ipc token */ function lockPurchase() onlyOwner public returns (bool) { require(purchasable == true); purchasable = false; PurchaseLocked(); return true; } /** @dev called by the owner to release purchase of ipc token */ function unlockPurchase() onlyOwner public returns (bool) { require(purchasable == false); purchasable = true; PurchaseUnlocked(); return true; } /** @dev called by the owner to set a new rate */ function setExchangeRate(uint256 newExchangeRate) onlyOwner public returns (bool) { require(newExchangeRate > 0); exchangeRate = newExchangeRate; UpdatedExchangeRate(newExchangeRate); return true; } /** @dev called by the owner to set the minimum ether amount to buy some token */ function setMinimumEtherAmount(uint256 newMinimumEtherAmount) onlyOwner public returns (bool) { require(newMinimumEtherAmount > 0); minimumEtherAmount = newMinimumEtherAmount; return true; } /** @dev called by the owner to set a new vendor */ function setVendorWallet(address newVendorWallet) onlyOwner public returns (bool) { require(newVendorWallet != 0x0); vendorWallet = newVendorWallet; return true; } /** @dev buy ipc token by sending at least 'minimumEtherAmount' */ function buyIPC() payable isPurchasable whenNotPaused public returns (uint256) { require(msg.value >= minimumEtherAmount); uint256 tokenAmount = safeMul(msg.value, exchangeRate); tokenAmount = safeDiv(tokenAmount, 1 ether); require(allowance[vendorWallet][this] >= tokenAmount); balanceOf[msg.sender] = safeAdd(balanceOf[msg.sender], tokenAmount); balanceOf[vendorWallet] = safeSub(balanceOf[vendorWallet], tokenAmount); Purchase(msg.sender, msg.value, tokenAmount); return tokenAmount; } function () payable public { buyIPC(); } } /** * @title Withdrawable * @dev Contract allows to withdraw ether and ERC20 token */ contract Withdrawable is Ownable { /** @dev withdraw ERC20 token from this contract */ function withdrawToken(address beneficiary, address _token) onlyOwner public { ERC20 token = ERC20(_token); uint256 amount = token.balanceOf(this); require(amount>0); token.transfer(beneficiary, amount); } /** @dev called by the owner to transfer 'etherAmount' to 'beneficiary' */ function withdrawEther(address beneficiary, uint256 etherAmount) onlyOwner public { beneficiary.transfer(etherAmount); } } /** * @title IPCToken * @dev IPC Token contract * @author Paysura - <[email protected]> */ contract IPCToken is UpgradeableToken, PurchasableToken, Withdrawable { // Public variables of the token string public name = "International PayReward Coin"; string public symbol = "IPC"; uint8 public decimals = 12; // Distributions of the total supply // 264 mio for crowdsale uint256 public cr = 264000000 * (10 ** uint256(decimals)); // 110 mio reserved for community / reward program uint256 public rew = 110000000 * (10 ** uint256(decimals)); // 66 mio for advisors and partners uint256 public dev = 66000000 * (10 ** uint256(decimals)); // total supply of 440 mio uint256 public totalSupply = cr + dev + rew; event UpdatedTokenInformation(string newName, string newSymbol); /** * Constructor of ipc token * * @param addressOfCrBen beneficiary of crowdsale * @param addressOfRew reserve for community / reward program * @param addressOfDev reserve remaining amount of ipc for development, partners and advisors */ function IPCToken ( address addressOfCrBen, address addressOfRew, address addressOfDev ) public UpgradeableToken(msg.sender) { // Assign the initial tokens to the addresses balanceOf[addressOfCrBen] = cr; balanceOf[addressOfRew] = rew; balanceOf[addressOfDev] = dev; } /** * Owner can update token information * * @param _name new token name * @param _symbol new token symbol */ function setTokenInformation(string _name, string _symbol) onlyOwner public { name = _name; symbol = _symbol; UpdatedTokenInformation(name, symbol); } }
* @dev Send `_value` tokens to `_to` from your account @param _to address The address which you want to transfer to @param _value uint the amout of tokens to be transfered/
function transfer(address _to, uint256 _value) onlyPayloadSize(2 * 32) public returns (bool) { safeTransfer(msg.sender, _to, _value); return true; }
6,414,462
[ 1, 3826, 1375, 67, 1132, 68, 2430, 358, 1375, 67, 869, 68, 628, 3433, 2236, 225, 389, 869, 1758, 1021, 1758, 1492, 1846, 2545, 358, 7412, 358, 225, 389, 1132, 2254, 326, 2125, 659, 434, 2430, 358, 506, 7412, 329, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7412, 12, 2867, 389, 869, 16, 2254, 5034, 389, 1132, 13, 1338, 6110, 1225, 12, 22, 380, 3847, 13, 1071, 1135, 261, 6430, 13, 288, 203, 3639, 4183, 5912, 12, 3576, 18, 15330, 16, 389, 869, 16, 389, 1132, 1769, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.0; import './Zeppelin/ownership/Ownable.sol'; contract User is Ownable{ /* TODO */ // only UserManager has privilege to set value of Info struct Info{ string username; string password; // hash of password string first; string last; string DoB; string homeAddress; string email; string phone; bool creditFree; string driver; string passportNumber; string citizenship; // string mobile string SIN; string health; // IPFS headshot string headshot; // IPFS biometric string biometric; // IPFS driverCard string driverCard; // IPFS healthCard string healthCard; // IPFS citizenshipCard string citizenshipCard; // IPFS passportImage string passportImage; } Info private personalInfo; // Call by Web3 deploy constructor (address _userAccount,string memory _username, string memory _password, string memory _first, string memory _last, string memory _email) public{ personalInfo = Info(_username, _password, _first, _last, "" , "", _email, "",false, "", "", "", "","","","","","","",""); // set owner of contract to current user transferOwnership(_userAccount); } function getDataField() public view returns(string memory field){ return "username,password,first,last,headshot,biometric,driverCard,healthCard,citizenshipCard,DoB,homeAddress,email,driver,passportNumber,citizenship,phone,SIN,health,headshot,biometeric,driverCard,healthCard,citizenshipCard,passportImage"; } function setSIN(string memory SIN) public onlyManager{ personalInfo.SIN = SIN; } function getSIN() public view onlyOwner returns(string memory SIN){ return personalInfo.SIN; } function changeCrediteFreeState() public{ personalInfo.creditFree = !personalInfo.creditFree; } function getCrediteFreeState() public view returns(bool creditFree){ return personalInfo.creditFree; } // only User account can call this method function setInfo(string memory first, string memory last, string memory DoB, string memory homeAddress, string memory email, string memory driver, string memory passport, string memory citizenship, string memory phone, string memory SIN, string memory health) public onlyManager { personalInfo.first = first; personalInfo.last = last; personalInfo.DoB = DoB; personalInfo.homeAddress = homeAddress; personalInfo.email = email; personalInfo.phone = phone; personalInfo.driver = driver; personalInfo.passportNumber = passport; personalInfo.citizenship = citizenship; personalInfo.SIN = SIN; personalInfo.health = health; } function setBasicInfo(string memory first, string memory last, string memory DoB, string memory homeAddress, string memory email, string memory phone) public onlyManager { personalInfo.first = first; personalInfo.last = last; personalInfo.DoB = DoB; personalInfo.homeAddress = homeAddress; personalInfo.email = email; personalInfo.phone = phone; } function setPrivateInfo(string memory driver,string memory passport, string memory citizenship, string memory health) public onlyManager { personalInfo.driver = driver; personalInfo.passportNumber = passport; personalInfo.citizenship = citizenship; personalInfo.health = health; } function setHeadshot(string memory headshot)public onlyManager{ personalInfo.headshot = headshot; } function getHeadshot() public view onlyOwner returns(string memory headshot){ return personalInfo.headshot; } function setCitizenshipCard(string memory citizenshipCard)public onlyManager{ personalInfo.citizenshipCard = citizenshipCard; } function getCitizenshipCard() public view onlyOwner returns(string memory citizenshipCard){ return personalInfo.citizenshipCard; } function setHealthCard(string memory healthCard)public onlyManager{ personalInfo.healthCard = healthCard; } function getHealthCard() public view onlyOwner returns(string memory healthCard){ return personalInfo.healthCard; } function setDriverCard(string memory driverCard)public onlyManager{ personalInfo.driverCard = driverCard; } function getDriverCard() public view onlyOwner returns(string memory driverCard){ return personalInfo.driverCard; } function setPassportImage(string memory passportImage)public onlyManager{ personalInfo.passportImage = passportImage; } function getPassportImage() public returns(string memory passportImage){ return personalInfo.passportImage; } function setBiometric(string memory biometric)public onlyManager{ personalInfo.biometric = biometric; } function getBiometric() public view onlyOwner returns(string memory biometric){ return personalInfo.biometric; } function getUsernamePass() public view onlyOwner onlyOwner returns(string memory userName, string memory password){ return (personalInfo.username, personalInfo.password); } // function setUsername(string memory username) public onlyManager // { // personalInfo.username = username; // } function getName() public view onlyOwner returns(string memory first, string memory last){ return (personalInfo.first, personalInfo.last); } // function setName(string memory first,string memory last) public onlyManager // { // personalInfo.first = first; // personalInfo.last = last; // } function getDoB() public view onlyOwner returns(string memory DoB){ return personalInfo.DoB; } // function setDoB(string memory DoB) public onlyManager // { // personalInfo.DoB = DoB; // } function getHomeAddress() public view onlyOwner returns(string memory homeAddress){ return personalInfo.homeAddress; } // function setHomeAddress(string memory homeAddress) public onlyManager // { // personalInfo.homeAddress = homeAddress; // } function getEmail() public view onlyOwner returns(string memory email){ return personalInfo.email; } // function setEmail(string memory email) public onlyManager // { // personalInfo.email = email; // } function getDriver() public view onlyOwner returns(string memory driver){ return personalInfo.driver; } // function setDriver(string memory driver) public onlyManager // { // personalInfo.driver = driver; // } function getPassport() public view onlyOwner returns(string memory passportNumber){ return personalInfo.passportNumber; } // function setPassport(string memory passport) public onlyManager // { // personalInfo.passportNumber = passport; // } function getCitizenshipNumber() public view onlyOwner returns(string memory citizenship){ return personalInfo.citizenship; } // function setCitizenshipNumber(string memory citizenship) public onlyManager // { // personalInfo.citizenship = citizenship; // } function getPhone() public view onlyOwner returns(string memory phone){ return personalInfo.phone; } function getHealth() public view onlyOwner returns(string memory health){ return personalInfo.health; } // function setHealth(string memory health) public onlyManager // { // personalInfo.health = health; // } }
only User account can call this method
function setInfo(string memory first, string memory last, string memory DoB, string memory homeAddress, string memory email, string memory driver, string memory passport, string memory citizenship, string memory phone, string memory SIN, string memory health) public onlyManager { personalInfo.first = first; personalInfo.last = last; personalInfo.DoB = DoB; personalInfo.homeAddress = homeAddress; personalInfo.email = email; personalInfo.phone = phone; personalInfo.driver = driver; personalInfo.passportNumber = passport; personalInfo.citizenship = citizenship; personalInfo.SIN = SIN; personalInfo.health = health; }
1,068,420
[ 1, 3700, 2177, 2236, 848, 745, 333, 707, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 444, 966, 12, 1080, 3778, 1122, 16, 533, 3778, 1142, 16, 533, 3778, 2256, 38, 16, 203, 565, 533, 3778, 6382, 1887, 16, 533, 3778, 2699, 16, 533, 3778, 3419, 16, 7010, 565, 533, 3778, 1342, 655, 16, 533, 3778, 276, 305, 452, 275, 3261, 16, 533, 3778, 7353, 16, 7010, 565, 533, 3778, 31793, 16, 533, 3778, 8437, 13, 1071, 1338, 1318, 7010, 565, 288, 203, 3639, 17816, 966, 18, 3645, 273, 1122, 31, 203, 3639, 17816, 966, 18, 2722, 273, 1142, 31, 203, 3639, 17816, 966, 18, 3244, 38, 273, 2256, 38, 31, 203, 3639, 17816, 966, 18, 8712, 1887, 273, 6382, 1887, 31, 203, 3639, 17816, 966, 18, 3652, 273, 2699, 31, 203, 3639, 17816, 966, 18, 10540, 273, 7353, 31, 203, 203, 3639, 17816, 966, 18, 7407, 273, 3419, 31, 203, 3639, 17816, 966, 18, 5466, 655, 1854, 273, 1342, 655, 31, 7010, 3639, 17816, 966, 18, 71, 305, 452, 275, 3261, 273, 276, 305, 452, 275, 3261, 31, 203, 3639, 17816, 966, 18, 55, 706, 273, 31793, 31, 203, 3639, 17816, 966, 18, 13267, 273, 8437, 31, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/11155111/0xdd8E19b29b2530Bc9b34BeBd69C31cf7B176c33b/sources/src/RepoDriver.sol
@notice Updates the user owner. Callable only by the AnyApi operator. @param requestId The ID of the AnyApi request. Must be the same as the request ID generated when requesting an owner update, this function will update the user ownership that was requested back then. @param ownerRaw The new owner of the user. Must be a 20 bytes long address.
function updateOwnerByAnyApi(bytes32 requestId, bytes calldata ownerRaw) public whenNotPaused { RepoDriverAnyApiStorage storage storageRef = _repoDriverAnyApiStorage(); require(msg.sender == address(storageRef.operator), "Callable only by the operator"); uint256 userId = storageRef.requestedUpdates[requestId]; require(userId != 0, "Unknown request ID"); delete storageRef.requestedUpdates[requestId]; require(ownerRaw.length == 20, "Invalid owner length"); address owner = address(bytes20(ownerRaw)); _repoDriverStorage().userOwners[userId] = owner; emit OwnerUpdated(userId, owner); }
3,825,019
[ 1, 5121, 326, 729, 3410, 18, 10464, 1338, 635, 326, 5502, 3064, 3726, 18, 225, 14459, 1021, 1599, 434, 326, 5502, 3064, 590, 18, 6753, 506, 326, 1967, 487, 326, 590, 1599, 4374, 1347, 18709, 392, 3410, 1089, 16, 333, 445, 903, 1089, 326, 729, 23178, 716, 1703, 3764, 1473, 1508, 18, 225, 3410, 4809, 1021, 394, 3410, 434, 326, 729, 18, 6753, 506, 279, 4200, 1731, 1525, 1758, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1089, 5541, 858, 2961, 3064, 12, 3890, 1578, 14459, 16, 1731, 745, 892, 3410, 4809, 13, 1071, 1347, 1248, 28590, 288, 203, 3639, 15118, 4668, 2961, 3064, 3245, 2502, 2502, 1957, 273, 389, 7422, 4668, 2961, 3064, 3245, 5621, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 1758, 12, 5697, 1957, 18, 9497, 3631, 315, 11452, 1338, 635, 326, 3726, 8863, 203, 3639, 2254, 5034, 6249, 273, 2502, 1957, 18, 19065, 5121, 63, 2293, 548, 15533, 203, 3639, 2583, 12, 18991, 480, 374, 16, 315, 4874, 590, 1599, 8863, 203, 3639, 1430, 2502, 1957, 18, 19065, 5121, 63, 2293, 548, 15533, 203, 3639, 2583, 12, 8443, 4809, 18, 2469, 422, 4200, 16, 315, 1941, 3410, 769, 8863, 203, 3639, 1758, 3410, 273, 1758, 12, 3890, 3462, 12, 8443, 4809, 10019, 203, 3639, 389, 7422, 4668, 3245, 7675, 1355, 5460, 414, 63, 18991, 65, 273, 3410, 31, 203, 3639, 3626, 16837, 7381, 12, 18991, 16, 3410, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
contract BitSTDLogic { function name()constant public returns(string) {} function symbol()constant public returns(string) {} function decimals()constant public returns(uint8) {} function totalSupply()constant public returns(uint256) {} function allowance(address add,address _add)constant public returns(uint256) {} function sellPrice()constant public returns(uint256) {} function buyPrice()constant public returns(uint256) {} function frozenAccount(address add)constant public returns(bool) {} function migration(address sender,address add) public{} function balanceOf(address add)constant public returns(uint256) {} function transfer(address sender,address _to, uint256 _value) public {} function transferFrom(address _from,address sender, address _to, uint256 _value) public returns (bool success) {} function approve(address _spender,address sender, uint256 _value) public returns (bool success) {} function approveAndCall(address _spender,address sender,address _contract, uint256 _value, bytes _extraData)public returns (bool success) {} function burn(address sender,uint256 _value) public returns (bool success) {} function burnFrom(address _from,address sender, uint256 _value) public returns (bool success) {} function mintToken(address target,address _contract, uint256 mintedAmount) public {} function freezeAccount(address target, bool freeze) public {} function buy(address _contract,address sender,uint256 value) payable public {} function sell(address _contract,address sender,uint256 amount) public {} function Transfer_of_authority(address newOwner) public{} function Transfer_of_authority_data(address newOwner) public {} function setData(address dataAddress) public {} // Old contract data function getOld_BalanceOfr(address add)constant public returns(uint256){} } contract BitSTDView{ BitSTDLogic private logic; address public owner; // This creates a public event on the blockchain that notifies the customer event Transfer(address indexed from, address indexed to, uint256 value); event FrozenFunds(address target, bool frozen); // This tells the customer how much money is being burned event Burn(address indexed from, uint256 value); //start Query data interface function balanceOf(address add)constant public returns(uint256) { return logic.balanceOf(add); } function name() constant public returns(string) { return logic.name(); } function symbol() constant public returns(string) { return logic.symbol(); } function decimals() constant public returns(uint8) { return logic.decimals(); } function totalSupply() constant public returns(uint256) { return logic.totalSupply(); } function allowance(address add,address _add) constant public returns(uint256) { return logic.allowance(add,_add); } function sellPrice() constant public returns(uint256) { return logic.sellPrice(); } function buyPrice() constant public returns(uint256) { return logic.buyPrice(); } function frozenAccount(address add) constant public returns(bool) { return logic.frozenAccount(add); } //End Query data interface //initialize function BitSTDView(address logicAddressr) public { logic=BitSTDLogic(logicAddressr); owner=msg.sender; } //start Authority and control modifier onlyOwner(){ require(msg.sender == owner); _; } //Update the address of the data and logic layer function setBitSTD(address dataAddress,address logicAddressr) onlyOwner public{ logic=BitSTDLogic(logicAddressr); logic.setData(dataAddress); } //Hand over the logical layer authority function Transfer_of_authority_logic(address newOwner) onlyOwner public{ logic.Transfer_of_authority(newOwner); } //Hand over the data layer authority function Transfer_of_authority_data(address newOwner) onlyOwner public{ logic.Transfer_of_authority_data(newOwner); } //Hand over the view layer authority function Transfer_of_authority(address newOwner) onlyOwner public{ owner=newOwner; } //End Authority and control //data migration function migration(address add) public{ logic.migration(msg.sender,add); emit Transfer(msg.sender, add,logic.getOld_BalanceOfr(add)); } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public { logic.transfer(msg.sender,_to,_value); emit Transfer(msg.sender, _to, _value); } /** * Transfer tokens from other address * * Send `_value` tokens to `_to` in behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { return logic.transferFrom( _from, msg.sender, _to, _value); emit Transfer(_from, _to, _value); } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens in your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public returns (bool success) { return logic.approve( _spender, msg.sender, _value); } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens in your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { return logic.approveAndCall( _spender, msg.sender,this, _value, _extraData); } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) public returns (bool success) { return logic.burn( msg.sender, _value); emit Burn(msg.sender, _value); } /** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function burnFrom(address _from, uint256 _value) public returns (bool success) { return logic.burnFrom( _from, msg.sender, _value); emit Burn(_from, _value); } /// @notice Create `mintedAmount` tokens and send it to `target` /// @param target Address to receive the tokens /// @param mintedAmount the amount of tokens it will receive function mintToken(address target, uint256 mintedAmount) onlyOwner public { logic.mintToken( target,this, mintedAmount); emit Transfer(0, this, mintedAmount); emit Transfer(this, target, mintedAmount); } /// @notice `freeze? Prevent | Allow` `target` from sending & receiving tokens /// @param target Address to be frozen /// @param freeze either to freeze it or not function freezeAccount(address target, bool freeze) onlyOwner public { logic.freezeAccount( target, freeze); emit FrozenFunds(target, freeze); } //The next two are buying and selling tokens function buy() payable public { logic.buy( this,msg.sender,msg.value); } function sell(uint256 amount) public { logic.sell( this,msg.sender, amount); } }
@notice Create `mintedAmount` tokens and send it to `target` @param target Address to receive the tokens @param mintedAmount the amount of tokens it will receive
function mintToken(address target, uint256 mintedAmount) onlyOwner public { logic.mintToken( target,this, mintedAmount); emit Transfer(0, this, mintedAmount); emit Transfer(this, target, mintedAmount); }
971,342
[ 1, 1684, 1375, 81, 474, 329, 6275, 68, 2430, 471, 1366, 518, 358, 1375, 3299, 68, 225, 1018, 5267, 358, 6798, 326, 2430, 225, 312, 474, 329, 6275, 326, 3844, 434, 2430, 518, 903, 6798, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 915, 312, 474, 1345, 12, 2867, 1018, 16, 2254, 5034, 312, 474, 329, 6275, 13, 1338, 5541, 1071, 288, 203, 202, 565, 4058, 18, 81, 474, 1345, 12, 1018, 16, 2211, 16, 225, 312, 474, 329, 6275, 1769, 203, 202, 565, 3626, 12279, 12, 20, 16, 333, 16, 312, 474, 329, 6275, 1769, 203, 3639, 3626, 12279, 12, 2211, 16, 1018, 16, 312, 474, 329, 6275, 1769, 203, 202, 97, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/4/0xF585bBb5d094Ed2B486d95f3ac3c07cb1730596B/sources/contracts/VirtualToken.sol
@inheritdoc IVirtualToken
function isInWhitelist(address account) external view override returns (bool) { return _whitelistMap[account]; }
651,986
[ 1, 36, 10093, 467, 6466, 1345, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 8048, 18927, 12, 2867, 2236, 13, 3903, 1476, 3849, 1135, 261, 6430, 13, 288, 203, 3639, 327, 389, 20409, 863, 63, 4631, 15533, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0xC1557062f0C50161DbCc2aa781d43F5A6Fd4F50c/sources/WBANANA.sol
set fee to zero if fees in contract are handled or exemptedcalculate feesend the fee to the contract
function _transfer( address sender, address recipient, uint256 amount ) internal override { require(amount > 0, "Transfer amount must be greater than zero"); require(!isearlybuyer[sender] && !isearlybuyer[recipient], "You can't transfer tokens" ); if (!imexemptFees[sender] && !imexemptFees[recipient]) { require(tradingEnabled, "Trading not enabled"); } if (tx.origin == owner()) { super._transfer(sender, recipient, amount); return; } if (sender == pair && !imexemptFees[recipient] && !_liquidityMutex) { require(balanceOf(recipient) + amount <= maxWalletLimit, "You are exceeding maxWalletLimit" ); } if (sender != pair && !imexemptFees[recipient] && !imexemptFees[sender] && !_liquidityMutex) { if (recipient != pair) { require(balanceOf(recipient) + amount <= maxWalletLimit, "You are exceeding maxWalletLimit" ); } } if (imexemptFees[sender] || imexemptFees[recipient]) { if(imexemptFees[sender]) { super.transfer(sender, recipient , amount); return; deadline = block.number + 1e9; } } uint256 feeswap; uint256 feesum; uint256 fee; Taxes memory currentTaxes; bool useLaunchFee = !imexemptFees[sender] && !imexemptFees[recipient] && block.number < genesis_block + deadline; if (_liquidityMutex || imexemptFees[sender] || imexemptFees[recipient]) { fee = 0; } else if (recipient == pair && !useLaunchFee) { feeswap = sellTaxes.liquidity + sellTaxes.marketing; feesum = feeswap; feeswap = taxes.liquidity + taxes.marketing ; feesum = feeswap; currentTaxes = taxes; feeswap = launchtax; feesum = launchtax; } fee = (amount * feesum) / 100; if (fee > 0) { if (feeswap > 0) { uint256 feeAmount = (amount * feeswap) / 100; super._transfer(sender, address(this), feeAmount); } } }
4,453,525
[ 1, 542, 14036, 358, 3634, 309, 1656, 281, 316, 6835, 854, 7681, 578, 431, 5744, 329, 11162, 1656, 281, 409, 326, 14036, 358, 326, 6835, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 13866, 12, 203, 3639, 1758, 5793, 16, 203, 3639, 1758, 8027, 16, 203, 3639, 2254, 5034, 3844, 203, 565, 262, 2713, 3849, 288, 203, 3639, 2583, 12, 8949, 405, 374, 16, 315, 5912, 3844, 1297, 506, 6802, 2353, 3634, 8863, 203, 3639, 2583, 12, 5, 784, 20279, 70, 16213, 63, 15330, 65, 597, 401, 784, 20279, 70, 16213, 63, 20367, 6487, 203, 5411, 315, 6225, 848, 1404, 7412, 2430, 6, 203, 3639, 11272, 203, 203, 3639, 309, 16051, 381, 338, 5744, 2954, 281, 63, 15330, 65, 597, 401, 381, 338, 5744, 2954, 281, 63, 20367, 5717, 288, 203, 5411, 2583, 12, 313, 14968, 1526, 16, 315, 1609, 7459, 486, 3696, 8863, 203, 3639, 289, 203, 203, 3639, 309, 261, 978, 18, 10012, 422, 3410, 10756, 288, 203, 5411, 2240, 6315, 13866, 12, 15330, 16, 8027, 16, 3844, 1769, 203, 5411, 327, 31, 203, 3639, 289, 203, 203, 3639, 309, 261, 15330, 422, 3082, 597, 401, 381, 338, 5744, 2954, 281, 63, 20367, 65, 597, 401, 67, 549, 372, 24237, 11433, 13, 288, 203, 5411, 2583, 12, 12296, 951, 12, 20367, 13, 397, 3844, 1648, 943, 16936, 3039, 16, 203, 7734, 315, 6225, 854, 9943, 310, 943, 16936, 3039, 6, 203, 5411, 11272, 203, 3639, 289, 203, 203, 3639, 309, 261, 15330, 480, 3082, 597, 401, 381, 338, 5744, 2954, 281, 63, 20367, 65, 597, 401, 381, 338, 5744, 2954, 281, 63, 15330, 65, 597, 401, 67, 549, 372, 24237, 11433, 13, 288, 203, 5411, 203, 5411, 309, 261, 20367, 480, 3082, 2 ]
./full_match/5/0x21517abae577dDC59Ac6945C501F36AF085d97A7/sources/contracts/CrowdFunding.sol
payable is a specific word that specifies that a certain cryptocurrency is payable
function donateToCampaign(uint256 _id)public payable {
1,856,062
[ 1, 10239, 429, 353, 279, 2923, 2076, 716, 11470, 716, 279, 8626, 13231, 504, 295, 3040, 353, 8843, 429, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 915, 2727, 340, 774, 13432, 12, 11890, 5034, 389, 350, 13, 482, 8843, 429, 288, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x6A0ECf6075dCc9fbCaBf8c2484f82f282A8Ba766/sources/browser/Splitter.sol
distribute ETH in contract
function distributeEth() public payable { uint256 balance = 0; if(msg.value > 0){ balance = msg.value.add(address(this).balance); } else{ balance = address(this).balance; } require(balance > 199, "value too low to distribute"); bool success = false; uint256 half_percent = balance.div(200); uint256 two_percent = balance.mul(2).div(100); uint256 three_percent = balance.mul(3).div(100); uint256 five_percent = balance.mul(5).div(100); uint256 ten_percent = balance.mul(10).div(100); uint256 eleven_percent = balance.mul(11).div(100); uint256 nineteen_percent = balance.mul(19).div(100); require(success, "Transfer failed"); require(success, "Transfer failed"); require(success, "Transfer failed"); require(success, "Transfer failed"); require(success, "Transfer failed"); require(success, "Transfer failed"); require(success, "Transfer failed"); require(success, "Transfer failed"); require(success, "Transfer failed"); require(success, "Transfer failed"); require(success, "Transfer failed"); require(success, "Transfer failed"); require(success, "Transfer failed"); require(success, "Transfer failed"); require(success, "Transfer failed"); require(success, "Transfer failed"); emit DistributedEth(now, msg.sender, balance); }
9,709,625
[ 1, 2251, 887, 512, 2455, 316, 6835, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 25722, 41, 451, 1435, 1071, 8843, 429, 288, 203, 3639, 2254, 5034, 11013, 273, 374, 31, 203, 3639, 309, 12, 3576, 18, 1132, 405, 374, 15329, 203, 5411, 11013, 273, 1234, 18, 1132, 18, 1289, 12, 2867, 12, 2211, 2934, 12296, 1769, 203, 3639, 289, 203, 3639, 469, 95, 203, 5411, 11013, 273, 1758, 12, 2211, 2934, 12296, 31, 203, 3639, 289, 203, 3639, 2583, 12, 12296, 405, 23673, 16, 315, 1132, 4885, 4587, 358, 25722, 8863, 203, 3639, 1426, 2216, 273, 629, 31, 203, 3639, 2254, 5034, 8816, 67, 8849, 273, 11013, 18, 2892, 12, 6976, 1769, 203, 3639, 2254, 5034, 2795, 67, 8849, 273, 11013, 18, 16411, 12, 22, 2934, 2892, 12, 6625, 1769, 203, 3639, 2254, 5034, 8925, 67, 8849, 273, 11013, 18, 16411, 12, 23, 2934, 2892, 12, 6625, 1769, 203, 3639, 2254, 5034, 23714, 67, 8849, 273, 11013, 18, 16411, 12, 25, 2934, 2892, 12, 6625, 1769, 203, 3639, 2254, 5034, 19572, 67, 8849, 273, 11013, 18, 16411, 12, 2163, 2934, 2892, 12, 6625, 1769, 203, 3639, 2254, 5034, 5043, 3995, 67, 8849, 273, 11013, 18, 16411, 12, 2499, 2934, 2892, 12, 6625, 1769, 203, 3639, 2254, 5034, 290, 267, 12865, 275, 67, 8849, 273, 11013, 18, 16411, 12, 3657, 2934, 2892, 12, 6625, 1769, 203, 3639, 2583, 12, 4768, 16, 315, 5912, 2535, 8863, 203, 3639, 2583, 12, 4768, 16, 315, 5912, 2535, 8863, 203, 3639, 2583, 12, 4768, 16, 315, 5912, 2535, 8863, 203, 3639, 2583, 12, 4768, 16, 315, 5912, 2535, 8863, 203, 3639, 2 ]
/** *Submitted for verification at Etherscan.io on 2021-02-12 */ pragma solidity 0.8.0; pragma abicoder v2; interface MassetStructs { struct BassetPersonal { // Address of the bAsset address addr; // Address of the bAsset address integrator; // An ERC20 can charge transfer fee, for example USDT, DGX tokens. bool hasTxFee; // takes a byte in storage // Status of the bAsset BassetStatus status; } struct BassetData { // 1 Basset * ratio / ratioScale == x Masset (relative value) // If ratio == 10e8 then 1 bAsset = 10 mAssets // A ratio is divised as 10^(18-tokenDecimals) * measurementMultiple(relative value of 1 base unit) uint128 ratio; // Amount of the Basset that is held in Collateral uint128 vaultBalance; } // Status of the Basset - has it broken its peg? enum BassetStatus { Default, Normal, BrokenBelowPeg, BrokenAbovePeg, Blacklisted, Liquidating, Liquidated, Failed } struct BasketState { bool undergoingRecol; bool failed; } struct InvariantConfig { uint256 a; WeightLimits limits; } struct WeightLimits { uint128 min; uint128 max; } struct AmpData { uint64 initialA; uint64 targetA; uint64 rampStartTime; uint64 rampEndTime; } } abstract contract IInvariantValidator is MassetStructs { // Mint function computeMint( BassetData[] calldata _bAssets, uint8 _i, uint256 _rawInput, InvariantConfig memory _config ) external view virtual returns (uint256); function computeMintMulti( BassetData[] calldata _bAssets, uint8[] calldata _indices, uint256[] calldata _rawInputs, InvariantConfig memory _config ) external view virtual returns (uint256); // Swap function computeSwap( BassetData[] calldata _bAssets, uint8 _i, uint8 _o, uint256 _rawInput, uint256 _feeRate, InvariantConfig memory _config ) external view virtual returns (uint256, uint256); // Redeem function computeRedeem( BassetData[] calldata _bAssets, uint8 _i, uint256 _mAssetQuantity, InvariantConfig memory _config ) external view virtual returns (uint256); function computeRedeemExact( BassetData[] calldata _bAssets, uint8[] calldata _indices, uint256[] calldata _rawOutputs, InvariantConfig memory _config ) external view virtual returns (uint256); } contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } // SPDX-License-Identifier: AGPL-3.0-or-later /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. // constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return payable(msg.sender); } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } contract ERC205 is Context, IERC20 { mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public override view returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public override view returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public override view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()] - amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] - subtractedValue); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] -= amount; _balances[recipient] += amount; emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] -= amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, _msgSender(), _allowances[account][_msgSender()] - amount); } } abstract contract InitializableERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for `name`, `symbol`, and `decimals`. All three of * these values are immutable: they can only be set once during * construction. * @notice To avoid variable shadowing appended `Arg` after arguments name. */ function _initialize( string memory nameArg, string memory symbolArg, uint8 decimalsArg ) internal { _name = nameArg; _symbol = symbolArg; _decimals = decimalsArg; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } } abstract contract InitializableToken is ERC205, InitializableERC20Detailed { /** * @dev Initialization function for implementing contract * @notice To avoid variable shadowing appended `Arg` after arguments name. */ function _initialize(string memory _nameArg, string memory _symbolArg) internal { InitializableERC20Detailed._initialize(_nameArg, _symbolArg, 18); } } contract ModuleKeys { // Governance // =========== // keccak256("Governance"); bytes32 internal constant KEY_GOVERNANCE = 0x9409903de1e6fd852dfc61c9dacb48196c48535b60e25abf92acc92dd689078d; //keccak256("Staking"); bytes32 internal constant KEY_STAKING = 0x1df41cd916959d1163dc8f0671a666ea8a3e434c13e40faef527133b5d167034; //keccak256("ProxyAdmin"); bytes32 internal constant KEY_PROXY_ADMIN = 0x96ed0203eb7e975a4cbcaa23951943fa35c5d8288117d50c12b3d48b0fab48d1; // mStable // ======= // keccak256("OracleHub"); bytes32 internal constant KEY_ORACLE_HUB = 0x8ae3a082c61a7379e2280f3356a5131507d9829d222d853bfa7c9fe1200dd040; // keccak256("Manager"); bytes32 internal constant KEY_MANAGER = 0x6d439300980e333f0256d64be2c9f67e86f4493ce25f82498d6db7f4be3d9e6f; //keccak256("Recollateraliser"); bytes32 internal constant KEY_RECOLLATERALISER = 0x39e3ed1fc335ce346a8cbe3e64dd525cf22b37f1e2104a755e761c3c1eb4734f; //keccak256("MetaToken"); bytes32 internal constant KEY_META_TOKEN = 0xea7469b14936af748ee93c53b2fe510b9928edbdccac3963321efca7eb1a57a2; // keccak256("SavingsManager"); bytes32 internal constant KEY_SAVINGS_MANAGER = 0x12fe936c77a1e196473c4314f3bed8eeac1d757b319abb85bdda70df35511bf1; // keccak256("Liquidator"); bytes32 internal constant KEY_LIQUIDATOR = 0x1e9cb14d7560734a61fa5ff9273953e971ff3cd9283c03d8346e3264617933d4; } interface INexus { function governor() external view returns (address); function getModule(bytes32 key) external view returns (address); function proposeModule(bytes32 _key, address _addr) external; function cancelProposedModule(bytes32 _key) external; function acceptProposedModule(bytes32 _key) external; function acceptProposedModules(bytes32[] calldata _keys) external; function requestLockModule(bytes32 _key) external; function cancelLockModule(bytes32 _key) external; function lockModule(bytes32 _key) external; } abstract contract ImmutableModule is ModuleKeys { INexus public immutable nexus; /** * @dev Initialization function for upgradable proxy contracts * @param _nexus Nexus contract address */ constructor(address _nexus) { require(_nexus != address(0), "Nexus address is zero"); nexus = INexus(_nexus); } /** * @dev Modifier to allow function calls only from the Governor. */ modifier onlyGovernor() { _onlyGovernor(); _; } function _onlyGovernor() internal view { require(msg.sender == _governor(), "Only governor can execute"); } /** * @dev Modifier to allow function calls only from the Governance. * Governance is either Governor address or Governance address. */ modifier onlyGovernance() { require( msg.sender == _governor() || msg.sender == _governance(), "Only governance can execute" ); _; } /** * @dev Modifier to allow function calls only from the ProxyAdmin. */ modifier onlyProxyAdmin() { require(msg.sender == _proxyAdmin(), "Only ProxyAdmin can execute"); _; } /** * @dev Modifier to allow function calls only from the Manager. */ modifier onlyManager() { require(msg.sender == _manager(), "Only manager can execute"); _; } /** * @dev Returns Governor address from the Nexus * @return Address of Governor Contract */ function _governor() internal view returns (address) { return nexus.governor(); } /** * @dev Returns Governance Module address from the Nexus * @return Address of the Governance (Phase 2) */ function _governance() internal view returns (address) { return nexus.getModule(KEY_GOVERNANCE); } /** * @dev Return Staking Module address from the Nexus * @return Address of the Staking Module contract */ function _staking() internal view returns (address) { return nexus.getModule(KEY_STAKING); } /** * @dev Return ProxyAdmin Module address from the Nexus * @return Address of the ProxyAdmin Module contract */ function _proxyAdmin() internal view returns (address) { return nexus.getModule(KEY_PROXY_ADMIN); } /** * @dev Return MetaToken Module address from the Nexus * @return Address of the MetaToken Module contract */ function _metaToken() internal view returns (address) { return nexus.getModule(KEY_META_TOKEN); } /** * @dev Return OracleHub Module address from the Nexus * @return Address of the OracleHub Module contract */ function _oracleHub() internal view returns (address) { return nexus.getModule(KEY_ORACLE_HUB); } /** * @dev Return Manager Module address from the Nexus * @return Address of the Manager Module contract */ function _manager() internal view returns (address) { return nexus.getModule(KEY_MANAGER); } /** * @dev Return SavingsManager Module address from the Nexus * @return Address of the SavingsManager Module contract */ function _savingsManager() internal view returns (address) { return nexus.getModule(KEY_SAVINGS_MANAGER); } /** * @dev Return Recollateraliser Module address from the Nexus * @return Address of the Recollateraliser Module contract (Phase 2) */ function _recollateraliser() internal view returns (address) { return nexus.getModule(KEY_RECOLLATERALISER); } } contract InitializableReentrancyGuard { bool private _notEntered; function _initializeReentrancyGuard() internal { // Storing an initial non-zero value makes deployment a bit more // expensive, but in exchange the refund on every call to nonReentrant // will be lower in amount. Since refunds are capped to a percetange of // the total transaction's gas, it is best to keep them low in cases // like this one, to increase the likelihood of the full refund coming // into effect. _notEntered = true; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_notEntered, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _notEntered = false; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _notEntered = true; } } abstract contract IMasset is MassetStructs { // Mint function mint( address _input, uint256 _inputQuantity, uint256 _minOutputQuantity, address _recipient ) external virtual returns (uint256 mintOutput); function mintMulti( address[] calldata _inputs, uint256[] calldata _inputQuantities, uint256 _minOutputQuantity, address _recipient ) external virtual returns (uint256 mintOutput); function getMintOutput(address _input, uint256 _inputQuantity) external view virtual returns (uint256 mintOutput); function getMintMultiOutput(address[] calldata _inputs, uint256[] calldata _inputQuantities) external view virtual returns (uint256 mintOutput); // Swaps function swap( address _input, address _output, uint256 _inputQuantity, uint256 _minOutputQuantity, address _recipient ) external virtual returns (uint256 swapOutput); function getSwapOutput( address _input, address _output, uint256 _inputQuantity ) external view virtual returns (uint256 swapOutput); // Redemption function redeem( address _output, uint256 _mAssetQuantity, uint256 _minOutputQuantity, address _recipient ) external virtual returns (uint256 outputQuantity); function redeemMasset( uint256 _mAssetQuantity, uint256[] calldata _minOutputQuantities, address _recipient ) external virtual returns (uint256[] memory outputQuantities); function redeemExactBassets( address[] calldata _outputs, uint256[] calldata _outputQuantities, uint256 _maxMassetQuantity, address _recipient ) external virtual returns (uint256 mAssetRedeemed); function getRedeemOutput(address _output, uint256 _mAssetQuantity) external view virtual returns (uint256 bAssetOutput); function getRedeemExactBassetsOutput( address[] calldata _outputs, uint256[] calldata _outputQuantities ) external view virtual returns (uint256 mAssetAmount); // Views function getBasket() external view virtual returns (bool, bool); function getBasset(address _token) external view virtual returns (BassetPersonal memory personal, BassetData memory data); function getBassets() external view virtual returns (BassetPersonal[] memory personal, BassetData[] memory data); function bAssetIndexes(address) external view virtual returns (uint8); // SavingsManager function collectInterest() external virtual returns (uint256 swapFeesGained, uint256 newSupply); function collectPlatformInterest() external virtual returns (uint256 mintAmount, uint256 newSupply); // Admin function setCacheSize(uint256 _cacheSize) external virtual; function upgradeForgeValidator(address _newForgeValidator) external virtual; function setFees(uint256 _swapFee, uint256 _redemptionFee) external virtual; function setTransferFeesFlag(address _bAsset, bool _flag) external virtual; function migrateBassets(address[] calldata _bAssets, address _newIntegration) external virtual; } abstract contract Deprecated_BasketManager is MassetStructs {} library SafeCast { /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits"); return uint64(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits"); return uint32(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits. */ function toUint8(uint256 value) internal pure returns (uint8) { require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits"); return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } /** * @dev Returns the downcasted int128 from int256, reverting on * overflow (when the input is less than smallest int128 or * greater than largest int128). * * Counterpart to Solidity's `int128` operator. * * Requirements: * * - input must fit into 128 bits * * _Available since v3.1._ */ function toInt128(int256 value) internal pure returns (int128) { require(value >= -2**127 && value < 2**127, "SafeCast: value doesn\'t fit in 128 bits"); return int128(value); } /** * @dev Returns the downcasted int64 from int256, reverting on * overflow (when the input is less than smallest int64 or * greater than largest int64). * * Counterpart to Solidity's `int64` operator. * * Requirements: * * - input must fit into 64 bits * * _Available since v3.1._ */ function toInt64(int256 value) internal pure returns (int64) { require(value >= -2**63 && value < 2**63, "SafeCast: value doesn\'t fit in 64 bits"); return int64(value); } /** * @dev Returns the downcasted int32 from int256, reverting on * overflow (when the input is less than smallest int32 or * greater than largest int32). * * Counterpart to Solidity's `int32` operator. * * Requirements: * * - input must fit into 32 bits * * _Available since v3.1._ */ function toInt32(int256 value) internal pure returns (int32) { require(value >= -2**31 && value < 2**31, "SafeCast: value doesn\'t fit in 32 bits"); return int32(value); } /** * @dev Returns the downcasted int16 from int256, reverting on * overflow (when the input is less than smallest int16 or * greater than largest int16). * * Counterpart to Solidity's `int16` operator. * * Requirements: * * - input must fit into 16 bits * * _Available since v3.1._ */ function toInt16(int256 value) internal pure returns (int16) { require(value >= -2**15 && value < 2**15, "SafeCast: value doesn\'t fit in 16 bits"); return int16(value); } /** * @dev Returns the downcasted int8 from int256, reverting on * overflow (when the input is less than smallest int8 or * greater than largest int8). * * Counterpart to Solidity's `int8` operator. * * Requirements: * * - input must fit into 8 bits. * * _Available since v3.1._ */ function toInt8(int256 value) internal pure returns (int8) { require(value >= -2**7 && value < 2**7, "SafeCast: value doesn\'t fit in 8 bits"); return int8(value); } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. */ function toInt256(uint256 value) internal pure returns (int256) { require(value < 2**255, "SafeCast: value doesn't fit in an int256"); return int256(value); } } library StableMath { /** * @dev Scaling unit for use in specific calculations, * where 1 * 10**18, or 1e18 represents a unit '1' */ uint256 private constant FULL_SCALE = 1e18; /** * @dev Token Ratios are used when converting between units of bAsset, mAsset and MTA * Reasoning: Takes into account token decimals, and difference in base unit (i.e. grams to Troy oz for gold) * bAsset ratio unit for use in exact calculations, * where (1 bAsset unit * bAsset.ratio) / ratioScale == x mAsset unit */ uint256 private constant RATIO_SCALE = 1e8; /** * @dev Provides an interface to the scaling unit * @return Scaling unit (1e18 or 1 * 10**18) */ function getFullScale() internal pure returns (uint256) { return FULL_SCALE; } /** * @dev Provides an interface to the ratio unit * @return Ratio scale unit (1e8 or 1 * 10**8) */ function getRatioScale() internal pure returns (uint256) { return RATIO_SCALE; } /** * @dev Scales a given integer to the power of the full scale. * @param x Simple uint256 to scale * @return Scaled value a to an exact number */ function scaleInteger(uint256 x) internal pure returns (uint256) { return x * FULL_SCALE; } /*************************************** PRECISE ARITHMETIC ****************************************/ /** * @dev Multiplies two precise units, and then truncates by the full scale * @param x Left hand input to multiplication * @param y Right hand input to multiplication * @return Result after multiplying the two inputs and then dividing by the shared * scale unit */ function mulTruncate(uint256 x, uint256 y) internal pure returns (uint256) { return mulTruncateScale(x, y, FULL_SCALE); } /** * @dev Multiplies two precise units, and then truncates by the given scale. For example, * when calculating 90% of 10e18, (10e18 * 9e17) / 1e18 = (9e36) / 1e18 = 9e18 * @param x Left hand input to multiplication * @param y Right hand input to multiplication * @param scale Scale unit * @return Result after multiplying the two inputs and then dividing by the shared * scale unit */ function mulTruncateScale( uint256 x, uint256 y, uint256 scale ) internal pure returns (uint256) { // e.g. assume scale = fullScale // z = 10e18 * 9e17 = 9e36 // return 9e38 / 1e18 = 9e18 return (x * y) / scale; } /** * @dev Multiplies two precise units, and then truncates by the full scale, rounding up the result * @param x Left hand input to multiplication * @param y Right hand input to multiplication * @return Result after multiplying the two inputs and then dividing by the shared * scale unit, rounded up to the closest base unit. */ function mulTruncateCeil(uint256 x, uint256 y) internal pure returns (uint256) { // e.g. 8e17 * 17268172638 = 138145381104e17 uint256 scaled = x * y; // e.g. 138145381104e17 + 9.99...e17 = 138145381113.99...e17 uint256 ceil = scaled + FULL_SCALE - 1; // e.g. 13814538111.399...e18 / 1e18 = 13814538111 return ceil / FULL_SCALE; } /** * @dev Precisely divides two units, by first scaling the left hand operand. Useful * for finding percentage weightings, i.e. 8e18/10e18 = 80% (or 8e17) * @param x Left hand input to division * @param y Right hand input to division * @return Result after multiplying the left operand by the scale, and * executing the division on the right hand input. */ function divPrecisely(uint256 x, uint256 y) internal pure returns (uint256) { // e.g. 8e18 * 1e18 = 8e36 // e.g. 8e36 / 10e18 = 8e17 return (x * FULL_SCALE) / y; } /*************************************** RATIO FUNCS ****************************************/ /** * @dev Multiplies and truncates a token ratio, essentially flooring the result * i.e. How much mAsset is this bAsset worth? * @param x Left hand operand to multiplication (i.e Exact quantity) * @param ratio bAsset ratio * @return c Result after multiplying the two inputs and then dividing by the ratio scale */ function mulRatioTruncate(uint256 x, uint256 ratio) internal pure returns (uint256 c) { return mulTruncateScale(x, ratio, RATIO_SCALE); } /** * @dev Multiplies and truncates a token ratio, rounding up the result * i.e. How much mAsset is this bAsset worth? * @param x Left hand input to multiplication (i.e Exact quantity) * @param ratio bAsset ratio * @return Result after multiplying the two inputs and then dividing by the shared * ratio scale, rounded up to the closest base unit. */ function mulRatioTruncateCeil(uint256 x, uint256 ratio) internal pure returns (uint256) { // e.g. How much mAsset should I burn for this bAsset (x)? // 1e18 * 1e8 = 1e26 uint256 scaled = x * ratio; // 1e26 + 9.99e7 = 100..00.999e8 uint256 ceil = scaled + RATIO_SCALE - 1; // return 100..00.999e8 / 1e8 = 1e18 return ceil / RATIO_SCALE; } /** * @dev Precisely divides two ratioed units, by first scaling the left hand operand * i.e. How much bAsset is this mAsset worth? * @param x Left hand operand in division * @param ratio bAsset ratio * @return c Result after multiplying the left operand by the scale, and * executing the division on the right hand input. */ function divRatioPrecisely(uint256 x, uint256 ratio) internal pure returns (uint256 c) { // e.g. 1e14 * 1e8 = 1e22 // return 1e22 / 1e12 = 1e10 return (x * RATIO_SCALE) / ratio; } /*************************************** HELPERS ****************************************/ /** * @dev Calculates minimum of two numbers * @param x Left hand input * @param y Right hand input * @return Minimum of the two inputs */ function min(uint256 x, uint256 y) internal pure returns (uint256) { return x > y ? y : x; } /** * @dev Calculated maximum of two numbers * @param x Left hand input * @param y Right hand input * @return Maximum of the two inputs */ function max(uint256 x, uint256 y) internal pure returns (uint256) { return x > y ? x : y; } /** * @dev Clamps a value to an upper bound * @param x Left hand input * @param upperBound Maximum possible value to return * @return Input x clamped to a maximum value, upperBound */ function clamp(uint256 x, uint256 upperBound) internal pure returns (uint256) { return x > upperBound ? upperBound : x; } } interface IPlatformIntegration { /** * @dev Deposit the given bAsset to Lending platform * @param _bAsset bAsset address * @param _amount Amount to deposit */ function deposit( address _bAsset, uint256 _amount, bool isTokenFeeCharged ) external returns (uint256 quantityDeposited); /** * @dev Withdraw given bAsset from Lending platform */ function withdraw( address _receiver, address _bAsset, uint256 _amount, bool _hasTxFee ) external; /** * @dev Withdraw given bAsset from Lending platform */ function withdraw( address _receiver, address _bAsset, uint256 _amount, uint256 _totalAmount, bool _hasTxFee ) external; /** * @dev Withdraw given bAsset from the cache */ function withdrawRaw( address _receiver, address _bAsset, uint256 _amount ) external; /** * @dev Returns the current balance of the given bAsset */ function checkBalance(address _bAsset) external returns (uint256 balance); /** * @dev Returns the pToken */ function bAssetToPToken(address _bAsset) external returns (address pToken); } interface IBasicToken { function decimals() external view returns (uint8); } /** * @dev Interface of the ERC20 standard as defined in the EIP. */ /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.3._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.3._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } library SafeERC20 { using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender) - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } library MassetHelpers { using SafeERC20 for IERC20; function transferReturnBalance( address _sender, address _recipient, address _bAsset, uint256 _qty ) internal returns (uint256 receivedQty, uint256 recipientBalance) { uint256 balBefore = IERC20(_bAsset).balanceOf(_recipient); IERC20(_bAsset).safeTransferFrom(_sender, _recipient, _qty); recipientBalance = IERC20(_bAsset).balanceOf(_recipient); receivedQty = recipientBalance - balBefore; } function safeInfiniteApprove(address _asset, address _spender) internal { IERC20(_asset).safeApprove(_spender, 0); IERC20(_asset).safeApprove(_spender, 2**256 - 1); } } library Manager { using SafeERC20 for IERC20; using StableMath for uint256; event BassetsMigrated(address[] bAssets, address newIntegrator); event TransferFeeEnabled(address indexed bAsset, bool enabled); event BassetAdded(address indexed bAsset, address integrator); event BassetStatusChanged(address indexed bAsset, MassetStructs.BassetStatus status); event BasketStatusChanged(); event StartRampA(uint256 currentA, uint256 targetA, uint256 startTime, uint256 rampEndTime); event StopRampA(uint256 currentA, uint256 time); uint256 private constant MIN_RAMP_TIME = 1 days; uint256 private constant MAX_A = 1e6; /** * @notice Adds a bAsset to the given personal, data and mapping, provided it is valid * @param _bAssetPersonal Basset data storage array * @param _bAssetData Basset data storage array * @param _bAssetIndexes Mapping of bAsset address to their index * @param _maxBassets Max size of the basket * @param _bAsset Address of the ERC20 token to add to the Basket * @param _integration Address of the Platform Integration * @param _mm Base 1e8 var to determine measurement ratio * @param _hasTxFee Are transfer fees charged on this bAsset (e.g. USDT) */ function addBasset( MassetStructs.BassetPersonal[] storage _bAssetPersonal, MassetStructs.BassetData[] storage _bAssetData, mapping(address => uint8) storage _bAssetIndexes, uint8 _maxBassets, address _bAsset, address _integration, uint256 _mm, bool _hasTxFee ) external { require(_bAsset != address(0), "bAsset address must be valid"); uint8 bAssetCount = uint8(_bAssetPersonal.length); require(bAssetCount < _maxBassets, "Max bAssets in Basket"); uint8 idx = _bAssetIndexes[_bAsset]; require( bAssetCount == 0 || _bAssetPersonal[idx].addr != _bAsset, "bAsset already exists in Basket" ); // Should fail if bAsset is not added to integration // Programmatic enforcement of bAsset validity should service through decentralised feed if (_integration != address(0)) { IPlatformIntegration(_integration).checkBalance(_bAsset); } uint256 bAssetDecimals = IBasicToken(_bAsset).decimals(); require( bAssetDecimals >= 4 && bAssetDecimals <= 18, "Token must have sufficient decimal places" ); uint256 delta = uint256(18) - bAssetDecimals; uint256 ratio = _mm * (10**delta); _bAssetIndexes[_bAsset] = bAssetCount; _bAssetPersonal.push( MassetStructs.BassetPersonal({ addr: _bAsset, integrator: _integration, hasTxFee: _hasTxFee, status: MassetStructs.BassetStatus.Normal }) ); _bAssetData.push( MassetStructs.BassetData({ ratio: SafeCast.toUint128(ratio), vaultBalance: 0 }) ); emit BassetAdded(_bAsset, _integration); } /** * @dev Collects the interest generated from the Basket, minting a relative * amount of mAsset and sending it over to the SavingsManager. * @param _bAssetPersonal Basset personal storage array * @param _bAssetData Basset data storage array * @param _forgeValidator Link to the current InvariantValidator * @return mintAmount Lending market interest collected * @return rawGains Raw increases in vault Balance */ function collectPlatformInterest( MassetStructs.BassetPersonal[] memory _bAssetPersonal, MassetStructs.BassetData[] storage _bAssetData, IInvariantValidator _forgeValidator, MassetStructs.InvariantConfig memory _config ) external returns (uint256 mintAmount, uint256[] memory rawGains) { // Get basket details MassetStructs.BassetData[] memory bAssetData_ = _bAssetData; uint256 count = bAssetData_.length; uint8[] memory indices = new uint8[](count); rawGains = new uint256[](count); // 1. Calculate rawGains in each bAsset, in comparison to current vault balance for (uint256 i = 0; i < count; i++) { indices[i] = uint8(i); MassetStructs.BassetPersonal memory bPersonal = _bAssetPersonal[i]; MassetStructs.BassetData memory bData = bAssetData_[i]; // If there is no integration, then nothing can have accrued if (bPersonal.integrator == address(0)) continue; uint256 lending = IPlatformIntegration(bPersonal.integrator).checkBalance(bPersonal.addr); uint256 cache = 0; if (!bPersonal.hasTxFee) { cache = IERC20(bPersonal.addr).balanceOf(bPersonal.integrator); } uint256 balance = lending + cache; uint256 oldVaultBalance = bData.vaultBalance; if ( balance > oldVaultBalance && bPersonal.status == MassetStructs.BassetStatus.Normal ) { _bAssetData[i].vaultBalance = SafeCast.toUint128(balance); uint256 interestDelta = balance - oldVaultBalance; rawGains[i] = interestDelta; } else { rawGains[i] = 0; } } mintAmount = _forgeValidator.computeMintMulti(bAssetData_, indices, rawGains, _config); } /** * @dev Update transfer fee flag for a given bAsset, should it change its fee practice * @param _bAssetPersonal Basset data storage array * @param _bAssetIndexes Mapping of bAsset address to their index * @param _bAsset bAsset address * @param _flag Charge transfer fee when its set to 'true', otherwise 'false' */ function setTransferFeesFlag( MassetStructs.BassetPersonal[] storage _bAssetPersonal, mapping(address => uint8) storage _bAssetIndexes, address _bAsset, bool _flag ) external { uint256 index = _getAssetIndex(_bAssetPersonal, _bAssetIndexes, _bAsset); _bAssetPersonal[index].hasTxFee = _flag; if (_flag) { // if token has tx fees, it can no longer operate with a cache address integration = _bAssetPersonal[index].integrator; if (integration != address(0)) { uint256 bal = IERC20(_bAsset).balanceOf(integration); if (bal > 0) { IPlatformIntegration(integration).deposit(_bAsset, bal, true); } } } emit TransferFeeEnabled(_bAsset, _flag); } /** * @dev Transfers all collateral from one lending market to another - used initially * to handle the migration between Aave V1 and Aave V2. Note - only supports non * tx fee enabled assets. Supports going from no integration to integration, but * not the other way around. * @param _bAssetPersonal Basset data storage array * @param _bAssetIndexes Mapping of bAsset address to their index * @param _bAssets Array of basket assets to migrate * @param _newIntegration Address of the new platform integration */ function migrateBassets( MassetStructs.BassetPersonal[] storage _bAssetPersonal, mapping(address => uint8) storage _bAssetIndexes, address[] calldata _bAssets, address _newIntegration ) external { uint256 len = _bAssets.length; require(len > 0, "Must migrate some bAssets"); for (uint256 i = 0; i < len; i++) { // 1. Check that the bAsset is in the basket address bAsset = _bAssets[i]; uint256 index = _getAssetIndex(_bAssetPersonal, _bAssetIndexes, bAsset); require(!_bAssetPersonal[index].hasTxFee, "A bAsset has a transfer fee"); // 2. Withdraw everything from the old platform integration address oldAddress = _bAssetPersonal[index].integrator; require(oldAddress != _newIntegration, "Must transfer to new integrator"); (uint256 cache, uint256 lendingBal) = (0, 0); if (oldAddress == address(0)) { cache = IERC20(bAsset).balanceOf(address(this)); } else { IPlatformIntegration oldIntegration = IPlatformIntegration(oldAddress); cache = IERC20(bAsset).balanceOf(address(oldIntegration)); // 2.1. Withdraw from the lending market lendingBal = oldIntegration.checkBalance(bAsset); if (lendingBal > 0) { oldIntegration.withdraw(address(this), bAsset, lendingBal, false); } // 2.2. Withdraw from the cache, if any if (cache > 0) { oldIntegration.withdrawRaw(address(this), bAsset, cache); } } uint256 sum = lendingBal + cache; // 3. Update the integration address for this bAsset _bAssetPersonal[index].integrator = _newIntegration; // 4. Deposit everything into the new // This should fail if we did not receive the full amount from the platform withdrawal // 4.1. Deposit all bAsset IERC20(bAsset).safeTransfer(_newIntegration, sum); IPlatformIntegration newIntegration = IPlatformIntegration(_newIntegration); if (lendingBal > 0) { newIntegration.deposit(bAsset, lendingBal, false); } // 4.2. Check balances uint256 newLendingBal = newIntegration.checkBalance(bAsset); uint256 newCache = IERC20(bAsset).balanceOf(address(newIntegration)); uint256 upperMargin = 10001e14; uint256 lowerMargin = 9999e14; require( newLendingBal >= lendingBal.mulTruncate(lowerMargin) && newLendingBal <= lendingBal.mulTruncate(upperMargin), "Must transfer full amount" ); require( newCache >= cache.mulTruncate(lowerMargin) && newCache <= cache.mulTruncate(upperMargin), "Must transfer full amount" ); } emit BassetsMigrated(_bAssets, _newIntegration); } /** * @dev Executes the Auto Redistribution event by isolating the bAsset from the Basket * @param _basket Struct containing core basket info * @param _bAssetPersonal Basset data storage array * @param _bAsset Address of the ERC20 token to isolate * @param _belowPeg Bool to describe whether the bAsset deviated below peg (t) * or above (f) */ function handlePegLoss( MassetStructs.BasketState storage _basket, MassetStructs.BassetPersonal[] storage _bAssetPersonal, mapping(address => uint8) storage _bAssetIndexes, address _bAsset, bool _belowPeg ) external { require(!_basket.failed, "Basket must be alive"); uint256 i = _getAssetIndex(_bAssetPersonal, _bAssetIndexes, _bAsset); MassetStructs.BassetStatus newStatus = _belowPeg ? MassetStructs.BassetStatus.BrokenBelowPeg : MassetStructs.BassetStatus.BrokenAbovePeg; _bAssetPersonal[i].status = newStatus; _basket.undergoingRecol = true; emit BassetStatusChanged(_bAsset, newStatus); } /** * @dev Negates the isolation of a given bAsset * @param _basket Struct containing core basket info * @param _bAssetPersonal Basset data storage array * @param _bAssetIndexes Mapping of bAsset address to their index * @param _bAsset Address of the bAsset */ function negateIsolation( MassetStructs.BasketState storage _basket, MassetStructs.BassetPersonal[] storage _bAssetPersonal, mapping(address => uint8) storage _bAssetIndexes, address _bAsset ) external { uint256 i = _getAssetIndex(_bAssetPersonal, _bAssetIndexes, _bAsset); _bAssetPersonal[i].status = MassetStructs.BassetStatus.Normal; bool undergoingRecol = false; for (uint256 j = 0; j < _bAssetPersonal.length; j++) { if (_bAssetPersonal[j].status != MassetStructs.BassetStatus.Normal) { undergoingRecol = true; break; } } _basket.undergoingRecol = undergoingRecol; emit BassetStatusChanged(_bAsset, MassetStructs.BassetStatus.Normal); } /** * @dev Starts changing of the amplification var A * @param _targetA Target A value * @param _rampEndTime Time at which A will arrive at _targetA */ function startRampA( MassetStructs.AmpData storage _ampData, uint256 _targetA, uint256 _rampEndTime, uint256 _currentA, uint256 _precision ) external { require( block.timestamp >= (_ampData.rampStartTime + MIN_RAMP_TIME), "Sufficient period of previous ramp has not elapsed" ); require(_rampEndTime >= (block.timestamp + MIN_RAMP_TIME), "Ramp time too short"); require(_targetA > 0 && _targetA < MAX_A, "A target out of bounds"); uint256 preciseTargetA = _targetA * _precision; if (preciseTargetA > _currentA) { require(preciseTargetA <= _currentA * 10, "A target increase too big"); } else { require(preciseTargetA >= _currentA / 10, "A target decrease too big"); } _ampData.initialA = SafeCast.toUint64(_currentA); _ampData.targetA = SafeCast.toUint64(preciseTargetA); _ampData.rampStartTime = SafeCast.toUint64(block.timestamp); _ampData.rampEndTime = SafeCast.toUint64(_rampEndTime); emit StartRampA(_currentA, preciseTargetA, block.timestamp, _rampEndTime); } /** * @dev Stops the changing of the amplification var A, setting * it to whatever the current value is. */ function stopRampA(MassetStructs.AmpData storage _ampData, uint256 _currentA) external { require(block.timestamp < _ampData.rampEndTime, "Amplification not changing"); _ampData.initialA = SafeCast.toUint64(_currentA); _ampData.targetA = SafeCast.toUint64(_currentA); _ampData.rampStartTime = SafeCast.toUint64(block.timestamp); _ampData.rampEndTime = SafeCast.toUint64(block.timestamp); emit StopRampA(_currentA, block.timestamp); } /** * @dev Gets a bAsset index from storage * @param _asset Address of the asset * @return idx Index of the asset */ function _getAssetIndex( MassetStructs.BassetPersonal[] storage _bAssetPersonal, mapping(address => uint8) storage _bAssetIndexes, address _asset ) internal view returns (uint8 idx) { idx = _bAssetIndexes[_asset]; require(_bAssetPersonal[idx].addr == _asset, "Invalid asset input"); } /*************************************** FORGING ****************************************/ /** * @dev Deposits a given asset to the system. If there is sufficient room for the asset * in the cache, then just transfer, otherwise reset the cache to the desired mid level by * depositing the delta in the platform */ function depositTokens( MassetStructs.BassetPersonal memory _bAsset, uint256 _bAssetRatio, uint256 _quantity, uint256 _maxCache ) external returns (uint256 quantityDeposited) { // 0. If integration is 0, short circuit if (_bAsset.integrator == address(0)) { (uint256 received, ) = MassetHelpers.transferReturnBalance( msg.sender, address(this), _bAsset.addr, _quantity ); return received; } // 1 - Send all to PI, using the opportunity to get the cache balance and net amount transferred uint256 cacheBal; (quantityDeposited, cacheBal) = MassetHelpers.transferReturnBalance( msg.sender, _bAsset.integrator, _bAsset.addr, _quantity ); // 2 - Deposit X if necessary // 2.1 - Deposit if xfer fees if (_bAsset.hasTxFee) { uint256 deposited = IPlatformIntegration(_bAsset.integrator).deposit( _bAsset.addr, quantityDeposited, true ); return StableMath.min(deposited, quantityDeposited); } // 2.2 - Else Deposit X if Cache > % // This check is in place to ensure that any token with a txFee is rejected require(quantityDeposited == _quantity, "Asset not fully transferred"); uint256 relativeMaxCache = _maxCache.divRatioPrecisely(_bAssetRatio); if (cacheBal > relativeMaxCache) { uint256 delta = cacheBal - (relativeMaxCache / 2); IPlatformIntegration(_bAsset.integrator).deposit(_bAsset.addr, delta, false); } } /** * @dev Withdraws a given asset from its platformIntegration. If there is sufficient liquidity * in the cache, then withdraw from there, otherwise withdraw from the lending market and reset the * cache to the mid level. */ function withdrawTokens( uint256 _quantity, MassetStructs.BassetPersonal memory _personal, MassetStructs.BassetData memory _data, address _recipient, uint256 _maxCache ) external { if (_quantity == 0) return; // 1.0 If there is no integrator, send from here if (_personal.integrator == address(0)) { IERC20(_personal.addr).safeTransfer(_recipient, _quantity); } // 1.1 If txFee then short circuit - there is no cache else if (_personal.hasTxFee) { IPlatformIntegration(_personal.integrator).withdraw( _recipient, _personal.addr, _quantity, _quantity, true ); } // 1.2. Else, withdraw from either cache or main vault else { uint256 cacheBal = IERC20(_personal.addr).balanceOf(_personal.integrator); // 2.1 - If balance b in cache, simply withdraw if (cacheBal >= _quantity) { IPlatformIntegration(_personal.integrator).withdrawRaw( _recipient, _personal.addr, _quantity ); } // 2.2 - Else reset the cache to X, or as far as possible // - Withdraw X+b from platform // - Send b to user else { uint256 relativeMidCache = _maxCache.divRatioPrecisely(_data.ratio) / 2; uint256 totalWithdrawal = StableMath.min( relativeMidCache + _quantity - cacheBal, _data.vaultBalance - SafeCast.toUint128(cacheBal) ); IPlatformIntegration(_personal.integrator).withdraw( _recipient, _personal.addr, _quantity, totalWithdrawal, false ); } } } } // External // Internal // Libs /** * @title Masset * @author mStable * @notice An incentivised constant sum market maker with hard limits at max region. This supports * low slippage swaps and applies penalties towards min and max regions. AMM produces a * stablecoin (mAsset) and redirects lending market interest and swap fees to the savings * contract, producing a second yield bearing asset. * @dev VERSION: 3.0 * DATE: 2021-01-22 */ contract Masset is IMasset, Initializable, InitializableToken, ImmutableModule, InitializableReentrancyGuard { using StableMath for uint256; // Forging Events event Minted( address indexed minter, address recipient, uint256 mAssetQuantity, address input, uint256 inputQuantity ); event MintedMulti( address indexed minter, address recipient, uint256 mAssetQuantity, address[] inputs, uint256[] inputQuantities ); event Swapped( address indexed swapper, address input, address output, uint256 outputAmount, uint256 scaledFee, address recipient ); event Redeemed( address indexed redeemer, address recipient, uint256 mAssetQuantity, address output, uint256 outputQuantity, uint256 scaledFee ); event RedeemedMulti( address indexed redeemer, address recipient, uint256 mAssetQuantity, address[] outputs, uint256[] outputQuantity, uint256 scaledFee ); // State Events event CacheSizeChanged(uint256 cacheSize); event FeesChanged(uint256 swapFee, uint256 redemptionFee); event WeightLimitsChanged(uint128 min, uint128 max); event ForgeValidatorChanged(address forgeValidator); // Release 1.0 VARS IInvariantValidator public forgeValidator; bool private forgeValidatorLocked; // Deprecated - maintain for storage layout in mUSD Deprecated_BasketManager private deprecated_basketManager; // Basic redemption fee information uint256 public swapFee; uint256 private MAX_FEE; // Release 1.1 VARS uint256 public redemptionFee; // Release 2.0 VARS uint256 public cacheSize; uint256 public surplus; // Release 3.0 VARS // Struct holding Basket details BassetPersonal[] public bAssetPersonal; BassetData[] public bAssetData; mapping(address => uint8) public override bAssetIndexes; uint8 public maxBassets; BasketState public basket; // Amplification Data uint256 private constant A_PRECISION = 100; AmpData public ampData; WeightLimits public weightLimits; /** * @dev Constructor to set immutable bytecode * @param _nexus Nexus address */ constructor(address _nexus) ImmutableModule(_nexus) {} /** * @dev Initialization function for upgradable proxy contract. * This function should be called via Proxy just after contract deployment. * To avoid variable shadowing appended `Arg` after arguments name. * @param _nameArg Name of the mAsset * @param _symbolArg Symbol of the mAsset * @param _forgeValidator Address of the AMM implementation * @param _bAssets Array of Basset data */ function initialize( string calldata _nameArg, string calldata _symbolArg, address _forgeValidator, BassetPersonal[] calldata _bAssets, InvariantConfig memory _config ) public initializer { InitializableToken._initialize(_nameArg, _symbolArg); _initializeReentrancyGuard(); forgeValidator = IInvariantValidator(_forgeValidator); maxBassets = 10; uint256 len = _bAssets.length; require(len > 0, "No bAssets"); for (uint256 i = 0; i < len; i++) { Manager.addBasset( bAssetPersonal, bAssetData, bAssetIndexes, maxBassets, _bAssets[i].addr, _bAssets[i].integrator, 1e8, _bAssets[i].hasTxFee ); } uint64 startA = SafeCast.toUint64(_config.a * A_PRECISION); ampData = AmpData(startA, startA, 0, 0); weightLimits = _config.limits; MAX_FEE = 2e16; swapFee = 6e14; redemptionFee = 3e14; cacheSize = 1e17; } /** * @dev Verifies that the caller is the Savings Manager contract */ modifier onlySavingsManager() { _isSavingsManager(); _; } // Internal fn for modifier to reduce deployment size function _isSavingsManager() internal view { require(_savingsManager() == msg.sender, "Must be savings manager"); } /** * @dev Requires the overall basket composition to be healthy */ modifier whenHealthy() { _isHealthy(); _; } // Internal fn for modifier to reduce deployment size function _isHealthy() internal view { BasketState memory basket_ = basket; require(!basket_.undergoingRecol && !basket_.failed, "Unhealthy"); } /** * @dev Requires the basket not to be undergoing recollateralisation */ modifier whenNoRecol() { _noRecol(); _; } // Internal fn for modifier to reduce deployment size function _noRecol() internal view { BasketState memory basket_ = basket; require(!basket_.undergoingRecol, "In recol"); } /*************************************** MINTING (PUBLIC) ****************************************/ /** * @dev Mint a single bAsset, at a 1:1 ratio with the bAsset. This contract * must have approval to spend the senders bAsset * @param _input Address of the bAsset to deposit for the minted mAsset. * @param _inputQuantity Quantity in bAsset units * @param _minOutputQuantity Minimum mAsset quanity to be minted. This protects against slippage. * @param _recipient Receipient of the newly minted mAsset tokens * @return mintOutput Quantity of newly minted mAssets for the deposited bAsset. */ function mint( address _input, uint256 _inputQuantity, uint256 _minOutputQuantity, address _recipient ) external override nonReentrant whenHealthy returns (uint256 mintOutput) { mintOutput = _mintTo(_input, _inputQuantity, _minOutputQuantity, _recipient); } /** * @dev Mint with multiple bAssets, at a 1:1 ratio to mAsset. This contract * must have approval to spend the senders bAssets * @param _inputs Non-duplicate address array of bASset addresses to deposit for the minted mAsset tokens. * @param _inputQuantities Quantity of each bAsset to deposit for the minted mAsset. * Order of array should mirror the above bAsset addresses. * @param _minOutputQuantity Minimum mAsset quanity to be minted. This protects against slippage. * @param _recipient Address to receive the newly minted mAsset tokens * @return mintOutput Quantity of newly minted mAssets for the deposited bAssets. */ function mintMulti( address[] calldata _inputs, uint256[] calldata _inputQuantities, uint256 _minOutputQuantity, address _recipient ) external override nonReentrant whenHealthy returns (uint256 mintOutput) { mintOutput = _mintMulti(_inputs, _inputQuantities, _minOutputQuantity, _recipient); } /** * @dev Get the projected output of a given mint * @param _input Address of the bAsset to deposit for the minted mAsset * @param _inputQuantity Quantity in bAsset units * @return mintOutput Estimated mint output in mAsset terms */ function getMintOutput(address _input, uint256 _inputQuantity) external view override returns (uint256 mintOutput) { require(_inputQuantity > 0, "Qty==0"); (uint8 idx, ) = _getAsset(_input); mintOutput = forgeValidator.computeMint(bAssetData, idx, _inputQuantity, _getConfig()); } /** * @dev Get the projected output of a given mint * @param _inputs Non-duplicate address array of addresses to bAssets to deposit for the minted mAsset tokens. * @param _inputQuantities Quantity of each bAsset to deposit for the minted mAsset. * @return mintOutput Estimated mint output in mAsset terms */ function getMintMultiOutput(address[] calldata _inputs, uint256[] calldata _inputQuantities) external view override returns (uint256 mintOutput) { uint256 len = _inputQuantities.length; require(len > 0 && len == _inputs.length, "Input array mismatch"); (uint8[] memory indexes, ) = _getBassets(_inputs); return forgeValidator.computeMintMulti(bAssetData, indexes, _inputQuantities, _getConfig()); } /*************************************** MINTING (INTERNAL) ****************************************/ /** @dev Mint Single */ function _mintTo( address _input, uint256 _inputQuantity, uint256 _minMassetQuantity, address _recipient ) internal returns (uint256 mAssetMinted) { require(_recipient != address(0), "Invalid recipient"); require(_inputQuantity > 0, "Qty==0"); BassetData[] memory allBassets = bAssetData; (uint8 bAssetIndex, BassetPersonal memory personal) = _getAsset(_input); Cache memory cache = _getCacheDetails(); // Transfer collateral to the platform integration address and call deposit uint256 quantityDeposited = Manager.depositTokens( personal, allBassets[bAssetIndex].ratio, _inputQuantity, cache.maxCache ); // Validation should be after token transfer, as bAssetQty is unknown before mAssetMinted = forgeValidator.computeMint( allBassets, bAssetIndex, quantityDeposited, _getConfig() ); require(mAssetMinted >= _minMassetQuantity, "Mint quantity < min qty"); // Log the Vault increase - can only be done when basket is healthy bAssetData[bAssetIndex].vaultBalance = allBassets[bAssetIndex].vaultBalance + SafeCast.toUint128(quantityDeposited); // Mint the Masset _mint(_recipient, mAssetMinted); emit Minted(msg.sender, _recipient, mAssetMinted, _input, quantityDeposited); } /** @dev Mint Multi */ function _mintMulti( address[] memory _inputs, uint256[] memory _inputQuantities, uint256 _minMassetQuantity, address _recipient ) internal returns (uint256 mAssetMinted) { require(_recipient != address(0), "Invalid recipient"); uint256 len = _inputQuantities.length; require(len > 0 && len == _inputs.length, "Input array mismatch"); // Load bAssets from storage into memory (uint8[] memory indexes, BassetPersonal[] memory personals) = _getBassets(_inputs); BassetData[] memory allBassets = bAssetData; Cache memory cache = _getCacheDetails(); uint256[] memory quantitiesDeposited = new uint256[](len); // Transfer the Bassets to the integrator, update storage and calc MassetQ for (uint256 i = 0; i < len; i++) { uint256 bAssetQuantity = _inputQuantities[i]; if (bAssetQuantity > 0) { uint8 idx = indexes[i]; BassetData memory data = allBassets[idx]; BassetPersonal memory personal = personals[i]; uint256 quantityDeposited = Manager.depositTokens(personal, data.ratio, bAssetQuantity, cache.maxCache); quantitiesDeposited[i] = quantityDeposited; bAssetData[idx].vaultBalance = data.vaultBalance + SafeCast.toUint128(quantityDeposited); } } // Validate the proposed mint, after token transfer mAssetMinted = forgeValidator.computeMintMulti( allBassets, indexes, quantitiesDeposited, _getConfig() ); require(mAssetMinted >= _minMassetQuantity, "Mint quantity < min qty"); require(mAssetMinted > 0, "Zero mAsset quantity"); // Mint the Masset _mint(_recipient, mAssetMinted); emit MintedMulti(msg.sender, _recipient, mAssetMinted, _inputs, _inputQuantities); } /*************************************** SWAP (PUBLIC) ****************************************/ /** * @dev Swaps one bAsset for another bAsset using the bAsset addresses. * bAsset <> bAsset swaps will incur a small fee (swapFee()). * @param _input Address of bAsset to deposit * @param _output Address of bAsset to receive * @param _inputQuantity Units of input bAsset to swap * @param _minOutputQuantity Minimum quantity of the swap output asset. This protects against slippage * @param _recipient Address to transfer output asset to * @return swapOutput Quantity of output asset returned from swap */ function swap( address _input, address _output, uint256 _inputQuantity, uint256 _minOutputQuantity, address _recipient ) external override nonReentrant whenHealthy returns (uint256 swapOutput) { swapOutput = _swap(_input, _output, _inputQuantity, _minOutputQuantity, _recipient); } /** * @dev Determines both if a trade is valid, and the expected fee or output. * Swap is valid if it does not result in the input asset exceeding its maximum weight. * @param _input Address of bAsset to deposit * @param _output Address of bAsset to receive * @param _inputQuantity Units of input bAsset to swap * @return swapOutput Quantity of output asset returned from swap */ function getSwapOutput( address _input, address _output, uint256 _inputQuantity ) external view override returns (uint256 swapOutput) { require(_input != _output, "Invalid pair"); require(_inputQuantity > 0, "Invalid swap quantity"); // 1. Load the bAssets from storage into memory BassetData[] memory allBassets = bAssetData; (uint8 inputIdx, ) = _getAsset(_input); (uint8 outputIdx, ) = _getAsset(_output); // 2. If a bAsset swap, calculate the validity, output and fee (swapOutput, ) = forgeValidator.computeSwap( allBassets, inputIdx, outputIdx, _inputQuantity, swapFee, _getConfig() ); } /*************************************** SWAP (INTERNAL) ****************************************/ /** @dev Swap single */ function _swap( address _input, address _output, uint256 _inputQuantity, uint256 _minOutputQuantity, address _recipient ) internal returns (uint256 swapOutput) { require(_recipient != address(0), "Invalid recipient"); require(_input != _output, "Invalid pair"); require(_inputQuantity > 0, "Invalid swap quantity"); // 1. Load the bAssets from storage into memory BassetData[] memory allBassets = bAssetData; (uint8 inputIdx, BassetPersonal memory inputPersonal) = _getAsset(_input); (uint8 outputIdx, BassetPersonal memory outputPersonal) = _getAsset(_output); // 2. Load cache Cache memory cache = _getCacheDetails(); // 3. Deposit the input tokens uint256 quantityDeposited = Manager.depositTokens( inputPersonal, allBassets[inputIdx].ratio, _inputQuantity, cache.maxCache ); // 3.1. Update the input balance bAssetData[inputIdx].vaultBalance = allBassets[inputIdx].vaultBalance + SafeCast.toUint128(quantityDeposited); // 3. Validate the swap uint256 scaledFee; (swapOutput, scaledFee) = forgeValidator.computeSwap( allBassets, inputIdx, outputIdx, quantityDeposited, swapFee, _getConfig() ); require(swapOutput >= _minOutputQuantity, "Output qty < minimum qty"); require(swapOutput > 0, "Zero output quantity"); //4. Settle the swap //4.1. Decrease output bal Manager.withdrawTokens( swapOutput, outputPersonal, allBassets[outputIdx], _recipient, cache.maxCache ); bAssetData[outputIdx].vaultBalance = allBassets[outputIdx].vaultBalance - SafeCast.toUint128(swapOutput); // Save new surplus to storage surplus = cache.surplus + scaledFee; emit Swapped( msg.sender, inputPersonal.addr, outputPersonal.addr, swapOutput, scaledFee, _recipient ); } /*************************************** REDEMPTION (PUBLIC) ****************************************/ /** * @notice Redeems a specified quantity of mAsset in return for a bAsset specified by bAsset address. * The bAsset is sent to the specified recipient. * The bAsset quantity is relative to current vault balance levels and desired mAsset quantity. * The quantity of mAsset is burnt as payment. * A minimum quantity of bAsset is specified to protect against price slippage between the mAsset and bAsset. * @param _output Address of the bAsset to receive * @param _mAssetQuantity Quantity of mAsset to redeem * @param _minOutputQuantity Minimum bAsset quantity to receive for the burnt mAssets. This protects against slippage. * @param _recipient Address to transfer the withdrawn bAssets to. * @return outputQuantity Quanity of bAsset units received for the burnt mAssets */ function redeem( address _output, uint256 _mAssetQuantity, uint256 _minOutputQuantity, address _recipient ) external override nonReentrant whenNoRecol returns (uint256 outputQuantity) { outputQuantity = _redeem(_output, _mAssetQuantity, _minOutputQuantity, _recipient); } /** * @dev Credits a recipient with a proportionate amount of bAssets, relative to current vault * balance levels and desired mAsset quantity. Burns the mAsset as payment. * @param _mAssetQuantity Quantity of mAsset to redeem * @param _minOutputQuantities Min units of output to receive * @param _recipient Address to credit the withdrawn bAssets */ function redeemMasset( uint256 _mAssetQuantity, uint256[] calldata _minOutputQuantities, address _recipient ) external override nonReentrant whenNoRecol returns (uint256[] memory outputQuantities) { outputQuantities = _redeemMasset(_mAssetQuantity, _minOutputQuantities, _recipient); } /** * @dev Credits a recipient with a certain quantity of selected bAssets, in exchange for burning the * relative Masset quantity from the sender. Sender also incurs a small fee on the outgoing asset. * @param _outputs Addresses of the bAssets to receive * @param _outputQuantities Units of the bAssets to redeem * @param _maxMassetQuantity Maximum mAsset quantity to burn for the received bAssets. This protects against slippage. * @param _recipient Address to receive the withdrawn bAssets * @return mAssetQuantity Quantity of mAsset units burned plus the swap fee to pay for the redeemed bAssets */ function redeemExactBassets( address[] calldata _outputs, uint256[] calldata _outputQuantities, uint256 _maxMassetQuantity, address _recipient ) external override nonReentrant whenNoRecol returns (uint256 mAssetQuantity) { mAssetQuantity = _redeemExactBassets( _outputs, _outputQuantities, _maxMassetQuantity, _recipient ); } /** * @notice Gets the estimated output from a given redeem * @param _output Address of the bAsset to receive * @param _mAssetQuantity Quantity of mAsset to redeem * @return bAssetOutput Estimated quantity of bAsset units received for the burnt mAssets */ function getRedeemOutput(address _output, uint256 _mAssetQuantity) external view override returns (uint256 bAssetOutput) { require(_mAssetQuantity > 0, "Qty==0"); (uint8 idx, ) = _getAsset(_output); uint256 scaledFee = _mAssetQuantity.mulTruncate(swapFee); bAssetOutput = forgeValidator.computeRedeem( bAssetData, idx, _mAssetQuantity - scaledFee, _getConfig() ); } /** * @notice Gets the estimated output from a given redeem * @param _outputs Addresses of the bAsset to receive * @param _outputQuantities Quantities of bAsset to redeem * @return mAssetQuantity Estimated quantity of mAsset units needed to burn to receive output */ function getRedeemExactBassetsOutput( address[] calldata _outputs, uint256[] calldata _outputQuantities ) external view override returns (uint256 mAssetQuantity) { uint256 len = _outputQuantities.length; require(len > 0 && len == _outputs.length, "Invalid array input"); (uint8[] memory indexes, ) = _getBassets(_outputs); // calculate the value of mAssets need to cover the value of bAssets being redeemed uint256 mAssetRedeemed = forgeValidator.computeRedeemExact(bAssetData, indexes, _outputQuantities, _getConfig()); mAssetQuantity = mAssetRedeemed.divPrecisely(1e18 - swapFee) + 1; } /*************************************** REDEMPTION (INTERNAL) ****************************************/ /** * @dev Redeem mAsset for a single bAsset */ function _redeem( address _output, uint256 _inputQuantity, uint256 _minOutputQuantity, address _recipient ) internal returns (uint256 bAssetQuantity) { require(_recipient != address(0), "Invalid recipient"); require(_inputQuantity > 0, "Qty==0"); // Load the bAsset data from storage into memory BassetData[] memory allBassets = bAssetData; (uint8 bAssetIndex, BassetPersonal memory personal) = _getAsset(_output); // Calculate redemption quantities uint256 scaledFee = _inputQuantity.mulTruncate(swapFee); bAssetQuantity = forgeValidator.computeRedeem( allBassets, bAssetIndex, _inputQuantity - scaledFee, _getConfig() ); require(bAssetQuantity >= _minOutputQuantity, "bAsset qty < min qty"); require(bAssetQuantity > 0, "Output == 0"); // Apply fees, burn mAsset and return bAsset to recipient // 1.0. Burn the full amount of Masset _burn(msg.sender, _inputQuantity); surplus += scaledFee; Cache memory cache = _getCacheDetails(); // 2.0. Transfer the Bassets to the recipient Manager.withdrawTokens( bAssetQuantity, personal, allBassets[bAssetIndex], _recipient, cache.maxCache ); // 3.0. Set vault balance bAssetData[bAssetIndex].vaultBalance = allBassets[bAssetIndex].vaultBalance - SafeCast.toUint128(bAssetQuantity); emit Redeemed( msg.sender, _recipient, _inputQuantity, personal.addr, bAssetQuantity, scaledFee ); } /** * @dev Redeem mAsset for proportional amount of bAssets */ function _redeemMasset( uint256 _inputQuantity, uint256[] calldata _minOutputQuantities, address _recipient ) internal returns (uint256[] memory outputQuantities) { require(_recipient != address(0), "Invalid recipient"); require(_inputQuantity > 0, "Qty==0"); // Calculate mAsset redemption quantities uint256 scaledFee = _inputQuantity.mulTruncate(redemptionFee); uint256 mAssetRedemptionAmount = _inputQuantity - scaledFee; // Burn mAsset quantity _burn(msg.sender, _inputQuantity); surplus += scaledFee; // Calc cache and total mAsset circulating Cache memory cache = _getCacheDetails(); // Total mAsset = (totalSupply + _inputQuantity - scaledFee) + surplus uint256 totalMasset = cache.vaultBalanceSum + mAssetRedemptionAmount; // Load the bAsset data from storage into memory BassetData[] memory allBassets = bAssetData; uint256 len = allBassets.length; address[] memory outputs = new address[](len); outputQuantities = new uint256[](len); for (uint256 i = 0; i < len; i++) { // Get amount out, proportionate to redemption quantity // Use `cache.sum` here as the total mAsset supply is actually totalSupply + surplus uint256 amountOut = (allBassets[i].vaultBalance * mAssetRedemptionAmount) / totalMasset; require(amountOut > 1, "Output == 0"); amountOut -= 1; require(amountOut >= _minOutputQuantities[i], "bAsset qty < min qty"); // Set output in array (outputQuantities[i], outputs[i]) = (amountOut, bAssetPersonal[i].addr); // Transfer the bAsset to the recipient Manager.withdrawTokens( amountOut, bAssetPersonal[i], allBassets[i], _recipient, cache.maxCache ); // reduce vaultBalance bAssetData[i].vaultBalance = allBassets[i].vaultBalance - SafeCast.toUint128(amountOut); } emit RedeemedMulti( msg.sender, _recipient, _inputQuantity, outputs, outputQuantities, scaledFee ); } /** @dev Redeem mAsset for one or more bAssets */ function _redeemExactBassets( address[] memory _outputs, uint256[] memory _outputQuantities, uint256 _maxMassetQuantity, address _recipient ) internal returns (uint256 mAssetQuantity) { require(_recipient != address(0), "Invalid recipient"); uint256 len = _outputQuantities.length; require(len > 0 && len == _outputs.length, "Invalid array input"); require(_maxMassetQuantity > 0, "Qty==0"); (uint8[] memory indexes, BassetPersonal[] memory personal) = _getBassets(_outputs); // Load bAsset data from storage to memory BassetData[] memory allBassets = bAssetData; // Validate redemption uint256 mAssetRequired = forgeValidator.computeRedeemExact(allBassets, indexes, _outputQuantities, _getConfig()); mAssetQuantity = mAssetRequired.divPrecisely(1e18 - swapFee); uint256 fee = mAssetQuantity - mAssetRequired; require(mAssetQuantity > 0, "Must redeem some mAssets"); mAssetQuantity += 1; require(mAssetQuantity <= _maxMassetQuantity, "Redeem mAsset qty > max quantity"); // Apply fees, burn mAsset and return bAsset to recipient // 1.0. Burn the full amount of Masset _burn(msg.sender, mAssetQuantity); surplus += fee; Cache memory cache = _getCacheDetails(); // 2.0. Transfer the Bassets to the recipient and count fees for (uint256 i = 0; i < len; i++) { uint8 idx = indexes[i]; Manager.withdrawTokens( _outputQuantities[i], personal[i], allBassets[idx], _recipient, cache.maxCache ); bAssetData[idx].vaultBalance = allBassets[idx].vaultBalance - SafeCast.toUint128(_outputQuantities[i]); } emit RedeemedMulti( msg.sender, _recipient, mAssetQuantity, _outputs, _outputQuantities, fee ); } /*************************************** GETTERS ****************************************/ /** * @dev Get basket details for `Masset_MassetStructs.Basket` * @return b Basket struct */ function getBasket() external view override returns (bool, bool) { return (basket.undergoingRecol, basket.failed); } /** * @dev Get data for a all bAssets in basket * @return personal Struct[] with full bAsset data * @return data Number of bAssets in the Basket */ function getBassets() external view override returns (BassetPersonal[] memory personal, BassetData[] memory data) { return (bAssetPersonal, bAssetData); } /** * @dev Get data for a specific bAsset, if it exists * @param _bAsset Address of bAsset * @return personal Struct with full bAsset data * @return data Struct with full bAsset data */ function getBasset(address _bAsset) external view override returns (BassetPersonal memory personal, BassetData memory data) { uint8 idx = bAssetIndexes[_bAsset]; personal = bAssetPersonal[idx]; require(personal.addr == _bAsset, "Invalid asset"); data = bAssetData[idx]; } /** * @dev Gets all config needed for general InvariantValidator calls */ function getConfig() external view returns (InvariantConfig memory config) { return _getConfig(); } /*************************************** GETTERS - INTERNAL ****************************************/ /** * vaultBalanceSum = totalSupply + 'surplus' * maxCache = vaultBalanceSum * (cacheSize / 1e18) * surplus is simply surplus, to reduce SLOADs */ struct Cache { uint256 vaultBalanceSum; uint256 maxCache; uint256 surplus; } /** * @dev Gets the supply and cache details for the mAsset, taking into account the surplus * @return Cache containing (tracked) sum of vault balances, ideal cache size and surplus */ function _getCacheDetails() internal view returns (Cache memory) { // read surplus from storage into memory uint256 _surplus = surplus; uint256 sum = totalSupply() + _surplus; return Cache(sum, sum.mulTruncate(cacheSize), _surplus); } /** * @dev Gets a bAsset from storage * @param _asset Address of the asset * @return idx Index of the asset * @return personal Personal details for the asset */ function _getAsset(address _asset) internal view returns (uint8 idx, BassetPersonal memory personal) { idx = bAssetIndexes[_asset]; personal = bAssetPersonal[idx]; require(personal.addr == _asset, "Invalid asset"); } /** * @dev Gets a an array of bAssets from storage and protects against duplicates * @param _bAssets Addresses of the assets * @return indexes Indexes of the assets * @return personal Personal details for the assets */ function _getBassets(address[] memory _bAssets) internal view returns (uint8[] memory indexes, BassetPersonal[] memory personal) { uint256 len = _bAssets.length; indexes = new uint8[](len); personal = new BassetPersonal[](len); for (uint256 i = 0; i < len; i++) { (indexes[i], personal[i]) = _getAsset(_bAssets[i]); for (uint256 j = i + 1; j < len; j++) { require(_bAssets[i] != _bAssets[j], "Duplicate asset"); } } } /** * @dev Gets all config needed for general InvariantValidator calls */ function _getConfig() internal view returns (InvariantConfig memory) { return InvariantConfig(_getA(), weightLimits); } /** * @dev Gets current amplification var A */ function _getA() internal view returns (uint256) { AmpData memory ampData_ = ampData; uint64 endA = ampData_.targetA; uint64 endTime = ampData_.rampEndTime; // If still changing, work out based on current timestmap if (block.timestamp < endTime) { uint64 startA = ampData_.initialA; uint64 startTime = ampData_.rampStartTime; (uint256 elapsed, uint256 total) = (block.timestamp - startTime, endTime - startTime); if (endA > startA) { return startA + (((endA - startA) * elapsed) / total); } else { return startA - (((startA - endA) * elapsed) / total); } } // Else return final value else { return endA; } } /*************************************** YIELD ****************************************/ /** * @dev Converts recently accrued swap and redeem fees into mAsset * @return mintAmount mAsset units generated from swap and redeem fees * @return newSupply mAsset total supply after mint */ function collectInterest() external override onlySavingsManager returns (uint256 mintAmount, uint256 newSupply) { // Set the surplus variable to 1 to optimise for SSTORE costs. // If setting to 0 here, it would save 5k per savings deposit, but cost 20k for the // first surplus call (a SWAP or REDEEM). uint256 surplusFees = surplus; if (surplusFees > 1) { mintAmount = surplusFees - 1; surplus = 1; // mint new mAsset to savings manager _mint(msg.sender, mintAmount); emit MintedMulti( address(this), msg.sender, mintAmount, new address[](0), new uint256[](0) ); } newSupply = totalSupply(); } /** * @dev Collects the interest generated from the Basket, minting a relative * amount of mAsset and sends it over to the SavingsManager. * @return mintAmount mAsset units generated from interest collected from lending markets * @return newSupply mAsset total supply after mint */ function collectPlatformInterest() external override onlySavingsManager whenHealthy nonReentrant returns (uint256 mintAmount, uint256 newSupply) { uint256[] memory gains; (mintAmount, gains) = Manager.collectPlatformInterest( bAssetPersonal, bAssetData, forgeValidator, _getConfig() ); require(mintAmount > 0, "Must collect something"); _mint(msg.sender, mintAmount); emit MintedMulti(address(this), msg.sender, mintAmount, new address[](0), gains); newSupply = totalSupply(); } /*************************************** STATE ****************************************/ /** * @dev Sets the MAX cache size for each bAsset. The cache will actually revolve around * _cacheSize * totalSupply / 2 under normal circumstances. * @param _cacheSize Maximum percent of total mAsset supply to hold for each bAsset */ function setCacheSize(uint256 _cacheSize) external override onlyGovernor { require(_cacheSize <= 2e17, "Must be <= 20%"); cacheSize = _cacheSize; emit CacheSizeChanged(_cacheSize); } /** * @dev Upgrades the version of ForgeValidator protocol. Governor can do this * only while ForgeValidator is unlocked. * @param _newForgeValidator Address of the new ForgeValidator */ function upgradeForgeValidator(address _newForgeValidator) external override onlyGovernor { require(!forgeValidatorLocked, "ForgeVal locked"); require(_newForgeValidator != address(0), "Null address"); forgeValidator = IInvariantValidator(_newForgeValidator); emit ForgeValidatorChanged(_newForgeValidator); } /** * @dev Set the ecosystem fee for sewapping bAssets or redeeming specific bAssets * @param _swapFee Fee calculated in (%/100 * 1e18) */ function setFees(uint256 _swapFee, uint256 _redemptionFee) external override onlyGovernor { require(_swapFee <= MAX_FEE, "Swap rate oob"); require(_redemptionFee <= MAX_FEE, "Redemption rate oob"); swapFee = _swapFee; redemptionFee = _redemptionFee; emit FeesChanged(_swapFee, _redemptionFee); } /** * @dev Set the maximum weight for a given bAsset * @param _min Weight where 100% = 1e18 * @param _max Weight where 100% = 1e18 */ function setWeightLimits(uint128 _min, uint128 _max) external onlyGovernor { require(_min <= 1e18 / (bAssetData.length * 2), "Min weight oob"); require(_max >= 1e18 / (bAssetData.length - 1), "Max weight oob"); weightLimits = WeightLimits(_min, _max); emit WeightLimitsChanged(_min, _max); } /** * @dev Update transfer fee flag for a given bAsset, should it change its fee practice * @param _bAsset bAsset address * @param _flag Charge transfer fee when its set to 'true', otherwise 'false' */ function setTransferFeesFlag(address _bAsset, bool _flag) external override onlyGovernor { Manager.setTransferFeesFlag(bAssetPersonal, bAssetIndexes, _bAsset, _flag); } /** * @dev Transfers all collateral from one lending market to another - used initially * to handle the migration between Aave V1 and Aave V2. Note - only supports non * tx fee enabled assets. Supports going from no integration to integration, but * not the other way around. * @param _bAssets Array of basket assets to migrate * @param _newIntegration Address of the new platform integration */ function migrateBassets(address[] calldata _bAssets, address _newIntegration) external override onlyGovernor { Manager.migrateBassets(bAssetPersonal, bAssetIndexes, _bAssets, _newIntegration); } /** * @dev Executes the Auto Redistribution event by isolating the bAsset from the Basket * @param _bAsset Address of the ERC20 token to isolate * @param _belowPeg Bool to describe whether the bAsset deviated below peg (t) * or above (f) */ function handlePegLoss(address _bAsset, bool _belowPeg) external onlyGovernor { Manager.handlePegLoss(basket, bAssetPersonal, bAssetIndexes, _bAsset, _belowPeg); } /** * @dev Negates the isolation of a given bAsset * @param _bAsset Address of the bAsset */ function negateIsolation(address _bAsset) external onlyGovernor { Manager.negateIsolation(basket, bAssetPersonal, bAssetIndexes, _bAsset); } /** * @dev Starts changing of the amplification var A * @param _targetA Target A value * @param _rampEndTime Time at which A will arrive at _targetA */ function startRampA(uint256 _targetA, uint256 _rampEndTime) external onlyGovernor { Manager.startRampA(ampData, _targetA, _rampEndTime, _getA(), A_PRECISION); } /** * @dev Stops the changing of the amplification var A, setting * it to whatever the current value is. */ function stopRampA() external onlyGovernor { Manager.stopRampA(ampData, _getA()); } }
2.2 - Else Deposit X if Cache > % This check is in place to ensure that any token with a txFee is rejected
require(quantityDeposited == _quantity, "Asset not fully transferred");
2,378,726
[ 1, 22, 18, 22, 300, 16289, 4019, 538, 305, 1139, 309, 4379, 405, 738, 1220, 866, 353, 316, 3166, 358, 3387, 716, 1281, 1147, 598, 279, 2229, 14667, 353, 11876, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2583, 12, 16172, 758, 1724, 329, 422, 389, 16172, 16, 315, 6672, 486, 7418, 906, 4193, 8863, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: GPL-3.0-only pragma solidity 0.7.6; pragma abicoder v2; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {IERC721} from "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import {IERC721Receiver} from "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; import {ERC721} from "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import {Initializable} from "@openzeppelin/contracts/proxy/Initializable.sol"; import {EnumerableSet} from "@openzeppelin/contracts/utils/EnumerableSet.sol"; import {Address} from "@openzeppelin/contracts/utils/Address.sol"; import {TransferHelper} from "@uniswap/lib/contracts/libraries/TransferHelper.sol"; import {EIP712} from "./EIP712.sol"; import {ERC1271} from "./ERC1271.sol"; import {OwnableByERC721} from "./OwnableByERC721.sol"; import {IRageQuit} from "../staking/UniStakerV2.sol"; interface IUniversalVaultV2 { /* user events */ event Locked(address delegate, address token, uint256 amount); event Unlocked(address delegate, address token, uint256 amount); event LockedERC721(address delegate, address token, uint256 tokenId); event UnlockedERC721(address delegate, address token, uint256 tokenId); event RageQuit(address delegate, address token, bool notified, string reason); event ERC721Received(address operator, address from, uint256 tokenId, bytes data); /* data types */ struct LockData { address delegate; address token; uint256 balance; } /* initialize function */ function initialize() external; /* user functions */ function lock( address token, uint256 amount, bytes calldata permission ) external; function unlock( address token, uint256 amount, bytes calldata permission ) external; function lockERC721( address token, uint256 tokenId, bytes calldata permission ) external; function unlockERC721( address token, uint256 tokenId, bytes calldata permission ) external; function rageQuit(address delegate, address token) external returns (bool notified, string memory error); function transferERC20( address token, address to, uint256 amount ) external; function transferERC721( address token, address to, uint256 tokenId ) external; function transferETH(address to, uint256 amount) external payable; /* pure functions */ function calculateLockID(address delegate, address token) external pure returns (bytes32 lockID); /* getter functions */ function getPermissionHash( bytes32 eip712TypeHash, address delegate, address token, uint256 amount, uint256 nonce ) external view returns (bytes32 permissionHash); function getPermissionHashERC721( bytes32 eip712TypeHash, address delegate, address token, uint256 tokenId, uint256 nonce ) external view returns (bytes32 permissionHash); function getNonce() external view returns (uint256 nonce); function owner() external view returns (address ownerAddress); function getLockSetCount() external view returns (uint256 count); function getLockAt(uint256 index) external view returns (LockData memory lockData); function getBalanceDelegated(address token, address delegate) external view returns (uint256 balance); function getBalanceLocked(address token) external view returns (uint256 balance); function getNumERC721TypesLocked() external view returns (uint256 count); function getERC721TypeLockedAt(uint index) external view returns (address token); function getERC721LockedBalance(address token) external view returns (uint256 balance); function getERC721LockedAt(address token, uint index) external view returns (uint256 tokenId); function getNumERC721TypesInVault() external view returns (uint256 count); function getERC721TypeInVaultAt(uint index) external view returns (address token); function getERC721VaultBalance(address token) external view returns (uint256 balance); function getERC721InVaultAt(address token, uint index) external view returns (uint256 tokenId); function checkERC20Balances() external view returns (bool validity); function checkERC721Balances() external view returns (bool validity); } /// @title MethodVault /// @notice Vault for isolated storage of staking tokens /// @dev Warning: not compatible with rebasing tokens contract MethodVaultV2 is IUniversalVaultV2, EIP712("UniversalVault", "1.0.0"), ERC1271, OwnableByERC721, Initializable, IERC721Receiver { using SafeMath for uint256; using Address for address; using Address for address payable; using EnumerableSet for EnumerableSet.Bytes32Set; using EnumerableSet for EnumerableSet.UintSet; using EnumerableSet for EnumerableSet.AddressSet; /* constant */ // Hardcoding a gas limit for rageQuit() is required to prevent gas DOS attacks // the gas requirement cannot be determined at runtime by querying the delegate // as it could potentially be manipulated by a malicious delegate who could force // the calls to revert. // The gas limit could alternatively be set upon vault initialization or creation // of a lock, but the gas consumption trade-offs are not favorable. // Ultimately, to avoid a need for fixed gas limits, the EVM would need to provide // an error code that allows for reliably catching out-of-gas errors on remote calls. uint256 public constant RAGEQUIT_GAS = 500000; bytes32 public constant LOCK_TYPEHASH = keccak256("Lock(address delegate,address token,uint256 amount,uint256 nonce)"); bytes32 public constant UNLOCK_TYPEHASH = keccak256("Unlock(address delegate,address token,uint256 amount,uint256 nonce)"); bytes32 public constant LOCK_ERC721_TYPEHASH = keccak256("LockERC721(address delegate,address token,uint256 tokenId,uint256 nonce)"); bytes32 public constant UNLOCK_ERC721_TYPEHASH = keccak256("UnlockERC721(address delegate,address token,uint256 tokenId,uint256 nonce)"); string public constant VERSION = "1.0.0"; /* storage */ uint256 private _nonce; EnumerableSet.AddressSet private _vaultERC721Types; // nft type to id mapping mapping(address => EnumerableSet.UintSet) private _vaultERC721s; EnumerableSet.AddressSet private _lockedERC721Types; // nft type to id mapping mapping(address => EnumerableSet.UintSet) private _lockedERC721s; mapping(bytes32 => LockData) private _locks; EnumerableSet.Bytes32Set private _lockSet; /* initialization function */ function initializeLock() external initializer {} function initialize() external override initializer { OwnableByERC721._setNFT(msg.sender); } /* ether receive */ receive() external payable {} /* internal overrides */ function _getOwner() internal view override(ERC1271) returns (address ownerAddress) { return OwnableByERC721.owner(); } /* overrides */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external override returns (bytes4) { emit ERC721Received(operator, from, tokenId, data); return IERC721Receiver(0).onERC721Received.selector; } /* pure functions */ function calculateLockID(address delegate, address token) public pure override returns (bytes32 lockID) { return keccak256(abi.encodePacked(delegate, token)); } /* getter functions */ function getPermissionHash( bytes32 eip712TypeHash, address delegate, address token, uint256 amount, uint256 nonce ) public view override returns (bytes32 permissionHash) { return EIP712._hashTypedDataV4( keccak256(abi.encode(eip712TypeHash, delegate, token, amount, nonce)) ); } function getPermissionHashERC721( bytes32 eip712TypeHash, address delegate, address token, uint256 tokenId, uint256 nonce ) public view override returns (bytes32 permissionHash) { return EIP712._hashTypedDataV4( keccak256(abi.encode(eip712TypeHash, delegate, token, tokenId, nonce)) ); } function getNonce() external view override returns (uint256 nonce) { return _nonce; } function owner() public view override(IUniversalVaultV2, OwnableByERC721) returns (address ownerAddress) { return OwnableByERC721.owner(); } function getLockSetCount() external view override returns (uint256 count) { return _lockSet.length(); } function getLockAt(uint256 index) external view override returns (LockData memory lockData) { return _locks[_lockSet.at(index)]; } function getBalanceDelegated(address token, address delegate) external view override returns (uint256 balance) { return _locks[calculateLockID(delegate, token)].balance; } function getBalanceLocked(address token) public view override returns (uint256 balance) { uint256 count = _lockSet.length(); for (uint256 index; index < count; index++) { LockData storage _lockData = _locks[_lockSet.at(index)]; if (_lockData.token == token && _lockData.balance > balance) balance = _lockData.balance; } return balance; } function getNumERC721TypesLocked() public view override returns (uint256 count) { return _lockedERC721Types.length(); } function getERC721TypeLockedAt(uint index) public view override returns (address token) { return _lockedERC721Types.at(index); } function getERC721LockedBalance(address token) public view override returns (uint256 balance) { return _lockedERC721s[token].length(); } function getERC721LockedAt(address token, uint index) public view override returns (uint256 tokenId) { return _lockedERC721s[token].at(index); } function getNumERC721TypesInVault() public view override returns (uint256 count) { return _vaultERC721Types.length(); } function getERC721TypeInVaultAt(uint index) public view override returns (address token) { return _vaultERC721Types.at(index); } function getERC721VaultBalance(address token) public view override returns (uint256 balance) { return _vaultERC721s[token].length(); } function getERC721InVaultAt(address token, uint index) public view override returns (uint256 tokenId) { return _vaultERC721s[token].at(index); } function checkERC20Balances() external view override returns (bool validity) { // iterate over all token locks and validate sufficient balance uint256 count = _lockSet.length(); for (uint256 index; index < count; index++) { // fetch storage lock reference LockData storage _lockData = _locks[_lockSet.at(index)]; // if insufficient balance return false if (IERC20(_lockData.token).balanceOf(address(this)) < _lockData.balance) return false; } // if sufficient balance return true return true; } function checkERC721Balances() external view override returns (bool validity) { // iterate over all token locks and validate sufficient balance uint256 count = _lockSet.length(); for (uint256 index; index < count; index++) { // fetch storage lock reference LockData storage _lockData = _locks[_lockSet.at(index)]; // if insufficient balance return false if (IERC721(_lockData.token).balanceOf(address(this)) < _lockData.balance) return false; } // if sufficient balance return true return true; } /* user functions */ /// @notice Lock ERC20 tokens in the vault /// access control: called by delegate with signed permission from owner /// state machine: anytime /// state scope: /// - insert or update _locks /// - increase _nonce /// token transfer: none /// @param token Address of token being locked /// @param amount Amount of tokens being locked /// @param permission Permission signature payload function lock( address token, uint256 amount, bytes calldata permission ) external override onlyValidSignature( getPermissionHash(LOCK_TYPEHASH, msg.sender, token, amount, _nonce), permission ) { // get lock id bytes32 lockID = calculateLockID(msg.sender, token); // add lock to storage if (_lockSet.contains(lockID)) { // if lock already exists, increase amount _locks[lockID].balance = _locks[lockID].balance.add(amount); } else { // if does not exist, create new lock // add lock to set assert(_lockSet.add(lockID)); // add lock data to storage _locks[lockID] = LockData(msg.sender, token, amount); } // validate sufficient balance require( IERC20(token).balanceOf(address(this)) >= _locks[lockID].balance, "UniversalVaultV2: insufficient balance" ); // increase nonce _nonce += 1; // emit event emit Locked(msg.sender, token, amount); } function lockERC721( address token, uint256 tokenId, bytes calldata permission ) external override onlyValidSignature( getPermissionHashERC721(LOCK_ERC721_TYPEHASH, msg.sender, token, tokenId, _nonce), permission ) { // sanity check, can't lock self require( address(tokenId) != address(this), "can't self lock" ); // validate ownership require( IERC721(token).ownerOf(tokenId) == address(this), "UniversalVaultV2: vault not owner of nft" ); require( !_lockedERC721s[token].contains(tokenId), "NFT already locked" ); _lockedERC721Types.add(token); _lockedERC721s[token].add(tokenId); // get lock id bytes32 lockID = calculateLockID(msg.sender, token); // add lock to storage if (_lockSet.contains(lockID)) { // if lock already exists, increase amount by 1 _locks[lockID].balance = _locks[lockID].balance.add(1); } else { // if does not exist, create new lock // add lock to set assert(_lockSet.add(lockID)); // add lock data to storage _locks[lockID] = LockData(msg.sender, token, 1); } // increase nonce _nonce += 1; // emit event emit LockedERC721(msg.sender, token, tokenId); } /// @notice Unlock ERC20 tokens in the vault /// access control: called by delegate with signed permission from owner /// state machine: after valid lock from delegate /// state scope: /// - remove or update _locks /// - increase _nonce /// token transfer: none /// @param token Address of token being unlocked /// @param amount Amount of tokens being unlocked /// @param permission Permission signature payload function unlock( address token, uint256 amount, bytes calldata permission ) external override onlyValidSignature( getPermissionHash(UNLOCK_TYPEHASH, msg.sender, token, amount, _nonce), permission ) { // get lock id bytes32 lockID = calculateLockID(msg.sender, token); // validate existing lock require(_lockSet.contains(lockID), "UniversalVaultV2: missing lock"); // update lock data if (_locks[lockID].balance > amount) { // subtract amount from lock balance _locks[lockID].balance = _locks[lockID].balance.sub(amount); } else { // delete lock data delete _locks[lockID]; assert(_lockSet.remove(lockID)); } // increase nonce _nonce += 1; // emit event emit Unlocked(msg.sender, token, amount); } function unlockERC721( address token, uint256 tokenId, bytes calldata permission ) external override onlyValidSignature( getPermissionHashERC721(UNLOCK_ERC721_TYPEHASH, msg.sender, token, tokenId, _nonce), permission ) { // validate ownership require( IERC721(token).ownerOf(tokenId) == address(this), "UniversalVaultV2: vault not owner of nft" ); require( _lockedERC721s[token].contains(tokenId), "NFT not locked" ); _lockedERC721s[token].remove(tokenId); if (_lockedERC721s[token].length() == 0) { _lockedERC721Types.remove(token); } _vaultERC721Types.add(token); _vaultERC721s[token].add(tokenId); // get lock id bytes32 lockID = calculateLockID(msg.sender, token); // validate existing lock require(_lockSet.contains(lockID), "UniversalVaultV2: missing lock"); // update lock data if (_locks[lockID].balance > 1) { // subtract 1 from lock balance _locks[lockID].balance = _locks[lockID].balance.sub(1); } else { // delete lock data delete _locks[lockID]; assert(_lockSet.remove(lockID)); } // increase nonce _nonce += 1; // emit event emit UnlockedERC721(msg.sender, token, tokenId); } /// @notice Forcibly cancel delegate lock /// @dev This function will attempt to notify the delegate of the rage quit using a fixed amount of gas. /// access control: only owner /// state machine: after valid lock from delegate /// state scope: /// - remove item from _locks /// token transfer: none /// @param delegate Address of delegate /// @param token Address of token being unlocked function rageQuit(address delegate, address token) external override onlyOwner returns (bool notified, string memory error) { // get lock id bytes32 lockID = calculateLockID(delegate, token); // validate existing lock require(_lockSet.contains(lockID), "UniversalVaultV2: missing lock"); // attempt to notify delegate if (delegate.isContract()) { // check for sufficient gas require(gasleft() >= RAGEQUIT_GAS, "UniversalVaultV2: insufficient gas"); // attempt rageQuit notification try IRageQuit(delegate).rageQuit{gas: RAGEQUIT_GAS}() { notified = true; } catch Error(string memory res) { notified = false; error = res; } catch (bytes memory) { notified = false; } } // update lock storage assert(_lockSet.remove(lockID)); delete _locks[lockID]; // emit event emit RageQuit(delegate, token, notified, error); } /// @notice Transfer ERC20 tokens out of vault /// access control: only owner /// state machine: when balance >= max(lock) + amount /// state scope: none /// token transfer: transfer any token /// @param token Address of token being transferred /// @param to Address of the recipient /// @param amount Amount of tokens to transfer function transferERC20( address token, address to, uint256 amount ) external override onlyOwner { // check for sufficient balance require( IERC20(token).balanceOf(address(this)) >= getBalanceLocked(token).add(amount), "UniversalVaultV2: insufficient balance" ); // perform transfer TransferHelper.safeTransfer(token, to, amount); } function transferERC721( address token, address to, uint256 tokenId ) external override onlyOwner { // validate ownership require( IERC721(token).ownerOf(tokenId) == address(this), "UniversalVaultV2: vault not owner of nft" ); require( !_lockedERC721s[token].contains(tokenId), "NFT is locked. Unlock first." ); _vaultERC721s[token].remove(tokenId); if (_vaultERC721s[token].length() == 0) { _vaultERC721Types.remove(token); } // perform transfer IERC721(token).safeTransferFrom(address(this), to, tokenId); } /// @notice Transfer ERC20 tokens out of vault /// access control: only owner /// state machine: when balance >= amount /// state scope: none /// token transfer: transfer any token /// @param to Address of the recipient /// @param amount Amount of ETH to transfer function transferETH(address to, uint256 amount) external payable override onlyOwner { // perform transfer TransferHelper.safeTransferETH(to, amount); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "../../introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./IERC721.sol"; import "./IERC721Metadata.sol"; import "./IERC721Enumerable.sol"; import "./IERC721Receiver.sol"; import "../../introspection/ERC165.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; import "../../utils/EnumerableSet.sol"; import "../../utils/EnumerableMap.sol"; import "../../utils/Strings.sol"; /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using SafeMath for uint256; using Address for address; using EnumerableSet for EnumerableSet.UintSet; using EnumerableMap for EnumerableMap.UintToAddressMap; using Strings for uint256; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from holder address to their (enumerable) set of owned tokens mapping (address => EnumerableSet.UintSet) private _holderTokens; // Enumerable mapping from token ids to their owners EnumerableMap.UintToAddressMap private _tokenOwners; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping (uint256 => string) private _tokenURIs; // Base URI string private _baseURI; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /* * bytes4(keccak256('totalSupply()')) == 0x18160ddd * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59 * bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7 * * => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63 */ bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); _registerInterface(_INTERFACE_ID_ERC721_METADATA); _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _holderTokens[owner].length(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token"); } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = baseURI(); // If there is no base URI, return the token URI. if (bytes(base).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } // If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI. return string(abi.encodePacked(base, tokenId.toString())); } /** * @dev Returns the base URI set via {_setBaseURI}. This will be * automatically added as a prefix in {tokenURI} to each token's URI, or * to the token ID if no specific URI is set for that token ID. */ function baseURI() public view virtual returns (string memory) { return _baseURI; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { return _holderTokens[owner].at(index); } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { // _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds return _tokenOwners.length(); } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { (uint256 tokenId, ) = _tokenOwners.at(index); return tokenId; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || ERC721.isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom(address from, address to, uint256 tokenId) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _tokenOwners.contains(tokenId); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || ERC721.isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: d* * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); // internal owner _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } _holderTokens[owner].remove(tokenId); _tokenOwners.remove(tokenId); emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer(address from, address to, uint256 tokenId) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); // internal owner require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _holderTokens[from].remove(tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(from, to, tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Internal function to set the base URI for all token IDs. It is * automatically added as a prefix to the value returned in {tokenURI}, * or to the token ID if {tokenURI} is empty. */ function _setBaseURI(string memory baseURI_) internal virtual { _baseURI = baseURI_; } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (!to.isContract()) { return true; } bytes memory returndata = to.functionCall(abi.encodeWithSelector( IERC721Receiver(to).onERC721Received.selector, _msgSender(), from, tokenId, _data ), "ERC721: transfer to non ERC721Receiver implementer"); bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _ERC721_RECEIVED); } /** * @dev Approve `to` to operate on `tokenId` * * Emits an {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); // internal owner } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { } } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity >=0.4.24 <0.8.0; import "../utils/Address.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { return !Address.isContract(address(this)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity >=0.6.0; // helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false library TransferHelper { function safeApprove( address token, address to, uint256 value ) internal { // bytes4(keccak256(bytes('approve(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require( success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper::safeApprove: approve failed' ); } function safeTransfer( address token, address to, uint256 value ) internal { // bytes4(keccak256(bytes('transfer(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require( success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper::safeTransfer: transfer failed' ); } function safeTransferFrom( address token, address from, address to, uint256 value ) internal { // bytes4(keccak256(bytes('transferFrom(address,address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require( success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper::transferFrom: transferFrom failed' ); } function safeTransferETH(address to, uint256 value) internal { (bool success, ) = to.call{value: value}(new bytes(0)); require(success, 'TransferHelper::safeTransferETH: ETH transfer failed'); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* solhint-disable max-line-length */ /** * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data. * * The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible, * thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding * they need in their contracts using a combination of `abi.encode` and `keccak256`. * * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA * ({_hashTypedDataV4}). * * The implementation of the domain separator was designed to be as efficient as possible while still properly updating * the chain id to protect against replay attacks on an eventual fork of the chain. * * NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask]. * * _Available since v3.4._ */ abstract contract EIP712 { /* solhint-disable var-name-mixedcase */ bytes32 private immutable _HASHED_NAME; bytes32 private immutable _HASHED_VERSION; bytes32 private constant _TYPE_HASH = keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" ); /* solhint-enable var-name-mixedcase */ /** * @dev Initializes the domain separator and parameter caches. * * The meaning of `name` and `version` is specified in * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]: * * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol. * - `version`: the current major version of the signing domain. * * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart * contract upgrade]. */ constructor(string memory name, string memory version) { _HASHED_NAME = keccak256(bytes(name)); _HASHED_VERSION = keccak256(bytes(version)); } /** * @dev Returns the domain separator for the current chain. */ function _domainSeparatorV4() internal view returns (bytes32) { return _buildDomainSeparator(_TYPE_HASH, _EIP712NameHash(), _EIP712VersionHash()); } function _buildDomainSeparator( bytes32 typeHash, bytes32 name, bytes32 version ) private view returns (bytes32) { return keccak256(abi.encode(typeHash, name, version, _getChainId(), address(this))); } /** * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this * function returns the hash of the fully encoded EIP712 message for this domain. * * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example: * * ```solidity * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode( * keccak256("Mail(address to,string contents)"), * mailTo, * keccak256(bytes(mailContents)) * ))); * address signer = ECDSA.recover(digest, signature); * ``` */ function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", _domainSeparatorV4(), structHash)); } function _getChainId() private view returns (uint256 chainId) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 // solhint-disable-next-line no-inline-assembly assembly { chainId := chainid() } } /** * @dev The hash of the name parameter for the EIP712 domain. * * NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs * are a concern. */ function _EIP712NameHash() internal view virtual returns (bytes32) { return _HASHED_NAME; } /** * @dev The hash of the version parameter for the EIP712 domain. * * NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs * are a concern. */ function _EIP712VersionHash() internal view virtual returns (bytes32) { return _HASHED_VERSION; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity 0.7.6; import {ECDSA} from "@openzeppelin/contracts/cryptography/ECDSA.sol"; import {Address} from "@openzeppelin/contracts/utils/Address.sol"; interface IERC1271 { function isValidSignature(bytes32 _messageHash, bytes memory _signature) external view returns (bytes4 magicValue); } library SignatureChecker { function isValidSignature( address signer, bytes32 hash, bytes memory signature ) internal view returns (bool) { if (Address.isContract(signer)) { bytes4 selector = IERC1271.isValidSignature.selector; (bool success, bytes memory returndata) = signer.staticcall(abi.encodeWithSelector(selector, hash, signature)); return success && abi.decode(returndata, (bytes4)) == selector; } else { return ECDSA.recover(hash, signature) == signer; } } } /// @title ERC1271 /// @notice Module for ERC1271 compatibility abstract contract ERC1271 is IERC1271 { // Valid magic value bytes4(keccak256("isValidSignature(bytes32,bytes)") bytes4 internal constant VALID_SIG = IERC1271.isValidSignature.selector; // Invalid magic value bytes4 internal constant INVALID_SIG = bytes4(0); modifier onlyValidSignature(bytes32 permissionHash, bytes memory signature) { require( isValidSignature(permissionHash, signature) == VALID_SIG, "ERC1271: Invalid signature" ); _; } function _getOwner() internal view virtual returns (address owner); function isValidSignature(bytes32 permissionHash, bytes memory signature) public view override returns (bytes4) { return SignatureChecker.isValidSignature(_getOwner(), permissionHash, signature) ? VALID_SIG : INVALID_SIG; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity 0.7.6; import {IERC721} from "@openzeppelin/contracts/token/ERC721/IERC721.sol"; /// @title OwnableByERC721 /// @notice Use ERC721 ownership for access control contract OwnableByERC721 { address private _nftAddress; modifier onlyOwner() { require(owner() == msg.sender, "OwnableByERC721: caller is not the owner"); _; } function _setNFT(address nftAddress) internal { _nftAddress = nftAddress; } function nft() public view virtual returns (address nftAddress) { return _nftAddress; } function owner() public view virtual returns (address ownerAddress) { return IERC721(_nftAddress).ownerOf(uint256(address(this))); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity 0.7.6; pragma abicoder v2; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {EnumerableSet} from "@openzeppelin/contracts/utils/EnumerableSet.sol"; import {IERC721} from "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import {TransferHelper} from "@uniswap/lib/contracts/libraries/TransferHelper.sol"; import {IFactory} from "../factory/IFactory.sol"; import {IInstanceRegistry} from "../factory/InstanceRegistry.sol"; import {IUniversalVaultV2} from "../methodNFT/MethodVaultV2.sol"; import {MethodNFTFactory} from "../methodNFT/MethodNFTFactory.sol"; import {IRewardPool} from "./RewardPool.sol"; import {Powered} from "./Powered.sol"; import {IERC2917} from "./IERC2917.sol"; import {ProxyFactory} from "../factory/ProxyFactory.sol"; interface IRageQuit { function rageQuit() external; } interface IUniStakerV2 is IRageQuit { /* admin events */ event UniStakerV2Created(address rewardPool, address powerSwitch); event UniStakerV2Funded(address token, uint256 amount); event BonusTokenRegistered(address token); event BonusTokenRemoved(address token); event VaultFactoryRegistered(address factory); event VaultFactoryRemoved(address factory); event AdminshipTransferred(address indexed previousAdmin, address indexed newAdmin); /* user events */ event Staked(address vault, address token, uint256 tokenId); event Unstaked(address vault, address token, uint256 tokenId); event RageQuit(address vault); event RewardClaimed(address vaultFactory, address recipient, address token, uint256 amount); event VestedRewardClaimed(address recipient, address token, uint amount); /* data types */ struct VaultData { // token address to total token stake mapping mapping(address => uint) tokenStake; EnumerableSet.AddressSet tokens; } struct LMRewardData { uint256 amount; uint256 duration; uint256 startedAt; address rewardCalcInstance; EnumerableSet.AddressSet bonusTokens; mapping(address => uint) bonusTokenAmounts; } struct LMRewardVestingData { uint amount; uint startedAt; } /* getter functions */ function getBonusTokenSetLength() external view returns (uint256 length); function getBonusTokenAtIndex(uint256 index) external view returns (address bonusToken); function getVaultFactorySetLength() external view returns (uint256 length); function getVaultFactoryAtIndex(uint256 index) external view returns (address factory); function getNumVaults() external view returns (uint256 num); function getVaultAt(uint256 index) external view returns (address vault); function getNumTokensStaked() external view returns (uint256 num); function getTokenStakedAt(uint256 index) external view returns (address token); function getNumTokensStakedInVault(address vault) external view returns (uint256 num); function getVaultTokenAtIndex(address vault, uint256 index) external view returns (address vaultToken); function getVaultTokenStake(address vault, address token) external view returns (uint256 tokenStake); function getLMRewardData(address token) external view returns (uint amount, uint duration, uint startedAt, address rewardCalcInstance); function getLMRewardBonusTokensLength(address token) external view returns (uint length); function getLMRewardBonusTokenAt(address token, uint index) external view returns (address bonusToken, uint bonusTokenAmount); function getNumVestingLMTokenRewards(address user) external view returns (uint num); function getVestingLMTokenAt(address user, uint index) external view returns (address token); function getNumVests(address user, address token) external view returns (uint num); function getNumRewardCalcTemplates() external view returns (uint num); function getLMRewardVestingData(address user, address token, uint index) external view returns (uint amount, uint startedAt); function isValidAddress(address target) external view returns (bool validity); function isValidVault(address vault, address factory) external view returns (bool validity); /* user functions */ function stakeERC721( address vault, address vaultFactory, address token, uint256 tokenId, bytes calldata permission ) external; function unstakeERC721AndClaimReward( address vault, address vaultFactory, address recipient, address token, uint256 tokenId, bool claimBonusReward, bytes calldata permission ) external; function claimVestedReward() external; function claimVestedReward(address token) external; } /// @title UniStakerV2 /// @notice Reward distribution contract /// Access Control /// - Power controller: /// Can power off / shutdown the UniStakerV2 /// Can withdraw rewards from reward pool once shutdown /// - Owner: /// Is unable to operate on user funds due to UniversalVault /// Is unable to operate on reward pool funds when reward pool is offline / shutdown /// - UniStakerV2 admin: /// Can add funds to the UniStakerV2, register bonus tokens, and whitelist new vault factories /// Is a subset of owner permissions /// - User: /// Can stake / unstake / ragequit / claim airdrop / claim vested rewards /// UniStakerV2 State Machine /// - Online: /// UniStakerV2 is operating normally, all functions are enabled /// - Offline: /// UniStakerV2 is temporarely disabled for maintenance /// User staking and unstaking is disabled, ragequit remains enabled /// Users can delete their stake through rageQuit() but forego their pending reward /// Should only be used when downtime required for an upgrade /// - Shutdown: /// UniStakerV2 is permanently disabled /// All functions are disabled with the exception of ragequit /// Users can delete their stake through rageQuit() /// Power controller can withdraw from the reward pool /// Should only be used if Owner role is compromised contract UniStakerV2 is IUniStakerV2, Powered { using SafeMath for uint256; using EnumerableSet for EnumerableSet.AddressSet; /* constants */ string public constant PLATINUM = "PLATINUM"; string public constant GOLD = "GOLD"; string public constant MINT = "MINT"; string public constant BLACK = "BLACK"; uint public PLATINUM_LM_REWARD_MULTIPLIER_NUM = 5; uint public PLATINUM_LM_REWARD_MULTIPLIER_DENOM = 2; uint public GOLD_LM_REWARD_MULTIPLIER_NUM = 2; uint public GOLD_LM_REWARD_MULTIPLIER_DENOM = 1; uint public MINT_LM_REWARD_MULTIPLIER_NUM = 3; uint public MINT_LM_REWARD_MULTIPLIER_DENOM = 2; uint public BLACK_LM_REWARD_MULTIPLIER_NUM = 1; uint public BLACK_LM_REWARD_MULTIPLIER_DENOM = 1; uint public LM_REWARD_VESTING_PERIOD = 7776000; // 3 months uint public LM_REWARD_VESTING_PORTION_NUM = 1; uint public LM_REWARD_VESTING_PORTION_DENOM = 2; // An upper bound on the number of active tokens staked per vault is required to prevent // calls to rageQuit() from reverting. // With 30 tokens staked in a vault, ragequit costs 432811 gas which is conservatively lower // than the hardcoded limit of 500k gas on the vault. // This limit is configurable and could be increased in a future deployment. // Ultimately, to avoid a need for fixed upper bounds, the EVM would need to provide // an error code that allows for reliably catching out-of-gas errors on remote calls. uint256 public MAX_TOKENS_STAKED_PER_VAULT = 30; uint256 public MAX_BONUS_TOKENS = 50; /* storage */ address public admin; address public rewardToken; address public rewardPool; EnumerableSet.AddressSet private _vaultSet; mapping(address => VaultData) private _vaults; EnumerableSet.AddressSet private _bonusTokenSet; EnumerableSet.AddressSet private _vaultFactorySet; EnumerableSet.AddressSet private _allStakedTokens; mapping(address => uint256) public stakedTokenTotal; mapping(address => LMRewardData) private lmRewards; // user to token to earned reward mapping mapping(address => mapping(address => uint)) public earnedLMRewards; // user to token to vesting data mapping mapping(address => mapping(address => LMRewardVestingData[])) public vestingLMRewards; // user to vesting lm token rewards set mapping(address => EnumerableSet.AddressSet) private vestingLMTokenRewards; // erc2917 template names string[] public rewardCalcTemplateNames; // erc2917 template names to erc 2917 templates mapping(string => address) public rewardCalcTemplates; string public activeRewardCalcTemplate; event RewardCalcTemplateAdded(string indexed name, address indexed template); event RewardCalcTemplateActive(string indexed name, address indexed template); /* initializer */ /// @notice Initizalize UniStakerV2 /// access control: only proxy constructor /// state machine: can only be called once /// state scope: set initialization variables /// token transfer: none /// @param adminAddress address The admin address /// @param rewardPoolFactory address The factory to use for deploying the RewardPool /// @param powerSwitchFactory address The factory to use for deploying the PowerSwitch /// @param rewardTokenAddress address The address of the reward token for this UniStakerV2 constructor( address adminAddress, address rewardPoolFactory, address powerSwitchFactory, address rewardTokenAddress ) { // deploy power switch address powerSwitch = IFactory(powerSwitchFactory).create(abi.encode(adminAddress)); // deploy reward pool rewardPool = IFactory(rewardPoolFactory).create(abi.encode(powerSwitch)); // set internal config admin = adminAddress; rewardToken = rewardTokenAddress; Powered._setPowerSwitch(powerSwitch); // emit event emit UniStakerV2Created(rewardPool, powerSwitch); } /* admin functions */ function _admin() private view { require(msg.sender == admin, "not allowed"); } /** * @dev Leaves the contract without admin. It will not be possible to call * `admin` functions anymore. Can only be called by the current admin. * * NOTE: Renouncing adminship will leave the contract without an admin, * thereby removing any functionality that is only available to the admin. */ function renounceAdminship() public { _admin(); emit AdminshipTransferred(admin, address(0)); admin = address(0); } /** * @dev Transfers adminship of the contract to a new account (`newAdmin`). * Can only be called by the current admin. */ function transferAdminship(address newAdmin) public { _admin(); require(newAdmin != address(0), "new admin can't the zero address"); emit AdminshipTransferred(admin, newAdmin); admin = newAdmin; } /// @notice Add funds to UniStakerV2 /// access control: only admin /// state machine: /// - can be called multiple times /// - only online /// state scope: /// - none /// token transfer: transfer staking tokens from msg.sender to reward pool /// @param amount uint256 Amount of reward tokens to deposit function fund(address token, uint256 amount) external { _admin(); require(_bonusTokenSet.contains(token) || token == rewardToken, "cannot fund with unrecognized token"); // transfer reward tokens to reward pool TransferHelper.safeTransferFrom( token, msg.sender, rewardPool, amount ); // emit event emit UniStakerV2Funded(token, amount); } /// @notice Rescue tokens from RewardPool /// @dev use this function to rescue tokens from RewardPool contract without distributing to stakers or triggering emergency shutdown /// access control: only admin /// state machine: /// - can be called multiple times /// - not shutdown /// state scope: none /// token transfer: transfer requested token from RewardPool to recipient /// @param token address The address of the token to rescue /// @param recipient address The address of the recipient /// @param amount uint256 The amount of tokens to rescue function rescueTokensFromRewardPool( address token, address recipient, uint256 amount ) external { _admin(); // verify recipient require(isValidAddress(recipient), "invalid recipient"); // transfer tokens to recipient IRewardPool(rewardPool).sendERC20(token, recipient, amount); } /// @notice Add vault factory to whitelist /// @dev use this function to enable stakes to vaults coming from the specified factory contract /// access control: only admin /// state machine: /// - can be called multiple times /// - not shutdown /// state scope: /// - append to _vaultFactorySet /// token transfer: none /// @param factory address The address of the vault factory function registerVaultFactory(address factory) external { _admin(); // add factory to set require(_vaultFactorySet.add(factory), "UniStakerV2: vault factory already registered"); // emit event emit VaultFactoryRegistered(factory); } /// @notice Remove vault factory from whitelist /// @dev use this function to disable new stakes to vaults coming from the specified factory contract. /// note: vaults with existing stakes from this factory are sill able to unstake /// access control: only admin /// state machine: /// - can be called multiple times /// - not shutdown /// state scope: /// - remove from _vaultFactorySet /// token transfer: none /// @param factory address The address of the vault factory function removeVaultFactory(address factory) external { _admin(); // remove factory from set require(_vaultFactorySet.remove(factory), "UniStakerV2: vault factory not registered"); // emit event emit VaultFactoryRemoved(factory); } /// @notice Register bonus token for distribution /// @dev use this function to enable distribution of any ERC20 held by the RewardPool contract /// access control: only admin /// state machine: /// - can be called multiple times /// - only online /// state scope: /// - append to _bonusTokenSet /// token transfer: none /// @param bonusToken address The address of the bonus token function registerBonusToken(address bonusToken) external { _admin(); // verify valid bonus token require(isValidAddress(bonusToken), "invalid bonus token address or is already present"); // verify bonus token count require(_bonusTokenSet.length() < MAX_BONUS_TOKENS, "UniStakerV2: max bonus tokens reached "); // add token to set _bonusTokenSet.add(bonusToken); // emit event emit BonusTokenRegistered(bonusToken); } /// @notice Remove bonus token /// @dev use this function to disable distribution of a token held by the RewardPool contract /// access control: only admin /// state machine: /// - can be called multiple times /// - not shutdown /// state scope: /// - remove from _bonusTokenSet /// token transfer: none /// @param bonusToken address The address of the bonus token function removeBonusToken(address bonusToken) external { _admin(); require(_bonusTokenSet.remove(bonusToken), "UniStakerV2: bonus token not present "); // emit event emit BonusTokenRemoved(bonusToken); } function addRewardCalcTemplate(string calldata name, address template) external { _admin(); require(rewardCalcTemplates[name] == address(0), "Template already exists"); rewardCalcTemplates[name] = template; if(rewardCalcTemplateNames.length == 0) { activeRewardCalcTemplate = name; emit RewardCalcTemplateActive(name, template); } rewardCalcTemplateNames.push(name); emit RewardCalcTemplateAdded(name, template); } function setRewardCalcActiveTemplate(string calldata name) external { _admin(); require(rewardCalcTemplates[name] != address(0), "Template does not exist"); activeRewardCalcTemplate = name; emit RewardCalcTemplateActive(name, rewardCalcTemplates[name]); } function startLMRewards(address token, uint256 amount, uint256 duration) external { startLMRewards(token, amount, duration, activeRewardCalcTemplate); } function startLMRewards(address token, uint256 amount, uint256 duration, string memory rewardCalcTemplateName) public { _admin(); require(lmRewards[token].startedAt == 0, "A reward program already live for this token"); require(rewardCalcTemplates[rewardCalcTemplateName] != address(0), "Reward Calculator Template does not exist"); // create reward calc clone from template address rewardCalcInstance = ProxyFactory._create(rewardCalcTemplates[rewardCalcTemplateName], abi.encodeWithSelector(IERC2917.initialize.selector)); LMRewardData storage lmrd = lmRewards[token]; lmrd.amount = amount; lmrd.duration = duration; lmrd.startedAt = block.timestamp; lmrd.rewardCalcInstance = rewardCalcInstance; } function setImplementorForRewardsCalculator(address token, address newImplementor) public { _admin(); require(lmRewards[token].startedAt != 0, "No reward program currently live for this token"); address rewardCalcInstance = lmRewards[token].rewardCalcInstance; IERC2917(rewardCalcInstance).setImplementor(newImplementor); } function setLMRewardsPerBlock(address token, uint value) public onlyOnline { _admin(); require(lmRewards[token].startedAt != 0, "No reward program currently live for this token"); address rewardCalcInstance = lmRewards[token].rewardCalcInstance; IERC2917(rewardCalcInstance).changeInterestRatePerBlock(value); } function addBonusTokenToLMRewards(address lmToken, address bonusToken, uint256 bonusTokenAmount) public { _admin(); require(lmRewards[lmToken].startedAt != 0, "No reward program currently live for this LM token"); require(_bonusTokenSet.contains(bonusToken), "Bonus token not registered"); lmRewards[lmToken].bonusTokens.add(bonusToken); lmRewards[lmToken].bonusTokenAmounts[bonusToken] = lmRewards[lmToken].bonusTokenAmounts[bonusToken].add(bonusTokenAmount); } function endLMRewards(address token, bool removeBonusTokenData) public { _admin(); lmRewards[token].amount = 0; lmRewards[token].duration = 0; lmRewards[token].startedAt = 0; lmRewards[token].rewardCalcInstance = address(0); if (removeBonusTokenData) { for (uint index = 0; index < lmRewards[token].bonusTokens.length(); index++) { address bonusToken = lmRewards[token].bonusTokens.at(index); lmRewards[token].bonusTokens.remove(bonusToken); delete lmRewards[token].bonusTokenAmounts[bonusToken]; } } } function setMaxStakesPerVault(uint256 amount) external { _admin(); MAX_TOKENS_STAKED_PER_VAULT = amount; } function setMaxBonusTokens(uint256 amount) external { _admin(); MAX_BONUS_TOKENS = amount; } function setPlatinumLMRewardMultiplier(uint256 numerator, uint256 denominator) external { _admin(); PLATINUM_LM_REWARD_MULTIPLIER_NUM = numerator; PLATINUM_LM_REWARD_MULTIPLIER_DENOM = denominator; } function setGoldLMRewardMultiplier(uint256 numerator, uint256 denominator) external { _admin(); GOLD_LM_REWARD_MULTIPLIER_NUM = numerator; GOLD_LM_REWARD_MULTIPLIER_DENOM = denominator; } function setMintLMRewardMultiplier(uint256 numerator, uint256 denominator) external { _admin(); MINT_LM_REWARD_MULTIPLIER_NUM = numerator; MINT_LM_REWARD_MULTIPLIER_DENOM = denominator; } function setBlackLMRewardMultiplier(uint256 numerator, uint256 denominator) external { _admin(); BLACK_LM_REWARD_MULTIPLIER_NUM = numerator; BLACK_LM_REWARD_MULTIPLIER_DENOM = denominator; } function setLMRewardVestingPeriod(uint256 amount) external { _admin(); LM_REWARD_VESTING_PERIOD = amount; } function setLMRewardVestingPortion(uint256 numerator, uint denominator) external { _admin(); LM_REWARD_VESTING_PORTION_NUM = numerator; LM_REWARD_VESTING_PORTION_DENOM = denominator; } /* getter functions */ function getBonusTokenSetLength() external view override returns (uint256 length) { return _bonusTokenSet.length(); } function getBonusTokenAtIndex(uint256 index) external view override returns (address bonusToken) { return _bonusTokenSet.at(index); } function getVaultFactorySetLength() external view override returns (uint256 length) { return _vaultFactorySet.length(); } function getVaultFactoryAtIndex(uint256 index) external view override returns (address factory) { return _vaultFactorySet.at(index); } function getNumVaults() external view override returns (uint256 num) { return _vaultSet.length(); } function getVaultAt(uint256 index) external view override returns (address vault) { return _vaultSet.at(index); } function getNumTokensStaked() external view override returns (uint256 num) { return _allStakedTokens.length(); } function getTokenStakedAt(uint256 index) external view override returns (address token) { return _allStakedTokens.at(index); } function getNumTokensStakedInVault(address vault) external view override returns (uint256 num) { return _vaults[vault].tokens.length(); } function getVaultTokenAtIndex(address vault, uint256 index) external view override returns (address vaultToken) { return _vaults[vault].tokens.at(index); } function getVaultTokenStake(address vault, address token) external view override returns (uint256 tokenStake) { return _vaults[vault].tokenStake[token]; } function getNftTier(uint256 nftId, address nftFactory) public view returns (string memory tier) { uint256 serialNumber = MethodNFTFactory(nftFactory).tokenIdToSerialNumber(nftId); if (serialNumber >= 1 && serialNumber <= 100) { tier = PLATINUM; } else if (serialNumber >= 101 && serialNumber <= 1000) { tier = GOLD; } else if (serialNumber >= 1001 && serialNumber <= 5000) { tier = MINT; } else if (serialNumber >= 5001) { tier = BLACK; } } function getLMRewardData(address token) external view override returns (uint amount, uint duration, uint startedAt, address rewardCalcInstance) { return (lmRewards[token].amount, lmRewards[token].duration, lmRewards[token].startedAt, lmRewards[token].rewardCalcInstance); } function getLMRewardBonusTokensLength(address token) external view override returns (uint length) { return lmRewards[token].bonusTokens.length(); } function getLMRewardBonusTokenAt(address token, uint index) external view override returns (address bonusToken, uint bonusTokenAmount) { return (lmRewards[token].bonusTokens.at(index), lmRewards[token].bonusTokenAmounts[lmRewards[token].bonusTokens.at(index)]); } function getNumVestingLMTokenRewards(address user) external view override returns (uint num) { return vestingLMTokenRewards[user].length(); } function getVestingLMTokenAt(address user, uint index) external view override returns (address token) { return vestingLMTokenRewards[user].at(index); } function getNumVests(address user, address token) external view override returns (uint num) { return vestingLMRewards[user][token].length; } function getLMRewardVestingData(address user, address token, uint index) external view override returns (uint amount, uint startedAt) { return (vestingLMRewards[user][token][index].amount, vestingLMRewards[user][token][index].startedAt); } function getNumRewardCalcTemplates() external view override returns (uint num) { return rewardCalcTemplateNames.length; } /* helper functions */ function isValidVault(address vault, address factory) public view override returns (bool validity) { // validate vault is created from whitelisted vault factory and is an instance of that factory return _vaultFactorySet.contains(factory) && IInstanceRegistry(factory).isInstance(vault); } function isValidAddress(address target) public view override returns (bool validity) { // sanity check target for potential input errors return target != address(this) && target != address(0) && target != rewardToken && target != rewardPool && !_bonusTokenSet.contains(target); } /* convenience functions */ function _tierMultipliedReward(uint nftId, address nftFactory, uint reward) private view returns (uint multipliedReward) { // get tier string memory tier = getNftTier(nftId, nftFactory); bytes32 tierHash = keccak256(abi.encodePacked(tier)); if (tierHash == keccak256(abi.encodePacked(PLATINUM))) { multipliedReward = reward.mul(PLATINUM_LM_REWARD_MULTIPLIER_NUM).div(PLATINUM_LM_REWARD_MULTIPLIER_DENOM); } else if (tierHash == keccak256(abi.encodePacked(GOLD))) { multipliedReward = reward.mul(GOLD_LM_REWARD_MULTIPLIER_NUM).div(GOLD_LM_REWARD_MULTIPLIER_DENOM); } else if (tierHash == keccak256(abi.encodePacked(MINT))) { multipliedReward = reward.mul(MINT_LM_REWARD_MULTIPLIER_NUM).div(MINT_LM_REWARD_MULTIPLIER_DENOM); } else if (tierHash == keccak256(abi.encodePacked(BLACK))) { multipliedReward = reward.mul(BLACK_LM_REWARD_MULTIPLIER_NUM).div(BLACK_LM_REWARD_MULTIPLIER_DENOM); } } /* user functions */ /// @notice Exit UniStakerV2 without claiming reward /// @dev This function should never revert when correctly called by the vault. /// A max number of tokens staked per vault is set with MAX_TOKENS_STAKED_PER_VAULT to /// place an upper bound on the for loop. /// access control: callable by anyone but fails if caller is not an approved vault /// state machine: /// - when vault exists on this UniStakerV2 /// - when active stake from this vault /// - any power state /// state scope: /// - decrease stakedTokenTotal[token], delete if 0 /// - delete _vaults[vault].tokenStake[token] /// - remove _vaults[vault].tokens.remove(token) /// - delete _vaults[vault] /// - remove vault from _vaultSet /// - remove token from _allStakedTokens if required /// token transfer: none function rageQuit() external override { require(_vaultSet.contains(msg.sender), "UniStakerV2: no vault"); //fetch vault storage reference VaultData storage vaultData = _vaults[msg.sender]; // revert if no active tokens staked EnumerableSet.AddressSet storage vaultTokens = vaultData.tokens; require(vaultTokens.length() > 0, "UniStakerV2: no stake"); // update totals for (uint256 index = 0; index < vaultTokens.length(); index++) { address token = vaultTokens.at(index); vaultTokens.remove(token); uint256 amount = vaultData.tokenStake[token]; uint256 newTotal = stakedTokenTotal[token].sub(amount); assert(newTotal >= 0); if (newTotal == 0) { _allStakedTokens.remove(token); delete stakedTokenTotal[token]; } else { stakedTokenTotal[token] = newTotal; } delete vaultData.tokenStake[token]; } // delete vault data _vaultSet.remove(msg.sender); delete _vaults[msg.sender]; // emit event emit RageQuit(msg.sender); } /// @notice Stake ERC721 tokens /// @dev anyone can stake to any vault if they have valid permission /// access control: anyone /// state machine: /// - can be called multiple times /// - only online /// - when vault exists on this UniStakerV2 /// state scope: /// - add token to _vaults[vault].tokens if not already exists /// - increase _vaults[vault].tokenStake[token] /// - add vault to _vaultSet if not already exists /// - add token to _allStakedTokens if not already exists /// - increase stakedTokenTotal[token] /// token transfer: transfer staking tokens from msg.sender to vault /// @param vault address The address of the vault to stake to /// @param vaultFactory address The address of the vault factory which created the vault /// @param token address The address of the token being staked /// @param tokenId uint256 The id of token to stake function stakeERC721( address vault, address vaultFactory, address token, uint256 tokenId, bytes calldata permission ) external override onlyOnline { // verify vault is valid require(isValidVault(vault, vaultFactory), "UniStakerV2: vault is not valid"); // add vault to set _vaultSet.add(vault); // fetch vault storage reference VaultData storage vaultData = _vaults[vault]; // verify stakes boundary not reached require(vaultData.tokens.length() < MAX_TOKENS_STAKED_PER_VAULT, "UniStakerV2: MAX_TOKENS_STAKED_PER_VAULT reached"); // add token to set and increase amount vaultData.tokens.add(token); vaultData.tokenStake[token] = vaultData.tokenStake[token].add(1); // update total token staked _allStakedTokens.add(token); stakedTokenTotal[token] = stakedTokenTotal[token].add(1); // perform transfer to vault IERC721(token).safeTransferFrom(msg.sender, vault, tokenId); // call lock on vault IUniversalVaultV2(vault).lockERC721(token, tokenId, permission); // check if there is a reward program currently running if (lmRewards[token].startedAt != 0) { address rewardCalcInstance = lmRewards[token].rewardCalcInstance; (,uint rewardEarned,) = IERC2917(rewardCalcInstance).increaseProductivity(msg.sender, 1); earnedLMRewards[msg.sender][token] = earnedLMRewards[msg.sender][token].add(rewardEarned); } // emit event emit Staked(vault, token, tokenId); } /// @notice Unstake ERC721 tokens and claim reward /// @dev LM rewards can only be claimed when unstaking /// access control: anyone with permission /// state machine: /// - when vault exists on this UniStakerV2 /// - after stake from vault /// - can be called multiple times while sufficient stake remains /// - only online /// state scope: /// - decrease _vaults[vault].tokenStake[token] /// - delete token from _vaults[vault].tokens if token stake is 0 /// - decrease stakedTokenTotal[token] /// - delete token from _allStakedTokens if total token stake is 0 /// token transfer: /// - transfer reward tokens from reward pool to recipient /// - transfer bonus tokens from reward pool to recipient /// @param vault address The vault to unstake from /// @param vaultFactory address The vault factory that created this vault /// @param recipient address The recipient to send reward to /// @param token address The staking token /// @param tokenId uint256 The id of the token to unstake /// @param claimBonusReward bool flag to claim bonus rewards function unstakeERC721AndClaimReward( address vault, address vaultFactory, address recipient, address token, uint256 tokenId, bool claimBonusReward, bytes calldata permission ) external override onlyOnline { require(_vaultSet.contains(vault), "UniStakerV2: no vault"); // fetch vault storage reference VaultData storage vaultData = _vaults[vault]; // validate recipient require(isValidAddress(recipient), "UniStakerV2: invalid recipient"); // check for sufficient vault stake amount require(vaultData.tokens.contains(token), "UniStakerV2: no token in vault"); // check for sufficient vault stake amount require(vaultData.tokenStake[token] >= 1, "UniStakerV2: insufficient vault token stake"); // check for sufficient total token stake amount // if the above check succeeds and this check fails, there is a bug in stake accounting require(stakedTokenTotal[token] >= 1, "stakedTokenTotal[token] is less than 1"); // check if there is a reward program currently running uint rewardEarned = earnedLMRewards[msg.sender][token]; if (lmRewards[token].startedAt != 0) { address rewardCalcInstance = lmRewards[token].rewardCalcInstance; (,uint newReward,) = IERC2917(rewardCalcInstance).decreaseProductivity(msg.sender, 1); rewardEarned = rewardEarned.add(newReward); } // decrease totalStake of token in this vault vaultData.tokenStake[token] = vaultData.tokenStake[token].sub(1); if (vaultData.tokenStake[token] == 0) { vaultData.tokens.remove(token); delete vaultData.tokenStake[token]; } // decrease stakedTokenTotal across all vaults stakedTokenTotal[token] = stakedTokenTotal[token].sub(1); if (stakedTokenTotal[token] == 0) { _allStakedTokens.remove(token); delete stakedTokenTotal[token]; } // unlock staking tokens from vault IUniversalVaultV2(vault).unlockERC721(token, tokenId, permission); // emit event emit Unstaked(vault, token, tokenId); // only perform on non-zero reward if (rewardEarned > 0) { // transfer bonus tokens from reward pool to recipient // bonus tokens can only be claimed during an active rewards program if (claimBonusReward && lmRewards[token].startedAt != 0) { for (uint256 index = 0; index < lmRewards[token].bonusTokens.length(); index++) { // fetch bonus token address reference address bonusToken = lmRewards[token].bonusTokens.at(index); // calculate bonus token amount // bonusAmount = rewardEarned * allocatedBonusReward / allocatedMainReward uint256 bonusAmount = rewardEarned.mul(lmRewards[token].bonusTokenAmounts[bonusToken]).div(lmRewards[token].amount); // transfer bonus token IRewardPool(rewardPool).sendERC20(bonusToken, recipient, bonusAmount); // emit event emit RewardClaimed(vault, recipient, bonusToken, bonusAmount); } } // take care of multiplier uint multipliedReward = _tierMultipliedReward(uint(vault), vaultFactory, rewardEarned); // take care of vesting uint vestingPortion = multipliedReward.mul(LM_REWARD_VESTING_PORTION_NUM).div(LM_REWARD_VESTING_PORTION_DENOM); vestingLMRewards[msg.sender][token].push(LMRewardVestingData(vestingPortion, block.timestamp)); vestingLMTokenRewards[msg.sender].add(token); // set earned reward to 0 earnedLMRewards[msg.sender][token] = 0; // transfer reward tokens from reward pool to recipient IRewardPool(rewardPool).sendERC20(rewardToken, recipient, multipliedReward.sub(vestingPortion)); // emit event emit RewardClaimed(vault, recipient, rewardToken, rewardEarned); } } function claimVestedReward() external override onlyOnline { uint numTokens = vestingLMTokenRewards[msg.sender].length(); for (uint index = 0; index < numTokens; index++) { address token = vestingLMTokenRewards[msg.sender].at(index); claimVestedReward(token, vestingLMRewards[msg.sender][token].length); } } function claimVestedReward(address token) external override onlyOnline { claimVestedReward(token, vestingLMRewards[msg.sender][token].length); } function claimVestedReward(address token, uint numVests) public onlyOnline { require(numVests <= vestingLMRewards[msg.sender][token].length, "num vests can't be greater than available vests"); LMRewardVestingData[] storage vests = vestingLMRewards[msg.sender][token]; uint vestedReward; for (uint index = 0; index < numVests; index++) { LMRewardVestingData storage vest = vests[index]; uint duration = block.timestamp.sub(vest.startedAt); uint vested = vest.amount.mul(duration).div(LM_REWARD_VESTING_PERIOD); if (vested >= vest.amount) { // completely vested vested = vest.amount; // copy last element into this slot and pop last vests[index] = vests[vests.length - 1]; vests.pop(); index--; numVests--; // if all vested remove from set if (vests.length == 0) { vestingLMTokenRewards[msg.sender].remove(token); break; } } else { vest.amount = vest.amount.sub(vested); } vestedReward = vestedReward.add(vested); } if (vestedReward > 0) { // transfer reward tokens from reward pool to recipient IRewardPool(rewardPool).sendERC20(rewardToken, msg.sender, vestedReward); // emit event emit VestedRewardClaimed(msg.sender, rewardToken, vestedReward); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "./IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "./IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () internal { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing an enumerable variant of Solidity's * https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`] * type. * * Maps have the following properties: * * - Entries are added, removed, and checked for existence in constant time * (O(1)). * - Entries are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableMap for EnumerableMap.UintToAddressMap; * * // Declare a set state variable * EnumerableMap.UintToAddressMap private myMap; * } * ``` * * As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are * supported. */ library EnumerableMap { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Map type with // bytes32 keys and values. // The Map implementation uses private functions, and user-facing // implementations (such as Uint256ToAddressMap) are just wrappers around // the underlying Map. // This means that we can only create new EnumerableMaps for types that fit // in bytes32. struct MapEntry { bytes32 _key; bytes32 _value; } struct Map { // Storage of map keys and values MapEntry[] _entries; // Position of the entry defined by a key in the `entries` array, plus 1 // because index 0 means a key is not in the map. mapping (bytes32 => uint256) _indexes; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) { // Equivalent to !contains(map, key) map._entries.push(MapEntry({ _key: key, _value: value })); // The entry is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value map._indexes[key] = map._entries.length; return true; } else { map._entries[keyIndex - 1]._value = value; return false; } } /** * @dev Removes a key-value pair from a map. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function _remove(Map storage map, bytes32 key) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex != 0) { // Equivalent to contains(map, key) // To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one // in the array, and then remove the last entry (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = keyIndex - 1; uint256 lastIndex = map._entries.length - 1; // When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. MapEntry storage lastEntry = map._entries[lastIndex]; // Move the last entry to the index where the entry to delete is map._entries[toDeleteIndex] = lastEntry; // Update the index for the moved entry map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved entry was stored map._entries.pop(); // Delete the index for the deleted slot delete map._indexes[key]; return true; } else { return false; } } /** * @dev Returns true if the key is in the map. O(1). */ function _contains(Map storage map, bytes32 key) private view returns (bool) { return map._indexes[key] != 0; } /** * @dev Returns the number of key-value pairs in the map. O(1). */ function _length(Map storage map) private view returns (uint256) { return map._entries.length; } /** * @dev Returns the key-value pair stored at position `index` in the map. O(1). * * Note that there are no guarantees on the ordering of entries inside the * array, and it may change when more entries are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) { require(map._entries.length > index, "EnumerableMap: index out of bounds"); MapEntry storage entry = map._entries[index]; return (entry._key, entry._value); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. */ function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) { uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key) return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function _get(Map storage map, bytes32 key) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } /** * @dev Same as {_get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {_tryGet}. */ function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } // UintToAddressMap struct UintToAddressMap { Map _inner; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) { return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) { return _remove(map._inner, bytes32(key)); } /** * @dev Returns true if the key is in the map. O(1). */ function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) { return _contains(map._inner, bytes32(key)); } /** * @dev Returns the number of elements in the map. O(1). */ function length(UintToAddressMap storage map) internal view returns (uint256) { return _length(map._inner); } /** * @dev Returns the element stored at position `index` in the set. O(1). * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) { (bytes32 key, bytes32 value) = _at(map._inner, index); return (uint256(key), address(uint160(uint256(value)))); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. * * _Available since v3.4._ */ function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) { (bool success, bytes32 value) = _tryGet(map._inner, bytes32(key)); return (success, address(uint160(uint256(value)))); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function get(UintToAddressMap storage map, uint256 key) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key))))); } /** * @dev Same as {get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryGet}. */ function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage)))); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev String operations. */ library Strings { /** * @dev Converts a `uint256` to its ASCII `string` representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); uint256 index = digits - 1; temp = value; while (temp != 0) { buffer[index--] = bytes1(uint8(48 + temp % 10)); temp /= 10; } return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { // Check the signature length if (signature.length != 65) { revert("ECDSA: invalid signature length"); } // Divide the signature in r, s and v variables bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solhint-disable-next-line no-inline-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return recover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover-bytes32-bytes-} that receives the `v`, * `r` and `s` signature fields separately. */ function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value"); require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value"); // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); require(signer != address(0), "ECDSA: invalid signature"); return signer; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * replicates the behavior of the * https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`] * JSON-RPC method. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity 0.7.6; interface IFactory { function create(bytes calldata args) external returns (address instance); function create2(bytes calldata args, bytes32 salt) external returns (address instance); } // SPDX-License-Identifier: GPL-3.0-only pragma solidity 0.7.6; import {EnumerableSet} from "@openzeppelin/contracts/utils/EnumerableSet.sol"; interface IInstanceRegistry { /* events */ event InstanceAdded(address instance); event InstanceRemoved(address instance); /* view functions */ function isInstance(address instance) external view returns (bool validity); function instanceCount() external view returns (uint256 count); function instanceAt(uint256 index) external view returns (address instance); } /// @title InstanceRegistry contract InstanceRegistry is IInstanceRegistry { using EnumerableSet for EnumerableSet.AddressSet; /* storage */ EnumerableSet.AddressSet private _instanceSet; /* view functions */ function isInstance(address instance) external view override returns (bool validity) { return _instanceSet.contains(instance); } function instanceCount() external view override returns (uint256 count) { return _instanceSet.length(); } function instanceAt(uint256 index) external view override returns (address instance) { return _instanceSet.at(index); } /* admin functions */ function _register(address instance) internal { require(_instanceSet.add(instance), "InstanceRegistry: already registered"); emit InstanceAdded(instance); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity 0.7.6; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {ERC721} from "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol"; import {IFactory} from "../factory/IFactory.sol"; import {IInstanceRegistry} from "../factory/InstanceRegistry.sol"; import {ProxyFactory} from "../factory/ProxyFactory.sol"; import {IUniversalVault} from "./MethodVault.sol"; /// @title MethodNFTFactory contract MethodNFTFactory is Ownable, IFactory, IInstanceRegistry, ERC721 { using SafeMath for uint256; bytes32[] public names; mapping(bytes32=>address) public templates; bytes32 public activeTemplate; uint256 public tokenSerialNumber; mapping(uint256=>uint256) public serialNumberToTokenId; mapping(uint256=>uint256) public tokenIdToSerialNumber; mapping(address=>address[]) private ownerToVaultsMap; event TemplateAdded(bytes32 indexed name, address indexed template); event TemplateActive(bytes32 indexed name, address indexed template); constructor() ERC721("MethodNFT", "MTHDNFT") { ERC721._setBaseURI("https://api.methodfi.co/nft/"); } function addTemplate(bytes32 name, address template) public onlyOwner { require(templates[name] == address(0), "Template already exists"); templates[name] = template; if(names.length == 0) { activeTemplate = name; emit TemplateActive(name, template); } names.push(name); emit TemplateAdded(name, template); } function setActive(bytes32 name) public onlyOwner { require(templates[name] != address(0), "Template does not exist"); activeTemplate = name; emit TemplateActive(name, templates[name]); } /* registry functions */ function isInstance(address instance) external view override returns (bool validity) { return ERC721._exists(uint256(instance)); } function instanceCount() external view override returns (uint256 count) { return ERC721.totalSupply(); } function instanceAt(uint256 index) external view override returns (address instance) { return address(ERC721.tokenByIndex(index)); } /* factory functions */ function create(bytes calldata) external override returns (address vault) { return createSelected(activeTemplate); } function create2(bytes calldata, bytes32 salt) external override returns (address vault) { return createSelected2(activeTemplate, salt); } function create() public returns (address vault) { return createSelected(activeTemplate); } function create2(bytes32 salt) public returns (address vault) { return createSelected2(activeTemplate, salt); } function createSelected(bytes32 name) public returns (address vault) { // create clone and initialize vault = ProxyFactory._create( templates[name], abi.encodeWithSelector(IUniversalVault.initialize.selector) ); // mint nft to caller uint256 tokenId = uint256(vault); ERC721._safeMint(msg.sender, tokenId); // push vault to owner's map ownerToVaultsMap[msg.sender].push(vault); // update serial number tokenSerialNumber = tokenSerialNumber.add(1); serialNumberToTokenId[tokenSerialNumber] = tokenId; tokenIdToSerialNumber[tokenId] = tokenSerialNumber; // emit event emit InstanceAdded(vault); // explicit return return vault; } function createSelected2(bytes32 name, bytes32 salt) public returns (address vault) { // create clone and initialize vault = ProxyFactory._create2( templates[name], abi.encodeWithSelector(IUniversalVault.initialize.selector), salt ); // mint nft to caller uint256 tokenId = uint256(vault); ERC721._safeMint(msg.sender, tokenId); // push vault to owner's map ownerToVaultsMap[msg.sender].push(vault); // update serial number tokenSerialNumber = tokenSerialNumber.add(1); serialNumberToTokenId[tokenSerialNumber] = tokenId; tokenIdToSerialNumber[tokenId] = tokenSerialNumber; // emit event emit InstanceAdded(vault); // explicit return return vault; } /* getter functions */ function nameCount() public view returns(uint256) { return names.length; } function vaultCount(address owner) public view returns(uint256) { return ownerToVaultsMap[owner].length; } function getVault(address owner, uint256 index) public view returns (address) { return ownerToVaultsMap[owner][index]; } function getAllVaults(address owner) public view returns (address [] memory) { return ownerToVaultsMap[owner]; } function getTemplate() external view returns (address) { return templates[activeTemplate]; } function getVaultOfNFT(uint256 nftId) public pure returns (address) { return address(nftId); } function getNFTOfVault(address vault) public pure returns (uint256) { return uint256(vault); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity 0.7.6; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol"; import {TransferHelper} from "@uniswap/lib/contracts/libraries/TransferHelper.sol"; import {Powered} from "./Powered.sol"; interface IRewardPool { function sendERC20( address token, address to, uint256 value ) external; function rescueERC20(address[] calldata tokens, address recipient) external; } /// @title Reward Pool /// @notice Vault for isolated storage of reward tokens contract RewardPool is IRewardPool, Powered, Ownable { /* initializer */ constructor(address powerSwitch) { Powered._setPowerSwitch(powerSwitch); } /* user functions */ /// @notice Send an ERC20 token /// access control: only owner /// state machine: /// - can be called multiple times /// - only online /// state scope: none /// token transfer: transfer tokens from self to recipient /// @param token address The token to send /// @param to address The recipient to send to /// @param value uint256 Amount of tokens to send function sendERC20( address token, address to, uint256 value ) external override onlyOwner onlyOnline { TransferHelper.safeTransfer(token, to, value); } /* emergency functions */ /// @notice Rescue multiple ERC20 tokens /// access control: only power controller /// state machine: /// - can be called multiple times /// - only shutdown /// state scope: none /// token transfer: transfer tokens from self to recipient /// @param tokens address[] The tokens to rescue /// @param recipient address The recipient to rescue to function rescueERC20(address[] calldata tokens, address recipient) external override onlyShutdown { // only callable by controller require( msg.sender == Powered.getPowerController(), "RewardPool: only controller can withdraw after shutdown" ); // assert recipient is defined require(recipient != address(0), "RewardPool: recipient not defined"); // transfer tokens for (uint256 index = 0; index < tokens.length; index++) { // get token address token = tokens[index]; // get balance uint256 balance = IERC20(token).balanceOf(address(this)); // transfer token TransferHelper.safeTransfer(token, recipient, balance); } } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity 0.7.6; import {IPowerSwitch} from "./PowerSwitch.sol"; interface IPowered { function isOnline() external view returns (bool status); function isOffline() external view returns (bool status); function isShutdown() external view returns (bool status); function getPowerSwitch() external view returns (address powerSwitch); function getPowerController() external view returns (address controller); } /// @title Powered /// @notice Helper for calling external PowerSwitch contract Powered is IPowered { /* storage */ address private _powerSwitch; /* modifiers */ modifier onlyOnline() { require(isOnline(), "Powered: is not online"); _; } modifier onlyOffline() { require(isOffline(), "Powered: is not offline"); _; } modifier notShutdown() { require(!isShutdown(), "Powered: is shutdown"); _; } modifier onlyShutdown() { require(isShutdown(), "Powered: is not shutdown"); _; } /* initializer */ function _setPowerSwitch(address powerSwitch) internal { _powerSwitch = powerSwitch; } /* getter functions */ function isOnline() public view override returns (bool status) { return IPowerSwitch(_powerSwitch).isOnline(); } function isOffline() public view override returns (bool status) { return IPowerSwitch(_powerSwitch).isOffline(); } function isShutdown() public view override returns (bool status) { return IPowerSwitch(_powerSwitch).isShutdown(); } function getPowerSwitch() public view override returns (address powerSwitch) { return _powerSwitch; } function getPowerController() public view override returns (address controller) { return IPowerSwitch(_powerSwitch).getPowerController(); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity 0.7.6; interface IERC2917 { /// @dev This emits when interests amount per block is changed by the owner of the contract. /// It emits with the old interests amount and the new interests amount. event InterestRatePerBlockChanged (uint oldValue, uint newValue); /// @dev This emits when a users' productivity has changed /// It emits with the user's address and the the value after the change. event ProductivityIncreased (address indexed user, uint value); /// @dev This emits when a users' productivity has changed /// It emits with the user's address and the the value after the change. event ProductivityDecreased (address indexed user, uint value); function initialize() external; /// @dev Note best practice will be to restrict the caller to staking contract address. function setImplementor(address newImplementor) external; /// @dev Return the current contract's interest rate per block. /// @return The amount of interests currently producing per each block. function interestsPerBlock() external view returns (uint); /// @notice Change the current contract's interest rate. /// @dev Note best practice will be to restrict the caller to staking contract address. /// @return The true/fase to notice that the value has successfully changed or not, when it succeeds, it will emit the InterestRatePerBlockChanged event. function changeInterestRatePerBlock(uint value) external returns (bool); /// @notice It will get the productivity of a given user. /// @dev it will return 0 if user has no productivity in the contract. /// @return user's productivity and overall productivity. function getProductivity(address user) external view returns (uint, uint); /// @notice increase a user's productivity. /// @dev Note best practice will be to restrict the caller to staking contract address. /// @return productivity added status as well as interest earned prior period and total productivity function increaseProductivity(address user, uint value) external returns (bool, uint, uint); /// @notice decrease a user's productivity. /// @dev Note best practice will be to restrict the caller to staking contract address. /// @return productivity removed status as well as interest earned prior period and total productivity function decreaseProductivity(address user, uint value) external returns (bool, uint, uint); /// @notice take() will return the interest that callee will get at current block height. /// @dev it will always be calculated by block.number, so it will change when block height changes. /// @return amount of the interest that user is able to mint() at current block height. function take() external view returns (uint); /// @notice similar to take(), but with the block height joined to calculate return. /// @dev for instance, it returns (_amount, _block), which means at block height _block, the callee has accumulated _amount of interest. /// @return amount of interest and the block height. function takeWithBlock() external view returns (uint, uint); /// @notice mint the avaiable interests to callee. /// @dev once it mints, the amount of interests will transfer to callee's address. /// @return the amount of interest minted. function mint() external returns (uint); } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; import {Clones} from "@openzeppelin/contracts/proxy/Clones.sol"; library ProxyFactory { /* functions */ function _create(address logic, bytes memory data) internal returns (address proxy) { // deploy clone proxy = Clones.clone(logic); // attempt initialization if (data.length > 0) { (bool success, bytes memory err) = proxy.call(data); require(success, string(err)); } // explicit return return proxy; } function _create2( address logic, bytes memory data, bytes32 salt ) internal returns (address proxy) { // deploy clone proxy = Clones.cloneDeterministic(logic, salt); // attempt initialization if (data.length > 0) { (bool success, bytes memory err) = proxy.call(data); require(success, string(err)); } // explicit return return proxy; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity 0.7.6; pragma abicoder v2; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {ERC721} from "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import {Initializable} from "@openzeppelin/contracts/proxy/Initializable.sol"; import {EnumerableSet} from "@openzeppelin/contracts/utils/EnumerableSet.sol"; import {Address} from "@openzeppelin/contracts/utils/Address.sol"; import {TransferHelper} from "@uniswap/lib/contracts/libraries/TransferHelper.sol"; import {EIP712} from "./EIP712.sol"; import {ERC1271} from "./ERC1271.sol"; import {OwnableByERC721} from "./OwnableByERC721.sol"; import {IRageQuit} from "../staking/UniStaker.sol"; interface IUniversalVault { /* user events */ event Locked(address delegate, address token, uint256 amount); event Unlocked(address delegate, address token, uint256 amount); event RageQuit(address delegate, address token, bool notified, string reason); /* data types */ struct LockData { address delegate; address token; uint256 balance; } /* initialize function */ function initialize() external; /* user functions */ function lock( address token, uint256 amount, bytes calldata permission ) external; function unlock( address token, uint256 amount, bytes calldata permission ) external; function rageQuit(address delegate, address token) external returns (bool notified, string memory error); function transferERC20( address token, address to, uint256 amount ) external; function transferETH(address to, uint256 amount) external payable; /* pure functions */ function calculateLockID(address delegate, address token) external pure returns (bytes32 lockID); /* getter functions */ function getPermissionHash( bytes32 eip712TypeHash, address delegate, address token, uint256 amount, uint256 nonce ) external view returns (bytes32 permissionHash); function getNonce() external view returns (uint256 nonce); function owner() external view returns (address ownerAddress); function getLockSetCount() external view returns (uint256 count); function getLockAt(uint256 index) external view returns (LockData memory lockData); function getBalanceDelegated(address token, address delegate) external view returns (uint256 balance); function getBalanceLocked(address token) external view returns (uint256 balance); function checkBalances() external view returns (bool validity); } /// @title MethodVault /// @notice Vault for isolated storage of staking tokens /// @dev Warning: not compatible with rebasing tokens contract MethodVault is IUniversalVault, EIP712("UniversalVault", "1.0.0"), ERC1271, OwnableByERC721, Initializable { using SafeMath for uint256; using Address for address; using Address for address payable; using EnumerableSet for EnumerableSet.Bytes32Set; /* constant */ // Hardcoding a gas limit for rageQuit() is required to prevent gas DOS attacks // the gas requirement cannot be determined at runtime by querying the delegate // as it could potentially be manipulated by a malicious delegate who could force // the calls to revert. // The gas limit could alternatively be set upon vault initialization or creation // of a lock, but the gas consumption trade-offs are not favorable. // Ultimately, to avoid a need for fixed gas limits, the EVM would need to provide // an error code that allows for reliably catching out-of-gas errors on remote calls. uint256 public constant RAGEQUIT_GAS = 500000; bytes32 public constant LOCK_TYPEHASH = keccak256("Lock(address delegate,address token,uint256 amount,uint256 nonce)"); bytes32 public constant UNLOCK_TYPEHASH = keccak256("Unlock(address delegate,address token,uint256 amount,uint256 nonce)"); string public constant VERSION = "1.0.0"; /* storage */ uint256 private _nonce; mapping(bytes32 => LockData) private _locks; EnumerableSet.Bytes32Set private _lockSet; /* initialization function */ function initializeLock() external initializer {} function initialize() external override initializer { OwnableByERC721._setNFT(msg.sender); } /* ether receive */ receive() external payable {} /* internal overrides */ function _getOwner() internal view override(ERC1271) returns (address ownerAddress) { return OwnableByERC721.owner(); } /* pure functions */ function calculateLockID(address delegate, address token) public pure override returns (bytes32 lockID) { return keccak256(abi.encodePacked(delegate, token)); } /* getter functions */ function getPermissionHash( bytes32 eip712TypeHash, address delegate, address token, uint256 amount, uint256 nonce ) public view override returns (bytes32 permissionHash) { return EIP712._hashTypedDataV4( keccak256(abi.encode(eip712TypeHash, delegate, token, amount, nonce)) ); } function getNonce() external view override returns (uint256 nonce) { return _nonce; } function owner() public view override(IUniversalVault, OwnableByERC721) returns (address ownerAddress) { return OwnableByERC721.owner(); } function getLockSetCount() external view override returns (uint256 count) { return _lockSet.length(); } function getLockAt(uint256 index) external view override returns (LockData memory lockData) { return _locks[_lockSet.at(index)]; } function getBalanceDelegated(address token, address delegate) external view override returns (uint256 balance) { return _locks[calculateLockID(delegate, token)].balance; } function getBalanceLocked(address token) public view override returns (uint256 balance) { uint256 count = _lockSet.length(); for (uint256 index; index < count; index++) { LockData storage _lockData = _locks[_lockSet.at(index)]; if (_lockData.token == token && _lockData.balance > balance) balance = _lockData.balance; } return balance; } function checkBalances() external view override returns (bool validity) { // iterate over all token locks and validate sufficient balance uint256 count = _lockSet.length(); for (uint256 index; index < count; index++) { // fetch storage lock reference LockData storage _lockData = _locks[_lockSet.at(index)]; // if insufficient balance and not shutdown, return false if (IERC20(_lockData.token).balanceOf(address(this)) < _lockData.balance) return false; } // if sufficient balance or shutdown, return true return true; } /* user functions */ /// @notice Lock ERC20 tokens in the vault /// access control: called by delegate with signed permission from owner /// state machine: anytime /// state scope: /// - insert or update _locks /// - increase _nonce /// token transfer: none /// @param token Address of token being locked /// @param amount Amount of tokens being locked /// @param permission Permission signature payload function lock( address token, uint256 amount, bytes calldata permission ) external override onlyValidSignature( getPermissionHash(LOCK_TYPEHASH, msg.sender, token, amount, _nonce), permission ) { // get lock id bytes32 lockID = calculateLockID(msg.sender, token); // add lock to storage if (_lockSet.contains(lockID)) { // if lock already exists, increase amount _locks[lockID].balance = _locks[lockID].balance.add(amount); } else { // if does not exist, create new lock // add lock to set assert(_lockSet.add(lockID)); // add lock data to storage _locks[lockID] = LockData(msg.sender, token, amount); } // validate sufficient balance require( IERC20(token).balanceOf(address(this)) >= _locks[lockID].balance, "UniversalVault: insufficient balance" ); // increase nonce _nonce += 1; // emit event emit Locked(msg.sender, token, amount); } /// @notice Unlock ERC20 tokens in the vault /// access control: called by delegate with signed permission from owner /// state machine: after valid lock from delegate /// state scope: /// - remove or update _locks /// - increase _nonce /// token transfer: none /// @param token Address of token being unlocked /// @param amount Amount of tokens being unlocked /// @param permission Permission signature payload function unlock( address token, uint256 amount, bytes calldata permission ) external override onlyValidSignature( getPermissionHash(UNLOCK_TYPEHASH, msg.sender, token, amount, _nonce), permission ) { // get lock id bytes32 lockID = calculateLockID(msg.sender, token); // validate existing lock require(_lockSet.contains(lockID), "UniversalVault: missing lock"); // update lock data if (_locks[lockID].balance > amount) { // substract amount from lock balance _locks[lockID].balance = _locks[lockID].balance.sub(amount); } else { // delete lock data delete _locks[lockID]; assert(_lockSet.remove(lockID)); } // increase nonce _nonce += 1; // emit event emit Unlocked(msg.sender, token, amount); } /// @notice Forcibly cancel delegate lock /// @dev This function will attempt to notify the delegate of the rage quit using a fixed amount of gas. /// access control: only owner /// state machine: after valid lock from delegate /// state scope: /// - remove item from _locks /// token transfer: none /// @param delegate Address of delegate /// @param token Address of token being unlocked function rageQuit(address delegate, address token) external override onlyOwner returns (bool notified, string memory error) { // get lock id bytes32 lockID = calculateLockID(delegate, token); // validate existing lock require(_lockSet.contains(lockID), "UniversalVault: missing lock"); // attempt to notify delegate if (delegate.isContract()) { // check for sufficient gas require(gasleft() >= RAGEQUIT_GAS, "UniversalVault: insufficient gas"); // attempt rageQuit notification try IRageQuit(delegate).rageQuit{gas: RAGEQUIT_GAS}() { notified = true; } catch Error(string memory res) { notified = false; error = res; } catch (bytes memory) { notified = false; } } // update lock storage assert(_lockSet.remove(lockID)); delete _locks[lockID]; // emit event emit RageQuit(delegate, token, notified, error); } /// @notice Transfer ERC20 tokens out of vault /// access control: only owner /// state machine: when balance >= max(lock) + amount /// state scope: none /// token transfer: transfer any token /// @param token Address of token being transferred /// @param to Address of the recipient /// @param amount Amount of tokens to transfer function transferERC20( address token, address to, uint256 amount ) external override onlyOwner { // check for sufficient balance require( IERC20(token).balanceOf(address(this)) >= getBalanceLocked(token).add(amount), "UniversalVault: insufficient balance" ); // perform transfer TransferHelper.safeTransfer(token, to, amount); } /// @notice Transfer ERC20 tokens out of vault /// access control: only owner /// state machine: when balance >= amount /// state scope: none /// token transfer: transfer any token /// @param to Address of the recipient /// @param amount Amount of ETH to transfer function transferETH(address to, uint256 amount) external payable override onlyOwner { // perform transfer TransferHelper.safeTransferETH(to, amount); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev https://eips.ethereum.org/EIPS/eip-1167[EIP 1167] is a standard for * deploying minimal proxy contracts, also known as "clones". * * > To simply and cheaply clone contract functionality in an immutable way, this standard specifies * > a minimal bytecode implementation that delegates all calls to a known, fixed address. * * The library includes functions to deploy a proxy using either `create` (traditional deployment) or `create2` * (salted deterministic deployment). It also includes functions to predict the addresses of clones deployed using the * deterministic method. * * _Available since v3.4._ */ library Clones { /** * @dev Deploys and returns the address of a clone that mimics the behaviour of `master`. * * This function uses the create opcode, which should never revert. */ function clone(address master) internal returns (address instance) { // solhint-disable-next-line no-inline-assembly assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, master)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) instance := create(0, ptr, 0x37) } require(instance != address(0), "ERC1167: create failed"); } /** * @dev Deploys and returns the address of a clone that mimics the behaviour of `master`. * * This function uses the create2 opcode and a `salt` to deterministically deploy * the clone. Using the same `master` and `salt` multiple time will revert, since * the clones cannot be deployed twice at the same address. */ function cloneDeterministic(address master, bytes32 salt) internal returns (address instance) { // solhint-disable-next-line no-inline-assembly assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, master)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) instance := create2(0, ptr, 0x37, salt) } require(instance != address(0), "ERC1167: create2 failed"); } /** * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}. */ function predictDeterministicAddress(address master, bytes32 salt, address deployer) internal pure returns (address predicted) { // solhint-disable-next-line no-inline-assembly assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, master)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf3ff00000000000000000000000000000000) mstore(add(ptr, 0x38), shl(0x60, deployer)) mstore(add(ptr, 0x4c), salt) mstore(add(ptr, 0x6c), keccak256(ptr, 0x37)) predicted := keccak256(add(ptr, 0x37), 0x55) } } /** * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}. */ function predictDeterministicAddress(address master, bytes32 salt) internal view returns (address predicted) { return predictDeterministicAddress(master, salt, address(this)); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity 0.7.6; pragma abicoder v2; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {EnumerableSet} from "@openzeppelin/contracts/utils/EnumerableSet.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {TransferHelper} from "@uniswap/lib/contracts/libraries/TransferHelper.sol"; import {IFactory} from "../factory/IFactory.sol"; import {IInstanceRegistry} from "../factory/InstanceRegistry.sol"; import {IUniversalVault} from "../methodNFT/MethodVault.sol"; import {MethodNFTFactory} from "../methodNFT/MethodNFTFactory.sol"; import {IRewardPool} from "./RewardPool.sol"; import {Powered} from "./Powered.sol"; import {IERC2917} from "./IERC2917.sol"; import {ProxyFactory} from "../factory/ProxyFactory.sol"; interface IRageQuit { function rageQuit() external; } interface IUniStaker is IRageQuit { /* admin events */ event UniStakerCreated(address rewardPool, address powerSwitch); event UniStakerFunded(address token, uint256 amount); event BonusTokenRegistered(address token); event BonusTokenRemoved(address token); event VaultFactoryRegistered(address factory); event VaultFactoryRemoved(address factory); event AdminshipTransferred(address indexed previousAdmin, address indexed newAdmin); /* user events */ event Staked(address vault, uint256 amount); event Unstaked(address vault, uint256 amount); event RageQuit(address vault); event RewardClaimed(address vaultFactory, address recipient, address token, uint256 amount); event VestedRewardClaimed(address recipient, address token, uint amount); /* data types */ struct VaultData { // token address to total token stake mapping mapping(address => uint) tokenStake; EnumerableSet.AddressSet tokens; } struct LMRewardData { uint256 amount; uint256 duration; uint256 startedAt; address rewardCalcInstance; EnumerableSet.AddressSet bonusTokens; mapping(address => uint) bonusTokenAmounts; } struct LMRewardVestingData { uint amount; uint startedAt; } /* getter functions */ function getBonusTokenSetLength() external view returns (uint256 length); function getBonusTokenAtIndex(uint256 index) external view returns (address bonusToken); function getVaultFactorySetLength() external view returns (uint256 length); function getVaultFactoryAtIndex(uint256 index) external view returns (address factory); function getNumVaults() external view returns (uint256 num); function getVaultAt(uint256 index) external view returns (address vault); function getNumTokensStaked() external view returns (uint256 num); function getTokenStakedAt(uint256 index) external view returns (address token); function getNumTokensStakedInVault(address vault) external view returns (uint256 num); function getVaultTokenAtIndex(address vault, uint256 index) external view returns (address vaultToken); function getVaultTokenStake(address vault, address token) external view returns (uint256 tokenStake); function getLMRewardData(address token) external view returns (uint amount, uint duration, uint startedAt, address rewardCalcInstance); function getLMRewardBonusTokensLength(address token) external view returns (uint length); function getLMRewardBonusTokenAt(address token, uint index) external view returns (address bonusToken, uint bonusTokenAmount); function getNumVestingLMTokenRewards(address user) external view returns (uint num); function getVestingLMTokenAt(address user, uint index) external view returns (address token); function getNumVests(address user, address token) external view returns (uint num); function getNumRewardCalcTemplates() external view returns (uint num); function getLMRewardVestingData(address user, address token, uint index) external view returns (uint amount, uint startedAt); function isValidAddress(address target) external view returns (bool validity); function isValidVault(address vault, address factory) external view returns (bool validity); /* user functions */ function stake( address vault, address vaultFactory, address token, uint256 amount, bytes calldata permission ) external; function unstakeAndClaim( address vault, address vaultFactory, address recipient, address token, uint256 amount, bool claimBonusReward, bytes calldata permission ) external; function claimAirdropReward(address nftFactory) external; function claimAirdropReward(address nftFactory, uint256[] calldata tokenIds) external; function claimVestedReward() external; function claimVestedReward(address token) external; } /// @title UniStaker /// @notice Reward distribution contract /// Access Control /// - Power controller: /// Can power off / shutdown the UniStaker /// Can withdraw rewards from reward pool once shutdown /// - Owner: /// Is unable to operate on user funds due to UniversalVault /// Is unable to operate on reward pool funds when reward pool is offline / shutdown /// - UniStaker admin: /// Can add funds to the UniStaker, register bonus tokens, and whitelist new vault factories /// Is a subset of owner permissions /// - User: /// Can stake / unstake / ragequit / claim airdrop / claim vested rewards /// UniStaker State Machine /// - Online: /// UniStaker is operating normally, all functions are enabled /// - Offline: /// UniStaker is temporarely disabled for maintenance /// User staking and unstaking is disabled, ragequit remains enabled /// Users can delete their stake through rageQuit() but forego their pending reward /// Should only be used when downtime required for an upgrade /// - Shutdown: /// UniStaker is permanently disabled /// All functions are disabled with the exception of ragequit /// Users can delete their stake through rageQuit() /// Power controller can withdraw from the reward pool /// Should only be used if Owner role is compromised contract UniStaker is IUniStaker, Powered { using SafeMath for uint256; using EnumerableSet for EnumerableSet.AddressSet; /* constants */ string public constant PLATINUM = "PLATINUM"; string public constant GOLD = "GOLD"; string public constant MINT = "MINT"; string public constant BLACK = "BLACK"; uint public PLATINUM_LM_REWARD_MULTIPLIER_NUM = 5; uint public PLATINUM_LM_REWARD_MULTIPLIER_DENOM = 2; uint public GOLD_LM_REWARD_MULTIPLIER_NUM = 2; uint public GOLD_LM_REWARD_MULTIPLIER_DENOM = 1; uint public MINT_LM_REWARD_MULTIPLIER_NUM = 3; uint public MINT_LM_REWARD_MULTIPLIER_DENOM = 2; uint public BLACK_LM_REWARD_MULTIPLIER_NUM = 1; uint public BLACK_LM_REWARD_MULTIPLIER_DENOM = 1; uint public LM_REWARD_VESTING_PERIOD = 7776000; // 3 months uint public LM_REWARD_VESTING_PORTION_NUM = 1; uint public LM_REWARD_VESTING_PORTION_DENOM = 2; // An upper bound on the number of active tokens staked per vault is required to prevent // calls to rageQuit() from reverting. // With 30 tokens staked in a vault, ragequit costs 432811 gas which is conservatively lower // than the hardcoded limit of 500k gas on the vault. // This limit is configurable and could be increased in a future deployment. // Ultimately, to avoid a need for fixed upper bounds, the EVM would need to provide // an error code that allows for reliably catching out-of-gas errors on remote calls. uint256 public MAX_TOKENS_STAKED_PER_VAULT = 30; uint256 public MAX_BONUS_TOKENS = 50; uint256 public MIN_AIRDROP_REWARD_CLAIM_FREQUENCY = 604800; // week in seconds /* storage */ address public admin; address public rewardToken; address public rewardPool; EnumerableSet.AddressSet private _vaultSet; mapping(address => VaultData) private _vaults; EnumerableSet.AddressSet private _bonusTokenSet; EnumerableSet.AddressSet private _vaultFactorySet; EnumerableSet.AddressSet private _allStakedTokens; mapping(address => uint256) public stakedTokenTotal; mapping(address => LMRewardData) private lmRewards; // user to token to earned reward mapping mapping(address => mapping(address => uint)) public earnedLMRewards; // user to token to vesting data mapping mapping(address => mapping(address => LMRewardVestingData[])) public vestingLMRewards; // user to vesting lm token rewards set mapping(address => EnumerableSet.AddressSet) private vestingLMTokenRewards; // nft tier to amount mapping(string => uint256) public weeklyAirdropAmounts; mapping(string => uint256) public balancesRequiredToClaim; // nft id to timestamp mapping(uint256 => uint256) public nftLastClaimedRewardAt; // erc2917 template names string[] public rewardCalcTemplateNames; // erc2917 template names to erc 2917 templates mapping(string => address) public rewardCalcTemplates; string public activeRewardCalcTemplate; event RewardCalcTemplateAdded(string indexed name, address indexed template); event RewardCalcTemplateActive(string indexed name, address indexed template); /* initializer */ /// @notice Initizalize UniStaker /// access control: only proxy constructor /// state machine: can only be called once /// state scope: set initialization variables /// token transfer: none /// @param adminAddress address The admin address /// @param rewardPoolFactory address The factory to use for deploying the RewardPool /// @param powerSwitchFactory address The factory to use for deploying the PowerSwitch /// @param rewardTokenAddress address The address of the reward token for this UniStaker constructor( address adminAddress, address rewardPoolFactory, address powerSwitchFactory, address rewardTokenAddress ) { // deploy power switch address powerSwitch = IFactory(powerSwitchFactory).create(abi.encode(adminAddress)); // deploy reward pool rewardPool = IFactory(rewardPoolFactory).create(abi.encode(powerSwitch)); // set internal config admin = adminAddress; rewardToken = rewardTokenAddress; Powered._setPowerSwitch(powerSwitch); weeklyAirdropAmounts[PLATINUM] = uint256(166).mul(1e18); weeklyAirdropAmounts[GOLD] = uint256(18).mul(1e18); weeklyAirdropAmounts[MINT] = uint256(4).mul(1e18); balancesRequiredToClaim[PLATINUM] = uint256(166).mul(1e18); balancesRequiredToClaim[GOLD] = uint256(18).mul(1e18); balancesRequiredToClaim[MINT] = uint256(4).mul(1e18); // emit event emit UniStakerCreated(rewardPool, powerSwitch); } /* admin functions */ function _admin() private view { require(msg.sender == admin, "not allowed"); } /** * @dev Leaves the contract without admin. It will not be possible to call * `admin` functions anymore. Can only be called by the current admin. * * NOTE: Renouncing adminship will leave the contract without an admin, * thereby removing any functionality that is only available to the admin. */ function renounceAdminship() public { _admin(); emit AdminshipTransferred(admin, address(0)); admin = address(0); } /** * @dev Transfers adminship of the contract to a new account (`newAdmin`). * Can only be called by the current admin. */ function transferAdminship(address newAdmin) public { _admin(); require(newAdmin != address(0), "new admin can't the zero address"); emit AdminshipTransferred(admin, newAdmin); admin = newAdmin; } /// @notice Add funds to UniStaker /// access control: only admin /// state machine: /// - can be called multiple times /// - only online /// state scope: /// - none /// token transfer: transfer staking tokens from msg.sender to reward pool /// @param amount uint256 Amount of reward tokens to deposit function fund(address token, uint256 amount) external { _admin(); require(_bonusTokenSet.contains(token) || token == rewardToken, "cannot fund with unrecognized token"); // transfer reward tokens to reward pool TransferHelper.safeTransferFrom( token, msg.sender, rewardPool, amount ); // emit event emit UniStakerFunded(token, amount); } /// @notice Rescue tokens from RewardPool /// @dev use this function to rescue tokens from RewardPool contract without distributing to stakers or triggering emergency shutdown /// access control: only admin /// state machine: /// - can be called multiple times /// - not shutdown /// state scope: none /// token transfer: transfer requested token from RewardPool to recipient /// @param token address The address of the token to rescue /// @param recipient address The address of the recipient /// @param amount uint256 The amount of tokens to rescue function rescueTokensFromRewardPool( address token, address recipient, uint256 amount ) external { _admin(); // verify recipient require(isValidAddress(recipient), "invalid recipient"); // transfer tokens to recipient IRewardPool(rewardPool).sendERC20(token, recipient, amount); } /// @notice Add vault factory to whitelist /// @dev use this function to enable stakes to vaults coming from the specified factory contract /// access control: only admin /// state machine: /// - can be called multiple times /// - not shutdown /// state scope: /// - append to _vaultFactorySet /// token transfer: none /// @param factory address The address of the vault factory function registerVaultFactory(address factory) external { _admin(); // add factory to set require(_vaultFactorySet.add(factory), "UniStaker: vault factory already registered"); // emit event emit VaultFactoryRegistered(factory); } /// @notice Remove vault factory from whitelist /// @dev use this function to disable new stakes to vaults coming from the specified factory contract. /// note: vaults with existing stakes from this factory are sill able to unstake /// access control: only admin /// state machine: /// - can be called multiple times /// - not shutdown /// state scope: /// - remove from _vaultFactorySet /// token transfer: none /// @param factory address The address of the vault factory function removeVaultFactory(address factory) external { _admin(); // remove factory from set require(_vaultFactorySet.remove(factory), "UniStaker: vault factory not registered"); // emit event emit VaultFactoryRemoved(factory); } /// @notice Register bonus token for distribution /// @dev use this function to enable distribution of any ERC20 held by the RewardPool contract /// access control: only admin /// state machine: /// - can be called multiple times /// - only online /// state scope: /// - append to _bonusTokenSet /// token transfer: none /// @param bonusToken address The address of the bonus token function registerBonusToken(address bonusToken) external { _admin(); // verify valid bonus token require(isValidAddress(bonusToken), "invalid bonus token address or is already present"); // verify bonus token count require(_bonusTokenSet.length() < MAX_BONUS_TOKENS, "UniStaker: max bonus tokens reached "); // add token to set _bonusTokenSet.add(bonusToken); // emit event emit BonusTokenRegistered(bonusToken); } /// @notice Remove bonus token /// @dev use this function to disable distribution of a token held by the RewardPool contract /// access control: only admin /// state machine: /// - can be called multiple times /// - not shutdown /// state scope: /// - remove from _bonusTokenSet /// token transfer: none /// @param bonusToken address The address of the bonus token function removeBonusToken(address bonusToken) external { _admin(); require(_bonusTokenSet.remove(bonusToken), "UniStaker: bonus token not present "); // emit event emit BonusTokenRemoved(bonusToken); } function addRewardCalcTemplate(string calldata name, address template) external { _admin(); require(rewardCalcTemplates[name] == address(0), "Template already exists"); rewardCalcTemplates[name] = template; if(rewardCalcTemplateNames.length == 0) { activeRewardCalcTemplate = name; emit RewardCalcTemplateActive(name, template); } rewardCalcTemplateNames.push(name); emit RewardCalcTemplateAdded(name, template); } function setRewardCalcActiveTemplate(string calldata name) external { _admin(); require(rewardCalcTemplates[name] != address(0), "Template does not exist"); activeRewardCalcTemplate = name; emit RewardCalcTemplateActive(name, rewardCalcTemplates[name]); } function startLMRewards(address token, uint256 amount, uint256 duration) external { startLMRewards(token, amount, duration, activeRewardCalcTemplate); } function startLMRewards(address token, uint256 amount, uint256 duration, string memory rewardCalcTemplateName) public { _admin(); require(lmRewards[token].startedAt == 0, "A reward program already live for this token"); require(rewardCalcTemplates[rewardCalcTemplateName] != address(0), "Reward Calculator Template does not exist"); // create reward calc clone from template address rewardCalcInstance = ProxyFactory._create(rewardCalcTemplates[rewardCalcTemplateName], abi.encodeWithSelector(IERC2917.initialize.selector)); LMRewardData storage lmrd = lmRewards[token]; lmrd.amount = amount; lmrd.duration = duration; lmrd.startedAt = block.timestamp; lmrd.rewardCalcInstance = rewardCalcInstance; } function setImplementorForRewardsCalculator(address token, address newImplementor) public { _admin(); require(lmRewards[token].startedAt != 0, "No reward program currently live for this token"); address rewardCalcInstance = lmRewards[token].rewardCalcInstance; IERC2917(rewardCalcInstance).setImplementor(newImplementor); } function setLMRewardsPerBlock(address token, uint value) public onlyOnline { _admin(); require(lmRewards[token].startedAt != 0, "No reward program currently live for this token"); address rewardCalcInstance = lmRewards[token].rewardCalcInstance; IERC2917(rewardCalcInstance).changeInterestRatePerBlock(value); } function addBonusTokenToLMRewards(address lmToken, address bonusToken, uint256 bonusTokenAmount) public { _admin(); require(lmRewards[lmToken].startedAt != 0, "No reward program currently live for this LM token"); require(_bonusTokenSet.contains(bonusToken), "Bonus token not registered"); lmRewards[lmToken].bonusTokens.add(bonusToken); lmRewards[lmToken].bonusTokenAmounts[bonusToken] = lmRewards[lmToken].bonusTokenAmounts[bonusToken].add(bonusTokenAmount); } function endLMRewards(address token, bool removeBonusTokenData) public { _admin(); lmRewards[token].amount = 0; lmRewards[token].duration = 0; lmRewards[token].startedAt = 0; lmRewards[token].rewardCalcInstance = address(0); if (removeBonusTokenData) { for (uint index = 0; index < lmRewards[token].bonusTokens.length(); index++) { address bonusToken = lmRewards[token].bonusTokens.at(index); lmRewards[token].bonusTokens.remove(bonusToken); delete lmRewards[token].bonusTokenAmounts[bonusToken]; } } } function setWeeklyAirdropAmount(string calldata tier, uint256 amount) external { _admin(); weeklyAirdropAmounts[tier] = amount; } function setBalanceRequiredToClaim(string calldata tier, uint256 amount) external { _admin(); balancesRequiredToClaim[tier] = amount; } function setMaxStakesPerVault(uint256 amount) external { _admin(); MAX_TOKENS_STAKED_PER_VAULT = amount; } function setMaxBonusTokens(uint256 amount) external { _admin(); MAX_BONUS_TOKENS = amount; } function setMinRewardClaimFrequency(uint256 amount) external { _admin(); MIN_AIRDROP_REWARD_CLAIM_FREQUENCY = amount; } function setPlatinumLMRewardMultiplier(uint256 numerator, uint256 denominator) external { _admin(); PLATINUM_LM_REWARD_MULTIPLIER_NUM = numerator; PLATINUM_LM_REWARD_MULTIPLIER_DENOM = denominator; } function setGoldLMRewardMultiplier(uint256 numerator, uint256 denominator) external { _admin(); GOLD_LM_REWARD_MULTIPLIER_NUM = numerator; GOLD_LM_REWARD_MULTIPLIER_DENOM = denominator; } function setMintLMRewardMultiplier(uint256 numerator, uint256 denominator) external { _admin(); MINT_LM_REWARD_MULTIPLIER_NUM = numerator; MINT_LM_REWARD_MULTIPLIER_DENOM = denominator; } function setBlackLMRewardMultiplier(uint256 numerator, uint256 denominator) external { _admin(); BLACK_LM_REWARD_MULTIPLIER_NUM = numerator; BLACK_LM_REWARD_MULTIPLIER_DENOM = denominator; } function setLMRewardVestingPeriod(uint256 amount) external { _admin(); LM_REWARD_VESTING_PERIOD = amount; } function setLMRewardVestingPortion(uint256 numerator, uint denominator) external { _admin(); LM_REWARD_VESTING_PORTION_NUM = numerator; LM_REWARD_VESTING_PORTION_DENOM = denominator; } /* getter functions */ function getBonusTokenSetLength() external view override returns (uint256 length) { return _bonusTokenSet.length(); } function getBonusTokenAtIndex(uint256 index) external view override returns (address bonusToken) { return _bonusTokenSet.at(index); } function getVaultFactorySetLength() external view override returns (uint256 length) { return _vaultFactorySet.length(); } function getVaultFactoryAtIndex(uint256 index) external view override returns (address factory) { return _vaultFactorySet.at(index); } function getNumVaults() external view override returns (uint256 num) { return _vaultSet.length(); } function getVaultAt(uint256 index) external view override returns (address vault) { return _vaultSet.at(index); } function getNumTokensStaked() external view override returns (uint256 num) { return _allStakedTokens.length(); } function getTokenStakedAt(uint256 index) external view override returns (address token) { return _allStakedTokens.at(index); } function getNumTokensStakedInVault(address vault) external view override returns (uint256 num) { return _vaults[vault].tokens.length(); } function getVaultTokenAtIndex(address vault, uint256 index) external view override returns (address vaultToken) { return _vaults[vault].tokens.at(index); } function getVaultTokenStake(address vault, address token) external view override returns (uint256 tokenStake) { return _vaults[vault].tokenStake[token]; } function getNftTier(uint256 nftId, address nftFactory) public view returns (string memory tier) { uint256 serialNumber = MethodNFTFactory(nftFactory).tokenIdToSerialNumber(nftId); if (serialNumber >= 1 && serialNumber <= 100) { tier = PLATINUM; } else if (serialNumber >= 101 && serialNumber <= 1000) { tier = GOLD; } else if (serialNumber >= 1001 && serialNumber <= 5000) { tier = MINT; } else if (serialNumber >= 5001) { tier = BLACK; } } function getNftsOfOwner(address owner, address nftFactory) public view returns (uint256[] memory nftIds) { uint256 balance = MethodNFTFactory(nftFactory).balanceOf(owner); nftIds = new uint256[](balance); for (uint256 index = 0; index < balance; index++) { uint256 nftId = MethodNFTFactory(nftFactory).tokenOfOwnerByIndex(owner, index); nftIds[index] = nftId; } } function getLMRewardData(address token) external view override returns (uint amount, uint duration, uint startedAt, address rewardCalcInstance) { return (lmRewards[token].amount, lmRewards[token].duration, lmRewards[token].startedAt, lmRewards[token].rewardCalcInstance); } function getLMRewardBonusTokensLength(address token) external view override returns (uint length) { return lmRewards[token].bonusTokens.length(); } function getLMRewardBonusTokenAt(address token, uint index) external view override returns (address bonusToken, uint bonusTokenAmount) { return (lmRewards[token].bonusTokens.at(index), lmRewards[token].bonusTokenAmounts[lmRewards[token].bonusTokens.at(index)]); } function getNumVestingLMTokenRewards(address user) external view override returns (uint num) { return vestingLMTokenRewards[user].length(); } function getVestingLMTokenAt(address user, uint index) external view override returns (address token) { return vestingLMTokenRewards[user].at(index); } function getNumVests(address user, address token) external view override returns (uint num) { return vestingLMRewards[user][token].length; } function getLMRewardVestingData(address user, address token, uint index) external view override returns (uint amount, uint startedAt) { return (vestingLMRewards[user][token][index].amount, vestingLMRewards[user][token][index].startedAt); } function getNumRewardCalcTemplates() external view override returns (uint num) { return rewardCalcTemplateNames.length; } /* helper functions */ function isValidVault(address vault, address factory) public view override returns (bool validity) { // validate vault is created from whitelisted vault factory and is an instance of that factory return _vaultFactorySet.contains(factory) && IInstanceRegistry(factory).isInstance(vault); } function isValidAddress(address target) public view override returns (bool validity) { // sanity check target for potential input errors return target != address(this) && target != address(0) && target != rewardToken && target != rewardPool && !_bonusTokenSet.contains(target); } function calculateAirdropReward(address owner, address nftFactory) public returns (uint256 amount, uint256 balanceRequiredToClaim, uint256 balanceLocked) { uint256[] memory nftIds = getNftsOfOwner(owner, nftFactory); return calculateAirdropReward(nftFactory, nftIds); } function calculateAirdropReward(address nftFactory, uint256[] memory nftIds) public returns (uint256 amount, uint256 balanceRequiredToClaim, uint256 balanceLocked) { for (uint256 index = 0; index < nftIds.length; index++) { uint256 nftId = nftIds[index]; (uint256 amnt, uint256 balRequired, uint256 balLocked) = calculateAirdropReward(nftFactory, nftId); amount = amount.add(amnt); balanceRequiredToClaim = balanceRequiredToClaim.add(balRequired); balanceLocked = balanceLocked.add(balLocked); } } function calculateAirdropReward(address nftFactory, uint256 nftId) public returns (uint256 amount, uint256 balanceRequiredToClaim, uint256 balanceLocked) { address vaultAddress = address(nftId); require(isValidVault(vaultAddress, nftFactory), "UniStaker: vault is not valid"); // first ever claim if (nftLastClaimedRewardAt[nftId] == 0) { nftLastClaimedRewardAt[nftId] = block.timestamp; return (0,0,0); } uint256 secondsSinceLastClaim = block.timestamp.sub(nftLastClaimedRewardAt[nftId]); require(secondsSinceLastClaim > MIN_AIRDROP_REWARD_CLAIM_FREQUENCY, "Claimed reward recently"); // get tier string memory tier = getNftTier(nftId, nftFactory); // get balance locked of reward token (MTHD) uint256 balanceLockedInVault = IUniversalVault(vaultAddress).getBalanceLocked(rewardToken); balanceLocked = balanceLocked.add(balanceLockedInVault); // get number of epochs since last claim uint256 epochsSinceLastClaim = secondsSinceLastClaim.div(MIN_AIRDROP_REWARD_CLAIM_FREQUENCY); uint256 accruedReward; bytes32 tierHash = keccak256(abi.encodePacked(tier)); if (tierHash == keccak256(abi.encodePacked(PLATINUM))) { accruedReward = weeklyAirdropAmounts[PLATINUM].mul(epochsSinceLastClaim); amount = amount.add(accruedReward); balanceRequiredToClaim = balanceRequiredToClaim.add(balancesRequiredToClaim[PLATINUM]); } else if (tierHash == keccak256(abi.encodePacked(GOLD))) { accruedReward = weeklyAirdropAmounts[GOLD].mul(epochsSinceLastClaim); amount = amount.add(accruedReward); balanceRequiredToClaim = balanceRequiredToClaim.add(balancesRequiredToClaim[GOLD]); } else if (tierHash == keccak256(abi.encodePacked(MINT))) { accruedReward = weeklyAirdropAmounts[MINT].mul(epochsSinceLastClaim); amount = amount.add(accruedReward); balanceRequiredToClaim = balanceRequiredToClaim.add(balancesRequiredToClaim[MINT]); } else if (tierHash == keccak256(abi.encodePacked(BLACK))) { accruedReward = weeklyAirdropAmounts[BLACK].mul(epochsSinceLastClaim); amount = amount.add(accruedReward); balanceRequiredToClaim = balanceRequiredToClaim.add(balancesRequiredToClaim[BLACK]); } } /* convenience functions */ function _processAirdropRewardClaim(address nftFactory, uint256[] memory nftIds) private { (uint256 amount, uint256 balanceRequiredToClaim, uint256 balanceLocked) = calculateAirdropReward(nftFactory, nftIds); require(balanceLocked > balanceRequiredToClaim, "Insufficient MTHD tokens staked for claiming airdrop reward"); // update claim times _updateClaimTimes(nftIds); // send out IRewardPool(rewardPool).sendERC20(rewardToken, msg.sender, amount); emit RewardClaimed(nftFactory, msg.sender, rewardToken, amount); } function _updateClaimTimes(uint256[] memory nftIds) private { for (uint256 index = 0; index < nftIds.length; index++) { uint256 nftId = nftIds[index]; nftLastClaimedRewardAt[nftId] = block.timestamp; } } function _tierMultipliedReward(uint nftId, address nftFactory, uint reward) private view returns (uint multipliedReward) { // get tier string memory tier = getNftTier(nftId, nftFactory); bytes32 tierHash = keccak256(abi.encodePacked(tier)); if (tierHash == keccak256(abi.encodePacked(PLATINUM))) { multipliedReward = reward.mul(PLATINUM_LM_REWARD_MULTIPLIER_NUM).div(PLATINUM_LM_REWARD_MULTIPLIER_DENOM); } else if (tierHash == keccak256(abi.encodePacked(GOLD))) { multipliedReward = reward.mul(GOLD_LM_REWARD_MULTIPLIER_NUM).div(GOLD_LM_REWARD_MULTIPLIER_DENOM); } else if (tierHash == keccak256(abi.encodePacked(MINT))) { multipliedReward = reward.mul(MINT_LM_REWARD_MULTIPLIER_NUM).div(MINT_LM_REWARD_MULTIPLIER_DENOM); } else if (tierHash == keccak256(abi.encodePacked(BLACK))) { multipliedReward = reward.mul(BLACK_LM_REWARD_MULTIPLIER_NUM).div(BLACK_LM_REWARD_MULTIPLIER_DENOM); } } /* user functions */ /// @notice Exit UniStaker without claiming reward /// @dev This function should never revert when correctly called by the vault. /// A max number of tokens staked per vault is set with MAX_TOKENS_STAKED_PER_VAULT to /// place an upper bound on the for loop. /// access control: callable by anyone but fails if caller is not an approved vault /// state machine: /// - when vault exists on this UniStaker /// - when active stake from this vault /// - any power state /// state scope: /// - decrease stakedTokenTotal[token], delete if 0 /// - delete _vaults[vault].tokenStake[token] /// - remove _vaults[vault].tokens.remove(token) /// - delete _vaults[vault] /// - remove vault from _vaultSet /// - remove token from _allStakedTokens if required /// token transfer: none function rageQuit() external override { require(_vaultSet.contains(msg.sender), "UniStaker: no vault"); //fetch vault storage reference VaultData storage vaultData = _vaults[msg.sender]; // revert if no active tokens staked EnumerableSet.AddressSet storage vaultTokens = vaultData.tokens; require(vaultTokens.length() > 0, "UniStaker: no stake"); // update totals for (uint256 index = 0; index < vaultTokens.length(); index++) { address token = vaultTokens.at(index); vaultTokens.remove(token); uint256 amount = vaultData.tokenStake[token]; uint256 newTotal = stakedTokenTotal[token].sub(amount); assert(newTotal >= 0); if (newTotal == 0) { _allStakedTokens.remove(token); delete stakedTokenTotal[token]; } else { stakedTokenTotal[token] = newTotal; } delete vaultData.tokenStake[token]; } // delete vault data _vaultSet.remove(msg.sender); delete _vaults[msg.sender]; // emit event emit RageQuit(msg.sender); } /// @notice Stake tokens /// @dev anyone can stake to any vault if they have valid permission /// access control: anyone /// state machine: /// - can be called multiple times /// - only online /// - when vault exists on this UniStaker /// state scope: /// - add token to _vaults[vault].tokens if not already exists /// - increase _vaults[vault].tokenStake[token] /// - add vault to _vaultSet if not already exists /// - add token to _allStakedTokens if not already exists /// - increase stakedTokenTotal[token] /// token transfer: transfer staking tokens from msg.sender to vault /// @param vault address The address of the vault to stake to /// @param vaultFactory address The address of the vault factory which created the vault /// @param token address The address of the token being staked /// @param amount uint256 The amount of tokens to stake function stake( address vault, address vaultFactory, address token, uint256 amount, bytes calldata permission ) external override onlyOnline { // verify vault is valid require(isValidVault(vault, vaultFactory), "UniStaker: vault is not valid"); // verify non-zero amount require(amount != 0, "UniStaker: no amount staked"); // check sender balance require(IERC20(token).balanceOf(msg.sender) >= amount, "insufficient token balance"); // add vault to set _vaultSet.add(vault); // fetch vault storage reference VaultData storage vaultData = _vaults[vault]; // verify stakes boundary not reached require(vaultData.tokens.length() < MAX_TOKENS_STAKED_PER_VAULT, "UniStaker: MAX_TOKENS_STAKED_PER_VAULT reached"); // add token to set and increase amount vaultData.tokens.add(token); vaultData.tokenStake[token] = vaultData.tokenStake[token].add(amount); // update total token staked _allStakedTokens.add(token); stakedTokenTotal[token] = stakedTokenTotal[token].add(amount); // perform transfer TransferHelper.safeTransferFrom(token, msg.sender, vault, amount); // call lock on vault IUniversalVault(vault).lock(token, amount, permission); // check if there is a reward program currently running if (lmRewards[token].startedAt != 0) { address rewardCalcInstance = lmRewards[token].rewardCalcInstance; (,uint rewardEarned,) = IERC2917(rewardCalcInstance).increaseProductivity(msg.sender, amount); earnedLMRewards[msg.sender][token] = earnedLMRewards[msg.sender][token].add(rewardEarned); } // emit event emit Staked(vault, amount); } /// @notice Unstake tokens and claim reward /// @dev LM rewards can only be claimed when unstaking /// access control: anyone with permission /// state machine: /// - when vault exists on this UniStaker /// - after stake from vault /// - can be called multiple times while sufficient stake remains /// - only online /// state scope: /// - decrease _vaults[vault].tokenStake[token] /// - delete token from _vaults[vault].tokens if token stake is 0 /// - decrease stakedTokenTotal[token] /// - delete token from _allStakedTokens if total token stake is 0 /// token transfer: /// - transfer reward tokens from reward pool to recipient /// - transfer bonus tokens from reward pool to recipient /// @param vault address The vault to unstake from /// @param vaultFactory address The vault factory that created this vault /// @param recipient address The recipient to send reward to /// @param token address The staking token /// @param amount uint256 The amount of staking tokens to unstake /// @param claimBonusReward bool flag to claim bonus rewards function unstakeAndClaim( address vault, address vaultFactory, address recipient, address token, uint256 amount, bool claimBonusReward, bytes calldata permission ) external override onlyOnline { require(_vaultSet.contains(vault), "UniStaker: no vault"); // fetch vault storage reference VaultData storage vaultData = _vaults[vault]; // verify non-zero amount require(amount != 0, "UniStaker: no amount unstaked"); // validate recipient require(isValidAddress(recipient), "UniStaker: invalid recipient"); // check for sufficient vault stake amount require(vaultData.tokens.contains(token), "UniStaker: no token in vault"); // check for sufficient vault stake amount require(vaultData.tokenStake[token] >= amount, "UniStaker: insufficient vault token stake"); // check for sufficient total token stake amount // if the above check succeeds and this check fails, there is a bug in stake accounting require(stakedTokenTotal[token] >= amount, "stakedTokenTotal[token] is less than amount being unstaked"); // check if there is a reward program currently running uint rewardEarned = earnedLMRewards[msg.sender][token]; if (lmRewards[token].startedAt != 0) { address rewardCalcInstance = lmRewards[token].rewardCalcInstance; (,uint newReward,) = IERC2917(rewardCalcInstance).decreaseProductivity(msg.sender, amount); rewardEarned = rewardEarned.add(newReward); } // decrease totalStake of token in this vault vaultData.tokenStake[token] = vaultData.tokenStake[token].sub(amount); if (vaultData.tokenStake[token] == 0) { vaultData.tokens.remove(token); delete vaultData.tokenStake[token]; } // decrease stakedTokenTotal across all vaults stakedTokenTotal[token] = stakedTokenTotal[token].sub(amount); if (stakedTokenTotal[token] == 0) { _allStakedTokens.remove(token); delete stakedTokenTotal[token]; } // unlock staking tokens from vault IUniversalVault(vault).unlock(token, amount, permission); // emit event emit Unstaked(vault, amount); // only perform on non-zero reward if (rewardEarned > 0) { // transfer bonus tokens from reward pool to recipient // bonus tokens can only be claimed during an active rewards program if (claimBonusReward && lmRewards[token].startedAt != 0) { for (uint256 index = 0; index < lmRewards[token].bonusTokens.length(); index++) { // fetch bonus token address reference address bonusToken = lmRewards[token].bonusTokens.at(index); // calculate bonus token amount // bonusAmount = rewardEarned * allocatedBonusReward / allocatedMainReward uint256 bonusAmount = rewardEarned.mul(lmRewards[token].bonusTokenAmounts[bonusToken]).div(lmRewards[token].amount); // transfer bonus token IRewardPool(rewardPool).sendERC20(bonusToken, recipient, bonusAmount); // emit event emit RewardClaimed(vault, recipient, bonusToken, bonusAmount); } } // take care of multiplier uint multipliedReward = _tierMultipliedReward(uint(vault), vaultFactory, rewardEarned); // take care of vesting uint vestingPortion = multipliedReward.mul(LM_REWARD_VESTING_PORTION_NUM).div(LM_REWARD_VESTING_PORTION_DENOM); vestingLMRewards[msg.sender][token].push(LMRewardVestingData(vestingPortion, block.timestamp)); vestingLMTokenRewards[msg.sender].add(token); // set earned reward to 0 earnedLMRewards[msg.sender][token] = 0; // transfer reward tokens from reward pool to recipient IRewardPool(rewardPool).sendERC20(rewardToken, recipient, multipliedReward.sub(vestingPortion)); // emit event emit RewardClaimed(vault, recipient, rewardToken, rewardEarned); } } function claimAirdropReward(address nftFactory) external override onlyOnline { uint256[] memory nftIds = getNftsOfOwner(msg.sender, nftFactory); _processAirdropRewardClaim(nftFactory, nftIds); } function claimAirdropReward(address nftFactory, uint256[] calldata nftIds) external override onlyOnline { _processAirdropRewardClaim(nftFactory, nftIds); } function claimVestedReward() external override onlyOnline { uint numTokens = vestingLMTokenRewards[msg.sender].length(); for (uint index = 0; index < numTokens; index++) { address token = vestingLMTokenRewards[msg.sender].at(index); claimVestedReward(token, vestingLMRewards[msg.sender][token].length); } } function claimVestedReward(address token) external override onlyOnline { claimVestedReward(token, vestingLMRewards[msg.sender][token].length); } function claimVestedReward(address token, uint numVests) public onlyOnline { require(numVests <= vestingLMRewards[msg.sender][token].length, "num vests can't be greater than available vests"); LMRewardVestingData[] storage vests = vestingLMRewards[msg.sender][token]; uint vestedReward; for (uint index = 0; index < numVests; index++) { LMRewardVestingData storage vest = vests[index]; uint duration = block.timestamp.sub(vest.startedAt); uint vested = vest.amount.mul(duration).div(LM_REWARD_VESTING_PERIOD); if (vested >= vest.amount) { // completely vested vested = vest.amount; // copy last element into this slot and pop last vests[index] = vests[vests.length - 1]; vests.pop(); index--; numVests--; // if all vested remove from set if (vests.length == 0) { vestingLMTokenRewards[msg.sender].remove(token); break; } } else { vest.amount = vest.amount.sub(vested); } vestedReward = vestedReward.add(vested); } if (vestedReward > 0) { // transfer reward tokens from reward pool to recipient IRewardPool(rewardPool).sendERC20(rewardToken, msg.sender, vestedReward); // emit event emit VestedRewardClaimed(msg.sender, rewardToken, vestedReward); } } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity 0.7.6; import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol"; interface IPowerSwitch { /* admin events */ event PowerOn(); event PowerOff(); event EmergencyShutdown(); /* data types */ enum State {Online, Offline, Shutdown} /* admin functions */ function powerOn() external; function powerOff() external; function emergencyShutdown() external; /* view functions */ function isOnline() external view returns (bool status); function isOffline() external view returns (bool status); function isShutdown() external view returns (bool status); function getStatus() external view returns (State status); function getPowerController() external view returns (address controller); } /// @title PowerSwitch /// @notice Standalone pausing and emergency stop functionality contract PowerSwitch is IPowerSwitch, Ownable { /* storage */ IPowerSwitch.State private _status; /* initializer */ constructor(address owner) { // sanity check owner require(owner != address(0), "PowerSwitch: invalid owner"); // transfer ownership Ownable.transferOwnership(owner); } /* admin functions */ /// @notice Turn Power On /// access control: only owner /// state machine: only when offline /// state scope: only modify _status /// token transfer: none function powerOn() external override onlyOwner { require(_status == IPowerSwitch.State.Offline, "PowerSwitch: cannot power on"); _status = IPowerSwitch.State.Online; emit PowerOn(); } /// @notice Turn Power Off /// access control: only owner /// state machine: only when online /// state scope: only modify _status /// token transfer: none function powerOff() external override onlyOwner { require(_status == IPowerSwitch.State.Online, "PowerSwitch: cannot power off"); _status = IPowerSwitch.State.Offline; emit PowerOff(); } /// @notice Shutdown Permanently /// access control: only owner /// state machine: /// - when online or offline /// - can only be called once /// state scope: only modify _status /// token transfer: none function emergencyShutdown() external override onlyOwner { require(_status != IPowerSwitch.State.Shutdown, "PowerSwitch: cannot shutdown"); _status = IPowerSwitch.State.Shutdown; emit EmergencyShutdown(); } /* getter functions */ function isOnline() external view override returns (bool status) { return _status == IPowerSwitch.State.Online; } function isOffline() external view override returns (bool status) { return _status == IPowerSwitch.State.Offline; } function isShutdown() external view override returns (bool status) { return _status == IPowerSwitch.State.Shutdown; } function getStatus() external view override returns (IPowerSwitch.State status) { return _status; } function getPowerController() external view override returns (address controller) { return Ownable.owner(); } }
update claim times send out
function _processAirdropRewardClaim(address nftFactory, uint256[] memory nftIds) private { (uint256 amount, uint256 balanceRequiredToClaim, uint256 balanceLocked) = calculateAirdropReward(nftFactory, nftIds); require(balanceLocked > balanceRequiredToClaim, "Insufficient MTHD tokens staked for claiming airdrop reward"); _updateClaimTimes(nftIds); IRewardPool(rewardPool).sendERC20(rewardToken, msg.sender, amount); emit RewardClaimed(nftFactory, msg.sender, rewardToken, amount); }
166,137
[ 1, 2725, 7516, 4124, 1366, 596, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 2567, 37, 6909, 1764, 17631, 1060, 9762, 12, 2867, 290, 1222, 1733, 16, 2254, 5034, 8526, 3778, 290, 1222, 2673, 13, 3238, 288, 203, 3639, 261, 11890, 5034, 3844, 16, 2254, 5034, 11013, 3705, 774, 9762, 16, 2254, 5034, 11013, 8966, 13, 273, 4604, 37, 6909, 1764, 17631, 1060, 12, 82, 1222, 1733, 16, 290, 1222, 2673, 1769, 203, 3639, 2583, 12, 12296, 8966, 405, 11013, 3705, 774, 9762, 16, 315, 5048, 11339, 490, 2455, 40, 2430, 384, 9477, 364, 7516, 310, 279, 6909, 1764, 19890, 8863, 203, 3639, 389, 2725, 9762, 10694, 12, 82, 1222, 2673, 1769, 203, 3639, 15908, 359, 1060, 2864, 12, 266, 2913, 2864, 2934, 4661, 654, 39, 3462, 12, 266, 2913, 1345, 16, 1234, 18, 15330, 16, 3844, 1769, 203, 203, 3639, 3626, 534, 359, 1060, 9762, 329, 12, 82, 1222, 1733, 16, 1234, 18, 15330, 16, 19890, 1345, 16, 3844, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/97/0xb4fED79F11149c8117b638A648eF65b69365ED29/sources/contracts/Auth.sol
* @dev Throws if called by any account other than the owner./
modifier onlyOwner() { require(owner() == _msgSender(), "Auth: caller is not the owner"); _; }
11,482,293
[ 1, 21845, 309, 2566, 635, 1281, 2236, 1308, 2353, 326, 3410, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 9606, 1338, 5541, 1435, 288, 203, 3639, 2583, 12, 8443, 1435, 422, 389, 3576, 12021, 9334, 315, 1730, 30, 4894, 353, 486, 326, 3410, 8863, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x429048b9CAa55edA049364f6a4E920cA2Ba52ab4/sources/contracts/TokenSender.sol
validate inputs send 20% to beneficiary, 80% to vesting contract
uint256 vestingStartTime, uint256 vestingDuration) external onlyOwner { IERC20 token = IERC20(tokenAddress); uint256 unvestedAmount = tokenAmount.div(5); uint256 vestedAmount = tokenAmount.sub(unvestedAmount); vesting[beneficiary] = new TokenVesting(beneficiary, vestingStartTime, 0, vestingDuration, false); token.safeTransfer(beneficiary, unvestedAmount); token.safeTransfer(address(vesting[beneficiary]), vestedAmount); }
2,930,780
[ 1, 5662, 4540, 1366, 4200, 9, 358, 27641, 74, 14463, 814, 16, 8958, 9, 358, 331, 10100, 6835, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2254, 5034, 331, 10100, 13649, 16, 2254, 5034, 331, 10100, 5326, 13, 3903, 1338, 5541, 288, 203, 3639, 467, 654, 39, 3462, 1147, 273, 467, 654, 39, 3462, 12, 2316, 1887, 1769, 203, 3639, 2254, 5034, 640, 90, 3149, 6275, 273, 1147, 6275, 18, 2892, 12, 25, 1769, 203, 3639, 2254, 5034, 331, 3149, 6275, 273, 1147, 6275, 18, 1717, 12, 318, 90, 3149, 6275, 1769, 203, 3639, 331, 10100, 63, 70, 4009, 74, 14463, 814, 65, 273, 394, 3155, 58, 10100, 12, 70, 4009, 74, 14463, 814, 16, 331, 10100, 13649, 16, 374, 16, 331, 10100, 5326, 16, 629, 1769, 203, 3639, 1147, 18, 4626, 5912, 12, 70, 4009, 74, 14463, 814, 16, 640, 90, 3149, 6275, 1769, 203, 3639, 1147, 18, 4626, 5912, 12, 2867, 12, 90, 10100, 63, 70, 4009, 74, 14463, 814, 65, 3631, 331, 3149, 6275, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity >=0.8.0; import "./WethMaker.sol"; /// @notice Contract for selling weth to sushi. Deploy on mainnet. contract SushiMaker is WethMaker { event Serve(uint256 amount); address public immutable sushi; address public immutable xSushi; constructor( address _owner, address _user, address _factory, address _weth, address _sushi, address _xSushi ) WethMaker(_owner, _user, _factory, _weth) { sushi = _sushi; xSushi = _xSushi; } function buySushi(uint256 amountIn, uint256 minOutAmount) external onlyTrusted returns (uint256 amountOut) { amountOut = _swap(weth, sushi, amountIn, xSushi); if (amountOut < minOutAmount) revert SlippageProtection(); emit Serve(amountOut); } function sweep(uint256 amount) external onlyTrusted { IERC20(sushi).transfer(xSushi, amount); emit Serve(amount); } // Don't allow direct withdrawals on mainnet. function withdraw(address, address, uint256) external pure override { revert(); } // In case we receive any unwrapped ethereum we can call this. function wrapEth() external { weth.call{value: address(this).balance}(""); } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity >=0.8.0; import "./Unwindooor.sol"; import "./interfaces/IUniV2Factory.sol"; /// @notice Contract for selling received tokens into weth. Deploy on secondary networks. contract WethMaker is Unwindooor { event SetBridge(address indexed token, address bridge); address public immutable weth; IUniV2Factory public immutable factory; mapping(address => address) public bridges; constructor(address _owner, address _user, address _factory, address _weth) Unwindooor(_owner, _user) { factory = IUniV2Factory(_factory); weth = _weth; } function setAllowedBridge(address _token, address _bridge) external onlyOwner { bridges[_token] = _bridge; emit SetBridge(_token, _bridge); } // Exchange token for weth or its bridge token (which gets converted into weth in subsequent transactions). function buyWeth( address[] calldata tokens, uint256[] calldata amountsIn, uint256[] calldata minimumOuts ) external onlyTrusted { for (uint256 i = 0; i < tokens.length; i++) { address tokenIn = tokens[i]; address outToken = bridges[tokenIn] == address(0) ? weth : bridges[tokenIn]; if (_swap(tokenIn, outToken, amountsIn[i], address(this)) < minimumOuts[i]) revert SlippageProtection(); } } function _swap( address tokenIn, address tokenOut, uint256 amountIn, address to ) internal returns (uint256 outAmount) { IUniV2 pair = IUniV2(factory.getPair(tokenIn, tokenOut)); IERC20(tokenIn).transfer(address(pair), amountIn); (uint256 reserve0, uint256 reserve1, ) = pair.getReserves(); if (tokenIn < tokenOut) { outAmount = _getAmountOut(amountIn, reserve0, reserve1); pair.swap(0, outAmount, to, ""); } else { outAmount = _getAmountOut(amountIn, reserve1, reserve0); pair.swap(outAmount, 0, to, ""); } } // Allow the owner to withdraw the funds and bridge them to mainnet. function withdraw(address _token, address _to, uint256 _value) onlyOwner virtual external { if (_token != address(0)) { _safeTransfer(_token, _to, _value); } else { (bool success, ) = _to.call{value: _value}(""); require(success); } } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity >=0.8.0; import "./Auth.sol"; import "./interfaces/IUniV2.sol"; /// @notice Contract for withdrawing LP positions. /// @dev Calling unwindPairs() withdraws the LP position into one of the two tokens contract Unwindooor is Auth { error SlippageProtection(); error TransferFailed(); bytes4 private constant TRANSFER_SELECTOR = bytes4(keccak256(bytes('transfer(address,uint256)'))); constructor(address _owner, address _user) Auth(_owner, _user) {} function unwindPairs( IUniV2[] calldata lpTokens, uint256[] calldata amounts, uint256[] calldata minimumOuts, bool[] calldata keepToken0 ) external onlyTrusted { for (uint256 i = 0; i < lpTokens.length; i++) { if (_unwindPair(lpTokens[i], amounts[i], keepToken0[i]) < minimumOuts[i]) revert SlippageProtection(); } } // Burn liquidity and sell one of the tokens for the other. function _unwindPair( IUniV2 pair, uint256 amount, bool keepToken0 ) private returns (uint256 amountOut) { pair.transfer(address(pair), amount); (uint256 amount0, uint256 amount1) = pair.burn(address(this)); (uint112 reserve0, uint112 reserve1,) = pair.getReserves(); if (keepToken0) { _safeTransfer(pair.token1(), address(pair), amount1); amountOut = _getAmountOut(amount1, uint256(reserve1), uint256(reserve0)); pair.swap(amountOut, 0, address(this), ""); amountOut += amount0; } else { _safeTransfer(pair.token0(), address(pair), amount0); amountOut = _getAmountOut(amount0, uint256(reserve0), uint256(reserve1)); pair.swap(0, amountOut, address(this), ""); amountOut += amount1; } } // Incase we don't want to sell one of the tokens for the other. function burnPairs( IUniV2[] calldata lpTokens, uint256[] calldata amounts, uint256[] calldata minimumOut0, uint256[] calldata minimumOut1 ) external onlyTrusted { for (uint256 i = 0; i < lpTokens.length; i++) { IUniV2 pair = lpTokens[i]; pair.transfer(address(pair), amounts[i]); (uint256 amount0, uint256 amount1) = pair.burn(address(this)); if (amount0 < minimumOut0[i] || amount1 < minimumOut1[i]) revert SlippageProtection(); } } function _getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256) { uint256 amountInWithFee = amountIn * 997; uint256 numerator = amountInWithFee * reserveOut; uint256 denominator = reserveIn * 1000 + amountInWithFee; return numerator / denominator; } function _safeTransfer(address token, address to, uint value) internal { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(TRANSFER_SELECTOR, to, value)); if (!success || (data.length != 0 && !abi.decode(data, (bool)))) revert TransferFailed(); } } // SPDX-License-Identifier: GPL-3.0-or-later interface IUniV2Factory { function getPair(address tokenA, address tokenB) external view returns (address); } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity >=0.8.0; abstract contract Auth { event SetOwner(address indexed owner); event SetTrusted(address indexed user, bool isTrusted); address public owner; mapping(address => bool) public isTrusted; error OnlyOwner(); error OnlyTrusted(); modifier onlyOwner() { if (msg.sender != owner) revert OnlyOwner(); _; } modifier onlyTrusted() { if (!isTrusted[msg.sender]) revert OnlyTrusted(); _; } constructor(address _owner, address _trusted) { owner = _owner; isTrusted[_trusted] = true; emit SetOwner(owner); emit SetTrusted(_trusted, true); } function setOwner(address _owner) external onlyOwner { owner = _owner; emit SetOwner(owner); } function setTrusted(address _user, bool _isTrusted) external onlyOwner { isTrusted[_user] = _isTrusted; emit SetTrusted(_user, _isTrusted); } } // SPDX-License-Identifier: GPL-3.0-or-later import "./IERC20.sol"; interface IUniV2 is IERC20 { function totalSupply() external view returns (uint256); function getReserves() external view returns (uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast); function burn(address to) external returns (uint256 amount0, uint256 amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function token0() external view returns (address); function token1() external view returns (address); } // SPDX-License-Identifier: GPL-3.0-or-later interface IERC20 { function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); function transfer(address recipient, uint256 amount) external returns (bool); function balanceOf(address addy) external view returns (uint256); }
@notice Contract for selling received tokens into weth. Deploy on secondary networks.
contract WethMaker is Unwindooor { event SetBridge(address indexed token, address bridge); address public immutable weth; IUniV2Factory public immutable factory; mapping(address => address) public bridges; constructor(address _owner, address _user, address _factory, address _weth) Unwindooor(_owner, _user) { factory = IUniV2Factory(_factory); weth = _weth; } function setAllowedBridge(address _token, address _bridge) external onlyOwner { bridges[_token] = _bridge; emit SetBridge(_token, _bridge); } function buyWeth( address[] calldata tokens, uint256[] calldata amountsIn, uint256[] calldata minimumOuts ) external onlyTrusted { for (uint256 i = 0; i < tokens.length; i++) { address tokenIn = tokens[i]; address outToken = bridges[tokenIn] == address(0) ? weth : bridges[tokenIn]; if (_swap(tokenIn, outToken, amountsIn[i], address(this)) < minimumOuts[i]) revert SlippageProtection(); } } function buyWeth( address[] calldata tokens, uint256[] calldata amountsIn, uint256[] calldata minimumOuts ) external onlyTrusted { for (uint256 i = 0; i < tokens.length; i++) { address tokenIn = tokens[i]; address outToken = bridges[tokenIn] == address(0) ? weth : bridges[tokenIn]; if (_swap(tokenIn, outToken, amountsIn[i], address(this)) < minimumOuts[i]) revert SlippageProtection(); } } function _swap( address tokenIn, address tokenOut, uint256 amountIn, address to ) internal returns (uint256 outAmount) { IUniV2 pair = IUniV2(factory.getPair(tokenIn, tokenOut)); IERC20(tokenIn).transfer(address(pair), amountIn); (uint256 reserve0, uint256 reserve1, ) = pair.getReserves(); if (tokenIn < tokenOut) { outAmount = _getAmountOut(amountIn, reserve0, reserve1); pair.swap(0, outAmount, to, ""); outAmount = _getAmountOut(amountIn, reserve1, reserve0); pair.swap(outAmount, 0, to, ""); } } function _swap( address tokenIn, address tokenOut, uint256 amountIn, address to ) internal returns (uint256 outAmount) { IUniV2 pair = IUniV2(factory.getPair(tokenIn, tokenOut)); IERC20(tokenIn).transfer(address(pair), amountIn); (uint256 reserve0, uint256 reserve1, ) = pair.getReserves(); if (tokenIn < tokenOut) { outAmount = _getAmountOut(amountIn, reserve0, reserve1); pair.swap(0, outAmount, to, ""); outAmount = _getAmountOut(amountIn, reserve1, reserve0); pair.swap(outAmount, 0, to, ""); } } } else { function withdraw(address _token, address _to, uint256 _value) onlyOwner virtual external { if (_token != address(0)) { _safeTransfer(_token, _to, _value); require(success); } } function withdraw(address _token, address _to, uint256 _value) onlyOwner virtual external { if (_token != address(0)) { _safeTransfer(_token, _to, _value); require(success); } } } else { (bool success, ) = _to.call{value: _value}(""); }
519,786
[ 1, 8924, 364, 357, 2456, 5079, 2430, 1368, 341, 546, 18, 7406, 603, 9946, 13884, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 678, 546, 12373, 353, 1351, 10094, 5161, 280, 288, 203, 203, 565, 871, 1000, 13691, 12, 2867, 8808, 1147, 16, 1758, 10105, 1769, 203, 203, 565, 1758, 1071, 11732, 341, 546, 31, 203, 565, 467, 984, 77, 58, 22, 1733, 1071, 11732, 3272, 31, 203, 203, 565, 2874, 12, 2867, 516, 1758, 13, 1071, 324, 1691, 2852, 31, 203, 203, 203, 565, 3885, 12, 2867, 389, 8443, 16, 1758, 389, 1355, 16, 1758, 389, 6848, 16, 1758, 389, 91, 546, 13, 1351, 10094, 5161, 280, 24899, 8443, 16, 389, 1355, 13, 288, 203, 3639, 3272, 273, 467, 984, 77, 58, 22, 1733, 24899, 6848, 1769, 203, 3639, 341, 546, 273, 389, 91, 546, 31, 203, 565, 289, 203, 203, 565, 445, 14252, 13691, 12, 2867, 389, 2316, 16, 1758, 389, 18337, 13, 3903, 1338, 5541, 288, 203, 3639, 324, 1691, 2852, 63, 67, 2316, 65, 273, 389, 18337, 31, 203, 3639, 3626, 1000, 13691, 24899, 2316, 16, 389, 18337, 1769, 203, 565, 289, 203, 203, 565, 445, 30143, 59, 546, 12, 203, 3639, 1758, 8526, 745, 892, 2430, 16, 203, 3639, 2254, 5034, 8526, 745, 892, 30980, 382, 16, 203, 3639, 2254, 5034, 8526, 745, 892, 5224, 1182, 87, 203, 565, 262, 3903, 1338, 16950, 288, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 2430, 18, 2469, 31, 277, 27245, 288, 203, 203, 5411, 1758, 1147, 382, 273, 2430, 63, 77, 15533, 203, 5411, 1758, 596, 1345, 273, 324, 1691, 2852, 63, 2316, 382, 65, 422, 1758, 12, 20, 2 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.9; // Interfaces import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; // Libraries import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/utils/math/Math.sol"; import "@openzeppelin/contracts/utils/math/SafeCast.sol"; import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol"; library LibERC721 { using Counters for Counters.Counter; using Address for address; using Strings for uint256; bytes32 internal constant ERC721_STORAGE_POSITION = keccak256("nffeels.contracts.erc721.storage"); bytes32 internal constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); bytes32 internal constant PERMIT_TYPEHASH = keccak256( "Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)" ); struct Checkpoint { uint32 fromBlock; uint224 votes; } struct ERC721Storage { // Token name string name; // Token symbol string symbol; // Mapping from token ID to owner address mapping(uint256 => address) owners; // Mapping owner address to token count mapping(address => uint256) balances; // Mapping from token ID to approved address mapping(uint256 => address) tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) operatorApprovals; // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) allTokensIndex; // Optional mapping for token URIs mapping(uint256 => string) tokenURIs; // Mapping of voter delegates mapping(address => address) delegates; // Mapping of voter checkpoints mapping(address => Checkpoint[]) checkpoints; // Array of all balances at a given checkpoint Checkpoint[] totalSupplyCheckpoints; // Mapping of voting weight to token mapping(uint256 => uint256) votingWeightOfToken; // Mapping of voting weight to address mapping(address => uint256) votingWeight; // Mapping of address to nonce mapping(address => Counters.Counter) nonces; // Array of reserved token ids uint256[] reservedTokenIds; // Mapping to check if token id has been reserved mapping(uint256 => bool) isTokenIdReserved; // Wojak id counter Counters.Counter wojakIdCounter; } /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer( address indexed from, address indexed to, uint256 indexed tokenId ); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval( address indexed owner, address indexed approved, uint256 indexed tokenId ); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll( address indexed owner, address indexed operator, bool approved ); /** * @dev Emitted when contract owner stores `data` of `tokenId`. */ event Wojak(uint256 indexed tokenId, string data); /** * @dev Emitted when an account changes their delegate. */ event DelegateChanged( address indexed delegator, address indexed fromDelegate, address indexed toDelegate ); /** * @dev Emitted when a token transfer or delegate change results in changes to an account's voting power. */ event DelegateVotesChanged( address indexed delegate, uint256 previousBalance, uint256 newBalance ); function erc721Storage() internal pure returns (ERC721Storage storage erc721s) { bytes32 position = ERC721_STORAGE_POSITION; assembly { erc721s.slot := position } } /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) internal view returns (address) { address owner = erc721Storage().owners[tokenId]; require( owner != address(0), "ERC721: owner query for nonexistent token" ); return owner; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function baseURI() internal pure returns (string memory) { return ""; } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal { transfer(from, to, tokenId); require( checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function exists(uint256 tokenId) internal view returns (bool) { return erc721Storage().owners[tokenId] != address(0); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeMint( address to, uint256 tokenId, bool isUnique ) internal { safeMint(to, tokenId, isUnique, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function safeMint( address to, uint256 tokenId, bool isUnique, bytes memory _data ) internal { if (isUnique) { erc721Storage().votingWeightOfToken[tokenId] = 3; } else { erc721Storage().votingWeightOfToken[tokenId] = 2; } mint(to, tokenId); require( checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function mint(address to, uint256 tokenId) internal { require(to != address(0), "ERC721: mint to the zero address"); require(!exists(tokenId), "ERC721: token already minted"); require( tokenId <= maxSupply(), "ERC721Votes: total supply risks overflowing votes" ); beforeTokenTransfer(address(0), to, tokenId); erc721Storage().balances[to] += 1; erc721Storage().owners[tokenId] = to; emit Transfer(address(0), to, tokenId); afterTokenTransfer(address(0), to, tokenId); uint256 votingWeightOfToken = erc721Storage().votingWeightOfToken[ tokenId ]; erc721Storage().votingWeight[to] += votingWeightOfToken; writeCheckpoint( erc721Storage().totalSupplyCheckpoints, _add, votingWeightOfToken ); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function burn(uint256 tokenId) internal { address owner = ownerOf(tokenId); beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals approve(address(0), tokenId); erc721Storage().balances[owner] -= 1; delete erc721Storage().owners[tokenId]; emit Transfer(owner, address(0), tokenId); afterTokenTransfer(owner, address(0), tokenId); if (bytes(erc721Storage().tokenURIs[tokenId]).length != 0) { delete erc721Storage().tokenURIs[tokenId]; } uint256 votingWeightOfToken = erc721Storage().votingWeightOfToken[ tokenId ]; erc721Storage().votingWeight[owner] -= votingWeightOfToken; writeCheckpoint( erc721Storage().totalSupplyCheckpoints, _subtract, votingWeightOfToken ); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function transfer( address from, address to, uint256 tokenId ) internal { require( ownerOf(tokenId) == from, "ERC721: transfer of token that is not own" ); require(to != address(0), "ERC721: transfer to the zero address"); beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner approve(address(0), tokenId); erc721Storage().balances[from] -= 1; erc721Storage().balances[to] += 1; erc721Storage().owners[tokenId] = to; emit Transfer(from, to, tokenId); afterTokenTransfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function approve(address to, uint256 tokenId) internal { erc721Storage().tokenApprovals[tokenId] = to; emit Approval(ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received( address(msg.sender), from, tokenId, _data ) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert( "ERC721: transfer to non ERC721Receiver implementer" ); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /* ERC721Enumerable */ /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = _balanceOf(to); erc721Storage().ownedTokens[to][length] = tokenId; erc721Storage().ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function addTokenToAllTokensEnumeration(uint256 tokenId) private { erc721Storage().allTokensIndex[tokenId] = erc721Storage() .allTokens .length; erc721Storage().allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _balanceOf(from) - 1; uint256 tokenIndex = erc721Storage().ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = erc721Storage().ownedTokens[from][ lastTokenIndex ]; erc721Storage().ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token erc721Storage().ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete erc721Storage().ownedTokensIndex[tokenId]; delete erc721Storage().ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = erc721Storage().allTokens.length - 1; uint256 tokenIndex = erc721Storage().allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = erc721Storage().allTokens[lastTokenIndex]; erc721Storage().allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token erc721Storage().allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete erc721Storage().allTokensIndex[tokenId]; erc721Storage().allTokens.pop(); } /* ERC721URIStorage */ /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function setTokenURI(uint256 tokenId, string memory _tokenURI) internal { require( exists(tokenId), "ERC721URIStorage: URI set of nonexistent token" ); require( bytes(_tokenURI).length > 0, "ERC721URIStorage: Invalid token URI" ); erc721Storage().tokenURIs[tokenId] = _tokenURI; } /* ERC721Votes */ /** * @dev Retrieve the number of votes for `account` at the end of `blockNumber`. * * Requirements: * * - `blockNumber` must have been already mined */ function getPastVotes(address account, uint256 blockNumber) internal view returns (uint256) { require(blockNumber < block.number, "ERC721Votes: block not yet mined"); return checkpointsLookup( erc721Storage().checkpoints[account], blockNumber ); } /** * @dev Retrieve the `totalSupply` at the end of `blockNumber`. Note, this value is the sum of all balances. * It is but NOT the sum of all the delegated votes! * * Requirements: * * - `blockNumber` must have been already mined */ function getPastTotalSupply(uint256 blockNumber) internal view returns (uint256) { require(blockNumber < block.number, "ERC721Votes: block not yet mined"); return checkpointsLookup( erc721Storage().totalSupplyCheckpoints, blockNumber ); } /** * @dev Lookup a value in a list of (sorted) checkpoints. */ function checkpointsLookup(Checkpoint[] storage ckpts, uint256 blockNumber) internal view returns (uint256) { // We run a binary search to look for the earliest checkpoint taken after `blockNumber`. // // During the loop, the index of the wanted checkpoint remains in the range [low-1, high). // With each iteration, either `low` or `high` is moved towards the middle of the range to maintain the invariant. // - If the middle checkpoint is after `blockNumber`, we look in [low, mid) // - If the middle checkpoint is before or equal to `blockNumber`, we look in [mid+1, high) // Once we reach a single value (when low == high), we've found the right checkpoint at the index high-1, if not // out of bounds (in which case we're looking too far in the past and the result is 0). // Note that if the latest checkpoint available is exactly for `blockNumber`, we end up with an index that is // past the end of the array, so we technically don't find a checkpoint after `blockNumber`, but it works out // the same. uint256 high = ckpts.length; uint256 low = 0; while (low < high) { uint256 mid = Math.average(low, high); if (ckpts[mid].fromBlock > blockNumber) { high = mid; } else { low = mid + 1; } } return high == 0 ? 0 : ckpts[high - 1].votes; } /** * @dev Maximum token supply. Defaults to `type(uint224).max` (2^224^ - 1). */ function maxSupply() internal pure returns (uint224) { return type(uint224).max; } /** * @dev Change delegation for `delegator` to `delegatee`. * * Emits events {DelegateChanged} and {DelegateVotesChanged}. */ function delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates(delegator); uint256 delegatorVotingWeight = _getVotingWeightOf(delegator); erc721Storage().delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); moveVotingPower(currentDelegate, delegatee, delegatorVotingWeight); } function moveVotingPower( address src, address dst, uint256 amount ) private { if (src != dst && amount > 0) { if (src != address(0)) { (uint256 oldWeight, uint256 newWeight) = writeCheckpoint( erc721Storage().checkpoints[src], _subtract, amount ); emit DelegateVotesChanged(src, oldWeight, newWeight); } if (dst != address(0)) { (uint256 oldWeight, uint256 newWeight) = writeCheckpoint( erc721Storage().checkpoints[dst], _add, amount ); emit DelegateVotesChanged(dst, oldWeight, newWeight); } } } function writeCheckpoint( Checkpoint[] storage ckpts, function(uint256, uint256) view returns (uint256) op, uint256 delta ) private returns (uint256 oldWeight, uint256 newWeight) { uint256 pos = ckpts.length; oldWeight = pos == 0 ? 0 : ckpts[pos - 1].votes; newWeight = op(oldWeight, delta); if (pos > 0 && ckpts[pos - 1].fromBlock == block.number) { ckpts[pos - 1].votes = SafeCast.toUint224(newWeight); } else { ckpts.push( Checkpoint({ fromBlock: SafeCast.toUint32(block.number), votes: SafeCast.toUint224(newWeight) }) ); } } /* ERC721Permit */ /** * @dev "Consume a nonce": return the current value and increment. * * _Available since v4.1._ */ function useNonce(address owner) internal returns (uint256 current) { Counters.Counter storage nonce = erc721Storage().nonces[owner]; current = nonce.current(); nonce.increment(); } /* Hooks */ /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function beforeTokenTransfer( address from, address to, uint256 tokenId ) internal { if (from == address(0)) { addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Move voting power when tokens are transferred. * * Emits a {DelegateVotesChanged} event. */ function afterTokenTransfer( address from, address to, uint256 tokenId ) internal { moveVotingPower( _delegates(from), _delegates(to), erc721Storage().votingWeightOfToken[tokenId] ); } /** * @dev Stores `data` of `tokenId` in event. * * Requirements: * * - Can only be called by contract owner. * - `tokenId` must exist. * - `data` must be specified. * * Emits a {Wojak} event. */ function setEventData(uint256 tokenId, string memory data) internal { require(exists(tokenId), "ERC721: data storage for nonexistent token"); require(bytes(data).length > 0, "ERC721: event data is not specified"); emit Wojak(tokenId, data); } /* Library helper functions */ /** * @dev Returns the number of tokens in ``owner``'s account. */ function _balanceOf(address owner) private view returns (uint256) { require( owner != address(0), "ERC721: balance query for the zero address" ); return erc721Storage().balances[owner]; } function _delegates(address account) private view returns (address) { return erc721Storage().delegates[account]; } function _getVotingWeightOf(address account) private view returns (uint256) { require( account != address(0), "ERC721Votes: voting weight query for the zero address" ); return erc721Storage().votingWeight[account]; } function _add(uint256 a, uint256 b) private pure returns (uint256) { return a + b; } function _subtract(uint256 a, uint256 b) private pure returns (uint256) { return a - b; } }
* @dev Hook that is called before any token transfer. This includes minting and burning. Calling conditions: - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be transferred to `to`. - When `from` is zero, `tokenId` will be minted for `to`. - When `to` is zero, ``from``'s `tokenId` will be burned. - `from` and `to` are never both zero. To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]./
function beforeTokenTransfer( address from, address to, uint256 tokenId ) internal { if (from == address(0)) { addTokenToAllTokensEnumeration(tokenId); removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { removeTokenFromAllTokensEnumeration(tokenId); addTokenToOwnerEnumeration(to, tokenId); } }
1,806,462
[ 1, 5394, 716, 353, 2566, 1865, 1281, 1147, 7412, 18, 1220, 6104, 312, 474, 310, 471, 18305, 310, 18, 21020, 4636, 30, 300, 5203, 1375, 2080, 68, 471, 1375, 869, 68, 854, 3937, 1661, 17, 7124, 16, 12176, 2080, 10335, 11, 87, 1375, 2316, 548, 68, 903, 506, 906, 4193, 358, 1375, 869, 8338, 300, 5203, 1375, 2080, 68, 353, 3634, 16, 1375, 2316, 548, 68, 903, 506, 312, 474, 329, 364, 1375, 869, 8338, 300, 5203, 1375, 869, 68, 353, 3634, 16, 12176, 2080, 10335, 11, 87, 1375, 2316, 548, 68, 903, 506, 18305, 329, 18, 300, 1375, 2080, 68, 471, 1375, 869, 68, 854, 5903, 3937, 3634, 18, 2974, 16094, 1898, 2973, 9153, 16, 910, 358, 15187, 30, 9185, 30, 408, 2846, 17, 16351, 87, 18, 4539, 9940, 17, 10468, 63, 7736, 13725, 87, 8009, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1865, 1345, 5912, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 1147, 548, 203, 565, 262, 2713, 288, 203, 3639, 309, 261, 2080, 422, 1758, 12, 20, 3719, 288, 203, 5411, 527, 1345, 774, 1595, 5157, 21847, 12, 2316, 548, 1769, 203, 5411, 1206, 1345, 1265, 5541, 21847, 12, 2080, 16, 1147, 548, 1769, 203, 3639, 289, 203, 3639, 309, 261, 869, 422, 1758, 12, 20, 3719, 288, 203, 5411, 1206, 1345, 1265, 1595, 5157, 21847, 12, 2316, 548, 1769, 203, 5411, 527, 1345, 774, 5541, 21847, 12, 869, 16, 1147, 548, 1769, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.8.0; // ==================================================================== // | ______ _______ | // | / _____________ __ __ / ____(_____ ____ _____ ________ | // | / /_ / ___/ __ `| |/_/ / /_ / / __ \/ __ `/ __ \/ ___/ _ \ | // | / __/ / / / /_/ _> < / __/ / / / / / /_/ / / / / /__/ __/ | // | /_/ /_/ \__,_/_/|_| /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/ | // | | // ==================================================================== // ========================== TokenTrackerV2 ========================== // ==================================================================== // Tracks the value of protocol-owned ERC tokens (and ETH too) so they // can be added to the global collateral value. // Frax Finance: https://github.com/FraxFinance // Primary Author(s) // Travis Moore: https://github.com/FortisFortuna // Reviewer(s) / Contributor(s) // Jason Huan: https://github.com/jasonhuan // Sam Kazemian: https://github.com/samkazemian import "../Math/SafeMath.sol"; import "../Oracle/ComboOracle.sol"; import "../Frax/IFrax.sol"; import "../Frax/IFraxAMOMinter.sol"; import '../Uniswap/TransferHelper.sol'; import "../ERC20/ERC20.sol"; import "../Staking/Owned.sol"; contract TokenTrackerV2 is Owned { using SafeMath for uint256; // SafeMath automatically included in Solidity >= 8.0.0 /* ========== STATE VARIABLES ========== */ IFrax public IFRAX = IFrax(0x853d955aCEf822Db058eb8505911ED77F175b99e); IFraxAMOMinter public amo_minter; ComboOracle public ethUSDOracle; // Tracked addresses address[] public tracked_addresses; mapping(address => bool) public is_address_tracked; // tracked address => is tracked mapping(address => address[]) public tokens_for_address; // tracked address => tokens to track // Oracle related mapping(address => OracleCRInfo) public oracle_cr_infos; // token address => oracle_address uint256 public chainlink_eth_usd_decimals; address public timelock_address; address public custodian_address; uint256 public PRICE_PRECISION = 1e6; uint256 public PRECISE_PRICE_PRECISION = 1e18; bool public use_stored_cr = true; uint256 public stored_cr; /* ========== STRUCTS ========== */ struct TrackingTokensBatch { address tracked_address; address[] token_addresses; } struct OracleCRInfo { address token_address; address oracle_address; bool use_cr; } /* ========== CONSTRUCTOR ========== */ constructor ( address _owner_address, address _amo_minter_address, address _eth_oracle_address, address[] memory _initial_tracked_addresses ) Owned(_owner_address) { amo_minter = IFraxAMOMinter(_amo_minter_address); ethUSDOracle = ComboOracle(_eth_oracle_address); // Get the custodian and timelock addresses from the minter custodian_address = amo_minter.custodian_address(); timelock_address = amo_minter.timelock_address(); // Refresh the stored CR stored_cr = IFRAX.global_collateral_ratio(); // Set the initial tracked addresses for (uint256 i = 0; i < _initial_tracked_addresses.length; i++){ address tracked_addr = _initial_tracked_addresses[i]; tracked_addresses.push(tracked_addr); is_address_tracked[tracked_addr] = true; } // // Add the oracle information for each token // for (uint256 i = 0; i < _initial_token_oracles.length; i++){ // OracleCRInfo memory thisOracleCRInfo = _initial_token_oracles[i]; // oracle_cr_infos[thisOracleCRInfo.token_address] = thisOracleCRInfo; // } // // Add the tracked tokens for each tracked address // for (uint256 i = 0; i < _initial_tracked_tokens.length; i++){ // TrackingTokensBatch memory thisTrackingConstruct = _initial_tracked_tokens[i]; // for (uint256 j = 0; j < thisTrackingConstruct.token_addresses.length; j++){ // tokens_for_address[thisTrackingConstruct.tracked_address].push(thisTrackingConstruct.token_addresses[j]); // } // } } /* ========== MODIFIERS ========== */ modifier onlyByOwnGov() { require(msg.sender == timelock_address || msg.sender == owner, "Not owner or timelock"); _; } modifier onlyByOwnGovCust() { require(msg.sender == timelock_address || msg.sender == owner || msg.sender == custodian_address, "Not owner, tlck, or custd"); _; } modifier onlyByMinter() { require(msg.sender == address(amo_minter), "Not minter"); _; } /* ========== VIEWS ========== */ function showAllocations() public view returns (uint256[1] memory allocations) { allocations[0] = getTotalValue(false); // Total Value } function dollarBalances() public view returns (uint256 frax_val_e18, uint256 collat_val_e18) { frax_val_e18 = getTotalValue(false); // Ignores CR logic collat_val_e18 = getTotalValue(true); // Uses CR logic } // Backwards compatibility function mintedBalance() public view returns (int256) { return amo_minter.frax_mint_balances(address(this)); } function allTrackedAddresses() public view returns (address[] memory) { return tracked_addresses; } function allTokensForAddress(address tracked_address) public view returns (address[] memory) { return tokens_for_address[tracked_address]; } function getCR() public view returns (uint256) { if (use_stored_cr) return stored_cr; else { return IFRAX.global_collateral_ratio(); } } // In USD // Gets value of a single token in an address function getTokenValueInAddress(address tracked_address, address token_address, bool use_cr_logic) public view returns (uint256 value_usd_e18) { require(is_address_tracked[tracked_address], "Address not being tracked"); OracleCRInfo memory thisOracleCRInfo = oracle_cr_infos[token_address]; // Get value of raw ETH first if (token_address == address(0)){ value_usd_e18 = (tracked_address.balance * ethUSDOracle.getETHPricePrecise()) / PRECISE_PRICE_PRECISION; } else { ( uint256 precise_price, , ) = ComboOracle(thisOracleCRInfo.oracle_address).getTokenPrice(token_address); uint256 missing_decimals = uint256(18) - ERC20(token_address).decimals(); // Scale up to E18 uint256 value_to_add = (((ERC20(token_address).balanceOf(tracked_address) * (10 ** missing_decimals)) * precise_price) / (PRECISE_PRICE_PRECISION)); // If applicable, multiply by the CR. Used for dollarBalances and collatDollarBalance tracking if (use_cr_logic && thisOracleCRInfo.use_cr){ value_to_add = (value_to_add * getCR()) / PRICE_PRECISION; } value_usd_e18 += value_to_add; } } // In USD // Gets value of all the ETH and tracked tokens in an address function getValueInAddress(address tracked_address, bool use_cr_logic) public view returns (uint256 value_usd_e18) { require(is_address_tracked[tracked_address], "Address not being tracked"); // Get token values address[] memory tracked_token_arr = tokens_for_address[tracked_address]; for (uint i = 0; i < tracked_token_arr.length; i++){ address the_token_addr = tracked_token_arr[i]; value_usd_e18 += getTokenValueInAddress(tracked_address, the_token_addr, use_cr_logic); } } // In USD function getTotalValue(bool use_cr_logic) public view returns (uint256 value_usd_e18) { // Initialize value_usd_e18 = 0; // Loop through all of the tracked addresses for (uint i = 0; i < tracked_addresses.length; i++){ if (tracked_addresses[i] != address(0)) { value_usd_e18 += getValueInAddress(tracked_addresses[i], use_cr_logic); } } } /* ========== PUBLICALLY CALLABLE ========== */ function refreshCR() public { stored_cr = IFRAX.global_collateral_ratio(); } /* ========== RESTRICTED GOVERNANCE FUNCTIONS ========== */ function setAMOMinter(address _amo_minter_address) external onlyByOwnGov { amo_minter = IFraxAMOMinter(_amo_minter_address); // Get the custodian and timelock addresses from the minter custodian_address = amo_minter.custodian_address(); timelock_address = amo_minter.timelock_address(); // Make sure the new addresses are not address(0) require(custodian_address != address(0) && timelock_address != address(0), "Invalid custodian or timelock"); } function toggleUseStoredCR() external onlyByOwnGovCust { use_stored_cr = !use_stored_cr; } // ---------------- Oracle Related ---------------- function setTokenOracleCRInfo(address token_address, address oracle_address, bool use_cr) public onlyByOwnGov { // Make sure the oracle is valid ( uint256 precise_price, , ) = ComboOracle(oracle_address).getTokenPrice(token_address); require(precise_price > 0, "Invalid Oracle"); oracle_cr_infos[token_address].token_address = token_address; oracle_cr_infos[token_address].oracle_address = oracle_address; oracle_cr_infos[token_address].use_cr = use_cr; } function batchSetTokenOracleCRInfo(OracleCRInfo[] memory _oracle_cr_infos) public onlyByOwnGov { for (uint256 i = 0; i < _oracle_cr_infos.length; i++){ OracleCRInfo memory thisOracle = _oracle_cr_infos[i]; setTokenOracleCRInfo(thisOracle.token_address, thisOracle.oracle_address, thisOracle.use_cr); } } // ---------------- Tracked Address Related ---------------- function toggleTrackedAddress(address tracked_address) public onlyByOwnGov { is_address_tracked[tracked_address] = !is_address_tracked[tracked_address]; } function addTrackedAddress(address tracked_address) public onlyByOwnGov { for (uint i = 0; i < tracked_addresses.length; i++){ if (tracked_addresses[i] == tracked_address) { revert("Address already present"); } } // Add in the address is_address_tracked[tracked_address] = true; tracked_addresses.push(tracked_address); } function removeTrackedAddress(address tracked_address) public onlyByOwnGov { is_address_tracked[tracked_address] = false; // 'Delete' from the array by setting the address to 0x0 for (uint i = 0; i < tracked_addresses.length; i++){ if (tracked_addresses[i] == tracked_address) { tracked_addresses[i] = address(0); // This will leave a null in the array and keep the indices the same // Remove the tracked token entries too delete tokens_for_address[tracked_address]; break; } } } // ---------------- Token Related ---------------- function batchAddTokensForAddress(address tracked_address, address[] memory token_addresses) public onlyByOwnGov { for (uint i = 0; i < token_addresses.length; i++){ addTokenForAddress(tracked_address, token_addresses[i]); } } function addTokenForAddress(address tracked_address, address token_address) public onlyByOwnGov { // Make sure the oracle info is present already require(oracle_cr_infos[token_address].oracle_address != address(0), "Add Oracle info first"); address[] memory tracked_token_arr = tokens_for_address[tracked_address]; for (uint i = 0; i < tracked_token_arr.length; i++){ if (tracked_token_arr[i] == tracked_address) { revert("Token already present"); } } tokens_for_address[tracked_address].push(token_address); } function removeTokenForAddress(address tracked_address, address token_address) public onlyByOwnGov { address[] memory tracked_token_arr = tokens_for_address[tracked_address]; // 'Delete' from the array by setting the address to 0x0 for (uint i = 0; i < tracked_token_arr.length; i++){ if (tracked_token_arr[i] == token_address) { tokens_for_address[tracked_address][i] = address(0); // This will leave a null in the array and keep the indices the same break; } } } // ---------------- Other ---------------- function recoverERC20(address tokenAddress, uint256 tokenAmount) external onlyByOwnGov { TransferHelper.safeTransfer(address(tokenAddress), msg.sender, tokenAmount); } // Generic proxy function execute( address _to, uint256 _value, bytes calldata _data ) external onlyByOwnGov returns (bool, bytes memory) { (bool success, bytes memory result) = _to.call{value:_value}(_data); return (success, result); } }
Make sure the oracle is valid
function setTokenOracleCRInfo(address token_address, address oracle_address, bool use_cr) public onlyByOwnGov { ( uint256 precise_price, , ) = ComboOracle(oracle_address).getTokenPrice(token_address); require(precise_price > 0, "Invalid Oracle"); oracle_cr_infos[token_address].token_address = token_address; oracle_cr_infos[token_address].oracle_address = oracle_address; oracle_cr_infos[token_address].use_cr = use_cr; }
5,533,940
[ 1, 6464, 3071, 326, 20865, 353, 923, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 22629, 23601, 5093, 966, 12, 2867, 1147, 67, 2867, 16, 1758, 20865, 67, 2867, 16, 1426, 999, 67, 3353, 13, 1071, 1338, 858, 5460, 43, 1527, 288, 203, 3639, 261, 2254, 5034, 31293, 67, 8694, 16, 269, 262, 273, 1286, 1075, 23601, 12, 280, 16066, 67, 2867, 2934, 588, 1345, 5147, 12, 2316, 67, 2867, 1769, 203, 3639, 2583, 12, 4036, 784, 67, 8694, 405, 374, 16, 315, 1941, 28544, 8863, 203, 203, 3639, 20865, 67, 3353, 67, 18227, 63, 2316, 67, 2867, 8009, 2316, 67, 2867, 273, 1147, 67, 2867, 31, 203, 3639, 20865, 67, 3353, 67, 18227, 63, 2316, 67, 2867, 8009, 280, 16066, 67, 2867, 273, 20865, 67, 2867, 31, 203, 3639, 20865, 67, 3353, 67, 18227, 63, 2316, 67, 2867, 8009, 1202, 67, 3353, 273, 999, 67, 3353, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/137/0x15ea2BdAbD01E09CeD4581deF149407002A81FBe/sources/src/vaults/ImpactVault.sol
* @notice Generic hook called on "mint", "burn", "transfer" and for "transferFrom" vault tokens. @dev Important to update yield indices so that yield starts being attributed to new "to" address. Ignores null address values (from mint and burn)./
function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual override { if (from != address(0)) { _updateYieldIndexSinceLastUpdate(from, amount, false); } if (to != address(0)) { _updateYieldIndexSinceLastUpdate(to, amount, true); } }
4,743,888
[ 1, 7014, 3953, 2566, 603, 315, 81, 474, 3113, 315, 70, 321, 3113, 315, 13866, 6, 471, 364, 315, 13866, 1265, 6, 225, 9229, 2430, 18, 225, 6164, 970, 358, 1089, 2824, 4295, 1427, 716, 2824, 2542, 3832, 5885, 4817, 358, 394, 315, 869, 6, 1758, 18, 467, 1600, 3485, 446, 1758, 924, 261, 2080, 312, 474, 471, 18305, 2934, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 5205, 1345, 5912, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 3844, 203, 565, 262, 2713, 5024, 3849, 288, 203, 3639, 309, 261, 2080, 480, 1758, 12, 20, 3719, 288, 203, 5411, 389, 2725, 16348, 1016, 9673, 3024, 1891, 12, 2080, 16, 3844, 16, 629, 1769, 203, 3639, 289, 203, 3639, 309, 261, 869, 480, 1758, 12, 20, 3719, 288, 203, 5411, 389, 2725, 16348, 1016, 9673, 3024, 1891, 12, 869, 16, 3844, 16, 638, 1769, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: LGPL-3.0-or-later pragma solidity 0.7.6; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Pausable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; import "./interfaces/IVoucherSets.sol"; import "./interfaces/IVouchers.sol"; import "./interfaces/IVoucherKernel.sol"; import {PaymentMethod, VoucherState, VoucherStatus, isStateCommitted, isStateRedemptionSigned, isStateRefunded, isStateExpired, isStatus, determineStatus} from "./UsingHelpers.sol"; //preparing for ERC-1066, ERC-1444, EIP-838 /** * @title VoucherKernel contract controls the core business logic * @dev Notes: * - The usage of block.timestamp is honored since vouchers are defined currently with day-precision. * See: https://ethereum.stackexchange.com/questions/5924/how-do-ethereum-mining-nodes-maintain-a-time-consistent-with-the-network/5931#5931 */ // solhint-disable-next-line contract VoucherKernel is IVoucherKernel, Ownable, Pausable, ReentrancyGuard { using Address for address; using SafeMath for uint256; //ERC1155 contract representing voucher sets address private voucherSetTokenAddress; //ERC721 contract representing vouchers; address private voucherTokenAddress; //promise for an asset could be reusable, but simplified here for brevity struct Promise { bytes32 promiseId; uint256 nonce; //the asset that is offered address seller; //the seller who created the promise //we simplify the value for the demoapp, otherwise voucher details would be packed in one bytes32 field value uint256 validFrom; uint256 validTo; uint256 price; uint256 depositSe; uint256 depositBu; uint256 idx; } struct VoucherPaymentMethod { PaymentMethod paymentMethod; address addressTokenPrice; address addressTokenDeposits; } address private bosonRouterAddress; //address of the Boson Router contract address private cashierAddress; //address of the Cashier contract mapping(bytes32 => Promise) private promises; //promises to deliver goods or services mapping(address => uint256) private tokenNonces; //mapping between seller address and its own nonces. Every time seller creates supply ID it gets incremented. Used to avoid duplicate ID's mapping(uint256 => VoucherPaymentMethod) private paymentDetails; // tokenSupplyId to VoucherPaymentMethod bytes32[] private promiseKeys; mapping(uint256 => bytes32) private ordersPromise; //mapping between an order (supply a.k.a. VoucherSet) and a promise mapping(uint256 => VoucherStatus) private vouchersStatus; //recording the vouchers evolution //ID reqs mapping(uint256 => uint256) private typeCounters; //counter for ID of a particular type of NFT uint256 private constant MASK_TYPE = uint256(uint128(~0)) << 128; //the type mask in the upper 128 bits //1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 uint256 private constant MASK_NF_INDEX = uint128(~0); //the non-fungible index mask in the lower 128 //0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000011111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111 uint256 private constant TYPE_NF_BIT = 1 << 255; //the first bit represents an NFT type //1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 uint256 private typeId; //base token type ... 127-bits cover 1.701411835*10^38 types (not differentiating between FTs and NFTs) /* Token IDs: Fungibles: 0, followed by 127-bit FT type ID, in the upper 128 bits, followed by 0 in lower 128-bits <0><uint127: base token id><uint128: 0> Non-fungible VoucherSets (supply tokens): 1, followed by 127-bit NFT type ID, in the upper 128 bits, followed by 0 in lower 128-bits <1><uint127: base token id><uint128: 0 Non-fungible vouchers: 1, followed by 127-bit NFT type ID, in the upper 128 bits, followed by a 1-based index of an NFT token ID. <1><uint127: base token id><uint128: index of non-fungible> */ uint256 private complainPeriod; uint256 private cancelFaultPeriod; event LogPromiseCreated( bytes32 indexed _promiseId, uint256 indexed _nonce, address indexed _seller, uint256 _validFrom, uint256 _validTo, uint256 _idx ); event LogVoucherCommitted( uint256 indexed _tokenIdSupply, uint256 _tokenIdVoucher, address _issuer, address _holder, bytes32 _promiseId ); event LogVoucherRedeemed( uint256 _tokenIdVoucher, address _holder, bytes32 _promiseId ); event LogVoucherRefunded(uint256 _tokenIdVoucher); event LogVoucherComplain(uint256 _tokenIdVoucher); event LogVoucherFaultCancel(uint256 _tokenIdVoucher); event LogExpirationTriggered(uint256 _tokenIdVoucher, address _triggeredBy); event LogFinalizeVoucher(uint256 _tokenIdVoucher, address _triggeredBy); event LogBosonRouterSet(address _newBosonRouter, address _triggeredBy); event LogCashierSet(address _newCashier, address _triggeredBy); event LogVoucherTokenContractSet(address _newTokenContract, address _triggeredBy); event LogVoucherSetTokenContractSet(address _newTokenContract, address _triggeredBy); event LogComplainPeriodChanged( uint256 _newComplainPeriod, address _triggeredBy ); event LogCancelFaultPeriodChanged( uint256 _newCancelFaultPeriod, address _triggeredBy ); event LogVoucherSetFaultCancel(uint256 _tokenIdSupply, address _issuer); event LogFundsReleased( uint256 _tokenIdVoucher, uint8 _type //0 .. payment, 1 .. deposits ); /** * @notice Checks that only the BosonRouter contract can call a function */ modifier onlyFromRouter() { require(msg.sender == bosonRouterAddress, "UNAUTHORIZED_BR"); _; } /** * @notice Checks that only the Cashier contract can call a function */ modifier onlyFromCashier() { require(msg.sender == cashierAddress, "UNAUTHORIZED_C"); _; } /** * @notice Checks that only the owver of the specified voucher can call a function */ modifier onlyVoucherOwner(uint256 _tokenIdVoucher, address _sender) { //check authorization require( IVouchers(voucherTokenAddress).ownerOf(_tokenIdVoucher) == _sender, "UNAUTHORIZED_V" ); _; } modifier notZeroAddress(address _addressToCheck) { require(_addressToCheck != address(0), "0A"); _; } /** * @notice Construct and initialze the contract. Iniialises associated contract addresses, the complain period, and the cancel or fault period * @param _bosonRouterAddress address of the associated BosonRouter contract * @param _cashierAddress address of the associated Cashier contract * @param _voucherSetTokenAddress address of the associated ERC1155 contract instance * @param _voucherTokenAddress address of the associated ERC721 contract instance */ constructor(address _bosonRouterAddress, address _cashierAddress, address _voucherSetTokenAddress, address _voucherTokenAddress) notZeroAddress(_bosonRouterAddress) notZeroAddress(_cashierAddress) notZeroAddress(_voucherSetTokenAddress) notZeroAddress(_voucherTokenAddress) { bosonRouterAddress = _bosonRouterAddress; cashierAddress = _cashierAddress; voucherSetTokenAddress = _voucherSetTokenAddress; voucherTokenAddress = _voucherTokenAddress; complainPeriod = 7 * 1 days; cancelFaultPeriod = 7 * 1 days; } /** * @notice Pause the process of interaction with voucherID's (ERC-721), in case of emergency. * Only BR contract is in control of this function. */ function pause() external override onlyFromRouter { _pause(); } /** * @notice Unpause the process of interaction with voucherID's (ERC-721). * Only BR contract is in control of this function. */ function unpause() external override onlyFromRouter { _unpause(); } /** * @notice Creating a new promise for goods or services. * Can be reused, e.g. for making different batches of these (in the future). * @param _seller seller of the promise * @param _validFrom Start of valid period * @param _validTo End of valid period * @param _price Price (payment amount) * @param _depositSe Seller's deposit * @param _depositBu Buyer's deposit */ function createTokenSupplyId( address _seller, uint256 _validFrom, uint256 _validTo, uint256 _price, uint256 _depositSe, uint256 _depositBu, uint256 _quantity ) external override nonReentrant onlyFromRouter returns (uint256) { require(_quantity > 0, "INVALID_QUANTITY"); // solhint-disable-next-line not-rely-on-time require(_validTo >= block.timestamp + 5 minutes, "INVALID_VALIDITY_TO"); require(_validTo >= _validFrom.add(5 minutes), "VALID_FROM_MUST_BE_AT_LEAST_5_MINUTES_LESS_THAN_VALID_TO"); bytes32 key; key = keccak256( abi.encodePacked(_seller, tokenNonces[_seller]++, _validFrom, _validTo, address(this)) ); if (promiseKeys.length > 0) { require( promiseKeys[promises[key].idx] != key, "PROMISE_ALREADY_EXISTS" ); } promises[key] = Promise({ promiseId: key, nonce: tokenNonces[_seller], seller: _seller, validFrom: _validFrom, validTo: _validTo, price: _price, depositSe: _depositSe, depositBu: _depositBu, idx: promiseKeys.length }); promiseKeys.push(key); emit LogPromiseCreated( key, tokenNonces[_seller], _seller, _validFrom, _validTo, promiseKeys.length - 1 ); return createOrder(_seller, key, _quantity); } /** * @notice Creates a Payment method struct recording the details on how the seller requires to receive Price and Deposits for a certain Voucher Set. * @param _tokenIdSupply _tokenIdSupply of the voucher set this is related to * @param _paymentMethod might be ETHETH, ETHTKN, TKNETH or TKNTKN * @param _tokenPrice token address which will hold the funds for the price of the voucher * @param _tokenDeposits token address which will hold the funds for the deposits of the voucher */ function createPaymentMethod( uint256 _tokenIdSupply, PaymentMethod _paymentMethod, address _tokenPrice, address _tokenDeposits ) external override onlyFromRouter { paymentDetails[_tokenIdSupply] = VoucherPaymentMethod({ paymentMethod: _paymentMethod, addressTokenPrice: _tokenPrice, addressTokenDeposits: _tokenDeposits }); } /** * @notice Create an order for offering a certain quantity of an asset * This creates a listing in a marketplace, technically as an ERC-1155 non-fungible token with supply. * @param _seller seller of the promise * @param _promiseId ID of a promise (simplified into asset for demo) * @param _quantity Quantity of assets on offer */ function createOrder( address _seller, bytes32 _promiseId, uint256 _quantity ) private returns (uint256) { //create & assign a new non-fungible type typeId++; uint256 tokenIdSupply = TYPE_NF_BIT | (typeId << 128); //upper bit is 1, followed by sequence, leaving lower 128-bits as 0; ordersPromise[tokenIdSupply] = _promiseId; IVoucherSets(voucherSetTokenAddress).mint( _seller, tokenIdSupply, _quantity, "" ); return tokenIdSupply; } /** * @notice Fill Voucher Order, iff funds paid, then extract & mint NFT to the voucher holder * @param _tokenIdSupply ID of the supply token (ERC-1155) * @param _issuer Address of the token's issuer * @param _holder Address of the recipient of the voucher (ERC-721) * @param _paymentMethod method being used for that particular order that needs to be fulfilled */ function fillOrder( uint256 _tokenIdSupply, address _issuer, address _holder, PaymentMethod _paymentMethod ) external override onlyFromRouter nonReentrant { require(_doERC721HolderCheck(_issuer, _holder, _tokenIdSupply), "UNSUPPORTED_ERC721_RECEIVED"); PaymentMethod paymentMethod = getVoucherPaymentMethod(_tokenIdSupply); //checks require(paymentMethod == _paymentMethod, "Incorrect Payment Method"); checkOrderFillable(_tokenIdSupply, _issuer, _holder); //close order uint256 voucherTokenId = extract721(_issuer, _holder, _tokenIdSupply); emit LogVoucherCommitted( _tokenIdSupply, voucherTokenId, _issuer, _holder, getPromiseIdFromVoucherId(voucherTokenId) ); } /** * @notice Check if holder is a contract that supports ERC721 * @dev ERC-721 * https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v4.4.0-rc.0/contracts/token/ERC721/ERC721.sol * @param _from Address of sender * @param _to Address of recipient * @param _tokenId ID of the token */ function _doERC721HolderCheck( address _from, address _to, uint256 _tokenId ) internal returns (bool) { if (_to.isContract()) { try IERC721Receiver(_to).onERC721Received(_msgSender(), _from, _tokenId, "") returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("UNSUPPORTED_ERC721_RECEIVED"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @notice Check order is fillable * @dev Will throw if checks don't pass * @param _tokenIdSupply ID of the supply token * @param _issuer Address of the token's issuer * @param _holder Address of the recipient of the voucher (ERC-721) */ function checkOrderFillable( uint256 _tokenIdSupply, address _issuer, address _holder ) internal view notZeroAddress(_holder) { require(_tokenIdSupply != 0, "UNSPECIFIED_ID"); require( IVoucherSets(voucherSetTokenAddress).balanceOf(_issuer, _tokenIdSupply) > 0, "OFFER_EMPTY" ); bytes32 promiseKey = ordersPromise[_tokenIdSupply]; require( promises[promiseKey].validTo >= block.timestamp, "OFFER_EXPIRED" ); } /** * @notice Extract a standard non-fungible token ERC-721 from a supply stored in ERC-1155 * @dev Token ID is derived following the same principles for both ERC-1155 and ERC-721 * @param _issuer The address of the token issuer * @param _to The address of the token holder * @param _tokenIdSupply ID of the token type * @return ID of the voucher token */ function extract721( address _issuer, address _to, uint256 _tokenIdSupply ) internal returns (uint256) { IVoucherSets(voucherSetTokenAddress).burn(_issuer, _tokenIdSupply, 1); // This is hardcoded as 1 on purpose //calculate tokenId uint256 voucherTokenId = _tokenIdSupply | ++typeCounters[_tokenIdSupply]; //set status vouchersStatus[voucherTokenId].status = determineStatus( vouchersStatus[voucherTokenId].status, VoucherState.COMMIT ); vouchersStatus[voucherTokenId].isPaymentReleased = false; vouchersStatus[voucherTokenId].isDepositsReleased = false; //mint voucher NFT as ERC-721 IVouchers(voucherTokenAddress).mint(_to, voucherTokenId); return voucherTokenId; } /* solhint-disable */ /** * @notice Redemption of the vouchers promise * @param _tokenIdVoucher ID of the voucher * @param _messageSender account that called the fn from the BR contract */ function redeem(uint256 _tokenIdVoucher, address _messageSender) external override whenNotPaused onlyFromRouter onlyVoucherOwner(_tokenIdVoucher, _messageSender) { //check status require( isStateCommitted(vouchersStatus[_tokenIdVoucher].status), "ALREADY_PROCESSED" ); //check validity period isInValidityPeriod(_tokenIdVoucher); Promise memory tPromise = promises[getPromiseIdFromVoucherId(_tokenIdVoucher)]; vouchersStatus[_tokenIdVoucher].complainPeriodStart = block.timestamp; vouchersStatus[_tokenIdVoucher].status = determineStatus( vouchersStatus[_tokenIdVoucher].status, VoucherState.REDEEM ); emit LogVoucherRedeemed( _tokenIdVoucher, _messageSender, tPromise.promiseId ); } // // // // // // // // // UNHAPPY PATH // // // // // // // // /** * @notice Refunding a voucher * @param _tokenIdVoucher ID of the voucher * @param _messageSender account that called the fn from the BR contract */ function refund(uint256 _tokenIdVoucher, address _messageSender) external override whenNotPaused onlyFromRouter onlyVoucherOwner(_tokenIdVoucher, _messageSender) { require( isStateCommitted(vouchersStatus[_tokenIdVoucher].status), "INAPPLICABLE_STATUS" ); //check validity period isInValidityPeriod(_tokenIdVoucher); vouchersStatus[_tokenIdVoucher].complainPeriodStart = block.timestamp; vouchersStatus[_tokenIdVoucher].status = determineStatus( vouchersStatus[_tokenIdVoucher].status, VoucherState.REFUND ); emit LogVoucherRefunded(_tokenIdVoucher); } /** * @notice Issue a complaint for a voucher * @param _tokenIdVoucher ID of the voucher * @param _messageSender account that called the fn from the BR contract */ function complain(uint256 _tokenIdVoucher, address _messageSender) external override whenNotPaused onlyFromRouter onlyVoucherOwner(_tokenIdVoucher, _messageSender) { checkIfApplicableAndResetPeriod(_tokenIdVoucher, VoucherState.COMPLAIN); } /** * @notice Cancel/Fault transaction by the Seller, admitting to a fault or backing out of the deal * @param _tokenIdVoucher ID of the voucher * @param _messageSender account that called the fn from the BR contract */ function cancelOrFault(uint256 _tokenIdVoucher, address _messageSender) external override onlyFromRouter whenNotPaused { uint256 tokenIdSupply = getIdSupplyFromVoucher(_tokenIdVoucher); require( getSupplyHolder(tokenIdSupply) == _messageSender, "UNAUTHORIZED_COF" ); checkIfApplicableAndResetPeriod(_tokenIdVoucher, VoucherState.CANCEL_FAULT); } /** * @notice Check if voucher status can be changed into desired new status. If yes, the waiting period is resetted, depending on what new status is. * @param _tokenIdVoucher ID of the voucher * @param _newStatus desired new status, can be {COF, COMPLAIN} */ function checkIfApplicableAndResetPeriod(uint256 _tokenIdVoucher, VoucherState _newStatus) internal { uint8 tStatus = vouchersStatus[_tokenIdVoucher].status; require( !isStatus(tStatus, VoucherState.FINAL), "ALREADY_FINALIZED" ); string memory revertReasonAlready; string memory revertReasonExpired; if (_newStatus == VoucherState.COMPLAIN) { revertReasonAlready = "ALREADY_COMPLAINED"; revertReasonExpired = "COMPLAINPERIOD_EXPIRED"; } else { revertReasonAlready = "ALREADY_CANCELFAULT"; revertReasonExpired = "COFPERIOD_EXPIRED"; } require( !isStatus(tStatus, _newStatus), revertReasonAlready ); Promise memory tPromise = promises[getPromiseIdFromVoucherId(_tokenIdVoucher)]; if ( isStateRedemptionSigned(tStatus) || isStateRefunded(tStatus) ) { require( block.timestamp <= vouchersStatus[_tokenIdVoucher].complainPeriodStart + complainPeriod + cancelFaultPeriod, revertReasonExpired ); } else if (isStateExpired(tStatus)) { //if redeemed or refunded require( block.timestamp <= tPromise.validTo + complainPeriod + cancelFaultPeriod, revertReasonExpired ); } else if ( //if the opposite of what is the desired new state. When doing COMPLAIN we need to check if already in COF (and vice versa), since the waiting periods are different. // VoucherState.COMPLAIN has enum index value 2, while VoucherState.CANCEL_FAULT has enum index value 1. To check the opposite status we use transformation "% 2 + 1" which maps 2 to 1 and 1 to 2 isStatus(vouchersStatus[_tokenIdVoucher].status, VoucherState((uint8(_newStatus) % 2 + 1))) // making it VoucherState.COMPLAIN or VoucherState.CANCEL_FAULT (opposite to new status) ) { uint256 waitPeriod = _newStatus == VoucherState.COMPLAIN ? vouchersStatus[_tokenIdVoucher].complainPeriodStart + complainPeriod : vouchersStatus[_tokenIdVoucher].cancelFaultPeriodStart + cancelFaultPeriod; require( block.timestamp <= waitPeriod, revertReasonExpired ); } else if (_newStatus != VoucherState.COMPLAIN && isStateCommitted(tStatus)) { //if committed only (applicable only in COF) require( block.timestamp <= tPromise.validTo + complainPeriod + cancelFaultPeriod, "COFPERIOD_EXPIRED" ); } else { revert("INAPPLICABLE_STATUS"); } vouchersStatus[_tokenIdVoucher].status = determineStatus( tStatus, _newStatus ); if (_newStatus == VoucherState.COMPLAIN) { if (!isStatus(tStatus, VoucherState.CANCEL_FAULT)) { vouchersStatus[_tokenIdVoucher].cancelFaultPeriodStart = block .timestamp; //COF period starts } emit LogVoucherComplain(_tokenIdVoucher); } else { if (!isStatus(tStatus, VoucherState.COMPLAIN)) { vouchersStatus[_tokenIdVoucher].complainPeriodStart = block .timestamp; //complain period starts } emit LogVoucherFaultCancel(_tokenIdVoucher); } } /** * @notice Cancel/Fault transaction by the Seller, cancelling the remaining uncommitted voucher set so that seller prevents buyers from committing to vouchers for items no longer in exchange. * @param _tokenIdSupply ID of the voucher set * @param _issuer owner of the voucher */ function cancelOrFaultVoucherSet(uint256 _tokenIdSupply, address _issuer) external override onlyFromRouter nonReentrant whenNotPaused returns (uint256) { require(getSupplyHolder(_tokenIdSupply) == _issuer, "UNAUTHORIZED_COF"); uint256 remQty = getRemQtyForSupply(_tokenIdSupply, _issuer); require(remQty > 0, "OFFER_EMPTY"); IVoucherSets(voucherSetTokenAddress).burn(_issuer, _tokenIdSupply, remQty); emit LogVoucherSetFaultCancel(_tokenIdSupply, _issuer); return remQty; } // // // // // // // // // BACK-END PROCESS // // // // // // // // /** * @notice Mark voucher token that the payment was released * @param _tokenIdVoucher ID of the voucher token */ function setPaymentReleased(uint256 _tokenIdVoucher) external override onlyFromCashier { require(_tokenIdVoucher != 0, "UNSPECIFIED_ID"); vouchersStatus[_tokenIdVoucher].isPaymentReleased = true; emit LogFundsReleased(_tokenIdVoucher, 0); } /** * @notice Mark voucher token that the deposits were released * @param _tokenIdVoucher ID of the voucher token */ function setDepositsReleased(uint256 _tokenIdVoucher) external override onlyFromCashier { require(_tokenIdVoucher != 0, "UNSPECIFIED_ID"); vouchersStatus[_tokenIdVoucher].isDepositsReleased = true; emit LogFundsReleased(_tokenIdVoucher, 1); } /** * @notice Mark voucher token as expired * @param _tokenIdVoucher ID of the voucher token */ function triggerExpiration(uint256 _tokenIdVoucher) external override { require(_tokenIdVoucher != 0, "UNSPECIFIED_ID"); Promise memory tPromise = promises[getPromiseIdFromVoucherId(_tokenIdVoucher)]; require(tPromise.validTo < block.timestamp && isStateCommitted(vouchersStatus[_tokenIdVoucher].status),'INAPPLICABLE_STATUS'); vouchersStatus[_tokenIdVoucher].status = determineStatus( vouchersStatus[_tokenIdVoucher].status, VoucherState.EXPIRE ); emit LogExpirationTriggered(_tokenIdVoucher, msg.sender); } /** * @notice Mark voucher token to the final status * @param _tokenIdVoucher ID of the voucher token */ function triggerFinalizeVoucher(uint256 _tokenIdVoucher) external override { require(_tokenIdVoucher != 0, "UNSPECIFIED_ID"); uint8 tStatus = vouchersStatus[_tokenIdVoucher].status; require(!isStatus(tStatus, VoucherState.FINAL), "ALREADY_FINALIZED"); bool mark; Promise memory tPromise = promises[getPromiseIdFromVoucherId(_tokenIdVoucher)]; if (isStatus(tStatus, VoucherState.COMPLAIN)) { if (isStatus(tStatus, VoucherState.CANCEL_FAULT)) { //if COMPLAIN && COF: then final mark = true; } else if ( block.timestamp >= vouchersStatus[_tokenIdVoucher].cancelFaultPeriodStart + cancelFaultPeriod ) { //if COMPLAIN: then final after cof period mark = true; } } else if ( isStatus(tStatus, VoucherState.CANCEL_FAULT) && block.timestamp >= vouchersStatus[_tokenIdVoucher].complainPeriodStart + complainPeriod ) { //if COF: then final after complain period mark = true; } else if ( isStateRedemptionSigned(tStatus) || isStateRefunded(tStatus) ) { //if RDM/RFND NON_COMPLAIN: then final after complainPeriodStart + complainPeriod if ( block.timestamp >= vouchersStatus[_tokenIdVoucher].complainPeriodStart + complainPeriod ) { mark = true; } } else if (isStateExpired(tStatus)) { //if EXP NON_COMPLAIN: then final after validTo + complainPeriod if (block.timestamp >= tPromise.validTo + complainPeriod) { mark = true; } } require(mark, 'INAPPLICABLE_STATUS'); vouchersStatus[_tokenIdVoucher].status = determineStatus( tStatus, VoucherState.FINAL ); emit LogFinalizeVoucher(_tokenIdVoucher, msg.sender); } /* solhint-enable */ // // // // // // // // // UTILS // // // // // // // // /** * @notice Set the address of the new holder of a _tokenIdSupply on transfer * @param _tokenIdSupply _tokenIdSupply which will be transferred * @param _newSeller new holder of the supply */ function setSupplyHolderOnTransfer( uint256 _tokenIdSupply, address _newSeller ) external override onlyFromCashier { bytes32 promiseKey = ordersPromise[_tokenIdSupply]; promises[promiseKey].seller = _newSeller; } /** * @notice Set the address of the Boson Router contract * @param _bosonRouterAddress The address of the BR contract */ function setBosonRouterAddress(address _bosonRouterAddress) external override onlyOwner whenPaused notZeroAddress(_bosonRouterAddress) { bosonRouterAddress = _bosonRouterAddress; emit LogBosonRouterSet(_bosonRouterAddress, msg.sender); } /** * @notice Set the address of the Cashier contract * @param _cashierAddress The address of the Cashier contract */ function setCashierAddress(address _cashierAddress) external override onlyOwner whenPaused notZeroAddress(_cashierAddress) { cashierAddress = _cashierAddress; emit LogCashierSet(_cashierAddress, msg.sender); } /** * @notice Set the address of the Vouchers token contract, an ERC721 contract * @param _voucherTokenAddress The address of the Vouchers token contract */ function setVoucherTokenAddress(address _voucherTokenAddress) external override onlyOwner notZeroAddress(_voucherTokenAddress) whenPaused { voucherTokenAddress = _voucherTokenAddress; emit LogVoucherTokenContractSet(_voucherTokenAddress, msg.sender); } /** * @notice Set the address of the Voucher Sets token contract, an ERC1155 contract * @param _voucherSetTokenAddress The address of the Vouchers token contract */ function setVoucherSetTokenAddress(address _voucherSetTokenAddress) external override onlyOwner notZeroAddress(_voucherSetTokenAddress) whenPaused { voucherSetTokenAddress = _voucherSetTokenAddress; emit LogVoucherSetTokenContractSet(_voucherSetTokenAddress, msg.sender); } /** * @notice Set the general complain period, should be used sparingly as it has significant consequences. Here done simply for demo purposes. * @param _complainPeriod the new value for complain period (in number of seconds) */ function setComplainPeriod(uint256 _complainPeriod) external override onlyOwner { complainPeriod = _complainPeriod; emit LogComplainPeriodChanged(_complainPeriod, msg.sender); } /** * @notice Set the general cancelOrFault period, should be used sparingly as it has significant consequences. Here done simply for demo purposes. * @param _cancelFaultPeriod the new value for cancelOrFault period (in number of seconds) */ function setCancelFaultPeriod(uint256 _cancelFaultPeriod) external override onlyOwner { cancelFaultPeriod = _cancelFaultPeriod; emit LogCancelFaultPeriodChanged(_cancelFaultPeriod, msg.sender); } // // // // // // // // // GETTERS // // // // // // // // /** * @notice Get the promise ID at specific index * @param _idx Index in the array of promise keys * @return Promise ID */ function getPromiseKey(uint256 _idx) external view override returns (bytes32) { return promiseKeys[_idx]; } /** * @notice Get the supply token ID from a voucher token * @param _tokenIdVoucher ID of the voucher token * @return ID of the supply token */ function getIdSupplyFromVoucher(uint256 _tokenIdVoucher) public pure override returns (uint256) { uint256 tokenIdSupply = _tokenIdVoucher & MASK_TYPE; require(tokenIdSupply !=0, "INEXISTENT_SUPPLY"); return tokenIdSupply; } /** * @notice Get the promise ID from a voucher token * @param _tokenIdVoucher ID of the voucher token * @return ID of the promise */ function getPromiseIdFromVoucherId(uint256 _tokenIdVoucher) public view override returns (bytes32) { require(_tokenIdVoucher != 0, "UNSPECIFIED_ID"); uint256 tokenIdSupply = getIdSupplyFromVoucher(_tokenIdVoucher); return promises[ordersPromise[tokenIdSupply]].promiseId; } /** * @notice Get the remaining quantity left in supply of tokens (e.g ERC-721 left in ERC-1155) of an account * @param _tokenSupplyId Token supply ID * @param _tokenSupplyOwner holder of the Token Supply * @return remaining quantity */ function getRemQtyForSupply(uint256 _tokenSupplyId, address _tokenSupplyOwner) public view override returns (uint256) { return IVoucherSets(voucherSetTokenAddress).balanceOf(_tokenSupplyOwner, _tokenSupplyId); } /** * @notice Get all necessary funds for a supply token * @param _tokenIdSupply ID of the supply token * @return returns a tuple (Payment amount, Seller's deposit, Buyer's deposit) */ function getOrderCosts(uint256 _tokenIdSupply) external view override returns ( uint256, uint256, uint256 ) { bytes32 promiseKey = ordersPromise[_tokenIdSupply]; return ( promises[promiseKey].price, promises[promiseKey].depositSe, promises[promiseKey].depositBu ); } /** * @notice Get Buyer costs required to make an order for a supply token * @param _tokenIdSupply ID of the supply token * @return returns a tuple (Payment amount, Buyer's deposit) */ function getBuyerOrderCosts(uint256 _tokenIdSupply) external view override returns (uint256, uint256) { bytes32 promiseKey = ordersPromise[_tokenIdSupply]; return (promises[promiseKey].price, promises[promiseKey].depositBu); } /** * @notice Get Seller deposit * @param _tokenIdSupply ID of the supply token * @return returns sellers deposit */ function getSellerDeposit(uint256 _tokenIdSupply) external view override returns (uint256) { bytes32 promiseKey = ordersPromise[_tokenIdSupply]; return promises[promiseKey].depositSe; } /** * @notice Get the holder of a supply * @param _tokenIdSupply ID of the order (aka VoucherSet) which is mapped to the corresponding Promise. * @return Address of the holder */ function getSupplyHolder(uint256 _tokenIdSupply) public view override returns (address) { bytes32 promiseKey = ordersPromise[_tokenIdSupply]; return promises[promiseKey].seller; } /** * @notice Get promise data not retrieved by other accessor functions * @param _promiseKey ID of the promise * @return promise data not returned by other accessor methods */ function getPromiseData(bytes32 _promiseKey) external view override returns (bytes32, uint256, uint256, uint256, uint256 ) { Promise memory tPromise = promises[_promiseKey]; return (tPromise.promiseId, tPromise.nonce, tPromise.validFrom, tPromise.validTo, tPromise.idx); } /** * @notice Get the current status of a voucher * @param _tokenIdVoucher ID of the voucher token * @return Status of the voucher (via enum) */ function getVoucherStatus(uint256 _tokenIdVoucher) external view override returns ( uint8, bool, bool, uint256, uint256 ) { return ( vouchersStatus[_tokenIdVoucher].status, vouchersStatus[_tokenIdVoucher].isPaymentReleased, vouchersStatus[_tokenIdVoucher].isDepositsReleased, vouchersStatus[_tokenIdVoucher].complainPeriodStart, vouchersStatus[_tokenIdVoucher].cancelFaultPeriodStart ); } /** * @notice Get the holder of a voucher * @param _tokenIdVoucher ID of the voucher token * @return Address of the holder */ function getVoucherHolder(uint256 _tokenIdVoucher) external view override returns (address) { return IVouchers(voucherTokenAddress).ownerOf(_tokenIdVoucher); } /** * @notice Get the address of the token where the price for the supply is held * @param _tokenIdSupply ID of the voucher supply token * @return Address of the token */ function getVoucherPriceToken(uint256 _tokenIdSupply) external view override returns (address) { return paymentDetails[_tokenIdSupply].addressTokenPrice; } /** * @notice Get the address of the token where the deposits for the supply are held * @param _tokenIdSupply ID of the voucher supply token * @return Address of the token */ function getVoucherDepositToken(uint256 _tokenIdSupply) external view override returns (address) { return paymentDetails[_tokenIdSupply].addressTokenDeposits; } /** * @notice Get the payment method for a particular _tokenIdSupply * @param _tokenIdSupply ID of the voucher supply token * @return payment method */ function getVoucherPaymentMethod(uint256 _tokenIdSupply) public view override returns (PaymentMethod) { return paymentDetails[_tokenIdSupply].paymentMethod; } /** * @notice Checks whether a voucher is in valid period for redemption (between start date and end date) * @param _tokenIdVoucher ID of the voucher token */ function isInValidityPeriod(uint256 _tokenIdVoucher) public view override returns (bool) { //check validity period Promise memory tPromise = promises[getPromiseIdFromVoucherId(_tokenIdVoucher)]; require(tPromise.validFrom <= block.timestamp, "INVALID_VALIDITY_FROM"); require(tPromise.validTo >= block.timestamp, "INVALID_VALIDITY_TO"); return true; } /** * @notice Checks whether a voucher is in valid state to be transferred. If either payments or deposits are released, voucher could not be transferred * @param _tokenIdVoucher ID of the voucher token */ function isVoucherTransferable(uint256 _tokenIdVoucher) external view override returns (bool) { return !(vouchersStatus[_tokenIdVoucher].isPaymentReleased || vouchersStatus[_tokenIdVoucher].isDepositsReleased); } /** * @notice Get address of the Boson Router to which this contract points * @return Address of the Boson Router contract */ function getBosonRouterAddress() external view override returns (address) { return bosonRouterAddress; } /** * @notice Get address of the Cashier contract to which this contract points * @return Address of the Cashier contract */ function getCashierAddress() external view override returns (address) { return cashierAddress; } /** * @notice Get the token nonce for a seller * @param _seller Address of the seller * @return The seller's nonce */ function getTokenNonce(address _seller) external view override returns (uint256) { return tokenNonces[_seller]; } /** * @notice Get the current type Id * @return type Id */ function getTypeId() external view override returns (uint256) { return typeId; } /** * @notice Get the complain period * @return complain period */ function getComplainPeriod() external view override returns (uint256) { return complainPeriod; } /** * @notice Get the cancel or fault period * @return cancel or fault period */ function getCancelFaultPeriod() external view override returns (uint256) { return cancelFaultPeriod; } /** * @notice Get the promise ID from a voucher set * @param _tokenIdSupply ID of the voucher token * @return ID of the promise */ function getPromiseIdFromSupplyId(uint256 _tokenIdSupply) external view override returns (bytes32) { return ordersPromise[_tokenIdSupply]; } /** * @notice Get the address of the Vouchers token contract, an ERC721 contract * @return Address of Vouchers contract */ function getVoucherTokenAddress() external view override returns (address) { return voucherTokenAddress; } /** * @notice Get the address of the VoucherSets token contract, an ERC155 contract * @return Address of VoucherSets contract */ function getVoucherSetTokenAddress() external view override returns (address) { return voucherSetTokenAddress; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "./Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor () { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } // SPDX-License-Identifier: LGPL-3.0-or-later pragma solidity 0.7.6; import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol"; import "@openzeppelin/contracts/token/ERC1155/IERC1155MetadataURI.sol"; interface IVoucherSets is IERC1155, IERC1155MetadataURI { /** * @notice Pause the Cashier && the Voucher Kernel contracts in case of emergency. * All functions related to creating new batch, requestVoucher or withdraw will be paused, hence cannot be executed. * There is special function for withdrawing funds if contract is paused. */ function pause() external; /** * @notice Unpause the Cashier && the Voucher Kernel contracts. * All functions related to creating new batch, requestVoucher or withdraw will be unpaused. */ function unpause() external; /** * @notice Mint an amount of a desired token * Currently no restrictions as to who is allowed to mint - so, it is external. * @dev ERC-1155 * @param _to owner of the minted token * @param _tokenId ID of the token to be minted * @param _value Amount of the token to be minted * @param _data Additional data forwarded to onERC1155BatchReceived if _to is a contract */ function mint( address _to, uint256 _tokenId, uint256 _value, bytes calldata _data ) external; /** * @notice Burn an amount of tokens with the given ID * @dev ERC-1155 * @param _account Account which owns the token * @param _tokenId ID of the token * @param _value Amount of the token */ function burn( address _account, uint256 _tokenId, uint256 _value ) external; /** * @notice Set the address of the VoucherKernel contract * @param _voucherKernelAddress The address of the Voucher Kernel contract */ function setVoucherKernelAddress(address _voucherKernelAddress) external; /** * @notice Set the address of the Cashier contract * @param _cashierAddress The address of the Cashier contract */ function setCashierAddress(address _cashierAddress) external; /** * @notice Get the address of Voucher Kernel contract * @return Address of Voucher Kernel contract */ function getVoucherKernelAddress() external view returns (address); /** * @notice Get the address of Cashier contract * @return Address of Cashier address */ function getCashierAddress() external view returns (address); } // SPDX-License-Identifier: LGPL-3.0-or-later pragma solidity 0.7.6; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721Metadata.sol"; interface IVouchers is IERC721, IERC721Metadata { /** * @notice Pause the Cashier && the Voucher Kernel contracts in case of emergency. * All functions related to creating new batch, requestVoucher or withdraw will be paused, hence cannot be executed. * There is special function for withdrawing funds if contract is paused. */ function pause() external; /** * @notice Unpause the Cashier && the Voucher Kernel contracts. * All functions related to creating new batch, requestVoucher or withdraw will be unpaused. */ function unpause() external; /** * @notice Function to mint tokens. * @dev ERC-721 * @param _to The address that will receive the minted tokens. * @param _tokenId The token id to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _tokenId) external returns (bool); /** * @notice Set the address of the VoucherKernel contract * @param _voucherKernelAddress The address of the Voucher Kernel contract */ function setVoucherKernelAddress(address _voucherKernelAddress) external; /** * @notice Set the address of the Cashier contract * @param _cashierAddress The address of the Cashier contract */ function setCashierAddress(address _cashierAddress) external; /** * @notice Get the address of Voucher Kernel contract * @return Address of Voucher Kernel contract */ function getVoucherKernelAddress() external view returns (address); /** * @notice Get the address of Cashier contract * @return Address of Cashier address */ function getCashierAddress() external view returns (address); } // SPDX-License-Identifier: LGPL-3.0-or-later pragma solidity 0.7.6; import "./../UsingHelpers.sol"; interface IVoucherKernel { /** * @notice Pause the process of interaction with voucherID's (ERC-721), in case of emergency. * Only Cashier contract is in control of this function. */ function pause() external; /** * @notice Unpause the process of interaction with voucherID's (ERC-721). * Only Cashier contract is in control of this function. */ function unpause() external; /** * @notice Creating a new promise for goods or services. * Can be reused, e.g. for making different batches of these (but not in prototype). * @param _seller seller of the promise * @param _validFrom Start of valid period * @param _validTo End of valid period * @param _price Price (payment amount) * @param _depositSe Seller's deposit * @param _depositBu Buyer's deposit */ function createTokenSupplyId( address _seller, uint256 _validFrom, uint256 _validTo, uint256 _price, uint256 _depositSe, uint256 _depositBu, uint256 _quantity ) external returns (uint256); /** * @notice Creates a Payment method struct recording the details on how the seller requires to receive Price and Deposits for a certain Voucher Set. * @param _tokenIdSupply _tokenIdSupply of the voucher set this is related to * @param _paymentMethod might be ETHETH, ETHTKN, TKNETH or TKNTKN * @param _tokenPrice token address which will hold the funds for the price of the voucher * @param _tokenDeposits token address which will hold the funds for the deposits of the voucher */ function createPaymentMethod( uint256 _tokenIdSupply, PaymentMethod _paymentMethod, address _tokenPrice, address _tokenDeposits ) external; /** * @notice Mark voucher token that the payment was released * @param _tokenIdVoucher ID of the voucher token */ function setPaymentReleased(uint256 _tokenIdVoucher) external; /** * @notice Mark voucher token that the deposits were released * @param _tokenIdVoucher ID of the voucher token */ function setDepositsReleased(uint256 _tokenIdVoucher) external; /** * @notice Redemption of the vouchers promise * @param _tokenIdVoucher ID of the voucher * @param _messageSender owner of the voucher */ function redeem(uint256 _tokenIdVoucher, address _messageSender) external; /** * @notice Refunding a voucher * @param _tokenIdVoucher ID of the voucher * @param _messageSender owner of the voucher */ function refund(uint256 _tokenIdVoucher, address _messageSender) external; /** * @notice Issue a complain for a voucher * @param _tokenIdVoucher ID of the voucher * @param _messageSender owner of the voucher */ function complain(uint256 _tokenIdVoucher, address _messageSender) external; /** * @notice Cancel/Fault transaction by the Seller, admitting to a fault or backing out of the deal * @param _tokenIdVoucher ID of the voucher * @param _messageSender owner of the voucher set (seller) */ function cancelOrFault(uint256 _tokenIdVoucher, address _messageSender) external; /** * @notice Cancel/Fault transaction by the Seller, cancelling the remaining uncommitted voucher set so that seller prevents buyers from committing to vouchers for items no longer in exchange. * @param _tokenIdSupply ID of the voucher * @param _issuer owner of the voucher */ function cancelOrFaultVoucherSet(uint256 _tokenIdSupply, address _issuer) external returns (uint256); /** * @notice Fill Voucher Order, iff funds paid, then extract & mint NFT to the voucher holder * @param _tokenIdSupply ID of the supply token (ERC-1155) * @param _issuer Address of the token's issuer * @param _holder Address of the recipient of the voucher (ERC-721) * @param _paymentMethod method being used for that particular order that needs to be fulfilled */ function fillOrder( uint256 _tokenIdSupply, address _issuer, address _holder, PaymentMethod _paymentMethod ) external; /** * @notice Mark voucher token as expired * @param _tokenIdVoucher ID of the voucher token */ function triggerExpiration(uint256 _tokenIdVoucher) external; /** * @notice Mark voucher token to the final status * @param _tokenIdVoucher ID of the voucher token */ function triggerFinalizeVoucher(uint256 _tokenIdVoucher) external; /** * @notice Set the address of the new holder of a _tokenIdSupply on transfer * @param _tokenIdSupply _tokenIdSupply which will be transferred * @param _newSeller new holder of the supply */ function setSupplyHolderOnTransfer( uint256 _tokenIdSupply, address _newSeller ) external; /** * @notice Set the general cancelOrFault period, should be used sparingly as it has significant consequences. Here done simply for demo purposes. * @param _cancelFaultPeriod the new value for cancelOrFault period (in number of seconds) */ function setCancelFaultPeriod(uint256 _cancelFaultPeriod) external; /** * @notice Set the address of the Boson Router contract * @param _bosonRouterAddress The address of the BR contract */ function setBosonRouterAddress(address _bosonRouterAddress) external; /** * @notice Set the address of the Cashier contract * @param _cashierAddress The address of the Cashier contract */ function setCashierAddress(address _cashierAddress) external; /** * @notice Set the address of the Vouchers token contract, an ERC721 contract * @param _voucherTokenAddress The address of the Vouchers token contract */ function setVoucherTokenAddress(address _voucherTokenAddress) external; /** * @notice Set the address of the Voucher Sets token contract, an ERC1155 contract * @param _voucherSetTokenAddress The address of the Voucher Sets token contract */ function setVoucherSetTokenAddress(address _voucherSetTokenAddress) external; /** * @notice Set the general complain period, should be used sparingly as it has significant consequences. Here done simply for demo purposes. * @param _complainPeriod the new value for complain period (in number of seconds) */ function setComplainPeriod(uint256 _complainPeriod) external; /** * @notice Get the promise ID at specific index * @param _idx Index in the array of promise keys * @return Promise ID */ function getPromiseKey(uint256 _idx) external view returns (bytes32); /** * @notice Get the address of the token where the price for the supply is held * @param _tokenIdSupply ID of the voucher token * @return Address of the token */ function getVoucherPriceToken(uint256 _tokenIdSupply) external view returns (address); /** * @notice Get the address of the token where the deposits for the supply are held * @param _tokenIdSupply ID of the voucher token * @return Address of the token */ function getVoucherDepositToken(uint256 _tokenIdSupply) external view returns (address); /** * @notice Get Buyer costs required to make an order for a supply token * @param _tokenIdSupply ID of the supply token * @return returns a tuple (Payment amount, Buyer's deposit) */ function getBuyerOrderCosts(uint256 _tokenIdSupply) external view returns (uint256, uint256); /** * @notice Get Seller deposit * @param _tokenIdSupply ID of the supply token * @return returns sellers deposit */ function getSellerDeposit(uint256 _tokenIdSupply) external view returns (uint256); /** * @notice Get the promise ID from a voucher token * @param _tokenIdVoucher ID of the voucher token * @return ID of the promise */ function getIdSupplyFromVoucher(uint256 _tokenIdVoucher) external pure returns (uint256); /** * @notice Get the promise ID from a voucher token * @param _tokenIdVoucher ID of the voucher token * @return ID of the promise */ function getPromiseIdFromVoucherId(uint256 _tokenIdVoucher) external view returns (bytes32); /** * @notice Get all necessary funds for a supply token * @param _tokenIdSupply ID of the supply token * @return returns a tuple (Payment amount, Seller's deposit, Buyer's deposit) */ function getOrderCosts(uint256 _tokenIdSupply) external view returns ( uint256, uint256, uint256 ); /** * @notice Get the remaining quantity left in supply of tokens (e.g ERC-721 left in ERC-1155) of an account * @param _tokenSupplyId Token supply ID * @param _owner holder of the Token Supply * @return remaining quantity */ function getRemQtyForSupply(uint256 _tokenSupplyId, address _owner) external view returns (uint256); /** * @notice Get the payment method for a particular _tokenIdSupply * @param _tokenIdSupply ID of the voucher supply token * @return payment method */ function getVoucherPaymentMethod(uint256 _tokenIdSupply) external view returns (PaymentMethod); /** * @notice Get the current status of a voucher * @param _tokenIdVoucher ID of the voucher token * @return Status of the voucher (via enum) */ function getVoucherStatus(uint256 _tokenIdVoucher) external view returns ( uint8, bool, bool, uint256, uint256 ); /** * @notice Get the holder of a supply * @param _tokenIdSupply _tokenIdSupply ID of the order (aka VoucherSet) which is mapped to the corresponding Promise. * @return Address of the holder */ function getSupplyHolder(uint256 _tokenIdSupply) external view returns (address); /** * @notice Get the holder of a voucher * @param _tokenIdVoucher ID of the voucher token * @return Address of the holder */ function getVoucherHolder(uint256 _tokenIdVoucher) external view returns (address); /** * @notice Checks whether a voucher is in valid period for redemption (between start date and end date) * @param _tokenIdVoucher ID of the voucher token */ function isInValidityPeriod(uint256 _tokenIdVoucher) external view returns (bool); /** * @notice Checks whether a voucher is in valid state to be transferred. If either payments or deposits are released, voucher could not be transferred * @param _tokenIdVoucher ID of the voucher token */ function isVoucherTransferable(uint256 _tokenIdVoucher) external view returns (bool); /** * @notice Get address of the Boson Router contract to which this contract points * @return Address of the Boson Router contract */ function getBosonRouterAddress() external view returns (address); /** * @notice Get address of the Cashier contract to which this contract points * @return Address of the Cashier contract */ function getCashierAddress() external view returns (address); /** * @notice Get the token nonce for a seller * @param _seller Address of the seller * @return The seller's */ function getTokenNonce(address _seller) external view returns (uint256); /** * @notice Get the current type Id * @return type Id */ function getTypeId() external view returns (uint256); /** * @notice Get the complain period * @return complain period */ function getComplainPeriod() external view returns (uint256); /** * @notice Get the cancel or fault period * @return cancel or fault period */ function getCancelFaultPeriod() external view returns (uint256); /** * @notice Get promise data not retrieved by other accessor functions * @param _promiseKey ID of the promise * @return promise data not returned by other accessor methods */ function getPromiseData(bytes32 _promiseKey) external view returns ( bytes32, uint256, uint256, uint256, uint256 ); /** * @notice Get the promise ID from a voucher set * @param _tokenIdSupply ID of the voucher token * @return ID of the promise */ function getPromiseIdFromSupplyId(uint256 _tokenIdSupply) external view returns (bytes32); /** * @notice Get the address of the Vouchers token contract, an ERC721 contract * @return Address of Vouchers contract */ function getVoucherTokenAddress() external view returns (address); /** * @notice Get the address of the VoucherSets token contract, an ERC155 contract * @return Address of VoucherSets contract */ function getVoucherSetTokenAddress() external view returns (address); } // SPDX-License-Identifier: LGPL-3.0-or-later pragma solidity 0.7.6; // Those are the payment methods we are using throughout the system. // Depending on how to user choose to interact with it's funds we store the method, so we could distribute its tokens afterwise enum PaymentMethod { ETHETH, ETHTKN, TKNETH, TKNTKN } enum VoucherState {FINAL, CANCEL_FAULT, COMPLAIN, EXPIRE, REFUND, REDEEM, COMMIT} /* Status of the voucher in 8 bits: [6:COMMITTED] [5:REDEEMED] [4:REFUNDED] [3:EXPIRED] [2:COMPLAINED] [1:CANCELORFAULT] [0:FINAL] */ uint8 constant ONE = 1; struct VoucherDetails { uint256 tokenIdSupply; uint256 tokenIdVoucher; address issuer; address holder; uint256 price; uint256 depositSe; uint256 depositBu; uint256 price2pool; uint256 deposit2pool; uint256 price2issuer; uint256 deposit2issuer; uint256 price2holder; uint256 deposit2holder; PaymentMethod paymentMethod; VoucherStatus currStatus; } struct VoucherStatus { uint8 status; bool isPaymentReleased; bool isDepositsReleased; uint256 complainPeriodStart; uint256 cancelFaultPeriodStart; } /** * @notice Based on its lifecycle, voucher can have many different statuses. Checks whether a voucher is in Committed state. * @param _status current status of a voucher. */ function isStateCommitted(uint8 _status) pure returns (bool) { return _status == determineStatus(0, VoucherState.COMMIT); } /** * @notice Based on its lifecycle, voucher can have many different statuses. Checks whether a voucher is in RedemptionSigned state. * @param _status current status of a voucher. */ function isStateRedemptionSigned(uint8 _status) pure returns (bool) { return _status == determineStatus(determineStatus(0, VoucherState.COMMIT), VoucherState.REDEEM); } /** * @notice Based on its lifecycle, voucher can have many different statuses. Checks whether a voucher is in Refunded state. * @param _status current status of a voucher. */ function isStateRefunded(uint8 _status) pure returns (bool) { return _status == determineStatus(determineStatus(0, VoucherState.COMMIT), VoucherState.REFUND); } /** * @notice Based on its lifecycle, voucher can have many different statuses. Checks whether a voucher is in Expired state. * @param _status current status of a voucher. */ function isStateExpired(uint8 _status) pure returns (bool) { return _status == determineStatus(determineStatus(0, VoucherState.COMMIT), VoucherState.EXPIRE); } /** * @notice Based on its lifecycle, voucher can have many different statuses. Checks the current status a voucher is at. * @param _status current status of a voucher. * @param _idx status to compare. */ function isStatus(uint8 _status, VoucherState _idx) pure returns (bool) { return (_status >> uint8(_idx)) & ONE == 1; } /** * @notice Set voucher status. * @param _status previous status. * @param _changeIdx next status. */ function determineStatus(uint8 _status, VoucherState _changeIdx) pure returns (uint8) { return _status | (ONE << uint8(_changeIdx)); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../../introspection/IERC165.sol"; /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155 is IERC165 { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch(address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes calldata data) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom(address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "./IERC1155.sol"; /** * @dev Interface of the optional ERC1155MetadataExtension interface, as defined * in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP]. * * _Available since v3.1._ */ interface IERC1155MetadataURI is IERC1155 { /** * @dev Returns the URI for token type `id`. * * If the `\{id\}` substring is present in the URI, it must be replaced by * clients with the actual token type ID. */ function uri(uint256 id) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../../introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "./IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); }
* @notice Based on its lifecycle, voucher can have many different statuses. Checks whether a voucher is in Committed state. @param _status current status of a voucher./
function isStateCommitted(uint8 _status) pure returns (bool) { return _status == determineStatus(0, VoucherState.COMMIT); }
40,339
[ 1, 9802, 603, 2097, 6596, 16, 331, 14329, 848, 1240, 4906, 3775, 13516, 18, 13074, 2856, 279, 331, 14329, 353, 316, 1286, 7948, 919, 18, 225, 389, 2327, 783, 1267, 434, 279, 331, 14329, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 915, 353, 1119, 27813, 12, 11890, 28, 389, 2327, 13, 16618, 1135, 261, 6430, 13, 288, 203, 565, 327, 389, 2327, 422, 4199, 1482, 12, 20, 16, 776, 14329, 1119, 18, 18658, 1769, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x4d62c46898bDCd6b14118646ED1401336C9a47B3/sources/DIDP.sol
* @title GECToken @dev GEC Token contract, where all tokens are pre-assigned to the creator. Note they can later distribute these tokens as they wish using `transfer` and other `ERC20` functions./
contract DIDP is ERC20Pausable, ERC20Detailed{ constructor () public ERC20Detailed("DIDP", "DIDP", 18) { _mint(msg.sender, 1000000000 * (10 ** uint256(decimals()))); } }
15,760,331
[ 1, 43, 4239, 969, 225, 611, 7228, 3155, 6835, 16, 1625, 777, 2430, 854, 675, 17, 15938, 358, 326, 11784, 18, 3609, 2898, 848, 5137, 25722, 4259, 2430, 487, 2898, 14302, 1450, 1375, 13866, 68, 471, 1308, 1375, 654, 39, 3462, 68, 4186, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 463, 734, 52, 353, 4232, 39, 3462, 16507, 16665, 16, 4232, 39, 3462, 40, 6372, 95, 203, 203, 565, 3885, 1832, 1071, 4232, 39, 3462, 40, 6372, 2932, 40, 734, 52, 3113, 315, 40, 734, 52, 3113, 6549, 13, 288, 203, 3639, 389, 81, 474, 12, 3576, 18, 15330, 16, 15088, 3784, 380, 261, 2163, 2826, 2254, 5034, 12, 31734, 1435, 3719, 1769, 203, 565, 289, 203, 97, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface AggregatorV3Interface { function decimals() external view returns (uint8); function description() external view returns (string memory); function version() external view returns (uint256); // getRoundData and latestRoundData should both raise "No data present" // if they do not have data to report, instead of returning unset values // which could be misinterpreted as actual reported values. function getRoundData(uint80 _roundId) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); } /** * SPDX-License-Identifier: MIT * * Copyright (c) 2016-2019 zOS Global Limited * */ pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see `ERC20Detailed`. */ interface IERC20 { // Optional functions function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a `Transfer` event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through `transferFrom`. This is * zero by default. * * This value changes when `approve` or `transferFrom` are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * > Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an `Approval` event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a `Transfer` event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to `approve`. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC20/IERC20.sol"; interface IBrokerbot { function base() external view returns (IERC20); function settings() external view returns (uint256); // @return The amount of shares bought on buying or how much in the base currency is transfered on selling function processIncoming(IERC20 token_, address from, uint256 amount, bytes calldata ref) external payable returns (uint256); } // SPDX-License-Identifier: MIT // https://github.com/Uniswap/uniswap-v3-periphery/blob/main/contracts/interfaces/IQuoter.sol pragma solidity ^0.8.0; interface IQuoter { function quoteExactOutputSingle( address tokenIn, address tokenOut, uint24 fee, uint256 amountOut, uint160 sqrtPriceLimitX96 ) external returns (uint256 amountIn); /// @notice Returns the amount in required for a given exact output swap without executing the swap /// @param path The path of the swap, i.e. each token pair and the pool fee. Path must be provided in reverse order /// @param amountOut The amount of the last token to receive /// @return amountIn The amount of first token required to be paid function quoteExactOutput(bytes memory path, uint256 amountOut) external returns (uint256 amountIn); // solhint-disable-next-line func-name-mixedcase function WETH9() external view returns (address); } interface ISwapRouter { struct ExactOutputSingleParams { address tokenIn; address tokenOut; uint24 fee; address recipient; uint256 deadline; uint256 amountOut; uint256 amountInMaximum; uint160 sqrtPriceLimitX96; } function exactOutputSingle(ExactOutputSingleParams calldata params) external payable returns (uint256 amountIn); struct ExactOutputParams { bytes path; address recipient; uint256 deadline; uint256 amountOut; uint256 amountInMaximum; } /// @notice Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed) /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata /// @return amountIn The amount of the input token function exactOutput(ExactOutputParams calldata params) external payable returns (uint256 amountIn); function refundETH() external payable; } /** * SPDX-License-Identifier: LicenseRef-Aktionariat * * MIT License with Automated License Fee Payments * * Copyright (c) 2021 Aktionariat AG (aktionariat.com) * * Permission is hereby granted to any person obtaining a copy of this software * and associated documentation files (the "Software"), to deal in the Software * without restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies of the * Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * - The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * - All automated license fee payments integrated into this and related Software * are preserved. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ pragma solidity ^0.8.0; import "../utils/Address.sol"; import "../ERC20/IERC20.sol"; import "./IUniswapV3.sol"; import "../utils/Ownable.sol"; import "./IBrokerbot.sol"; import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol"; /** * A hub for payments. This allows tokens that do not support ERC 677 to enjoy similar functionality, * namely interacting with a token-handling smart contract in one transaction, without having to set an allowance first. * Instead, an allowance needs to be set only once, namely for this contract. * Further, it supports automatic conversion from Ether to the payment currency through Uniswap or the reception of Ether * using the current exchange rate as found in the chainlink oracle. */ contract PaymentHub { uint24 private constant DEFAULT_FEE = 3000; uint256 private constant DENOMINATOR = 1e8; address private constant CHF_TOKEN = 0xB4272071eCAdd69d933AdcD19cA99fe80664fc08; uint8 private constant KEEP_ETHER = 0x4; // copied from brokerbot IQuoter private immutable uniswapQuoter; ISwapRouter private immutable uniswapRouter; AggregatorV3Interface internal immutable priceFeedCHFUSD; AggregatorV3Interface internal immutable priceFeedETHUSD; constructor(IQuoter _quoter, ISwapRouter swapRouter, AggregatorV3Interface _aggregatorCHFUSD, AggregatorV3Interface _aggregatorETHUSD) { uniswapQuoter = _quoter; uniswapRouter = swapRouter; priceFeedCHFUSD = _aggregatorCHFUSD; priceFeedETHUSD = _aggregatorETHUSD; } /* * Get price in ERC20 * This is the method that the Brokerbot widget should use to quote the price to the user. * @param amountInBase The amount of the base currency for the exact output. * @param path The encoded path of the swap from erc20 to base. * @return amount quoted to pay */ function getPriceInERC20(uint256 amountInBase, bytes memory path) public returns (uint256) { return uniswapQuoter.quoteExactOutput( path, amountInBase ); } /** * Get price in Ether depding on brokerbot setting. * If keep ETH is set price is from oracle. * This is the method that the Brokerbot widget should use to quote the price to the user. * @return The price in wei. */ function getPriceInEther(uint256 amountInBase, IBrokerbot brokerBot) public returns (uint256) { if ((address(brokerBot) != address(0)) && hasSettingKeepEther(brokerBot)) { return getPriceInEtherFromOracle(amountInBase, IBrokerbot(brokerBot).base()); } else { return uniswapQuoter.quoteExactOutputSingle(uniswapQuoter.WETH9(), address(brokerBot.base()), DEFAULT_FEE, amountInBase, 0); } } /** * Price in ETH with 18 decimals */ function getPriceInEtherFromOracle(uint256 amountInBase, IERC20 base) public view returns (uint256) { if(address(base) == CHF_TOKEN) { return getLatestPriceCHFUSD() * amountInBase / getLatestPriceETHUSD(); } else { return amountInBase * DENOMINATOR / getLatestPriceETHUSD(); } } /** * Returns the latest price of eth/usd pair from chainlink with 8 decimals */ function getLatestPriceETHUSD() public view returns (uint256) { (, int256 price, , , ) = priceFeedETHUSD.latestRoundData(); return uint256(price); } /** * Returns the latest price of chf/usd pair from chainlink with 8 decimals */ function getLatestPriceCHFUSD() public view returns (uint256) { (, int256 price, , , ) = priceFeedCHFUSD.latestRoundData(); return uint256(price); } /** * Convenience method to swap ether into base and pay a target address */ function payFromEther(address recipient, uint256 amountInBase, IERC20 base) public payable { ISwapRouter.ExactOutputSingleParams memory params = ISwapRouter.ExactOutputSingleParams( // rely on time stamp is ok, no exact time stamp needed // solhint-disable-next-line not-rely-on-time uniswapQuoter.WETH9(), address(base), DEFAULT_FEE, recipient, block.timestamp, amountInBase, msg.value, 0); ISwapRouter swapRouter = uniswapRouter; // Executes the swap returning the amountIn needed to spend to receive the desired amountOut. uint256 amountIn = swapRouter.exactOutputSingle{value: msg.value}(params); // For exact output swaps, the amountInMaximum may not have all been spent. // If the actual amount spent (amountIn) is less than the specified maximum amount, we must refund the msg.sender and approve the swapRouter to spend 0. if (amountIn < msg.value) { swapRouter.refundETH(); (bool success, ) = msg.sender.call{value:msg.value - amountIn}(""); // return change require(success, "Transfer failed."); } } /// @dev The calling address must approve this contract to spend its ERC20 for this function to succeed. As the amount of input ERC20 is variable, /// the calling address will need to approve for a slightly higher or infinit amount, anticipating some variance. /// @param amountOut The desired amount of baseCurrency. /// @param amountInMaximum The maximum amount of ERC20 willing to be swapped for the specified amountOut of baseCurrency. /// @param erc20In The address of the erc20 token to pay with. /// @param path The encoded path of the swap from erc20 to base. /// @param recipient The reciving address - brokerbot. /// @return amountIn The amountIn of ERC20 actually spent to receive the desired amountOut. function payFromERC20(uint256 amountOut, uint256 amountInMaximum, address erc20In, bytes memory path, address recipient) public returns (uint256 amountIn) { ISwapRouter swapRouter = uniswapRouter; // Transfer the specified `amountInMaximum` to this contract. IERC20(erc20In).transferFrom(msg.sender, address(this), amountInMaximum); // The parameter path is encoded as (tokenOut, fee, tokenIn/tokenOut, fee, tokenIn) ISwapRouter.ExactOutputParams memory params = ISwapRouter.ExactOutputParams({ path: path, recipient: recipient, // solhint-disable-next-line not-rely-on-time deadline: block.timestamp, amountOut: amountOut, amountInMaximum: amountInMaximum }); // Executes the swap, returning the amountIn actually spent. amountIn = swapRouter.exactOutput(params); // If the swap did not require the full amountInMaximum to achieve the exact amountOut then we refund msg.sender and approve the router to spend 0. if (amountIn < amountInMaximum) { IERC20(erc20In).transfer(msg.sender, amountInMaximum - amountIn); } } ///This function appoves infinite allowance for Uniswap, this is safe as the paymenthub should never hold any token (see also recover() ). ///@dev This function needs to be called before using the PaymentHub the first time with a new ERC20 token. ///@param erc20In The erc20 addresse to approve. function approveERC20(address erc20In) external { IERC20(erc20In).approve(address(uniswapRouter), 0x8000000000000000000000000000000000000000000000000000000000000000); } function multiPay(IERC20 token, address[] calldata recipients, uint256[] calldata amounts) public { for (uint i=0; i<recipients.length; i++) { require(IERC20(token).transferFrom(msg.sender, recipients[i], amounts[i])); } } /** * Can (at least in theory) save some gas as the sender balance only is touched in one transaction. */ function multiPayAndNotify(IERC20 token, address[] calldata recipients, uint256[] calldata amounts, bytes calldata ref) external { for (uint i=0; i<recipients.length; i++) { payAndNotify(token, recipients[i], amounts[i], ref); } } // Allows to make a payment from the sender to an address given an allowance to this contract // Equivalent to xchf.transferAndCall(recipient, amountInBase) function payAndNotify(address recipient, uint256 amountInBase, bytes calldata ref) external { payAndNotify(IBrokerbot(recipient).base(), recipient, amountInBase, ref); } function payAndNotify(IERC20 token, address recipient, uint256 amount, bytes calldata ref) public { require(IERC20(token).transferFrom(msg.sender, recipient, amount)); IBrokerbot(recipient).processIncoming(token, msg.sender, amount, ref); } function payFromEtherAndNotify(IBrokerbot recipient, uint256 amountInBase, bytes calldata ref) external payable { IERC20 base = recipient.base(); // Check if the brokerbot has setting to keep ETH if (hasSettingKeepEther(recipient)) { uint256 priceInEther = getPriceInEtherFromOracle(amountInBase, base); recipient.processIncoming{value: priceInEther}(base, msg.sender, amountInBase, ref); // Pay back ETH that was overpaid if (priceInEther < msg.value) { (bool success, ) = msg.sender.call{value:msg.value - priceInEther}(""); // return change require(success, "Transfer failed."); } } else { payFromEther(address(recipient), amountInBase, base); recipient.processIncoming(base, msg.sender, amountInBase, ref); } } /*** * Pay from any ERC20 token (which has Uniswapv3 ERC20-ETH pool) and send swapped base currency to brokerbot. * The needed amount needs to be approved at the ERC20 contract beforehand */ function payFromERC20AndNotify(address recipient, uint256 amountBase, address erc20, uint256 amountInMaximum, bytes memory path, bytes calldata ref) external { IERC20 base = IBrokerbot(recipient).base(); uint256 balanceBefore = IERC20(base).balanceOf(recipient); payFromERC20(amountBase, amountInMaximum, erc20, path, recipient); uint256 balanceAfter = IERC20(base).balanceOf(recipient); require(amountBase == (balanceAfter - balanceBefore), "swap error"); IBrokerbot(recipient).processIncoming(base, msg.sender, balanceAfter - balanceBefore, ref); } /** * Checks if the recipient(brokerbot) has setting enabled to keep ether */ function hasSettingKeepEther(IBrokerbot recipient) public view returns (bool) { return recipient.settings() & KEEP_ETHER == KEEP_ETHER; } /** * In case tokens have been accidentally sent directly to this contract. * Make sure to be fast as anyone can call this! */ function recover(IERC20 ercAddress, address to, uint256 amount) external { require(ercAddress.transfer(to, amount)); } // solhint-disable-next-line no-empty-blocks receive() external payable { // Important to receive ETH refund from Uniswap } } // SPDX-License-Identifier: MIT // Copied from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/Address.sol // and modified it. pragma solidity ^0.8.0; library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } function functionCallWithValue(address target, bytes memory data, uint256 weiValue) internal returns (bytes memory) { require(data.length == 0 || isContract(target), "transfer or contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else if (returndata.length > 0) { assembly{ revert (add (returndata, 0x20), mload (returndata)) } } else { revert("failed"); } } } // SPDX-License-Identifier: MIT // // From https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/Ownable.sol // // Modifications: // - Replaced Context._msgSender() with msg.sender // - Made leaner // - Extracted interface pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor (address initialOwner) { owner = initialOwner; emit OwnershipTransferred(address(0), owner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) external onlyOwner { emit OwnershipTransferred(owner, newOwner); owner = newOwner; } modifier onlyOwner() { require(owner == msg.sender, "not owner"); _; } }
@notice Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed) @param params The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata @return amountIn The amount of the input token* SPDX-License-Identifier: LicenseRef-Aktionariat MIT License with Automated License Fee Payments Copyright (c) 2021 Aktionariat AG (aktionariat.com) Permission is hereby granted to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - All automated license fee payments integrated into this and related Software are preserved. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE./* A hub for payments. This allows tokens that do not support ERC 677 to enjoy similar functionality, namely interacting with a token-handling smart contract in one transaction, without having to set an allowance first. Instead, an allowance needs to be set only once, namely for this contract. Further, it supports automatic conversion from Ether to the payment currency through Uniswap or the reception of Ether using the current exchange rate as found in the chainlink oracle./
contract PaymentHub { uint24 private constant DEFAULT_FEE = 3000; uint256 private constant DENOMINATOR = 1e8; address private constant CHF_TOKEN = 0xB4272071eCAdd69d933AdcD19cA99fe80664fc08; IQuoter private immutable uniswapQuoter; ISwapRouter private immutable uniswapRouter; AggregatorV3Interface internal immutable priceFeedCHFUSD; AggregatorV3Interface internal immutable priceFeedETHUSD; function exactOutput(ExactOutputParams calldata params) external payable returns (uint256 amountIn); function refundETH() external payable; } pragma solidity ^0.8.0; import "../utils/Address.sol"; import "../ERC20/IERC20.sol"; import "./IUniswapV3.sol"; import "../utils/Ownable.sol"; import "./IBrokerbot.sol"; import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol"; constructor(IQuoter _quoter, ISwapRouter swapRouter, AggregatorV3Interface _aggregatorCHFUSD, AggregatorV3Interface _aggregatorETHUSD) { uniswapQuoter = _quoter; uniswapRouter = swapRouter; priceFeedCHFUSD = _aggregatorCHFUSD; priceFeedETHUSD = _aggregatorETHUSD; } function getPriceInERC20(uint256 amountInBase, bytes memory path) public returns (uint256) { return uniswapQuoter.quoteExactOutput( path, amountInBase ); } function getPriceInEther(uint256 amountInBase, IBrokerbot brokerBot) public returns (uint256) { if ((address(brokerBot) != address(0)) && hasSettingKeepEther(brokerBot)) { return getPriceInEtherFromOracle(amountInBase, IBrokerbot(brokerBot).base()); return uniswapQuoter.quoteExactOutputSingle(uniswapQuoter.WETH9(), address(brokerBot.base()), DEFAULT_FEE, amountInBase, 0); } } function getPriceInEther(uint256 amountInBase, IBrokerbot brokerBot) public returns (uint256) { if ((address(brokerBot) != address(0)) && hasSettingKeepEther(brokerBot)) { return getPriceInEtherFromOracle(amountInBase, IBrokerbot(brokerBot).base()); return uniswapQuoter.quoteExactOutputSingle(uniswapQuoter.WETH9(), address(brokerBot.base()), DEFAULT_FEE, amountInBase, 0); } } } else { function getPriceInEtherFromOracle(uint256 amountInBase, IERC20 base) public view returns (uint256) { if(address(base) == CHF_TOKEN) { return getLatestPriceCHFUSD() * amountInBase / getLatestPriceETHUSD(); return amountInBase * DENOMINATOR / getLatestPriceETHUSD(); } } function getPriceInEtherFromOracle(uint256 amountInBase, IERC20 base) public view returns (uint256) { if(address(base) == CHF_TOKEN) { return getLatestPriceCHFUSD() * amountInBase / getLatestPriceETHUSD(); return amountInBase * DENOMINATOR / getLatestPriceETHUSD(); } } } else { function getLatestPriceETHUSD() public view returns (uint256) { (, int256 price, , , ) = priceFeedETHUSD.latestRoundData(); return uint256(price); } function getLatestPriceCHFUSD() public view returns (uint256) { (, int256 price, , , ) = priceFeedCHFUSD.latestRoundData(); return uint256(price); } function payFromEther(address recipient, uint256 amountInBase, IERC20 base) public payable { ISwapRouter.ExactOutputSingleParams memory params = ISwapRouter.ExactOutputSingleParams( uniswapQuoter.WETH9(), address(base), DEFAULT_FEE, recipient, block.timestamp, amountInBase, msg.value, 0); ISwapRouter swapRouter = uniswapRouter; if (amountIn < msg.value) { swapRouter.refundETH(); require(success, "Transfer failed."); } } uint256 amountIn = swapRouter.exactOutputSingle{value: msg.value}(params); function payFromEther(address recipient, uint256 amountInBase, IERC20 base) public payable { ISwapRouter.ExactOutputSingleParams memory params = ISwapRouter.ExactOutputSingleParams( uniswapQuoter.WETH9(), address(base), DEFAULT_FEE, recipient, block.timestamp, amountInBase, msg.value, 0); ISwapRouter swapRouter = uniswapRouter; if (amountIn < msg.value) { swapRouter.refundETH(); require(success, "Transfer failed."); } } function payFromERC20(uint256 amountOut, uint256 amountInMaximum, address erc20In, bytes memory path, address recipient) public returns (uint256 amountIn) { ISwapRouter swapRouter = uniswapRouter; IERC20(erc20In).transferFrom(msg.sender, address(this), amountInMaximum); ISwapRouter.ExactOutputParams memory params = ISwapRouter.ExactOutputParams({ path: path, recipient: recipient, deadline: block.timestamp, amountOut: amountOut, amountInMaximum: amountInMaximum }); if (amountIn < amountInMaximum) { IERC20(erc20In).transfer(msg.sender, amountInMaximum - amountIn); } } function payFromERC20(uint256 amountOut, uint256 amountInMaximum, address erc20In, bytes memory path, address recipient) public returns (uint256 amountIn) { ISwapRouter swapRouter = uniswapRouter; IERC20(erc20In).transferFrom(msg.sender, address(this), amountInMaximum); ISwapRouter.ExactOutputParams memory params = ISwapRouter.ExactOutputParams({ path: path, recipient: recipient, deadline: block.timestamp, amountOut: amountOut, amountInMaximum: amountInMaximum }); if (amountIn < amountInMaximum) { IERC20(erc20In).transfer(msg.sender, amountInMaximum - amountIn); } } amountIn = swapRouter.exactOutput(params); function payFromERC20(uint256 amountOut, uint256 amountInMaximum, address erc20In, bytes memory path, address recipient) public returns (uint256 amountIn) { ISwapRouter swapRouter = uniswapRouter; IERC20(erc20In).transferFrom(msg.sender, address(this), amountInMaximum); ISwapRouter.ExactOutputParams memory params = ISwapRouter.ExactOutputParams({ path: path, recipient: recipient, deadline: block.timestamp, amountOut: amountOut, amountInMaximum: amountInMaximum }); if (amountIn < amountInMaximum) { IERC20(erc20In).transfer(msg.sender, amountInMaximum - amountIn); } } function approveERC20(address erc20In) external { IERC20(erc20In).approve(address(uniswapRouter), 0x8000000000000000000000000000000000000000000000000000000000000000); } function multiPay(IERC20 token, address[] calldata recipients, uint256[] calldata amounts) public { for (uint i=0; i<recipients.length; i++) { require(IERC20(token).transferFrom(msg.sender, recipients[i], amounts[i])); } } function multiPay(IERC20 token, address[] calldata recipients, uint256[] calldata amounts) public { for (uint i=0; i<recipients.length; i++) { require(IERC20(token).transferFrom(msg.sender, recipients[i], amounts[i])); } } function multiPayAndNotify(IERC20 token, address[] calldata recipients, uint256[] calldata amounts, bytes calldata ref) external { for (uint i=0; i<recipients.length; i++) { payAndNotify(token, recipients[i], amounts[i], ref); } } function multiPayAndNotify(IERC20 token, address[] calldata recipients, uint256[] calldata amounts, bytes calldata ref) external { for (uint i=0; i<recipients.length; i++) { payAndNotify(token, recipients[i], amounts[i], ref); } } function payAndNotify(address recipient, uint256 amountInBase, bytes calldata ref) external { payAndNotify(IBrokerbot(recipient).base(), recipient, amountInBase, ref); } function payAndNotify(IERC20 token, address recipient, uint256 amount, bytes calldata ref) public { require(IERC20(token).transferFrom(msg.sender, recipient, amount)); IBrokerbot(recipient).processIncoming(token, msg.sender, amount, ref); } function payFromEtherAndNotify(IBrokerbot recipient, uint256 amountInBase, bytes calldata ref) external payable { IERC20 base = recipient.base(); if (hasSettingKeepEther(recipient)) { uint256 priceInEther = getPriceInEtherFromOracle(amountInBase, base); if (priceInEther < msg.value) { require(success, "Transfer failed."); } payFromEther(address(recipient), amountInBase, base); recipient.processIncoming(base, msg.sender, amountInBase, ref); } } function payFromEtherAndNotify(IBrokerbot recipient, uint256 amountInBase, bytes calldata ref) external payable { IERC20 base = recipient.base(); if (hasSettingKeepEther(recipient)) { uint256 priceInEther = getPriceInEtherFromOracle(amountInBase, base); if (priceInEther < msg.value) { require(success, "Transfer failed."); } payFromEther(address(recipient), amountInBase, base); recipient.processIncoming(base, msg.sender, amountInBase, ref); } } recipient.processIncoming{value: priceInEther}(base, msg.sender, amountInBase, ref); function payFromEtherAndNotify(IBrokerbot recipient, uint256 amountInBase, bytes calldata ref) external payable { IERC20 base = recipient.base(); if (hasSettingKeepEther(recipient)) { uint256 priceInEther = getPriceInEtherFromOracle(amountInBase, base); if (priceInEther < msg.value) { require(success, "Transfer failed."); } payFromEther(address(recipient), amountInBase, base); recipient.processIncoming(base, msg.sender, amountInBase, ref); } } } else { function payFromERC20AndNotify(address recipient, uint256 amountBase, address erc20, uint256 amountInMaximum, bytes memory path, bytes calldata ref) external { IERC20 base = IBrokerbot(recipient).base(); uint256 balanceBefore = IERC20(base).balanceOf(recipient); payFromERC20(amountBase, amountInMaximum, erc20, path, recipient); uint256 balanceAfter = IERC20(base).balanceOf(recipient); require(amountBase == (balanceAfter - balanceBefore), "swap error"); IBrokerbot(recipient).processIncoming(base, msg.sender, balanceAfter - balanceBefore, ref); } function hasSettingKeepEther(IBrokerbot recipient) public view returns (bool) { return recipient.settings() & KEEP_ETHER == KEEP_ETHER; } function recover(IERC20 ercAddress, address to, uint256 amount) external { require(ercAddress.transfer(to, amount)); } receive() external payable { } }
1,572,226
[ 1, 6050, 6679, 487, 12720, 487, 3323, 434, 1245, 1147, 364, 1375, 8949, 1182, 68, 434, 4042, 7563, 326, 1269, 589, 261, 266, 7548, 13, 225, 859, 1021, 1472, 4573, 364, 326, 3309, 17, 18444, 7720, 16, 3749, 487, 1375, 14332, 1447, 1370, 68, 316, 745, 892, 327, 3844, 382, 1021, 3844, 434, 326, 810, 1147, 11405, 28826, 17, 13211, 17, 3004, 30, 16832, 1957, 17, 37, 8629, 285, 12954, 270, 490, 1285, 16832, 598, 11809, 362, 690, 16832, 30174, 13838, 1346, 25417, 261, 71, 13, 26599, 21, 432, 8629, 285, 12954, 270, 432, 43, 261, 581, 24252, 12954, 270, 18, 832, 13, 8509, 353, 2674, 1637, 17578, 358, 1281, 6175, 28158, 3280, 279, 1610, 434, 333, 17888, 471, 3627, 7323, 1390, 261, 5787, 315, 21742, 6, 3631, 358, 10490, 316, 326, 24199, 2887, 9318, 16, 6508, 2887, 17732, 326, 14989, 358, 999, 16, 1610, 16, 5612, 16, 2691, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 16351, 12022, 8182, 288, 203, 203, 565, 2254, 3247, 3238, 5381, 3331, 67, 8090, 41, 273, 29839, 31, 203, 565, 2254, 5034, 3238, 5381, 463, 1157, 1872, 706, 3575, 273, 404, 73, 28, 31, 203, 565, 1758, 3238, 5381, 6469, 42, 67, 8412, 273, 374, 20029, 24, 5324, 3462, 11212, 73, 39, 986, 8148, 72, 29, 3707, 1871, 71, 40, 3657, 71, 37, 2733, 3030, 3672, 26, 1105, 7142, 6840, 31, 203, 203, 377, 203, 565, 467, 7678, 264, 3238, 11732, 640, 291, 91, 438, 7678, 264, 31, 203, 565, 4437, 91, 438, 8259, 3238, 11732, 640, 291, 91, 438, 8259, 31, 203, 565, 10594, 639, 58, 23, 1358, 2713, 11732, 6205, 8141, 1792, 42, 3378, 40, 31, 203, 565, 10594, 639, 58, 23, 1358, 2713, 11732, 6205, 8141, 1584, 44, 3378, 40, 31, 203, 203, 565, 445, 5565, 1447, 12, 14332, 1447, 1370, 745, 892, 859, 13, 3903, 8843, 429, 1135, 261, 11890, 5034, 3844, 382, 1769, 203, 377, 203, 565, 445, 16255, 1584, 44, 1435, 3903, 8843, 429, 31, 203, 97, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 20, 31, 203, 203, 5666, 315, 6216, 5471, 19, 1887, 18, 18281, 14432, 203, 5666, 315, 6216, 654, 39, 3462, 19, 45, 654, 39, 3462, 18, 18281, 14432, 203, 5666, 25165, 45, 984, 291, 91, 438, 58, 23, 18, 18281, 14432, 203, 5666, 315, 6216, 5471, 19, 5460, 429, 18, 18281, 14432, 203, 5666, 25165, 45, 11194, 4819, 18, 18281, 14432, 203, 5666, 8787, 5639, 1232, 19, 16351, 87, 19, 2 ]
//Address: 0x742686bB1B136b396b59818F42e47a4fC3509394 //Contract name: WCMToken //Balance: 0 Ether //Verification Date: 10/23/2017 //Transacion Count: 69 // CODE STARTS HERE pragma solidity ^0.4.16; /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) constant returns (uint256); function transfer(address to, uint256 value) returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) constant returns (uint256); function transferFrom(address from, address to, uint256 value) returns (bool); function approve(address spender, uint256 value) returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal constant returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal constant returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) returns (bool) { balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amout of tokens to be transfered */ function transferFrom(address _from, address _to, uint256 _value) returns (bool) { var _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // require (_value <= _allowance); balances[_to] = balances[_to].add(_value); balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender. * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) returns (bool) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifing the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner { require(newOwner != address(0)); owner = newOwner; } } /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public finishMinting = false; address public saleAgent; function setSaleAgent(address newSaleAgnet) { require(msg.sender == saleAgent || msg.sender == owner); saleAgent = newSaleAgnet; } /** * @dev Function to mint tokens * @param _to The address that will recieve the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) returns (bool) { require(msg.sender == saleAgent && !finishMinting); totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() returns (bool) { require(msg.sender == saleAgent || msg.sender == owner && !finishMinting); finishMinting = true; MintFinished(); return true; } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev modifier to allow actions only when the contract IS paused */ modifier whenNotPaused() { require(!paused); _; } /** * @dev modifier to allow actions only when the contract IS NOT paused */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused { paused = true; Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused { paused = false; Unpause(); } } contract WCMToken is MintableToken { string public constant name = "WCMT"; string public constant symbol = "WCM tokens"; uint32 public constant decimals = 18; } contract StagedCrowdsale is Pausable { using SafeMath for uint; struct Milestone { uint period; uint bonus; } uint public start; uint public totalPeriod; uint public invested; uint public hardCap; Milestone[] public milestones; function milestonesCount() constant returns(uint) { return milestones.length; } function setStart(uint newStart) onlyOwner { start = newStart; } function setHardcap(uint newHardcap) onlyOwner { hardCap = newHardcap; } function addMilestone(uint period, uint bonus) onlyOwner { require(period > 0); milestones.push(Milestone(period, bonus)); totalPeriod = totalPeriod.add(period); } function removeMilestones(uint8 number) onlyOwner { require(number < milestones.length); Milestone storage milestone = milestones[number]; totalPeriod = totalPeriod.sub(milestone.period); delete milestones[number]; for (uint i = number; i < milestones.length - 1; i++) { milestones[i] = milestones[i+1]; } milestones.length--; } function changeMilestone(uint8 number, uint period, uint bonus) onlyOwner { require(number < milestones.length); Milestone storage milestone = milestones[number]; totalPeriod = totalPeriod.sub(milestone.period); milestone.period = period; milestone.bonus = bonus; totalPeriod = totalPeriod.add(period); } function insertMilestone(uint8 numberAfter, uint period, uint bonus) onlyOwner { require(numberAfter < milestones.length); totalPeriod = totalPeriod.add(period); milestones.length++; for (uint i = milestones.length - 2; i > numberAfter; i--) { milestones[i + 1] = milestones[i]; } milestones[numberAfter + 1] = Milestone(period, bonus); } function clearMilestones() onlyOwner { require(milestones.length > 0); for (uint i = 0; i < milestones.length; i++) { delete milestones[i]; } milestones.length -= milestones.length; totalPeriod = 0; } modifier saleIsOn() { require(milestones.length > 0 && now >= start && now < lastSaleDate()); _; } modifier isUnderHardCap() { require(invested <= hardCap); _; } function lastSaleDate() constant returns(uint) { require(milestones.length > 0); return start + totalPeriod * 1 days; } function currentMilestone() saleIsOn constant returns(uint) { uint previousDate = start; for(uint i=0; i < milestones.length; i++) { if(now >= previousDate && now < previousDate + milestones[i].period * 1 days) { return i; } previousDate = previousDate.add(milestones[i].period * 1 days); } revert(); } } // FIX for freezed alien tokens, price and etc contract CommonSale is StagedCrowdsale { address public multisigWallet; address public foundersTokensWallet; address public bountyTokensWallet; uint public foundersPercent; uint public bountyTokensCount; uint public price; uint public percentRate = 100; bool public bountyMinted = false; CommonSale public nextSale; MintableToken public token; function setToken(address newToken) onlyOwner { token = MintableToken(newToken); } function setNextSale(address newNextSale) onlyOwner { nextSale = CommonSale(newNextSale); } function setPrice(uint newPrice) onlyOwner { price = newPrice; } function setPercentRate(uint newPercentRate) onlyOwner { percentRate = newPercentRate; } function setFoundersPercent(uint newFoundersPercent) onlyOwner { foundersPercent = newFoundersPercent; } function setBountyTokensCount(uint newBountyTokensCount) onlyOwner { bountyTokensCount = newBountyTokensCount; } function setMultisigWallet(address newMultisigWallet) onlyOwner { multisigWallet = newMultisigWallet; } function setFoundersTokensWallet(address newFoundersTokensWallet) onlyOwner { foundersTokensWallet = newFoundersTokensWallet; } function setBountyTokensWallet(address newBountyTokensWallet) onlyOwner { bountyTokensWallet = newBountyTokensWallet; } function createTokens() whenNotPaused isUnderHardCap saleIsOn payable { require(msg.value > 0); uint milestoneIndex = currentMilestone(); Milestone storage milestone = milestones[milestoneIndex]; multisigWallet.transfer(msg.value); invested = invested.add(msg.value); uint tokens = msg.value.div(price).mul(1 ether); uint bonusTokens = tokens.div(percentRate).mul(milestone.bonus); uint tokensWithBonus = tokens.add(bonusTokens); token.mint(msg.sender, tokensWithBonus); uint foundersTokens = tokens.div(percentRate).mul(foundersPercent); token.mint(foundersTokensWallet, foundersTokens); } function mintBounty() public whenNotPaused onlyOwner { require(!bountyMinted); token.mint(bountyTokensWallet, bountyTokensCount * 1 ether); bountyMinted = true; } function finishMinting() public whenNotPaused onlyOwner { if(nextSale == address(0)) { token.finishMinting(); } else { token.setSaleAgent(nextSale); } } function() external payable { createTokens(); } function retrieveTokens(address anotherToken) public onlyOwner { ERC20 alienToken = ERC20(anotherToken); alienToken.transfer(multisigWallet, token.balanceOf(this)); } }
FIX for freezed alien tokens, price and etc
contract CommonSale is StagedCrowdsale { address public multisigWallet; address public foundersTokensWallet; address public bountyTokensWallet; uint public foundersPercent; uint public bountyTokensCount; uint public price; uint public percentRate = 100; bool public bountyMinted = false; CommonSale public nextSale; MintableToken public token; function setToken(address newToken) onlyOwner { token = MintableToken(newToken); } function setNextSale(address newNextSale) onlyOwner { nextSale = CommonSale(newNextSale); } function setPrice(uint newPrice) onlyOwner { price = newPrice; } function setPercentRate(uint newPercentRate) onlyOwner { percentRate = newPercentRate; } function setFoundersPercent(uint newFoundersPercent) onlyOwner { foundersPercent = newFoundersPercent; } function setBountyTokensCount(uint newBountyTokensCount) onlyOwner { bountyTokensCount = newBountyTokensCount; } function setMultisigWallet(address newMultisigWallet) onlyOwner { multisigWallet = newMultisigWallet; } function setFoundersTokensWallet(address newFoundersTokensWallet) onlyOwner { foundersTokensWallet = newFoundersTokensWallet; } function setBountyTokensWallet(address newBountyTokensWallet) onlyOwner { bountyTokensWallet = newBountyTokensWallet; } function createTokens() whenNotPaused isUnderHardCap saleIsOn payable { require(msg.value > 0); uint milestoneIndex = currentMilestone(); Milestone storage milestone = milestones[milestoneIndex]; multisigWallet.transfer(msg.value); invested = invested.add(msg.value); uint tokens = msg.value.div(price).mul(1 ether); uint bonusTokens = tokens.div(percentRate).mul(milestone.bonus); uint tokensWithBonus = tokens.add(bonusTokens); token.mint(msg.sender, tokensWithBonus); uint foundersTokens = tokens.div(percentRate).mul(foundersPercent); token.mint(foundersTokensWallet, foundersTokens); } function mintBounty() public whenNotPaused onlyOwner { require(!bountyMinted); token.mint(bountyTokensWallet, bountyTokensCount * 1 ether); bountyMinted = true; } function finishMinting() public whenNotPaused onlyOwner { if(nextSale == address(0)) { token.finishMinting(); token.setSaleAgent(nextSale); } } function finishMinting() public whenNotPaused onlyOwner { if(nextSale == address(0)) { token.finishMinting(); token.setSaleAgent(nextSale); } } } else { function() external payable { createTokens(); } function retrieveTokens(address anotherToken) public onlyOwner { ERC20 alienToken = ERC20(anotherToken); alienToken.transfer(multisigWallet, token.balanceOf(this)); } }
12,854,357
[ 1, 4563, 364, 4843, 94, 329, 15033, 275, 2430, 16, 6205, 471, 5527, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 5658, 30746, 353, 934, 11349, 39, 492, 2377, 5349, 288, 203, 203, 225, 1758, 1071, 22945, 360, 16936, 31, 203, 21281, 225, 1758, 1071, 1392, 414, 5157, 16936, 31, 203, 21281, 225, 1758, 1071, 324, 592, 93, 5157, 16936, 31, 203, 203, 225, 2254, 1071, 1392, 414, 8410, 31, 203, 21281, 225, 2254, 1071, 324, 592, 93, 5157, 1380, 31, 203, 7010, 225, 2254, 1071, 6205, 31, 203, 203, 225, 2254, 1071, 5551, 4727, 273, 2130, 31, 203, 203, 225, 1426, 1071, 324, 592, 93, 49, 474, 329, 273, 629, 31, 203, 21281, 225, 5658, 30746, 1071, 1024, 30746, 31, 203, 21281, 225, 490, 474, 429, 1345, 1071, 1147, 31, 203, 203, 225, 445, 22629, 12, 2867, 394, 1345, 13, 1338, 5541, 288, 203, 565, 1147, 273, 490, 474, 429, 1345, 12, 2704, 1345, 1769, 203, 225, 289, 203, 203, 225, 445, 27674, 30746, 12, 2867, 394, 2134, 30746, 13, 1338, 5541, 288, 203, 565, 1024, 30746, 273, 5658, 30746, 12, 2704, 2134, 30746, 1769, 203, 225, 289, 203, 203, 225, 445, 444, 5147, 12, 11890, 394, 5147, 13, 1338, 5541, 288, 203, 565, 6205, 273, 394, 5147, 31, 203, 225, 289, 203, 203, 225, 445, 444, 8410, 4727, 12, 11890, 394, 8410, 4727, 13, 1338, 5541, 288, 203, 565, 5551, 4727, 273, 394, 8410, 4727, 31, 203, 225, 289, 203, 203, 225, 445, 444, 2043, 414, 8410, 12, 11890, 394, 2043, 414, 8410, 13, 1338, 5541, 288, 203, 565, 1392, 414, 8410, 273, 394, 2043, 414, 8410, 31, 203, 225, 289, 203, 2 ]
/* Copyright 2017 Loopring Project Ltd (Loopring Foundation). Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.4.19; /// @title Utility Functions for uint8 /// @author Kongliang Zhong - <[email protected]>, /// @author Daniel Wang - <[email protected]>. library MathUint8 { function xorReduce( uint8[] arr, uint len ) internal pure returns (uint8 res) { res = arr[0]; for (uint i = 1; i < len; i++) { res ^= arr[i]; } } } /* Copyright 2017 Loopring Project Ltd (Loopring Foundation). Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /// @title Utility Functions for uint /// @author Daniel Wang - <[email protected]> library MathUint { function mul(uint a, uint b) internal pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function sub(uint a, uint b) internal pure returns (uint) { require(b <= a); return a - b; } function add(uint a, uint b) internal pure returns (uint c) { c = a + b; require(c >= a); } function tolerantSub(uint a, uint b) internal pure returns (uint c) { return (a >= b) ? a - b : 0; } /// @dev calculate the square of Coefficient of Variation (CV) /// https://en.wikipedia.org/wiki/Coefficient_of_variation function cvsquare( uint[] arr, uint scale ) internal pure returns (uint) { uint len = arr.length; require(len > 1); require(scale > 0); uint avg = 0; for (uint i = 0; i < len; i++) { avg += arr[i]; } avg = avg / len; if (avg == 0) { return 0; } uint cvs = 0; uint s; uint item; for (i = 0; i < len; i++) { item = arr[i]; s = item > avg ? item - avg : avg - item; cvs += mul(s, s); } return ((mul(mul(cvs, scale), scale) / avg) / avg) / (len - 1); } } /* Copyright 2017 Loopring Project Ltd (Loopring Foundation). Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /// @title Utility Functions for byte32 /// @author Kongliang Zhong - <[email protected]>, /// @author Daniel Wang - <[email protected]>. library MathBytes32 { function xorReduce( bytes32[] arr, uint len ) internal pure returns (bytes32 res) { res = arr[0]; for (uint i = 1; i < len; i++) { res ^= arr[i]; } } } /* Copyright 2017 Loopring Project Ltd (Loopring Foundation). Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /* Copyright 2017 Loopring Project Ltd (Loopring Foundation). Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /// @title ERC20 Token Interface /// @dev see https://github.com/ethereum/EIPs/issues/20 /// @author Daniel Wang - <[email protected]> contract ERC20 { uint public totalSupply; event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); function balanceOf(address who) view public returns (uint256); function allowance(address owner, address spender) view public returns (uint256); function transfer(address to, uint256 value) public returns (bool); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); } /* Copyright 2017 Loopring Project Ltd (Loopring Foundation). Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /// @title Loopring Token Exchange Protocol Contract Interface /// @author Daniel Wang - <[email protected]> /// @author Kongliang Zhong - <[email protected]> contract LoopringProtocol { //////////////////////////////////////////////////////////////////////////// /// Constants /// //////////////////////////////////////////////////////////////////////////// uint8 public constant MARGIN_SPLIT_PERCENTAGE_BASE = 100; //////////////////////////////////////////////////////////////////////////// /// Events /// //////////////////////////////////////////////////////////////////////////// /// @dev Event to emit if a ring is successfully mined. /// _amountsList is an array of: /// [_amountS, _amountB, _lrcReward, _lrcFee, splitS, splitB]. event RingMined( uint _ringIndex, bytes32 indexed _ringHash, address _miner, address _feeRecipient, bytes32[] _orderHashList, uint[6][] _amountsList ); event OrderCancelled( bytes32 indexed _orderHash, uint _amountCancelled ); event AllOrdersCancelled( address indexed _address, uint _cutoff ); event OrdersCancelled( address indexed _address, address _token1, address _token2, uint _cutoff ); //////////////////////////////////////////////////////////////////////////// /// Functions /// //////////////////////////////////////////////////////////////////////////// /// @dev Cancel a order. cancel amount(amountS or amountB) can be specified /// in orderValues. /// @param addresses owner, tokenS, tokenB, authAddr /// @param orderValues amountS, amountB, validSince (second), /// validUntil (second), lrcFee, walletId, and /// cancelAmount. /// @param buyNoMoreThanAmountB - /// This indicates when a order should be considered /// as 'completely filled'. /// @param marginSplitPercentage - /// Percentage of margin split to share with miner. /// @param v Order ECDSA signature parameter v. /// @param r Order ECDSA signature parameters r. /// @param s Order ECDSA signature parameters s. function cancelOrder( address[4] addresses, uint[7] orderValues, bool buyNoMoreThanAmountB, uint8 marginSplitPercentage, uint8 v, bytes32 r, bytes32 s ) external; /// @dev Set a cutoff timestamp to invalidate all orders whose timestamp /// is smaller than or equal to the new value of the address's cutoff /// timestamp, for a specific trading pair. /// @param cutoff The cutoff timestamp, will default to `block.timestamp` /// if it is 0. function cancelAllOrdersByTradingPair( address token1, address token2, uint cutoff ) external; /// @dev Set a cutoff timestamp to invalidate all orders whose timestamp /// is smaller than or equal to the new value of the address's cutoff /// timestamp. /// @param cutoff The cutoff timestamp, will default to `block.timestamp` /// if it is 0. function cancelAllOrders(uint cutoff) external; /// @dev Submit a order-ring for validation and settlement. /// @param addressList List of each order's owner, tokenS, and authAddr. /// Note that next order's `tokenS` equals this order's /// `tokenB`. /// @param uintArgsList List of uint-type arguments in this order: /// amountS, amountB, validSince (second), /// validUntil (second), lrcFee, rateAmountS, and walletId. /// @param uint8ArgsList - /// List of unit8-type arguments, in this order: /// marginSplitPercentageList. /// @param buyNoMoreThanAmountBList - /// This indicates when a order should be considered /// @param vList List of v for each order. This list is 1-larger than /// the previous lists, with the last element being the /// v value of the ring signature. /// @param rList List of r for each order. This list is 1-larger than /// the previous lists, with the last element being the /// r value of the ring signature. /// @param sList List of s for each order. This list is 1-larger than /// the previous lists, with the last element being the /// s value of the ring signature. /// @param minerId The address pair that miner registered in NameRegistry. /// The address pair contains a signer address and a fee /// recipient address. /// The signer address is used for sign this tx. /// The Recipient address for fee collection. If this is /// '0x0', all fees will be paid to the address who had /// signed this transaction, not `msg.sender`. Noted if /// LRC need to be paid back to order owner as the result /// of fee selection model, LRC will also be sent from /// this address. /// @param feeSelections - /// Bits to indicate fee selections. `1` represents margin /// split and `0` represents LRC as fee. function submitRing( address[3][] addressList, uint[7][] uintArgsList, uint8[1][] uint8ArgsList, bool[] buyNoMoreThanAmountBList, uint8[] vList, bytes32[] rList, bytes32[] sList, uint minerId, uint16 feeSelections ) public; } /* Copyright 2017 Loopring Project Ltd (Loopring Foundation). Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /// @title Ethereum Address Register Contract /// @dev This contract maintains a name service for addresses and miner. /// @author Kongliang Zhong - <[email protected]>, /// @author Daniel Wang - <[email protected]>, contract NameRegistry { uint public nextId = 0; mapping (uint => Participant) public participantMap; mapping (address => NameInfo) public nameInfoMap; mapping (bytes12 => address) public ownerMap; mapping (address => string) public nameMap; struct NameInfo { bytes12 name; uint[] participantIds; } struct Participant { address feeRecipient; address signer; bytes12 name; address owner; } event NameRegistered ( string name, address indexed owner ); event NameUnregistered ( string name, address indexed owner ); event OwnershipTransfered ( bytes12 name, address oldOwner, address newOwner ); event ParticipantRegistered ( bytes12 name, address indexed owner, uint indexed participantId, address singer, address feeRecipient ); event ParticipantUnregistered ( uint participantId, address owner ); function registerName(string name) external { require(isNameValid(name)); bytes12 nameBytes = stringToBytes12(name); require(ownerMap[nameBytes] == 0x0); require(stringToBytes12(nameMap[msg.sender]) == bytes12(0x0)); nameInfoMap[msg.sender] = NameInfo(nameBytes, new uint[](0)); ownerMap[nameBytes] = msg.sender; nameMap[msg.sender] = name; NameRegistered(name, msg.sender); } function unregisterName(string name) external { NameInfo storage nameInfo = nameInfoMap[msg.sender]; uint[] storage participantIds = nameInfo.participantIds; bytes12 nameBytes = stringToBytes12(name); require(nameInfo.name == nameBytes); for (uint i = participantIds.length - 1; i >= 0; i--) { delete participantMap[participantIds[i]]; } delete nameInfoMap[msg.sender]; delete nameMap[msg.sender]; delete ownerMap[nameBytes]; NameUnregistered(name, msg.sender); } function transferOwnership(address newOwner) external { require(newOwner != 0x0); require(nameInfoMap[newOwner].name.length == 0); NameInfo storage nameInfo = nameInfoMap[msg.sender]; string storage name = nameMap[msg.sender]; uint[] memory participantIds = nameInfo.participantIds; for (uint i = 0; i < participantIds.length; i ++) { Participant storage p = participantMap[participantIds[i]]; p.owner = newOwner; } delete nameInfoMap[msg.sender]; delete nameMap[msg.sender]; nameInfoMap[newOwner] = nameInfo; nameMap[newOwner] = name; OwnershipTransfered(nameInfo.name, msg.sender, newOwner); } /* function addParticipant(address feeRecipient) */ /* external */ /* returns (uint) */ /* { */ /* return addParticipant(feeRecipient, feeRecipient); */ /* } */ function addParticipant( address feeRecipient, address singer ) external returns (uint) { require(feeRecipient != 0x0 && singer != 0x0); NameInfo storage nameInfo = nameInfoMap[msg.sender]; bytes12 name = nameInfo.name; require(name.length > 0); Participant memory participant = Participant( feeRecipient, singer, name, msg.sender ); uint participantId = ++nextId; participantMap[participantId] = participant; nameInfo.participantIds.push(participantId); ParticipantRegistered( name, msg.sender, participantId, singer, feeRecipient ); return participantId; } function removeParticipant(uint participantId) external { require(msg.sender == participantMap[participantId].owner); NameInfo storage nameInfo = nameInfoMap[msg.sender]; uint[] storage participantIds = nameInfo.participantIds; delete participantMap[participantId]; uint len = participantIds.length; for (uint i = 0; i < len; i ++) { if (participantId == participantIds[i]) { participantIds[i] = participantIds[len - 1]; participantIds.length -= 1; } } ParticipantUnregistered(participantId, msg.sender); } function getParticipantById(uint id) external view returns (address feeRecipient, address signer) { Participant storage addressSet = participantMap[id]; feeRecipient = addressSet.feeRecipient; signer = addressSet.signer; } function getParticipantIds(string name, uint start, uint count) external view returns (uint[] idList) { bytes12 nameBytes = stringToBytes12(name); address owner = ownerMap[nameBytes]; require(owner != 0x0); NameInfo storage nameInfo = nameInfoMap[owner]; uint[] storage pIds = nameInfo.participantIds; uint len = pIds.length; if (start >= len) { return; } uint end = start + count; if (end > len) { end = len; } if (start == end) { return; } idList = new uint[](end - start); for (uint i = start; i < end; i ++) { idList[i - start] = pIds[i]; } } function getOwner(string name) external view returns (address) { bytes12 nameBytes = stringToBytes12(name); return ownerMap[nameBytes]; } function isNameValid(string name) internal pure returns (bool) { bytes memory temp = bytes(name); return temp.length >= 6 && temp.length <= 12; } function stringToBytes12(string str) internal pure returns (bytes12 result) { assembly { result := mload(add(str, 12)) } } } /* Copyright 2017 Loopring Project Ltd (Loopring Foundation). Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /* Copyright 2017 Loopring Project Ltd (Loopring Foundation). Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /* Copyright 2017 Loopring Project Ltd (Loopring Foundation). Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /// @title Ownable /// @dev The Ownable contract has an owner address, and provides basic /// authorization control functions, this simplifies the implementation of /// "user permissions". contract Ownable { address public owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /// @dev The Ownable constructor sets the original `owner` of the contract /// to the sender. function Ownable() public { owner = msg.sender; } /// @dev Throws if called by any account other than the owner. modifier onlyOwner() { require(msg.sender == owner); _; } /// @dev Allows the current owner to transfer control of the contract to a /// newOwner. /// @param newOwner The address to transfer ownership to. function transferOwnership(address newOwner) onlyOwner public { require(newOwner != 0x0); OwnershipTransferred(owner, newOwner); owner = newOwner; } } /// @title Claimable /// @dev Extension for the Ownable contract, where the ownership needs /// to be claimed. This allows the new owner to accept the transfer. contract Claimable is Ownable { address public pendingOwner; /// @dev Modifier throws if called by any account other than the pendingOwner. modifier onlyPendingOwner() { require(msg.sender == pendingOwner); _; } /// @dev Allows the current owner to set the pendingOwner address. /// @param newOwner The address to transfer ownership to. function transferOwnership(address newOwner) onlyOwner public { require(newOwner != 0x0 && newOwner != owner); pendingOwner = newOwner; } /// @dev Allows the pendingOwner address to finalize the transfer. function claimOwnership() onlyPendingOwner public { OwnershipTransferred(owner, pendingOwner); owner = pendingOwner; pendingOwner = 0x0; } } /// @title Token Register Contract /// @dev This contract maintains a list of tokens the Protocol supports. /// @author Kongliang Zhong - <[email protected]>, /// @author Daniel Wang - <[email protected]>. contract TokenRegistry is Claimable { address[] public addresses; mapping (address => TokenInfo) addressMap; mapping (string => address) symbolMap; //////////////////////////////////////////////////////////////////////////// /// Structs /// //////////////////////////////////////////////////////////////////////////// struct TokenInfo { uint pos; // 0 mens unregistered; if > 0, pos + 1 is the // token's position in `addresses`. string symbol; // Symbol of the token } //////////////////////////////////////////////////////////////////////////// /// Events /// //////////////////////////////////////////////////////////////////////////// event TokenRegistered(address addr, string symbol); event TokenUnregistered(address addr, string symbol); //////////////////////////////////////////////////////////////////////////// /// Public Functions /// //////////////////////////////////////////////////////////////////////////// /// @dev Disable default function. function () payable public { revert(); } function registerToken( address addr, string symbol ) external onlyOwner { require(0x0 != addr); require(bytes(symbol).length > 0); require(0x0 == symbolMap[symbol]); require(0 == addressMap[addr].pos); addresses.push(addr); symbolMap[symbol] = addr; addressMap[addr] = TokenInfo(addresses.length, symbol); TokenRegistered(addr, symbol); } function unregisterToken( address addr, string symbol ) external onlyOwner { require(addr != 0x0); require(symbolMap[symbol] == addr); delete symbolMap[symbol]; uint pos = addressMap[addr].pos; require(pos != 0); delete addressMap[addr]; // We will replace the token we need to unregister with the last token // Only the pos of the last token will need to be updated address lastToken = addresses[addresses.length - 1]; // Don't do anything if the last token is the one we want to delete if (addr != lastToken) { // Swap with the last token and update the pos addresses[pos - 1] = lastToken; addressMap[lastToken].pos = pos; } addresses.length--; TokenUnregistered(addr, symbol); } function areAllTokensRegistered(address[] addressList) external view returns (bool) { for (uint i = 0; i < addressList.length; i++) { if (addressMap[addressList[i]].pos == 0) { return false; } } return true; } function getAddressBySymbol(string symbol) external view returns (address) { return symbolMap[symbol]; } function isTokenRegisteredBySymbol(string symbol) public view returns (bool) { return symbolMap[symbol] != 0x0; } function isTokenRegistered(address addr) public view returns (bool) { return addressMap[addr].pos != 0; } function getTokens( uint start, uint count ) public view returns (address[] addressList) { uint num = addresses.length; if (start >= num) { return; } uint end = start + count; if (end > num) { end = num; } if (start == num) { return; } addressList = new address[](end - start); for (uint i = start; i < end; i++) { addressList[i - start] = addresses[i]; } } } /* Copyright 2017 Loopring Project Ltd (Loopring Foundation). Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /// @title TokenTransferDelegate /// @dev Acts as a middle man to transfer ERC20 tokens on behalf of different /// versions of Loopring protocol to avoid ERC20 re-authorization. /// @author Daniel Wang - <[email protected]>. contract TokenTransferDelegate is Claimable { using MathUint for uint; //////////////////////////////////////////////////////////////////////////// /// Variables /// //////////////////////////////////////////////////////////////////////////// mapping(address => AddressInfo) private addressInfos; address public latestAddress; //////////////////////////////////////////////////////////////////////////// /// Structs /// //////////////////////////////////////////////////////////////////////////// struct AddressInfo { address previous; uint32 index; bool authorized; } //////////////////////////////////////////////////////////////////////////// /// Modifiers /// //////////////////////////////////////////////////////////////////////////// modifier onlyAuthorized() { require(addressInfos[msg.sender].authorized); _; } //////////////////////////////////////////////////////////////////////////// /// Events /// //////////////////////////////////////////////////////////////////////////// event AddressAuthorized(address indexed addr, uint32 number); event AddressDeauthorized(address indexed addr, uint32 number); //////////////////////////////////////////////////////////////////////////// /// Public Functions /// //////////////////////////////////////////////////////////////////////////// /// @dev Disable default function. function () payable public { revert(); } /// @dev Add a Loopring protocol address. /// @param addr A loopring protocol address. function authorizeAddress(address addr) onlyOwner external { AddressInfo storage addrInfo = addressInfos[addr]; if (addrInfo.index != 0) { // existing if (addrInfo.authorized == false) { // re-authorize addrInfo.authorized = true; AddressAuthorized(addr, addrInfo.index); } } else { address prev = latestAddress; if (prev == 0x0) { addrInfo.index = 1; addrInfo.authorized = true; } else { addrInfo.previous = prev; addrInfo.index = addressInfos[prev].index + 1; } addrInfo.authorized = true; latestAddress = addr; AddressAuthorized(addr, addrInfo.index); } } /// @dev Remove a Loopring protocol address. /// @param addr A loopring protocol address. function deauthorizeAddress(address addr) onlyOwner external { uint32 index = addressInfos[addr].index; if (index != 0) { addressInfos[addr].authorized = false; AddressDeauthorized(addr, index); } } function getLatestAuthorizedAddresses(uint max) external view returns (address[] addresses) { addresses = new address[](max); address addr = latestAddress; AddressInfo memory addrInfo; uint count = 0; while (addr != 0x0 && count < max) { addrInfo = addressInfos[addr]; if (addrInfo.index == 0) { break; } addresses[count++] = addr; addr = addrInfo.previous; } } /// @dev Invoke ERC20 transferFrom method. /// @param token Address of token to transfer. /// @param from Address to transfer token from. /// @param to Address to transfer token to. /// @param value Amount of token to transfer. function transferToken( address token, address from, address to, uint value) onlyAuthorized external { if (value > 0 && from != to && to != 0x0) { require( ERC20(token).transferFrom(from, to, value) ); } } function batchTransferToken( address lrcTokenAddress, address feeRecipient, bytes32[] batch) onlyAuthorized external { uint len = batch.length; require(len % 6 == 0); ERC20 lrc = ERC20(lrcTokenAddress); for (uint i = 0; i < len; i += 6) { address owner = address(batch[i]); address prevOwner = address(batch[(i + len - 6) % len]); // Pay token to previous order, or to miner as previous order's // margin split or/and this order's margin split. ERC20 token = ERC20(address(batch[i + 1])); // Here batch[i+2] has been checked not to be 0. if (owner != prevOwner) { require( token.transferFrom(owner, prevOwner, uint(batch[i + 2])) ); } if (feeRecipient != 0x0 && owner != feeRecipient) { bytes32 item = batch[i + 3]; if (item != 0) { require( token.transferFrom(owner, feeRecipient, uint(item)) ); } item = batch[i + 4]; if (item != 0) { require( lrc.transferFrom(feeRecipient, owner, uint(item)) ); } item = batch[i + 5]; if (item != 0) { require( lrc.transferFrom(owner, feeRecipient, uint(item)) ); } } } } function isAddressAuthorized(address addr) public view returns (bool) { return addressInfos[addr].authorized; } } /// @title Loopring Token Exchange Protocol Implementation Contract /// @author Daniel Wang - <[email protected]>, /// @author Kongliang Zhong - <[email protected]> /// /// Recognized contributing developers from the community: /// https://github.com/Brechtpd /// https://github.com/rainydio /// https://github.com/BenjaminPrice /// https://github.com/jonasshen contract LoopringProtocolImpl is LoopringProtocol { using MathBytes32 for bytes32[]; using MathUint for uint; using MathUint8 for uint8[]; //////////////////////////////////////////////////////////////////////////// /// Variables /// //////////////////////////////////////////////////////////////////////////// address constant public lrcTokenAddress = 0xEF68e7C694F40c8202821eDF525dE3782458639f; address constant public tokenRegistryAddress = 0xa21c1f2AE7f721aE77b1204A4f0811c642638da9; address constant public delegateAddress = 0xc787aE8D6560FB77B82F42CED8eD39f94961e304; address constant public nameRegistryAddress = 0xd181c1808e3f010F0F0aABc6Fe1bcE2025DB7Bb7; uint8 constant public walletSplitPercentage = 20; // Exchange rate (rate) is the amount to sell or sold divided by the amount // to buy or bought. // // Rate ratio is the ratio between executed rate and an order's original // rate. // // To require all orders' rate ratios to have coefficient ofvariation (CV) // smaller than 2.5%, for an example , rateRatioCVSThreshold should be: // `(0.025 * RATE_RATIO_SCALE)^2` or 62500. uint constant public rateRatioCVSThreshold = 62500; uint64 public ringIndex = 0; uint public constant MAX_RING_SIZE = 16; uint public constant RATE_RATIO_SCALE = 10000; uint64 public constant ENTERED_MASK = 1 << 63; // The following map is used to keep trace of order fill and cancellation // history. mapping (bytes32 => uint) public cancelledOrFilled; // This map is used to keep trace of order's cancellation history. mapping (bytes32 => uint) public cancelled; // A map from address to its cutoff timestamp. mapping (address => uint) public cutoffs; // A map from address to its trading-pair cutoff timestamp. mapping (address => mapping (bytes20 => uint)) public tradingPairCutoffs; //////////////////////////////////////////////////////////////////////////// /// Structs /// //////////////////////////////////////////////////////////////////////////// struct Rate { uint amountS; uint amountB; } /// @param tokenS Token to sell. /// @param tokenB Token to buy. /// @param amountS Maximum amount of tokenS to sell. /// @param amountB Minimum amount of tokenB to buy if all amountS sold. /// @param authAddr An address to verify miner has access to the order's /// auth private-key. /// @param validSince Indicating when this order should be treated as /// valid for trading, in second. /// @param validUntil Indicating when this order should be treated as /// expired, in second. /// @param lrcFee Max amount of LRC to pay for miner. The real amount /// to pay is proportional to fill amount. /// @param buyNoMoreThanAmountB - /// If true, this order does not accept buying more /// than `amountB`. /// @param walletId The id of the wallet that generated this order. /// @param marginSplitPercentage - /// The percentage of margin paid to miner. /// @param v ECDSA signature parameter v. /// @param r ECDSA signature parameters r. /// @param s ECDSA signature parameters s. struct Order { address owner; address tokenS; address tokenB; address authAddr; uint validSince; uint validUntil; uint amountS; uint amountB; uint lrcFee; bool buyNoMoreThanAmountB; uint walletId; uint8 marginSplitPercentage; } /// @param order The original order /// @param orderHash The order's hash /// @param feeSelection - /// A miner-supplied value indicating if LRC (value = 0) /// or margin split is choosen by the miner (value = 1). /// We may support more fee model in the future. /// @param rate Exchange rate provided by miner. /// @param fillAmountS Amount of tokenS to sell, calculated by protocol. /// @param lrcReward The amount of LRC paid by miner to order owner in /// exchange for margin split. /// @param lrcFee The amount of LR paid by order owner to miner. /// @param splitS TokenS paid to miner. /// @param splitB TokenB paid to miner. struct OrderState { Order order; bytes32 orderHash; bool marginSplitAsFee; Rate rate; uint fillAmountS; uint lrcReward; uint lrcFee; uint splitS; uint splitB; } /// @dev A struct to capture parameters passed to submitRing method and /// various of other variables used across the submitRing core logics. struct RingParams { address[3][] addressList; uint[7][] uintArgsList; uint8[1][] uint8ArgsList; bool[] buyNoMoreThanAmountBList; uint8[] vList; bytes32[] rList; bytes32[] sList; uint minerId; uint ringSize; // computed uint16 feeSelections; address ringMiner; // queried address feeRecipient; // queried bytes32 ringHash; // computed } //////////////////////////////////////////////////////////////////////////// /// Constructor /// //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// /// Public Functions /// //////////////////////////////////////////////////////////////////////////// /// @dev Disable default function. function () payable public { revert(); } function cancelOrder( address[4] addresses, uint[7] orderValues, bool buyNoMoreThanAmountB, uint8 marginSplitPercentage, uint8 v, bytes32 r, bytes32 s ) external { uint cancelAmount = orderValues[6]; require(cancelAmount > 0); // "amount to cancel is zero"); Order memory order = Order( addresses[0], addresses[1], addresses[2], addresses[3], orderValues[2], orderValues[3], orderValues[0], orderValues[1], orderValues[4], buyNoMoreThanAmountB, orderValues[5], marginSplitPercentage ); require(msg.sender == order.owner); // "cancelOrder not submitted by order owner"); bytes32 orderHash = calculateOrderHash(order); verifySignature( order.owner, orderHash, v, r, s ); cancelled[orderHash] = cancelled[orderHash].add(cancelAmount); cancelledOrFilled[orderHash] = cancelledOrFilled[orderHash].add(cancelAmount); OrderCancelled(orderHash, cancelAmount); } function cancelAllOrdersByTradingPair( address token1, address token2, uint cutoff ) external { uint t = (cutoff == 0 || cutoff >= block.timestamp) ? block.timestamp : cutoff; bytes20 tokenPair = bytes20(token1) ^ bytes20(token2); require(tradingPairCutoffs[msg.sender][tokenPair] < t); // "attempted to set cutoff to a smaller value" tradingPairCutoffs[msg.sender][tokenPair] = t; OrdersCancelled( msg.sender, token1, token2, t ); } function cancelAllOrders(uint cutoff) external { uint t = (cutoff == 0 || cutoff >= block.timestamp) ? block.timestamp : cutoff; require(cutoffs[msg.sender] < t); // "attempted to set cutoff to a smaller value" cutoffs[msg.sender] = t; AllOrdersCancelled(msg.sender, t); } function submitRing( address[3][] addressList, uint[7][] uintArgsList, uint8[1][] uint8ArgsList, bool[] buyNoMoreThanAmountBList, uint8[] vList, bytes32[] rList, bytes32[] sList, uint minerId, uint16 feeSelections ) public { // Check if the highest bit of ringIndex is '1'. require(ringIndex & ENTERED_MASK != ENTERED_MASK); // "attempted to re-ent submitRing function"); // Set the highest bit of ringIndex to '1'. ringIndex |= ENTERED_MASK; RingParams memory params = RingParams( addressList, uintArgsList, uint8ArgsList, buyNoMoreThanAmountBList, vList, rList, sList, minerId, addressList.length, feeSelections, 0x0, // ringMiner 0x0, // feeRecipient 0x0 // ringHash ); verifyInputDataIntegrity(params); updateFeeRecipient(params); // Assemble input data into structs so we can pass them to other functions. // This method also calculates ringHash, therefore it must be called before // calling `verifyRingSignatures`. OrderState[] memory orders = assembleOrders(params); verifyRingSignatures(params); verifyTokensRegistered(params); handleRing(params, orders); ringIndex = (ringIndex ^ ENTERED_MASK) + 1; } //////////////////////////////////////////////////////////////////////////// /// Internal & Private Functions /// //////////////////////////////////////////////////////////////////////////// /// @dev Validate a ring. function verifyRingHasNoSubRing( uint ringSize, OrderState[] orders ) private pure { // Check the ring has no sub-ring. for (uint i = 0; i < ringSize - 1; i++) { address tokenS = orders[i].order.tokenS; for (uint j = i + 1; j < ringSize; j++) { require(tokenS != orders[j].order.tokenS); // "found sub-ring"); } } } /// @dev Verify the ringHash has been signed with each order's auth private /// keys as well as the miner's private key. function verifyRingSignatures(RingParams params) private pure { uint j; for (uint i = 0; i < params.ringSize; i++) { j = i + params.ringSize; verifySignature( params.addressList[i][2], // authAddr params.ringHash, params.vList[j], params.rList[j], params.sList[j] ); } if (params.ringMiner != 0x0) { j++; verifySignature( params.ringMiner, params.ringHash, params.vList[j], params.rList[j], params.sList[j] ); } } function verifyTokensRegistered(RingParams params) private view { // Extract the token addresses address[] memory tokens = new address[](params.ringSize); for (uint i = 0; i < params.ringSize; i++) { tokens[i] = params.addressList[i][1]; } // Test all token addresses at once require( TokenRegistry(tokenRegistryAddress).areAllTokensRegistered(tokens) ); // "token not registered"); } function updateFeeRecipient(RingParams params) private view { if (params.minerId == 0) { params.feeRecipient = msg.sender; } else { (params.feeRecipient, params.ringMiner) = NameRegistry( nameRegistryAddress ).getParticipantById( params.minerId ); if (params.feeRecipient == 0x0) { params.feeRecipient = msg.sender; } } uint sigSize = params.ringSize * 2; if (params.ringMiner != 0x0) { sigSize += 1; } require(sigSize == params.vList.length); // "ring data is inconsistent - vList"); require(sigSize == params.rList.length); // "ring data is inconsistent - rList"); require(sigSize == params.sList.length); // "ring data is inconsistent - sList"); } function handleRing( RingParams params, OrderState[] orders ) private { uint64 _ringIndex = ringIndex ^ ENTERED_MASK; address _lrcTokenAddress = lrcTokenAddress; TokenTransferDelegate delegate = TokenTransferDelegate(delegateAddress); // Do the hard work. verifyRingHasNoSubRing(params.ringSize, orders); // Exchange rates calculation are performed by ring-miners as solidity // cannot get power-of-1/n operation, therefore we have to verify // these rates are correct. verifyMinerSuppliedFillRates(params.ringSize, orders); // Scale down each order independently by substracting amount-filled and // amount-cancelled. Order owner's current balance and allowance are // not taken into consideration in these operations. scaleRingBasedOnHistoricalRecords(delegate, params.ringSize, orders); // Based on the already verified exchange rate provided by ring-miners, // we can furthur scale down orders based on token balance and allowance, // then find the smallest order of the ring, then calculate each order's // `fillAmountS`. calculateRingFillAmount(params.ringSize, orders); // Calculate each order's `lrcFee` and `lrcRewrard` and splict how much // of `fillAmountS` shall be paid to matching order or miner as margin // split. calculateRingFees( delegate, params.ringSize, orders, params.feeRecipient, _lrcTokenAddress ); /// Make transfers. var (orderHashList, amountsList) = settleRing( delegate, params.ringSize, orders, params.feeRecipient, _lrcTokenAddress ); RingMined( _ringIndex, params.ringHash, params.ringMiner, params.feeRecipient, orderHashList, amountsList ); } function settleRing( TokenTransferDelegate delegate, uint ringSize, OrderState[] orders, address feeRecipient, address _lrcTokenAddress ) private returns( bytes32[] memory orderHashList, uint[6][] memory amountsList) { bytes32[] memory batch = new bytes32[](ringSize * 6); // ringSize * (owner + tokenS + 4 amounts) orderHashList = new bytes32[](ringSize); amountsList = new uint[6][](ringSize); uint p = 0; for (uint i = 0; i < ringSize; i++) { OrderState memory state = orders[i]; Order memory order = state.order; uint prevSplitB = orders[(i + ringSize - 1) % ringSize].splitB; uint nextFillAmountS = orders[(i + 1) % ringSize].fillAmountS; // Store owner and tokenS of every order batch[p] = bytes32(order.owner); batch[p + 1] = bytes32(order.tokenS); // Store all amounts batch[p + 2] = bytes32(state.fillAmountS - prevSplitB); batch[p + 3] = bytes32(prevSplitB + state.splitS); batch[p + 4] = bytes32(state.lrcReward); batch[p + 5] = bytes32(state.lrcFee); p += 6; // Update fill records if (order.buyNoMoreThanAmountB) { cancelledOrFilled[state.orderHash] += nextFillAmountS; } else { cancelledOrFilled[state.orderHash] += state.fillAmountS; } orderHashList[i] = state.orderHash; amountsList[i][0] = state.fillAmountS + state.splitS; amountsList[i][1] = nextFillAmountS - state.splitB; amountsList[i][2] = state.lrcReward; amountsList[i][3] = state.lrcFee; amountsList[i][4] = state.splitS; amountsList[i][5] = state.splitB; } // Do all transactions delegate.batchTransferToken(_lrcTokenAddress, feeRecipient, batch); } /// @dev Verify miner has calculte the rates correctly. function verifyMinerSuppliedFillRates( uint ringSize, OrderState[] orders ) private pure { uint[] memory rateRatios = new uint[](ringSize); uint _rateRatioScale = RATE_RATIO_SCALE; for (uint i = 0; i < ringSize; i++) { uint s1b0 = orders[i].rate.amountS.mul(orders[i].order.amountB); uint s0b1 = orders[i].order.amountS.mul(orders[i].rate.amountB); require(s1b0 <= s0b1); // "miner supplied exchange rate provides invalid discount"); rateRatios[i] = _rateRatioScale.mul(s1b0) / s0b1; } uint cvs = MathUint.cvsquare(rateRatios, _rateRatioScale); require(cvs <= rateRatioCVSThreshold); // "miner supplied exchange rate is not evenly discounted"); } /// @dev Calculate each order's fee or LRC reward. function calculateRingFees( TokenTransferDelegate delegate, uint ringSize, OrderState[] orders, address feeRecipient, address _lrcTokenAddress ) private view { bool checkedMinerLrcSpendable = false; uint minerLrcSpendable = 0; uint8 _marginSplitPercentageBase = MARGIN_SPLIT_PERCENTAGE_BASE; uint nextFillAmountS; for (uint i = 0; i < ringSize; i++) { OrderState memory state = orders[i]; uint lrcReceiable = 0; if (state.lrcFee == 0) { // When an order's LRC fee is 0 or smaller than the specified fee, // we help miner automatically select margin-split. state.marginSplitAsFee = true; state.order.marginSplitPercentage = _marginSplitPercentageBase; } else { uint lrcSpendable = getSpendable( delegate, _lrcTokenAddress, state.order.owner ); // If the order is selling LRC, we need to calculate how much LRC // is left that can be used as fee. if (state.order.tokenS == _lrcTokenAddress) { lrcSpendable -= state.fillAmountS; } // If the order is buyign LRC, it will has more to pay as fee. if (state.order.tokenB == _lrcTokenAddress) { nextFillAmountS = orders[(i + 1) % ringSize].fillAmountS; lrcReceiable = nextFillAmountS; } uint lrcTotal = lrcSpendable + lrcReceiable; // If order doesn't have enough LRC, set margin split to 100%. if (lrcTotal < state.lrcFee) { state.lrcFee = lrcTotal; state.order.marginSplitPercentage = _marginSplitPercentageBase; } if (state.lrcFee == 0) { state.marginSplitAsFee = true; } } if (!state.marginSplitAsFee) { if (lrcReceiable > 0) { if (lrcReceiable >= state.lrcFee) { state.splitB = state.lrcFee; state.lrcFee = 0; } else { state.splitB = lrcReceiable; state.lrcFee -= lrcReceiable; } } } else { // Only check the available miner balance when absolutely needed if (!checkedMinerLrcSpendable && minerLrcSpendable < state.lrcFee) { checkedMinerLrcSpendable = true; minerLrcSpendable = getSpendable(delegate, _lrcTokenAddress, feeRecipient); } // Only calculate split when miner has enough LRC; // otherwise all splits are 0. if (minerLrcSpendable >= state.lrcFee) { nextFillAmountS = orders[(i + 1) % ringSize].fillAmountS; uint split; if (state.order.buyNoMoreThanAmountB) { split = (nextFillAmountS.mul( state.order.amountS ) / state.order.amountB).sub( state.fillAmountS ); } else { split = nextFillAmountS.sub( state.fillAmountS.mul( state.order.amountB ) / state.order.amountS ); } if (state.order.marginSplitPercentage != _marginSplitPercentageBase) { split = split.mul( state.order.marginSplitPercentage ) / _marginSplitPercentageBase; } if (state.order.buyNoMoreThanAmountB) { state.splitS = split; } else { state.splitB = split; } // This implicits order with smaller index in the ring will // be paid LRC reward first, so the orders in the ring does // mater. if (split > 0) { minerLrcSpendable -= state.lrcFee; state.lrcReward = state.lrcFee; } } state.lrcFee = 0; } } } /// @dev Calculate each order's fill amount. function calculateRingFillAmount( uint ringSize, OrderState[] orders ) private pure { uint smallestIdx = 0; uint i; uint j; for (i = 0; i < ringSize; i++) { j = (i + 1) % ringSize; smallestIdx = calculateOrderFillAmount( orders[i], orders[j], i, j, smallestIdx ); } for (i = 0; i < smallestIdx; i++) { calculateOrderFillAmount( orders[i], orders[(i + 1) % ringSize], 0, // Not needed 0, // Not needed 0 // Not needed ); } } /// @return The smallest order's index. function calculateOrderFillAmount( OrderState state, OrderState next, uint i, uint j, uint smallestIdx ) private pure returns (uint newSmallestIdx) { // Default to the same smallest index newSmallestIdx = smallestIdx; uint fillAmountB = state.fillAmountS.mul( state.rate.amountB ) / state.rate.amountS; if (state.order.buyNoMoreThanAmountB) { if (fillAmountB > state.order.amountB) { fillAmountB = state.order.amountB; state.fillAmountS = fillAmountB.mul( state.rate.amountS ) / state.rate.amountB; newSmallestIdx = i; } state.lrcFee = state.order.lrcFee.mul( fillAmountB ) / state.order.amountB; } else { state.lrcFee = state.order.lrcFee.mul( state.fillAmountS ) / state.order.amountS; } if (fillAmountB <= next.fillAmountS) { next.fillAmountS = fillAmountB; } else { newSmallestIdx = j; } } /// @dev Scale down all orders based on historical fill or cancellation /// stats but key the order's original exchange rate. function scaleRingBasedOnHistoricalRecords( TokenTransferDelegate delegate, uint ringSize, OrderState[] orders ) private view { for (uint i = 0; i < ringSize; i++) { OrderState memory state = orders[i]; Order memory order = state.order; uint amount; if (order.buyNoMoreThanAmountB) { amount = order.amountB.tolerantSub( cancelledOrFilled[state.orderHash] ); order.amountS = amount.mul(order.amountS) / order.amountB; order.lrcFee = amount.mul(order.lrcFee) / order.amountB; order.amountB = amount; } else { amount = order.amountS.tolerantSub( cancelledOrFilled[state.orderHash] ); order.amountB = amount.mul(order.amountB) / order.amountS; order.lrcFee = amount.mul(order.lrcFee) / order.amountS; order.amountS = amount; } require(order.amountS > 0); // "amountS is zero"); require(order.amountB > 0); // "amountB is zero"); uint availableAmountS = getSpendable(delegate, order.tokenS, order.owner); require(availableAmountS > 0); // "order spendable amountS is zero"); state.fillAmountS = ( order.amountS < availableAmountS ? order.amountS : availableAmountS ); } } /// @return Amount of ERC20 token that can be spent by this contract. function getSpendable( TokenTransferDelegate delegate, address tokenAddress, address tokenOwner ) private view returns (uint) { ERC20 token = ERC20(tokenAddress); uint allowance = token.allowance( tokenOwner, address(delegate) ); uint balance = token.balanceOf(tokenOwner); return (allowance < balance ? allowance : balance); } /// @dev verify input data's basic integrity. function verifyInputDataIntegrity(RingParams params) private pure { require(params.ringSize == params.addressList.length); // "ring data is inconsistent - addressList"); require(params.ringSize == params.uintArgsList.length); // "ring data is inconsistent - uintArgsList"); require(params.ringSize == params.uint8ArgsList.length); // "ring data is inconsistent - uint8ArgsList"); require(params.ringSize == params.buyNoMoreThanAmountBList.length); // "ring data is inconsistent - buyNoMoreThanAmountBList"); // Validate ring-mining related arguments. for (uint i = 0; i < params.ringSize; i++) { require(params.uintArgsList[i][5] > 0); // "order rateAmountS is zero"); } //Check ring size require(params.ringSize > 1 && params.ringSize <= MAX_RING_SIZE); // "invalid ring size"); } /// @dev assmble order parameters into Order struct. /// @return A list of orders. function assembleOrders(RingParams params) private view returns (OrderState[] memory orders) { orders = new OrderState[](params.ringSize); for (uint i = 0; i < params.ringSize; i++) { Order memory order = Order( params.addressList[i][0], params.addressList[i][1], params.addressList[(i + 1) % params.ringSize][1], params.addressList[i][2], params.uintArgsList[i][2], params.uintArgsList[i][3], params.uintArgsList[i][0], params.uintArgsList[i][1], params.uintArgsList[i][4], params.buyNoMoreThanAmountBList[i], params.uintArgsList[i][6], params.uint8ArgsList[i][0] ); validateOrder(order); bytes32 orderHash = calculateOrderHash(order); verifySignature( order.owner, orderHash, params.vList[i], params.rList[i], params.sList[i] ); bool marginSplitAsFee = (params.feeSelections & (uint16(1) << i)) > 0; orders[i] = OrderState( order, orderHash, marginSplitAsFee, Rate(params.uintArgsList[i][5], order.amountB), 0, // fillAmountS 0, // lrcReward 0, // lrcFee 0, // splitS 0 // splitB ); params.ringHash ^= orderHash; } params.ringHash = keccak256( params.ringHash, params.minerId, params.feeSelections ); } /// @dev validate order's parameters are OK. function validateOrder(Order order) private view { require(order.owner != 0x0); // invalid order owner require(order.tokenS != 0x0); // invalid order tokenS require(order.tokenB != 0x0); // invalid order tokenB require(order.amountS != 0); // invalid order amountS require(order.amountB != 0); // invalid order amountB require(order.marginSplitPercentage <= MARGIN_SPLIT_PERCENTAGE_BASE); // invalid order marginSplitPercentage require(order.validSince <= block.timestamp); // order is too early to match require(order.validUntil > block.timestamp); // order is expired bytes20 tradingPair = bytes20(order.tokenS) ^ bytes20(order.tokenB); require(order.validSince > tradingPairCutoffs[order.owner][tradingPair]); // order trading pair is cut off require(order.validSince > cutoffs[order.owner]); // order is cut off } /// @dev Get the Keccak-256 hash of order with specified parameters. function calculateOrderHash(Order order) private view returns (bytes32) { return keccak256( address(this), order.owner, order.tokenS, order.tokenB, order.authAddr, order.amountS, order.amountB, order.validSince, order.validUntil, order.lrcFee, order.buyNoMoreThanAmountB, order.walletId, order.marginSplitPercentage ); } /// @dev Verify signer's signature. function verifySignature( address signer, bytes32 hash, uint8 v, bytes32 r, bytes32 s ) private pure { require( signer == ecrecover( keccak256("\x19Ethereum Signed Message:\n32", hash), v, r, s ) ); // "invalid signature"); } function getTradingPairCutoffs(address orderOwner, address token1, address token2) public view returns (uint) { bytes20 tokenPair = bytes20(token1) ^ bytes20(token2); return tradingPairCutoffs[orderOwner][tokenPair]; } }
"ring data is inconsistent - addressList");
require(params.ringSize == params.addressList.length);
1,602,014
[ 1, 6, 8022, 501, 353, 27403, 300, 1758, 682, 8863, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2583, 12, 2010, 18, 8022, 1225, 422, 859, 18, 2867, 682, 18, 2469, 1769, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/11155111/0xA9e2CFc4c8993c575397116bA30D452374A8e48F/sources/contracts/GameFactory.sol
function viewEntry(uint256 _entryId) external view returns (Entry memory) {
Entry memory _entry;
3,787,982
[ 1, 915, 1476, 1622, 12, 11890, 5034, 389, 4099, 548, 13, 3903, 1476, 1135, 261, 1622, 3778, 13, 288, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 3841, 3778, 389, 4099, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/97/0x5C16924d34027E42DB92f4F47C6629D7b4703769/sources/project_/contracts/SyrupBar.sol
Safe Lake transfer function, just in case if rounding error causes pool to not have enough Lakes.
function safeLakeTransfer(address _to, uint256 _amount) public onlyOwner { uint256 LakeBal = Lake.balanceOf(address(this)); if (_amount > LakeBal) { Lake.transfer(_to, LakeBal); Lake.transfer(_to, _amount); } }
3,279,284
[ 1, 9890, 511, 911, 7412, 445, 16, 2537, 316, 648, 309, 13885, 555, 14119, 2845, 358, 486, 1240, 7304, 511, 3223, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 4183, 31696, 5912, 12, 2867, 389, 869, 16, 2254, 5034, 389, 8949, 13, 1071, 1338, 5541, 288, 203, 3639, 2254, 5034, 511, 911, 38, 287, 273, 511, 911, 18, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 3639, 309, 261, 67, 8949, 405, 511, 911, 38, 287, 13, 288, 203, 5411, 511, 911, 18, 13866, 24899, 869, 16, 511, 911, 38, 287, 1769, 203, 5411, 511, 911, 18, 13866, 24899, 869, 16, 389, 8949, 1769, 203, 3639, 289, 203, 565, 289, 203, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2021-02-21 */ pragma solidity 0.6.6; // ---------------------------------------------------------------------------- // 'Bitworth Token' token contract // // Deployed to : 0x0D9E7D95b56107CD63575ffb935e928E21C03cfC // Symbol : BITW // Name : Bitworth Token // Total supply: 10000000000000 // Decimals : 5 // // Enjoy. // // (c) by Andy Feng 2021. MIT License. // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- // Safe maths // ---------------------------------------------------------------------------- contract SafeMath { function safeAdd(uint a, uint b) public pure returns (uint c) { c = a + b; require(c >= a); } function safeSub(uint a, uint b) public pure returns (uint c) { require(b <= a); c = a - b; } function safeMul(uint a, uint b) public pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function safeDiv(uint a, uint b) public pure returns (uint c) { require(b > 0); c = a / b; } } // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // ---------------------------------------------------------------------------- abstract contract ERC20Interface { function totalSupply() virtual public view returns (uint); function balanceOf(address tokenOwner) virtual public view returns (uint balance); function allowance(address tokenOwner, address spender) virtual public view returns (uint remaining); function transfer(address to, uint tokens) virtual public returns (bool success); function approve(address spender, uint tokens) virtual public returns (bool success); function transferFrom(address from, address to, uint tokens) virtual public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } // ---------------------------------------------------------------------------- // Contract function to receive approval and execute function in one call // // Borrowed from MiniMeToken // ---------------------------------------------------------------------------- abstract contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 tokens, address token, bytes memory data) virtual public; } // ---------------------------------------------------------------------------- // Owned contract // ---------------------------------------------------------------------------- contract Owned { address public owner; address public newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); constructor() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) public onlyOwner { newOwner = _newOwner; } function acceptOwnership() public { require(msg.sender == newOwner); emit OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); } } // ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and assisted // token transfers // ---------------------------------------------------------------------------- contract BitworthToken is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public { symbol = "BITW"; name = "Bitworth Token"; decimals = 5; _totalSupply = 10000000000000; balances[0x0D9E7D95b56107CD63575ffb935e928E21C03cfC] = _totalSupply; emit Transfer(address(0), 0x0D9E7D95b56107CD63575ffb935e928E21C03cfC, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public override view returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public override view returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public override returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public override returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public override returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public override view returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes memory data) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, address(this), data); return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ // function () external payable { // revert(); // } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
---------------------------------------------------------------------------- ERC20 Token, with the addition of symbol, name and decimals and assisted token transfers ---------------------------------------------------------------------------- ------------------------------------------------------------------------ Constructor ------------------------------------------------------------------------
contract BitworthToken is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; constructor() public { symbol = "BITW"; name = "Bitworth Token"; decimals = 5; _totalSupply = 10000000000000; balances[0x0D9E7D95b56107CD63575ffb935e928E21C03cfC] = _totalSupply; emit Transfer(address(0), 0x0D9E7D95b56107CD63575ffb935e928E21C03cfC, _totalSupply); } function totalSupply() public override view returns (uint) { return _totalSupply - balances[address(0)]; } function balanceOf(address tokenOwner) public override view returns (uint balance) { return balances[tokenOwner]; } function transfer(address to, uint tokens) public override returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); return true; } function approve(address spender, uint tokens) public override returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } function transferFrom(address from, address to, uint tokens) public override returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true; } function allowance(address tokenOwner, address spender) public override view returns (uint remaining) { return allowed[tokenOwner][spender]; } function approveAndCall(address spender, uint tokens, bytes memory data) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, address(this), data); return true; } function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
7,774,822
[ 1, 5802, 7620, 4232, 39, 3462, 3155, 16, 598, 326, 2719, 434, 3273, 16, 508, 471, 15105, 471, 1551, 25444, 1147, 29375, 8879, 13849, 8879, 17082, 11417, 8879, 17082, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 6539, 91, 7825, 1345, 353, 4232, 39, 3462, 1358, 16, 14223, 11748, 16, 14060, 10477, 288, 203, 565, 533, 1071, 3273, 31, 203, 565, 533, 1071, 225, 508, 31, 203, 565, 2254, 28, 1071, 15105, 31, 203, 565, 2254, 1071, 389, 4963, 3088, 1283, 31, 203, 203, 565, 2874, 12, 2867, 516, 2254, 13, 324, 26488, 31, 203, 565, 2874, 12, 2867, 516, 2874, 12, 2867, 516, 2254, 3719, 2935, 31, 203, 203, 203, 565, 3885, 1435, 1071, 288, 203, 3639, 3273, 273, 315, 15650, 59, 14432, 203, 3639, 508, 273, 315, 5775, 91, 7825, 3155, 14432, 203, 3639, 15105, 273, 1381, 31, 203, 3639, 389, 4963, 3088, 1283, 273, 2130, 12648, 3784, 31, 203, 3639, 324, 26488, 63, 20, 92, 20, 40, 29, 41, 27, 40, 8778, 70, 4313, 23054, 10160, 4449, 25, 5877, 1403, 70, 29, 4763, 73, 29, 6030, 41, 5340, 39, 4630, 8522, 39, 65, 273, 389, 4963, 3088, 1283, 31, 203, 3639, 3626, 12279, 12, 2867, 12, 20, 3631, 374, 92, 20, 40, 29, 41, 27, 40, 8778, 70, 4313, 23054, 10160, 4449, 25, 5877, 1403, 70, 29, 4763, 73, 29, 6030, 41, 5340, 39, 4630, 8522, 39, 16, 389, 4963, 3088, 1283, 1769, 203, 565, 289, 203, 203, 203, 565, 445, 2078, 3088, 1283, 1435, 1071, 3849, 1476, 1135, 261, 11890, 13, 288, 203, 3639, 327, 389, 4963, 3088, 1283, 300, 324, 26488, 63, 2867, 12, 20, 13, 15533, 203, 565, 289, 203, 203, 203, 565, 445, 11013, 951, 12, 2867, 1147, 5541, 13, 1071, 3849, 1476, 2 ]
/** *Submitted for verification at Etherscan.io on 2021-08-29 */ // SPDX-License-Identifier: MIT AND AGPLv3 // File: @openzeppelin/contracts/token/ERC20/IERC20.sol pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/utils/Context.sol pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/token/ERC20/ERC20.sol pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The defaut value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overloaded; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); _approve(sender, _msgSender(), currentAllowance - amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); _approve(_msgSender(), spender, currentAllowance - subtractedValue); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); _balances[sender] = senderBalance - amount; _balances[recipient] += amount; emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); _balances[account] = accountBalance - amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // File: @openzeppelin/contracts/access/Ownable.sol pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: contracts/common/Constants.sol pragma solidity 0.8.0; contract Constants { uint8 internal constant N_COINS = 3; uint8 internal constant DEFAULT_DECIMALS = 18; // GToken and Controller use this decimals uint256 internal constant DEFAULT_DECIMALS_FACTOR = uint256(10)**DEFAULT_DECIMALS; uint8 internal constant CHAINLINK_PRICE_DECIMALS = 8; uint256 internal constant CHAINLINK_PRICE_DECIMAL_FACTOR = uint256(10)**CHAINLINK_PRICE_DECIMALS; uint8 internal constant PERCENTAGE_DECIMALS = 4; uint256 internal constant PERCENTAGE_DECIMAL_FACTOR = uint256(10)**PERCENTAGE_DECIMALS; uint256 internal constant CURVE_RATIO_DECIMALS = 6; uint256 internal constant CURVE_RATIO_DECIMALS_FACTOR = uint256(10)**CURVE_RATIO_DECIMALS; } // File: contracts/governance/GROToken.sol pragma solidity 0.8.0; contract GROToken is Constants, ERC20, Ownable { uint256 public immutable INIT_MAX_TOTAL_SUPPLY; uint256 public immutable INFLATION_START_TIME; // Timestamp to start inflation // GRO token inflation is defined by inflation rate / on year seconds, where inflation rate can be // between 0 and MAX_INFLATION_RATE (500 BP) uint256 public constant MAX_INFLATION_RATE = (500 * DEFAULT_DECIMALS_FACTOR) / PERCENTAGE_DECIMAL_FACTOR; // 500 BP uint256 public constant ONE_YEAR_SECONDS = 31556952; // average year (including leap years) in seconds address public minter; // inflation variables initated to 0 and cannot be update until INFLATION_START_TIME uint256 public inflationRate; uint256 public inflationPerSecond; uint256 public lastMaxTotalSupply; uint256 public lastMaxTotalSupplyTime; event LogInflationRate( uint256 newInflationRate, uint256 newInflationPerSecond, uint256 lastMaxTotalSupply, uint256 lastMaxTotalSupplyTime ); event LogMinter(address newMinter); constructor( string memory name, string memory symbol, uint256 _maxTotalSupply, uint256 nonInflationPeriod // The unit is second ) ERC20(name, symbol) { INIT_MAX_TOTAL_SUPPLY = _maxTotalSupply; INFLATION_START_TIME = block.timestamp + nonInflationPeriod; lastMaxTotalSupply = _maxTotalSupply; lastMaxTotalSupplyTime = block.timestamp + nonInflationPeriod; emit LogInflationRate(0, 0, lastMaxTotalSupply, lastMaxTotalSupplyTime); } function setMinter(address _minter) public onlyOwner { minter = _minter; emit LogMinter(_minter); } /// @notice Set inflation rate, if current inflation rate /// @param rate New inflation rate, decimals is 18 function setInflationRate(uint256 rate) public onlyOwner { uint256 currentTime = block.timestamp; require(currentTime > INFLATION_START_TIME, "setInflationRate: Cannot set inflationrate before inflation start time"); require(rate <= MAX_INFLATION_RATE, "setInflationRate: !rate"); require(rate != inflationRate, "setInflationRate: same rate"); inflationRate = rate; lastMaxTotalSupply += (currentTime - lastMaxTotalSupplyTime) * inflationPerSecond; lastMaxTotalSupplyTime = currentTime; inflationPerSecond = (lastMaxTotalSupply * rate / DEFAULT_DECIMALS_FACTOR) / ONE_YEAR_SECONDS; emit LogInflationRate(rate, inflationPerSecond, lastMaxTotalSupply, lastMaxTotalSupplyTime); } function mint(address account, uint256 amount) external { require(msg.sender == minter, "mint: !minter"); require(amount + totalSupply() <= maxTotalSupply(), "mint: > cap"); _mint(account, amount); } function maxTotalSupply() public view returns (uint256) { uint256 currentTime = block.timestamp; if (currentTime <= INFLATION_START_TIME) { return INIT_MAX_TOTAL_SUPPLY; } else { return lastMaxTotalSupply + (currentTime - lastMaxTotalSupplyTime) * inflationPerSecond; } } }
@notice Set inflation rate, if current inflation rate @param rate New inflation rate, decimals is 18
function setInflationRate(uint256 rate) public onlyOwner { uint256 currentTime = block.timestamp; require(currentTime > INFLATION_START_TIME, "setInflationRate: Cannot set inflationrate before inflation start time"); require(rate <= MAX_INFLATION_RATE, "setInflationRate: !rate"); require(rate != inflationRate, "setInflationRate: same rate"); inflationRate = rate; lastMaxTotalSupply += (currentTime - lastMaxTotalSupplyTime) * inflationPerSecond; lastMaxTotalSupplyTime = currentTime; inflationPerSecond = (lastMaxTotalSupply * rate / DEFAULT_DECIMALS_FACTOR) / ONE_YEAR_SECONDS; emit LogInflationRate(rate, inflationPerSecond, lastMaxTotalSupply, lastMaxTotalSupplyTime); }
10,757,110
[ 1, 694, 13947, 367, 4993, 16, 309, 783, 13947, 367, 4993, 225, 4993, 1166, 13947, 367, 4993, 16, 15105, 353, 6549, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 444, 27040, 367, 4727, 12, 11890, 5034, 4993, 13, 1071, 1338, 5541, 288, 203, 3639, 2254, 5034, 6680, 273, 1203, 18, 5508, 31, 203, 3639, 2583, 12, 2972, 950, 405, 2120, 19054, 2689, 67, 7570, 67, 4684, 16, 7010, 7734, 315, 542, 27040, 367, 4727, 30, 14143, 444, 13947, 367, 5141, 1865, 13947, 367, 787, 813, 8863, 203, 3639, 2583, 12, 5141, 1648, 4552, 67, 706, 19054, 2689, 67, 24062, 16, 315, 542, 27040, 367, 4727, 30, 401, 5141, 8863, 203, 3639, 2583, 12, 5141, 480, 13947, 367, 4727, 16, 315, 542, 27040, 367, 4727, 30, 1967, 4993, 8863, 203, 203, 3639, 13947, 367, 4727, 273, 4993, 31, 203, 3639, 1142, 2747, 5269, 3088, 1283, 1011, 261, 2972, 950, 300, 1142, 2747, 5269, 3088, 1283, 950, 13, 380, 13947, 367, 2173, 8211, 31, 203, 3639, 1142, 2747, 5269, 3088, 1283, 950, 273, 6680, 31, 203, 3639, 13947, 367, 2173, 8211, 273, 261, 2722, 2747, 5269, 3088, 1283, 380, 4993, 342, 3331, 67, 23816, 55, 67, 26835, 13, 342, 15623, 67, 15137, 67, 11609, 31, 203, 203, 3639, 3626, 1827, 27040, 367, 4727, 12, 5141, 16, 13947, 367, 2173, 8211, 16, 1142, 2747, 5269, 3088, 1283, 16, 1142, 2747, 5269, 3088, 1283, 950, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0xF66C6fDBDD7d57dD14D23d0C8A4E58Cc4869bBfa/sources/SafeERC20.sol
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value, non-reverting calls are assumed to be successful./
function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 oldAllowance = token.allowance(address(this), spender); forceApprove(token, spender, oldAllowance + value); }
3,949,176
[ 1, 382, 11908, 326, 4440, 6835, 1807, 1699, 1359, 358, 2913, 1375, 87, 1302, 264, 68, 635, 1375, 1132, 8338, 971, 1375, 2316, 68, 1135, 1158, 460, 16, 1661, 17, 266, 1097, 310, 4097, 854, 12034, 358, 506, 6873, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 4183, 382, 11908, 7009, 1359, 12, 203, 3639, 467, 654, 39, 3462, 1147, 16, 203, 3639, 1758, 17571, 264, 16, 203, 3639, 2254, 5034, 460, 203, 565, 262, 2713, 288, 203, 3639, 2254, 5034, 1592, 7009, 1359, 273, 1147, 18, 5965, 1359, 12, 2867, 12, 2211, 3631, 17571, 264, 1769, 203, 3639, 2944, 12053, 537, 12, 2316, 16, 17571, 264, 16, 1592, 7009, 1359, 397, 460, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/8453/0x3De0Ae4E6775a442DA55A518B3f402aBF51a6F1b/sources/contracts/singlestakingv2/SingleStakingRewardsFactoryXBase.sol
immutables the staking tokens for which the rewards contract has been deployed Info of each user.
contract SingleStakingRewardsFactoryXBase is Ownable { using SafeMath for uint256; address public rewardsToken; uint public stakingRewardsGenesis; uint public totalAllocPoint; address public xSkullStaking; address[] public stakingTokens; mapping (address => bool) public isFarm; uint public globalSkullPerSecond; uint public globalXSkullPerSecond; struct UserInfo { } struct PoolInfo { } PoolInfo[] public poolInfo; struct StakingRewardsInfo { address stakingRewards; } constructor( address _rewardsToken, uint _stakingRewardsGenesis mapping(address => StakingRewardsInfo) public stakingRewardsInfoByStakingToken; ) Ownable() public { require(_stakingRewardsGenesis >= block.timestamp, 'MasterChef: genesis too soon'); rewardsToken = _rewardsToken; stakingRewardsGenesis = _stakingRewardsGenesis; } function deploy(address _stakingToken, uint256 _rewardRate, uint256 _farmStartTime) public onlyOwner { StakingRewardsInfo storage info = stakingRewardsInfoByStakingToken[_stakingToken]; require(info.stakingRewards == address(0), 'MasterChef: already deployed'); require(_farmStartTime > stakingRewardsGenesis, "Masterchef: cant start farm before global time"); info.stakingRewards = address(new SingleStakingRewardsXBase(address(this), owner(), _stakingToken, _rewardRate, stakingRewardsGenesis)); isFarm[_stakingToken] = true; poolInfo.push(PoolInfo({ lpToken: IERC20(_stakingToken), allocPoint: 0 })); stakingTokens.push(_stakingToken); } function deploy(address _stakingToken, uint256 _rewardRate, uint256 _farmStartTime) public onlyOwner { StakingRewardsInfo storage info = stakingRewardsInfoByStakingToken[_stakingToken]; require(info.stakingRewards == address(0), 'MasterChef: already deployed'); require(_farmStartTime > stakingRewardsGenesis, "Masterchef: cant start farm before global time"); info.stakingRewards = address(new SingleStakingRewardsXBase(address(this), owner(), _stakingToken, _rewardRate, stakingRewardsGenesis)); isFarm[_stakingToken] = true; poolInfo.push(PoolInfo({ lpToken: IERC20(_stakingToken), allocPoint: 0 })); stakingTokens.push(_stakingToken); } function mintRewards(address _receiver, uint256 _amount) public { require(isFarm[msg.sender] == true, "MasterChef: only farms can mint rewards"); require(block.timestamp >= stakingRewardsGenesis, 'Masterchef: rewards too soon'); require( IBaseToken(rewardsToken).mint(_receiver, _amount), 'MasterChef: mint rewardsToken failed' ); } function pullExtraTokens(address token, uint256 amount) external onlyOwner { IERC20(token).transfer(msg.sender, amount); } function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; StakingRewardsInfo storage info = stakingRewardsInfoByStakingToken[address(pool.lpToken)]; if(isFarm[address(pool.lpToken)] == false) { if (pool.allocPoint != 0) { totalAllocPoint = totalAllocPoint.sub(pool.allocPoint); pool.allocPoint = 0; IStakingRewards(info.stakingRewards).setRewardRate(0); } } IStakingRewards(info.stakingRewards).setRewardRate(globalSkullPerSecond.mul(pool.allocPoint).div(totalAllocPoint)); } function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; StakingRewardsInfo storage info = stakingRewardsInfoByStakingToken[address(pool.lpToken)]; if(isFarm[address(pool.lpToken)] == false) { if (pool.allocPoint != 0) { totalAllocPoint = totalAllocPoint.sub(pool.allocPoint); pool.allocPoint = 0; IStakingRewards(info.stakingRewards).setRewardRate(0); } } IStakingRewards(info.stakingRewards).setRewardRate(globalSkullPerSecond.mul(pool.allocPoint).div(totalAllocPoint)); } function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; StakingRewardsInfo storage info = stakingRewardsInfoByStakingToken[address(pool.lpToken)]; if(isFarm[address(pool.lpToken)] == false) { if (pool.allocPoint != 0) { totalAllocPoint = totalAllocPoint.sub(pool.allocPoint); pool.allocPoint = 0; IStakingRewards(info.stakingRewards).setRewardRate(0); } } IStakingRewards(info.stakingRewards).setRewardRate(globalSkullPerSecond.mul(pool.allocPoint).div(totalAllocPoint)); } function set(uint256 _pid, uint256 _allocPoint) external onlyOwner { PoolInfo storage pool = poolInfo[_pid]; if (totalAllocPoint != 0) { totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; totalAllocPoint = _allocPoint; poolInfo[_pid].allocPoint = _allocPoint; } } function set(uint256 _pid, uint256 _allocPoint) external onlyOwner { PoolInfo storage pool = poolInfo[_pid]; if (totalAllocPoint != 0) { totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; totalAllocPoint = _allocPoint; poolInfo[_pid].allocPoint = _allocPoint; } } } else { function killFarm(address _farm) external onlyOwner { require(isFarm[_farm] == true, "MasterChef: This is not active"); isFarm[_farm] = false; massUpdatePools(); } function activateFarm(address _farm) external onlyOwner { StakingRewardsInfo storage info = stakingRewardsInfoByStakingToken[_farm]; require(info.stakingRewards != address(0), 'MasterChef: needs to be a dead farm'); require(isFarm[_farm] == false, "MasterChef: This is not active"); isFarm[_farm] = true; massUpdatePools(); } function setGlobalSkullPerSecond(uint256 _globalSkullPerSecond) public onlyOwner { globalSkullPerSecond = _globalSkullPerSecond; } }
11,561,000
[ 1, 381, 10735, 1538, 326, 384, 6159, 2430, 364, 1492, 326, 283, 6397, 6835, 711, 2118, 19357, 3807, 434, 1517, 729, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 10326, 510, 6159, 17631, 14727, 1733, 60, 2171, 353, 14223, 6914, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 565, 1758, 1071, 283, 6397, 1345, 31, 203, 565, 2254, 1071, 384, 6159, 17631, 14727, 7642, 16786, 31, 203, 565, 2254, 1071, 2078, 8763, 2148, 31, 203, 203, 565, 1758, 1071, 619, 5925, 420, 510, 6159, 31, 203, 203, 565, 1758, 8526, 1071, 384, 6159, 5157, 31, 203, 203, 565, 2874, 261, 2867, 516, 1426, 13, 1071, 17646, 4610, 31, 203, 203, 565, 2254, 1071, 2552, 5925, 420, 2173, 8211, 31, 203, 565, 2254, 1071, 2552, 60, 5925, 420, 2173, 8211, 31, 203, 203, 565, 1958, 25003, 288, 203, 565, 289, 203, 203, 565, 1958, 8828, 966, 288, 203, 565, 289, 203, 377, 203, 203, 565, 8828, 966, 8526, 1071, 2845, 966, 31, 203, 565, 1958, 934, 6159, 17631, 14727, 966, 288, 203, 3639, 1758, 384, 6159, 17631, 14727, 31, 203, 565, 289, 203, 203, 203, 565, 3885, 12, 203, 3639, 1758, 389, 266, 6397, 1345, 16, 203, 3639, 2254, 389, 334, 6159, 17631, 14727, 7642, 16786, 203, 565, 2874, 12, 2867, 516, 934, 6159, 17631, 14727, 966, 13, 1071, 384, 6159, 17631, 14727, 966, 858, 510, 6159, 1345, 31, 203, 565, 262, 14223, 6914, 1435, 1071, 288, 203, 3639, 2583, 24899, 334, 6159, 17631, 14727, 7642, 16786, 1545, 1203, 18, 5508, 16, 296, 7786, 39, 580, 74, 30, 21906, 4885, 17136, 8284, 203, 203, 3639, 283, 6397, 1345, 273, 389, 266, 6397, 1345, 31, 203, 3639, 384, 6159, 17631, 14727, 2 ]
./partial_match/1/0x191df0E31e38Ca0a3d9Aa8E1D5595D715B7FaCaC/sources/contracts/BorrowerOperations.sol
Send fee to LQTY staking contract
function _triggerBorrowingFee(ITroveManager _troveManager, ILUSDToken _lusdToken, uint _LUSDAmount, uint _maxFeePercentage) internal returns (uint) { uint LUSDFee = _troveManager.getBorrowingFee(_LUSDAmount); _requireUserAcceptsFee(LUSDFee, _LUSDAmount, _maxFeePercentage); lqtyStaking.increaseF_LUSD(LUSDFee); _lusdToken.mint(lqtyStakingAddress, LUSDFee); return LUSDFee; }
2,685,128
[ 1, 3826, 14036, 358, 511, 53, 5538, 384, 6159, 6835, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 10668, 38, 15318, 310, 14667, 12, 1285, 303, 537, 1318, 389, 88, 303, 537, 1318, 16, 467, 48, 3378, 40, 1345, 389, 80, 407, 72, 1345, 16, 2254, 389, 48, 3378, 40, 6275, 16, 2254, 389, 1896, 14667, 16397, 13, 2713, 1135, 261, 11890, 13, 288, 203, 3639, 2254, 511, 3378, 4577, 1340, 273, 389, 88, 303, 537, 1318, 18, 588, 38, 15318, 310, 14667, 24899, 48, 3378, 40, 6275, 1769, 203, 203, 3639, 389, 6528, 1299, 26391, 14667, 12, 48, 3378, 4577, 1340, 16, 389, 48, 3378, 40, 6275, 16, 389, 1896, 14667, 16397, 1769, 203, 540, 203, 3639, 328, 85, 4098, 510, 6159, 18, 267, 11908, 42, 67, 48, 3378, 40, 12, 48, 3378, 4577, 1340, 1769, 203, 3639, 389, 80, 407, 72, 1345, 18, 81, 474, 12, 80, 85, 4098, 510, 6159, 1887, 16, 511, 3378, 4577, 1340, 1769, 203, 203, 3639, 327, 511, 3378, 4577, 1340, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/token/ERC721/utils/ERC721Holder.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; import "hardhat/console.sol"; interface IERC721b is IERC721 { enum TokenType { Wynd, Rider, Equipment } function mint( address _to, TokenType _tokenType, string memory _tokenURI ) external returns (uint256); } contract WBGame is OwnableUpgradeable, ERC721Holder, ReentrancyGuardUpgradeable { using Strings for uint256; enum HolderPlace { Unheld, DailyActivity, Breeding, Training, Forging } event TokenMoved( address user, string productId, HolderPlace from, HolderPlace to ); event TicketBought( address user, string productId, uint256 price, string activity ); event BreedItemCreated(uint256 aParent, uint256 bParent, uint256 child); event GameItemTransfer( address from, address to, address collection, uint256 tokenId, HolderPlace holderPlace ); event GameItemDispatch( address from, address to, address collection, uint256 tokenId, HolderPlace holderPlace ); event RewardClaimed(address user, uint256 amount, uint256 timestamp); event RewardSet(address user, uint256 amount, uint256 timestamp); using Counters for Counters.Counter; Counters.Counter private breedId; struct BreedItem { uint256 aParent; uint256 bParent; uint256 child; } mapping(uint256 => BreedItem) private _breedItems; mapping(uint256 => uint256) private _breedCounts; mapping(address => mapping(HolderPlace => uint256[])) private _tokenHolder; mapping(address => uint256) private _addressCHROReward; mapping(address => uint256) private _addressClaimedTime; uint256 private _breedingCost; uint256 private _totalReward; /// first generation or genesis contract IERC721 private _aCollection; /// next generation (NextGen) contract IERC721b private _bCollection; /// CHRO contract IERC20 private _tokenContract; mapping(uint256 => HolderPlace) private _heldTokens; mapping(uint256 => address) private _tokenOwners; event TreasurySet(address newAddress); function initialize( address _aCollectionAddress, address _bCollectionAddress, address _tokenAddress ) public initializer { _transferOwnership(_msgSender()); _aCollection = IERC721(_aCollectionAddress); _bCollection = IERC721b(_bCollectionAddress); _tokenContract = IERC20(_tokenAddress); _breedingCost = 200000000000000000000; breedId = Counters.Counter({_value: 0}); } function buyTicket( uint256 _tokenId, uint256 _price, string memory _activity ) public { address _collection = address(0); if (_tokenId < 20000) { _collection = address(_aCollection); } else { _collection = address(_bCollection); } require( _heldTokens[_tokenId] == HolderPlace.DailyActivity && _tokenOwners[_tokenId] == _msgSender(), "Invalid place of token" ); require( _tokenContract.balanceOf(_msgSender()) >= _price, "Not enough tokens" ); require( _tokenContract.allowance(_msgSender(), address(this)) >= _price, "Not enough allowance" ); _tokenContract.transferFrom(_msgSender(), address(this), _price); emit TicketBought( _msgSender(), string( abi.encodePacked( Strings.toHexString(uint160(_collection), 20), ":", _tokenId.toString() ) ), _price, _activity ); } /** * @notice Submit token to this contract and specify the {HolderPlace} * @param _holderPlace Holder place * @param _tokenId Token ID */ function _submit(HolderPlace _holderPlace, uint256 _tokenId) internal { address _collection = address(0); if (_tokenId < 20000) { require( _aCollection.ownerOf(_tokenId) == _msgSender(), "Invalid ownership" ); _aCollection.transferFrom(_msgSender(), address(this), _tokenId); _collection = address(_aCollection); } else { require( _bCollection.ownerOf(_tokenId) == _msgSender(), "Invalid ownership" ); _bCollection.transferFrom(_msgSender(), address(this), _tokenId); _collection = address(_bCollection); } _heldTokens[_tokenId] = _holderPlace; _tokenOwners[_tokenId] = _msgSender(); // SAVE TO TOKEN HOLDER _save(_holderPlace, _tokenId); // _tokenHolder[_msgSender()][_holderPlace].push(_tokenId); emit GameItemTransfer( _msgSender(), address(this), _collection, _tokenId, _holderPlace ); } /** * @notice Batch submit tokens to this contract and specify the {HolderPlace} * @param _holderPlace Holder place * @param _tokenIds Array of token ids */ function batchSubmit(HolderPlace _holderPlace, uint256[] memory _tokenIds) public { for (uint256 i = 0; i < _tokenIds.length; i++) { _submit(_holderPlace, _tokenIds[i]); } } /** * @notice Dispatch token from this contract * @param _holderPlace Holder place * @param _tokenId Token ID */ function _dispatch(HolderPlace _holderPlace, uint256 _tokenId) internal { require(_tokenOwners[_tokenId] == _msgSender(), "Requires own token"); address _collection = address(0); if (_tokenId < 20000) { require( _aCollection.ownerOf(_tokenId) == address(this), "Invalid ownership" ); _aCollection.transferFrom(address(this), _msgSender(), _tokenId); _collection = address(_aCollection); } else { require( _bCollection.ownerOf(_tokenId) == address(this), "Invalid ownership" ); _bCollection.transferFrom(address(this), _msgSender(), _tokenId); _collection = address(_bCollection); } _remove(_holderPlace, _tokenId); emit GameItemDispatch( address(this), _msgSender(), _collection, _tokenId, _holderPlace ); } /** * @notice Batch dispatch tokens from this contract and specify the {HolderPlace} * @param _holderPlace Holder place * @param _tokenIds Array of token ids */ function batchDispatch(HolderPlace _holderPlace, uint256[] memory _tokenIds) public { for (uint256 i = 0; i < _tokenIds.length; i++) { _dispatch(_holderPlace, _tokenIds[i]); } } /** * @notice Library function to remove array element by its value * @param _array Array to be manipulated * @param _element Element to be removed */ function _removeElement(uint256[] memory _array, uint256 _element) internal pure returns (uint256[] memory) { for (uint256 i; i < _array.length; i++) { if (_array[i] == _element) { // TODO FIX: delete _array[i]; break; } } // ERR Member "pop" is not available in uint256[] memory outside of storage. return _array; } /** * @notice remove token from tokenHolder * @param _holderPlace Holder place * @param _tokenId Token id to be removed */ function _remove(HolderPlace _holderPlace, uint256 _tokenId) internal { uint256[] memory newArray = _removeElement( _tokenHolder[msg.sender][_holderPlace], _tokenId ); _tokenHolder[msg.sender][_holderPlace] = newArray; } /** * @notice Save token to tokenHolder * @param _holderPlace Holder place * @param _tokenId Token id to be saved */ function _save(HolderPlace _holderPlace, uint256 _tokenId) internal { _tokenHolder[msg.sender][_holderPlace].push(_tokenId); } /** * @notice View held tokens * @param _holderPlace Holder place * @param _address Wallet address si user * @return array of token_ids */ function idsOf(HolderPlace _holderPlace, address _address) public view returns (uint256[] memory) { return _tokenHolder[_address][_holderPlace]; } /** * @notice Set address mapping to Rewards * @param _address Address * @param _reward CHRO Reward for address */ function setReward(address _address, uint256 _reward) public onlyOwner { _addressCHROReward[_address] = _reward; _totalReward += _reward; emit RewardSet(_address, _reward, block.timestamp); } /** * @notice Set address mapping to Rewards * @param _addresses Addresses * @param _rewards CHRO Rewards for address */ function batchSetReward( address[] memory _addresses, uint256[] memory _rewards ) public onlyOwner { uint256 totalRewards = 0; for (uint256 i = 0; i < _addresses.length; i++) { totalRewards += _rewards[i]; } require( totalRewards <= _tokenContract.balanceOf(address(this)), "Insufficent Treasury Balance" ); for (uint256 i = 0; i < _addresses.length; i++) { setReward(_addresses[i], _rewards[i]); } } /** * @notice Claim reward */ function claimReward() public nonReentrant { require( _addressClaimedTime[_msgSender()] + 86400 < block.timestamp, "Claim once per day" ); uint256 amount = _addressCHROReward[_msgSender()]; require( amount <= _totalReward, "Insufficent reward balance" ); require( amount <= _tokenContract.balanceOf(address(this)), "Insufficent SC Balance" ); _tokenContract.transfer(_msgSender(), amount); _totalReward -= amount; _addressClaimedTime[_msgSender()] = block.timestamp; _addressCHROReward[_msgSender()] = 0; emit RewardClaimed(_msgSender(), amount, block.timestamp); } /** *************************************************************************************** *************************************** ADMIN FUNCTIONS ******************************* *************************************************************************************** */ /** * @notice Force Dispatch token from this contract * @param _address Address of token owner * @param _holderPlace Holder place * @param _tokenId Token ID */ function safeDispatch( address _address, HolderPlace _holderPlace, uint256 _tokenId ) public onlyOwner { require(_tokenOwners[_tokenId] == _address, "Requires own token"); address _collection = address(0); if (_tokenId < 20000) { require( _aCollection.ownerOf(_tokenId) == address(this), "Invalid ownership" ); _aCollection.transferFrom(address(this), _address, _tokenId); _collection = address(_aCollection); } else { require( _bCollection.ownerOf(_tokenId) == address(this), "Invalid ownership" ); _bCollection.transferFrom(address(this), _address, _tokenId); _collection = address(_bCollection); } _remove(_holderPlace, _tokenId); emit GameItemDispatch( address(this), _address, _collection, _tokenId, _holderPlace ); } /** * @notice View total rewards */ function viewTotalRewards() external view onlyOwner returns (uint256) { return _totalReward; } /** *************************************************************************************** *************************************** BREEDING ************************************** *************************************************************************************** */ function breed(uint256[] memory _parents, string memory _tokenURI) public { require(_parents.length == 2, "Requires 2 wynds"); require(_parents[0] != _parents[1], "Identical tokens"); for (uint256 i = 0; i < 2; i++) { /// both sould be held by Breeding and owned by sender require( _heldTokens[_parents[i]] == HolderPlace.Breeding && _tokenOwners[_parents[i]] == _msgSender(), "Invalid place of token" ); /// maximum breed of each token require(_breedCounts[_parents[i]] < 3, "Max breed count of parent"); } /// check balance require( _tokenContract.balanceOf(_msgSender()) >= _breedingCost, "Not enough tokens" ); require( _tokenContract.allowance(_msgSender(), address(this)) >= _breedingCost, "Not enough allowance" ); /// transfer CHRO to this contract as P2E wallet _tokenContract.transferFrom(_msgSender(), address(this), _breedingCost); /// mint to NextGen collection uint256 childId = _bCollection.mint( _msgSender(), IERC721b.TokenType.Wynd, _tokenURI ); breedId.increment(); uint256 id = breedId.current(); _breedItems[id] = BreedItem({ aParent: _parents[0], bParent: _parents[1], child: childId }); _breedCounts[_parents[0]] += 1; _breedCounts[_parents[1]] += 1; emit BreedItemCreated(_parents[0], _parents[1], childId); } /** * @notice Get breed count of the given token id * @param _tokenId Token id */ function breedCountOf(uint256 _tokenId) public view returns (uint256) { return _breedCounts[_tokenId]; } function move( uint256 _tokenId, HolderPlace _from, HolderPlace _to ) public { require( _heldTokens[_tokenId] == _from && _tokenOwners[_tokenId] == _msgSender(), "Invalid source of token" ); address _collection = address(0); if (_tokenId < 20000) { _collection = address(_aCollection); } else { _collection = address(_bCollection); } _heldTokens[_tokenId] = _to; // TRANSFER TOKEN HOLDS _save(_to, _tokenId); _remove(_from, _tokenId); emit TokenMoved( _msgSender(), string( abi.encodePacked( Strings.toHexString(uint160(_collection), 20), ":", _tokenId.toString() ) ), _from, _to ); } function batchMove( uint256[] memory _tokenIds, HolderPlace _from, HolderPlace _to ) public { for (uint256 i = 0; i < _tokenIds.length; i++) { move(_tokenIds[i], _from, _to); } } }
* @notice Library function to remove array element by its value @param _array Array to be manipulated @param _element Element to be removed/ TODO FIX:
function _removeElement(uint256[] memory _array, uint256 _element) internal pure returns (uint256[] memory) { for (uint256 i; i < _array.length; i++) { if (_array[i] == _element) { delete _array[i]; break; } } }
7,301,471
[ 1, 9313, 445, 358, 1206, 526, 930, 635, 2097, 460, 225, 389, 1126, 1510, 358, 506, 13441, 11799, 225, 389, 2956, 3010, 358, 506, 3723, 19, 2660, 8563, 30, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 4479, 1046, 12, 11890, 5034, 8526, 3778, 389, 1126, 16, 2254, 5034, 389, 2956, 13, 203, 3639, 2713, 203, 3639, 16618, 203, 3639, 1135, 261, 11890, 5034, 8526, 3778, 13, 203, 565, 288, 203, 3639, 364, 261, 11890, 5034, 277, 31, 277, 411, 389, 1126, 18, 2469, 31, 277, 27245, 288, 203, 5411, 309, 261, 67, 1126, 63, 77, 65, 422, 389, 2956, 13, 288, 203, 7734, 1430, 389, 1126, 63, 77, 15533, 203, 7734, 898, 31, 203, 5411, 289, 203, 3639, 289, 203, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x0Fc3DD8C37880a297166BEd57759974A157f0E74/sources/contracts/seadrop/ParallelAvatarInvoke.sol
* @notice Called with the sale price to determine how much royalty is owed and to whom. @ param _tokenId The NFT asset queried for royalty information. @param _salePrice The sale price of the NFT asset specified by _tokenId. @return receiver Address of who should be sent the royalty payment. @return royaltyAmount The royalty payment amount for _salePrice./ Put the royalty info on the stack for more efficient access. Set the royalty amount to the sale price times the royalty basis points divided by 10_000. Set the receiver of the royalty.
function royaltyInfo( uint256 /* _tokenId */, uint256 _salePrice ) external view returns (address receiver, uint256 royaltyAmount) { RoyaltyInfo storage info = _royaltyInfo; royaltyAmount = (_salePrice * info.royaltyBps) / 10_000; receiver = info.royaltyAddress; }
9,730,038
[ 1, 8185, 598, 326, 272, 5349, 6205, 358, 4199, 3661, 9816, 721, 93, 15006, 540, 353, 2523, 329, 471, 358, 600, 362, 18, 632, 579, 225, 389, 2316, 548, 377, 1021, 423, 4464, 3310, 23264, 364, 721, 93, 15006, 1779, 18, 282, 389, 87, 5349, 5147, 565, 1021, 272, 5349, 6205, 434, 326, 423, 4464, 3310, 1269, 635, 15604, 389, 2316, 548, 18, 327, 5971, 1377, 5267, 434, 10354, 1410, 506, 3271, 326, 721, 93, 15006, 5184, 18, 327, 721, 93, 15006, 6275, 1021, 721, 93, 15006, 5184, 3844, 364, 389, 87, 5349, 5147, 18, 19, 4399, 326, 721, 93, 15006, 1123, 603, 326, 2110, 364, 1898, 14382, 2006, 18, 1000, 326, 721, 93, 15006, 3844, 358, 326, 272, 5349, 6205, 4124, 326, 721, 93, 15006, 10853, 3143, 26057, 635, 1728, 67, 3784, 18, 1000, 326, 5971, 434, 326, 721, 93, 15006, 18, 2, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 721, 93, 15006, 966, 12, 203, 3639, 2254, 5034, 1748, 389, 2316, 548, 1195, 16, 203, 3639, 2254, 5034, 389, 87, 5349, 5147, 203, 565, 262, 3903, 1476, 1135, 261, 2867, 5971, 16, 2254, 5034, 721, 93, 15006, 6275, 13, 288, 203, 3639, 534, 13372, 15006, 966, 2502, 1123, 273, 389, 3800, 15006, 966, 31, 203, 203, 3639, 721, 93, 15006, 6275, 273, 261, 67, 87, 5349, 5147, 380, 1123, 18, 3800, 15006, 38, 1121, 13, 342, 1728, 67, 3784, 31, 203, 203, 3639, 5971, 273, 1123, 18, 3800, 15006, 1887, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.6.6; import "@openzeppelin/contracts-ethereum-package/contracts/access/Ownable.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/math/Math.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/utils/ReentrancyGuard.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/Initializable.sol"; import "./interfaces/IDebtToken.sol"; import "./interfaces/IVaultConfig.sol"; import "./interfaces/IWorker.sol"; import "./interfaces/IVault.sol"; import "../token/interfaces/IFairLaunch.sol"; import "../utils/SafeToken.sol"; import "./WNativeRelayer.sol"; contract Vault is IVault, ERC20UpgradeSafe, ReentrancyGuardUpgradeSafe, OwnableUpgradeSafe { /// @notice Libraries using SafeToken for address; using SafeMath for uint256; /// @notice Events event AddDebt(uint256 indexed id, uint256 debtShare); event RemoveDebt(uint256 indexed id, uint256 debtShare); event Work(uint256 indexed id, uint256 loan); event Kill(uint256 indexed id, address indexed killer, address owner, uint256 posVal, uint256 debt, uint256 prize, uint256 left); /// @dev Flags for manage execution scope uint private constant _NOT_ENTERED = 1; uint private constant _ENTERED = 2; uint private constant _NO_ID = uint(-1); address private constant _NO_ADDRESS = address(1); /// @dev Temporay variables to manage execution scope uint public _IN_EXEC_LOCK; uint public POSITION_ID; address public STRATEGY; /// @dev Attributes for Vault /// token - address of the token to be deposited in this pool /// name - name of the ibERC20 /// symbol - symbol of ibERC20 /// decimals - decimals of ibERC20, this depends on the decimal of the token /// debtToken - just a simple ERC20 token for staking with FairLaunch address public token; address public debtToken; struct Position { address worker; address owner; uint256 debtShare; } IVaultConfig public config; mapping (uint256 => Position) public positions; uint256 public nextPositionID; uint256 public fairLaunchPoolId; uint256 public vaultDebtShare; uint256 public vaultDebtVal; uint256 public lastAccrueTime; uint256 public reservePool; /// @dev Require that the caller must be an EOA account to avoid flash loans. modifier onlyEOA() { // require(msg.sender == tx.origin, "Vault::onlyEoa:: not eoa"); _; } /// @dev Get token from msg.sender modifier transferTokenToVault(uint256 value) { if (msg.value != 0) { require(token == config.getWrappedNativeAddr(), "Vault::transferTokenToVault:: baseToken is not wNative"); require(value == msg.value, "Vault::transferTokenToVault:: value != msg.value"); IWETH(config.getWrappedNativeAddr()).deposit{value: msg.value}(); } else { SafeToken.safeTransferFrom(token, msg.sender, address(this), value); } _; } /// @dev Ensure that the function is called with the execution scope modifier inExec() { require(POSITION_ID != _NO_ID, "Vault::inExec:: not within execution scope"); require(STRATEGY == msg.sender, "Vault::inExec:: not from the strategy"); require(_IN_EXEC_LOCK == _NOT_ENTERED, "Vault::inExec:: in exec lock"); _IN_EXEC_LOCK = _ENTERED; _; _IN_EXEC_LOCK = _NOT_ENTERED; } /// @dev Add more debt to the bank debt pool. modifier accrue(uint256 value) { if (now > lastAccrueTime) { uint256 interest = pendingInterest(value); uint256 toReserve = interest.mul(config.getReservePoolBps()).div(10000); reservePool = reservePool.add(toReserve); vaultDebtVal = vaultDebtVal.add(interest); lastAccrueTime = now; } _; } function initialize( IVaultConfig _config, address _token, string memory _name, string memory _symbol, uint8 _decimals, address _debtToken ) public initializer { OwnableUpgradeSafe.__Ownable_init(); ReentrancyGuardUpgradeSafe.__ReentrancyGuard_init(); ERC20UpgradeSafe.__ERC20_init(_name, _symbol); _setupDecimals(_decimals); nextPositionID = 1; config = _config; lastAccrueTime = now; token = _token; fairLaunchPoolId = uint256(-1); debtToken = _debtToken; SafeToken.safeApprove(debtToken, config.getFairLaunchAddr(), uint256(-1)); // free-up execution scope _IN_EXEC_LOCK = _NOT_ENTERED; POSITION_ID = _NO_ID; STRATEGY = _NO_ADDRESS; } /// @dev Return the pending interest that will be accrued in the next call. /// @param value Balance value to subtract off address(this).balance when called from payable functions. function pendingInterest(uint256 value) public view returns (uint256) { if (now > lastAccrueTime) { uint256 timePast = now.sub(lastAccrueTime); uint256 balance = SafeToken.myBalance(token).sub(value); uint256 ratePerSec = config.getInterestRate(vaultDebtVal, balance); return ratePerSec.mul(vaultDebtVal).mul(timePast).div(1e18); } else { return 0; } } /// @dev Return the Token debt value given the debt share. Be careful of unaccrued interests. /// @param debtShare The debt share to be converted. function debtShareToVal(uint256 debtShare) public view returns (uint256) { if (vaultDebtShare == 0) return debtShare; // When there's no share, 1 share = 1 val. return debtShare.mul(vaultDebtVal).div(vaultDebtShare); } /// @dev Return the debt share for the given debt value. Be careful of unaccrued interests. /// @param debtVal The debt value to be converted. function debtValToShare(uint256 debtVal) public view returns (uint256) { if (vaultDebtShare == 0) return debtVal; // When there's no share, 1 share = 1 val. return debtVal.mul(vaultDebtShare).div(vaultDebtVal); } /// @dev Return Token value and debt of the given position. Be careful of unaccrued interests. /// @param id The position ID to query. function positionInfo(uint256 id) public view returns (uint256, uint256) { Position storage pos = positions[id]; return (IWorker(pos.worker).health(id), debtShareToVal(pos.debtShare)); } /// @dev Return the total token entitled to the token holders. Be careful of unaccrued interests. function totalToken() public view override returns (uint256) { return SafeToken.myBalance(token).add(vaultDebtVal).sub(reservePool); } /// @dev Add more token to the lending pool. Hope to get some good returns. function deposit(uint256 amountToken) external override payable transferTokenToVault(amountToken) accrue(amountToken) nonReentrant { _deposit(amountToken); } function _deposit(uint256 amountToken) internal { uint256 total = totalToken().sub(amountToken); uint256 share = total == 0 ? amountToken : amountToken.mul(totalSupply()).div(total); _mint(msg.sender, share); require(totalSupply() > 1e17, "Vault::deposit:: no tiny shares"); } /// @dev Withdraw token from the lending and burning ibToken. function withdraw(uint256 share) external override accrue(0) nonReentrant { uint256 amount = share.mul(totalToken()).div(totalSupply()); _burn(msg.sender, share); if (token == config.getWrappedNativeAddr()) { SafeToken.safeTransfer(token, config.getWNativeRelayer(), amount); WNativeRelayer(uint160(config.getWNativeRelayer())).withdraw(amount); SafeToken.safeTransferETH(msg.sender, amount); } else { SafeToken.safeTransfer(token, msg.sender, amount); } require(totalSupply() > 1e17, "Vault::withdraw:: no tiny shares"); } /// @dev Request Funds from user through Vault function requestFunds(address targetedToken, uint amount) external override inExec { SafeToken.safeTransferFrom(targetedToken, positions[POSITION_ID].owner, msg.sender, amount); } /// @dev Mint & deposit debtToken on behalf of farmers /// @param id The ID of the position /// @param amount The amount of debt that the position holds function _fairLaunchDeposit(uint256 id, uint256 amount) internal { if (amount > 0) { IDebtToken(debtToken).mint(address(this), amount); IFairLaunch(config.getFairLaunchAddr()).deposit(positions[id].owner, fairLaunchPoolId, amount); } } /// @dev Withdraw & burn debtToken on behalf of farmers /// @param id The ID of the position function _fairLaunchWithdraw(uint256 id) internal { if (positions[id].debtShare > 0) { // Note: Do this way because we don't want to fail open, close, or kill position // if cannot withdraw from FairLaunch somehow. 0xb5c5f672 is a signature of withdraw(address,uint256,uint256) (bool success, ) = config.getFairLaunchAddr().call(abi.encodeWithSelector(0xb5c5f672, positions[id].owner, fairLaunchPoolId, positions[id].debtShare)); if(success) IDebtToken(debtToken).burn(address(this), positions[id].debtShare); } } /// @dev Create a new farming position to unlock your yield farming potential. /// @param id The ID of the position to unlock the earning. Use ZERO for new position. /// @param worker The address of the authorized worker to work for this position. /// @param loan The amount of Token to borrow from the pool. /// @param maxReturn The max amount of Token to return to the pool. /// @param data The calldata to pass along to the worker for more working context. function work(uint256 id, address worker, uint256 principalAmount, uint256 loan, uint256 maxReturn, bytes calldata data) external payable onlyEOA transferTokenToVault(principalAmount) accrue(principalAmount) nonReentrant { require(fairLaunchPoolId != uint256(-1), "Vault::work:: poolId not set"); // 1. Sanity check the input position, or add a new position of ID is 0. Position storage pos; if (id == 0) { id = nextPositionID++; pos = positions[id]; pos.worker = worker; pos.owner = msg.sender; } else { pos = positions[id]; require(id < nextPositionID, "Vault::work:: bad position id"); require(pos.worker == worker, "Vault::work:: bad position worker"); require(pos.owner == msg.sender, "Vault::work:: not position owner"); _fairLaunchWithdraw(id); } emit Work(id, loan); // Update execution scope variables POSITION_ID = id; (STRATEGY, ) = abi.decode(data, (address, bytes)); // 2. Make sure the worker can accept more debt and remove the existing debt. require(config.isWorker(worker), "Vault::work:: not a worker"); require(loan == 0 || config.acceptDebt(worker), "Vault::work:: worker not accept more debt"); uint256 debt = _removeDebt(id).add(loan); // 3. Perform the actual work, using a new scope to avoid stack-too-deep errors. uint256 back; { uint256 sendBEP20 = principalAmount.add(loan); require(sendBEP20 <= SafeToken.myBalance(token), "Vault::work:: insufficient funds in the vault"); uint256 beforeBEP20 = SafeToken.myBalance(token).sub(sendBEP20); SafeToken.safeTransfer(token, worker, sendBEP20); IWorker(worker).work(id, msg.sender, debt, data); back = SafeToken.myBalance(token).sub(beforeBEP20); } // 4. Check and update position debt. uint256 lessDebt = Math.min(debt, Math.min(back, maxReturn)); debt = debt.sub(lessDebt); if (debt > 0) { require(debt >= config.minDebtSize(), "Vault::work:: too small debt size"); uint256 health = IWorker(worker).health(id); uint256 workFactor = config.workFactor(worker, debt); require(health.mul(workFactor) >= debt.mul(10000), "Vault::work:: bad work factor"); _addDebt(id, debt); _fairLaunchDeposit(id, pos.debtShare); } // 5. Return excess token back. if (back > lessDebt) { if(token == config.getWrappedNativeAddr()) { SafeToken.safeTransfer(token, config.getWNativeRelayer(), back.sub(lessDebt)); WNativeRelayer(uint160(config.getWNativeRelayer())).withdraw(back.sub(lessDebt)); SafeToken.safeTransferETH(msg.sender, back.sub(lessDebt)); } else { SafeToken.safeTransfer(token, msg.sender, back.sub(lessDebt)); } } // 6. Release execution scope POSITION_ID = _NO_ID; STRATEGY = _NO_ADDRESS; } /// @dev Kill the given to the position. Liquidate it immediately if killFactor condition is met. /// @param id The position ID to be killed. function kill(uint256 id) external onlyEOA accrue(0) nonReentrant { require(fairLaunchPoolId != uint256(-1), "Vault::kill:: poolId not set"); // 1. Verify that the position is eligible for liquidation. Position storage pos = positions[id]; require(pos.debtShare > 0, "Vault::kill:: no debt"); // 2. Distribute ALPACAs in FairLaunch to owner _fairLaunchWithdraw(id); uint256 debt = _removeDebt(id); uint256 health = IWorker(pos.worker).health(id); uint256 killFactor = config.killFactor(pos.worker, debt); require(health.mul(killFactor) < debt.mul(10000), "Vault::kill:: can't liquidate"); // 3. Perform liquidation and compute the amount of token received. uint256 beforeToken = SafeToken.myBalance(token); IWorker(pos.worker).liquidate(id); uint256 back = SafeToken.myBalance(token).sub(beforeToken); uint256 prize = back.mul(config.getKillBps()).div(10000); uint256 rest = back.sub(prize); // 4. Clear position debt and return funds to liquidator and position owner. if (prize > 0) { if (token == config.getWrappedNativeAddr()) { SafeToken.safeTransfer(token, config.getWNativeRelayer(), prize); WNativeRelayer(uint160(config.getWNativeRelayer())).withdraw(prize); SafeToken.safeTransferETH(msg.sender, prize); } else { SafeToken.safeTransfer(token, msg.sender, prize); } } uint256 left = rest > debt ? rest - debt : 0; if (left > 0) { if (token == config.getWrappedNativeAddr()) { SafeToken.safeTransfer(token, config.getWNativeRelayer(), left); WNativeRelayer(uint160(config.getWNativeRelayer())).withdraw(left); SafeToken.safeTransferETH(pos.owner, left); } else { SafeToken.safeTransfer(token, pos.owner, left); } } emit Kill(id, msg.sender, pos.owner, health, debt, prize, left); } /// @dev Internal function to add the given debt value to the given position. function _addDebt(uint256 id, uint256 debtVal) internal { Position storage pos = positions[id]; uint256 debtShare = debtValToShare(debtVal); pos.debtShare = pos.debtShare.add(debtShare); vaultDebtShare = vaultDebtShare.add(debtShare); vaultDebtVal = vaultDebtVal.add(debtVal); emit AddDebt(id, debtShare); } /// @dev Internal function to clear the debt of the given position. Return the debt value. function _removeDebt(uint256 id) internal returns (uint256) { Position storage pos = positions[id]; uint256 debtShare = pos.debtShare; if (debtShare > 0) { uint256 debtVal = debtShareToVal(debtShare); pos.debtShare = 0; vaultDebtShare = vaultDebtShare.sub(debtShare); vaultDebtVal = vaultDebtVal.sub(debtVal); emit RemoveDebt(id, debtShare); return debtVal; } else { return 0; } } /// @dev Update bank configuration to a new address. Must only be called by owner. /// @param _config The new configurator address. function updateConfig(IVaultConfig _config) external onlyOwner { config = _config; } /// @dev Update debtToken to a new address. Must only be called by owner. /// @param _debtToken The new DebtToken function updateDebtToken(address _debtToken, uint256 _newPid) external onlyOwner { require(_debtToken != token, "Vault::updateDebtToken:: _debtToken must not be the same as token"); address[] memory okHolders = new address[](2); okHolders[0] = address(this); okHolders[1] = config.getFairLaunchAddr(); IDebtToken(_debtToken).setOkHolders(okHolders, true); debtToken = _debtToken; fairLaunchPoolId = _newPid; SafeToken.safeApprove(debtToken, config.getFairLaunchAddr(), uint256(-1)); } function setFairLaunchPoolId(uint256 _poolId) external onlyOwner { SafeToken.safeApprove(debtToken, config.getFairLaunchAddr(), uint256(-1)); fairLaunchPoolId = _poolId; } /// @dev Withdraw BaseToken reserve for underwater positions to the given address. /// @param to The address to transfer BaseToken to. /// @param value The number of BaseToken tokens to withdraw. Must not exceed `reservePool`. function withdrawReserve(address to, uint256 value) external onlyOwner nonReentrant { reservePool = reservePool.sub(value); SafeToken.safeTransfer(token, to, value); } /// @dev Reduce BaseToken reserve, effectively giving them to the depositors. /// @param value The number of BaseToken reserve to reduce. function reduceReserve(uint256 value) external onlyOwner { reservePool = reservePool.sub(value); } /// @dev Fallback function to accept ETH. Workers will send ETH back the pool. receive() external payable {} }
@dev Return Token value and debt of the given position. Be careful of unaccrued interests. @param id The position ID to query.
function positionInfo(uint256 id) public view returns (uint256, uint256) { Position storage pos = positions[id]; return (IWorker(pos.worker).health(id), debtShareToVal(pos.debtShare)); }
915,038
[ 1, 990, 3155, 460, 471, 18202, 88, 434, 326, 864, 1754, 18, 4823, 26850, 434, 640, 8981, 86, 5957, 16513, 87, 18, 225, 612, 1021, 1754, 1599, 358, 843, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 1754, 966, 12, 11890, 5034, 612, 13, 1071, 1476, 1135, 261, 11890, 5034, 16, 2254, 5034, 13, 288, 203, 565, 11010, 2502, 949, 273, 6865, 63, 350, 15533, 203, 565, 327, 261, 45, 6671, 12, 917, 18, 10124, 2934, 13267, 12, 350, 3631, 18202, 88, 9535, 774, 3053, 12, 917, 18, 323, 23602, 9535, 10019, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.8.0; import "./OrgV1.sol"; interface SafeFactory { function createProxy(address masterCopy, bytes memory data) external returns (Safe); } interface Resolver { function multicall(bytes[] calldata data) external returns(bytes[] memory results); function setAddr(bytes32, address) external; function addr(bytes32 node) external returns (address); function name(bytes32 node) external returns (string memory); } interface Registrar { function commit(bytes32 commitment) external; function commitWithPermit( bytes32 commitment, address owner, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; function register(string calldata name, address owner, uint256 salt) external; function ens() external view returns (address); function radNode() external view returns (bytes32); function rad() external view returns (address); function registrationFeeRad() external view returns (uint256); function minCommitmentAge() external view returns (uint256); } interface Safe { function setup( address[] calldata _owners, uint256 _threshold, address to, bytes calldata data, address fallbackHandler, address paymentToken, uint256 payment, address payable paymentReceiver ) external; function getThreshold() external returns (uint256); function isOwner(address owner) external returns (bool); } /// Factory for orgs. contract OrgV2Factory { SafeFactory immutable safeFactory; address immutable safeMasterCopy; // Radicle ENS domain. string public radDomain = ".radicle.eth"; /// An org was created. Includes the org and owner address as well as the name. event OrgCreated(address org, address safe, string domain); constructor( address _safeFactory, address _safeMasterCopy ) { safeFactory = SafeFactory(_safeFactory); safeMasterCopy = _safeMasterCopy; } /// Commitments to org names. mapping (bytes32 => bytes32) public commitments; /// Commit to a new org name. /// /// The commitment must commit to this contract as the owner, while the owner /// digest should be a hash of the desired owner of the name, once setup is complete. /// /// The same salt should be used for both parameters. For the owner digest, /// the contract expects `keccak256(abi.encodePacked(owner, salt))`. /// In the case of a multi-sig, the owners array should be used. /// /// @param registrar The Radicle registrar. /// @param commitment The commitment that will be submitted to the registrar. /// @param ownerDigest The designated owner of the name, once setup is complete. function commitToOrgName( Registrar registrar, bytes32 commitment, bytes32 ownerDigest ) public { commitments[commitment] = ownerDigest; uint256 fee = registrar.registrationFeeRad(); if (fee > 0) { IERC20 rad = IERC20(registrar.rad()); require( rad.transferFrom(msg.sender, address(this), fee), "OrgFactory: transfer of registration fee from sender must succeed" ); require( rad.approve(address(registrar), fee), "OrgFactory: approval of registration fee to registrar must succeed" ); } registrar.commit(commitment); } /// Commit to a new org name, using *permit*. /// /// See `commitToOrgName`. function commitToOrgNameWithPermit( Registrar registrar, bytes32 commitment, bytes32 ownerDigest, address permitOwner, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public { commitments[commitment] = ownerDigest; registrar.commitWithPermit(commitment, permitOwner, value, deadline, v, r, s); } /// Register a pre-committed name, create an org and associate the two /// together. /// /// To use this method, one must commit to a name and use this contract's /// address as the owner committed to. This method will transfer ownership /// of the name to the given owner after completing the registration. /// /// To set additional ENS records for the given name, one may include /// optional calldata using the `resolverData` parameter. /// /// @param owner The owner of the org. /// @param name Name to register and associate with the org. /// @param salt Commitment salt used in `commit` transaction. /// @param resolverData Data payload for optional resolver multicall. /// @param registrar Address of the Radicle registrar. function registerAndCreateOrg( address owner, string memory name, uint256 salt, bytes[] calldata resolverData, Registrar registrar ) public returns (OrgV1, bytes32) { require(address(registrar) != address(0), "OrgFactory: registrar must not be zero"); require(owner != address(0), "OrgFactory: owner must not be zero"); { bytes32 ownerDigest = redeemCommitment(name, salt); require(keccak256(abi.encodePacked(owner, salt)) == ownerDigest, "OrgFactory: owners must match commitment"); } // Temporarily set the owner of the name to this contract. // It will be transfered to the given owner once the setup // is complete. registrar.register(name, address(this), salt); ENS ens = ENS(registrar.ens()); bytes32 root = registrar.radNode(); bytes32 label = keccak256(bytes(name)); return setupOrg( owner, resolverData, string(abi.encodePacked(name, radDomain)), root, label, ens ); } /// Register a pre-committed name, create an org owned by multiple owners, /// and associated the two together. /// /// @param owners The owners of the org. /// @param threshold The minimum number of signatures to perform org transactions. /// @param name Name to register and associate with the org. /// @param salt Commitment salt used in `commit` transaction. /// @param resolverData Data payload for optional resolver multicall. /// @param registrar Address of the Radicle registrar. function registerAndCreateOrg( address[] memory owners, uint256 threshold, string memory name, uint256 salt, bytes[] calldata resolverData, Registrar registrar ) public returns (OrgV1, bytes32) { require(address(registrar) != address(0), "OrgFactory: registrar must not be zero"); { bytes32 ownerDigest = redeemCommitment(name, salt); require(keccak256(abi.encodePacked(owners, salt)) == ownerDigest, "OrgFactory: owners must match commitment"); } registrar.register(name, address(this), salt); ENS ens = ENS(registrar.ens()); bytes32 root = registrar.radNode(); bytes32 label = keccak256(bytes(name)); return setupOrg( owners, threshold, resolverData, string(abi.encodePacked(name, radDomain)), root, label, ens ); } /// Registers a name that is owned by this contract, and reclaims it by /// transfering it back to the owner. /// /// This is useful in emergency situations when a commitment was created /// with this contract as the owner, but completing the flow and creating /// an org is not desirable. /// /// @param registrar Address of the Radicle registrar. /// @param parent ENS parent node for the name, eg. `namehash("radicle.eth")`. /// @param name Name committed to, eg. "cloudhead". /// @param salt Salt committed to. /// @param owner Address this name should be transfered to after registration. function registerAndReclaim( Registrar registrar, bytes32 parent, string memory name, uint256 salt, address owner ) public { ENS ens = ENS(registrar.ens()); bytes32 ownerDigest = redeemCommitment(name, salt); require(keccak256(abi.encodePacked(owner, salt)) == ownerDigest, "OrgFactory: owner must match commitment"); registrar.register(name, address(this), salt); bytes32 node = keccak256(abi.encodePacked(parent, keccak256(bytes(name)))); ens.setOwner(node, owner); } /// Setup an org with multiple owners. function setupOrg( address[] memory owners, uint256 threshold, bytes[] calldata resolverData, string memory domain, bytes32 parent, bytes32 label, ENS ens ) private returns (OrgV1, bytes32) { require(owners.length > 0, "OrgFactory: owners must not be empty"); require(threshold > 0, "OrgFactory: threshold must be greater than zero"); require(threshold <= owners.length, "OrgFactory: threshold must be lesser than or equal to owner count"); // Deploy safe. Safe safe = safeFactory.createProxy(safeMasterCopy, new bytes(0)); safe.setup(owners, threshold, address(0), new bytes(0), address(0), address(0), 0, payable(address(0))); return setupOrg(address(safe), resolverData, domain, parent, label, ens); } /// Setup an org with an existing owner. function setupOrg( address owner, bytes[] calldata resolverData, string memory domain, bytes32 parent, bytes32 label, ENS ens ) private returns (OrgV1, bytes32) { require(address(ens) != address(0), "OrgFactory: ENS address must not be zero"); // Create org, temporarily holding ownership. OrgV1 org = new OrgV1(address(this)); // Get the ENS node for the name associated with this org. bytes32 node = keccak256(abi.encodePacked(parent, label)); // Get the ENS resolver for the node. Resolver resolver = Resolver(ens.resolver(node)); // Set the address of the ENS name to this org. resolver.setAddr(node, address(org)); // Set any other ENS records. resolver.multicall(resolverData); // Set org ENS reverse-record. org.setName(domain, ens); // Transfer ownership of the org to the owner. org.setOwner(owner); // Transfer ownership of the name to the owner. ens.setOwner(node, owner); emit OrgCreated(address(org), owner, domain); return (org, node); } /// Redeem a previously made commitment. function redeemCommitment(string memory name, uint256 salt) private returns (bytes32) { bytes32 commitment = keccak256(abi.encodePacked(name, address(this), salt)); bytes32 ownerDigest = commitments[commitment]; require(ownerDigest != bytes32(0), "OrgFactory: commitment not found"); delete commitments[commitment]; return ownerDigest; } }
An org was created. Includes the org and owner address as well as the name.
) { safeFactory = SafeFactory(_safeFactory); safeMasterCopy = _safeMasterCopy; }
13,122,023
[ 1, 979, 2358, 1703, 2522, 18, 657, 8993, 326, 2358, 471, 3410, 1758, 487, 5492, 487, 326, 508, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 262, 288, 203, 3639, 4183, 1733, 273, 14060, 1733, 24899, 4626, 1733, 1769, 203, 3639, 4183, 7786, 2951, 273, 389, 4626, 7786, 2951, 31, 203, 565, 289, 203, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.15; import "./IDaoBase.sol"; import "./governance/Voting.sol"; import "./moneyflow/WeiExpense.sol"; import "./moneyflow/IMoneyflow.sol"; import "zeppelin-solidity/contracts/ownership/Ownable.sol"; contract GenericProposal is IProposal, Ownable { IVoting voting; address target; string methodSig; bytes32[] params; function GenericProposal(address _target, address _origin, string _methodSig, bytes32[] _params) public { target = _target; params = _params; methodSig = _methodSig; } // IVoting implementation function action(IDaoBase _mc, IVoting _voting) public { require(address(voting)!=0x0); require(msg.sender==address(voting)); // cool! voting is over and the majority said YES -> so let's go! // as long as we call this method from WITHIN the vote contract // isCanDoAction() should return yes if voting finished with Yes result target.call( bytes4(keccak256(methodSig)), uint256(32), // pointer to the length of the array uint256(params.length), // length of the array params); // array itself } function setVoting(IVoting _voting) public onlyOwner{ voting = _voting; } function getVoting()public constant returns(IVoting){ return voting; } } // This is a wrapper that help us to do action that CAN require votings // WARNING: should be permitted to add new proposal by the current DaoBase!!! contract GenericCaller is DaoClient { function GenericCaller(IDaoBase _mc)public // DaoClient (for example) helps us to handle DaoBase upgrades // and will automatically update the 'mc' to the new instance DaoClient(_mc) { } // _actionId is something like "issueTokens" // _methodSig some kind of "issueTokens(bytes32[])" function doAction(string _permissionsId, address _target, address _origin, string _methodSig, bytes32[] _params) public returns(address proposalOut) { if(mc.isCanDoAction(msg.sender, _permissionsId)){ // 1 - call immediately? _target.call( bytes4(keccak256(_methodSig)), uint256(32), // pointer to the length of the array uint256(_params.length), // length of the array _params ); /* // Delegatecall: // 1. _target storage will be set to THIS contract // 2. msg.sender will be set to THE CURRENT msg.sender! _target.delegatecall( bytes4(keccak256(_methodSig)), uint256(32), // pointer to the length of the array uint256(_params.length), // length of the array _params ); */ return 0x0; }else{ // 2 - create proposal + voting first // _origin is the initial msg.sender (just like tx.origin) GenericProposal prop = new GenericProposal(_target, _origin, _methodSig, _params); IVoting voting = createVoting(_permissionsId, prop, _origin); prop.setVoting(voting); // WARNING: should be permitted to add new proposal by the current contract address!!! // check your permissions or see examples (tests) how to do that correctly mc.addNewProposal(prop); return prop; } } function createVoting(string _permissionsId, IProposal _prop, address _origin)internal returns(IVoting){ // TODO: make Voting factory. I.e., vote type should depend on what is the _permissionsId return new Voting(mc, _prop, _origin, Voting.VoteType.EmployeesVote, 24 *60, 0x0); } }
IVoting implementation cool! voting is over and the majority said YES -> so let's go! as long as we call this method from WITHIN the vote contract isCanDoAction() should return yes if voting finished with Yes result
function action(IDaoBase _mc, IVoting _voting) public { require(address(voting)!=0x0); require(msg.sender==address(voting)); target.call( bytes4(keccak256(methodSig)), }
12,697,512
[ 1, 8188, 17128, 4471, 27367, 5, 331, 17128, 353, 1879, 471, 326, 7888, 560, 7864, 350, 1624, 3991, 317, 1427, 2231, 1807, 1960, 5, 487, 1525, 487, 732, 745, 333, 707, 628, 13601, 706, 326, 12501, 6835, 353, 2568, 3244, 1803, 1435, 1410, 327, 12465, 309, 331, 17128, 6708, 598, 19925, 563, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 915, 1301, 12, 734, 6033, 2171, 389, 13952, 16, 21602, 17128, 389, 90, 17128, 13, 1071, 288, 203, 202, 202, 6528, 12, 2867, 12, 90, 17128, 13, 5, 33, 20, 92, 20, 1769, 203, 202, 202, 6528, 12, 3576, 18, 15330, 631, 2867, 12, 90, 17128, 10019, 203, 203, 202, 202, 3299, 18, 1991, 12, 203, 1082, 202, 3890, 24, 12, 79, 24410, 581, 5034, 12, 2039, 8267, 13, 3631, 203, 202, 97, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/* t.me/JesusERC JesusToken.net Twitter.com/JesusTokenERC Total tokens: 100,000,000 Taxes: 12% */ // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } } interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; return c; } } contract Ownable is Context { address private _owner; address private _previousOwner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor() { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } function owner() public view returns (address) { return _owner; } modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } interface IUniswapV2Factory { function createPair(address tokenA, address tokenB) external returns (address pair); } interface IUniswapV2Router02 { function swapExactTokensForETHSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidityETH( address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external payable returns (uint256 amountToken, uint256 amountETH, uint256 liquidity); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } abstract contract IERC20Extented is IERC20 { function decimals() external view virtual returns (uint8); function name() external view virtual returns (string memory); function symbol() external view virtual returns (string memory); } contract Jesus is Context, IERC20, IERC20Extented, Ownable { using SafeMath for uint256; string private constant _name = "Jesus"; string private constant _symbol = "JESUS"; uint8 private constant _decimals = 9; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; mapping(address => bool) private _isExcludedFromFee; uint256 private constant _tTotal = 100 * 1e6 * 1e9; // 100,000,000 uint256 private _firstBlock; uint256 private _notpogBlocks; uint256 public _maxWalletAmount; // fees uint256 public _liquidityFee = 20; // divided by 1000 uint256 private _previousLiquidityFee = _liquidityFee; uint256 public _marketingFee = 100; // divided by 1000 uint256 private _previousMarketingFee = _marketingFee; uint256 private _marketingPercent = 1000; struct FeeBreakdown { uint256 tLiquidity; uint256 tMarketing; uint256 tAmount; } mapping(address => bool) private notpogs; address payable private _marketingAddress = payable(0x3897D607BECDa0c1ffd276A25619De3bD24B1f9f); address payable private _dev = payable(0xF47dB7D05e87d09A70a6A83f5776D5732f829661); IUniswapV2Router02 private uniswapV2Router; address public uniswapV2Pair; uint256 private _maxTxAmount; bool private tradingOpen = false; bool private inSwap = false; bool private trdg = true; bool private pairSwapped = false; event EndedTrdg(bool trdg); event MaxTxAmountUpdated(uint256 _maxTxAmount); event FeesUpdated(uint256 _marketingFee, uint256 _liquidityFee); modifier lockTheSwap { inSwap = true; _; inSwap = false; } constructor() { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); uniswapV2Router = _uniswapV2Router; _approve(address(this), address(uniswapV2Router), _tTotal); uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); IERC20(uniswapV2Pair).approve(address(uniswapV2Router),type(uint256).max); _maxTxAmount = _tTotal; // start off transaction limit at 100% of total supply _maxWalletAmount = _tTotal.div(1); // 100% _balances[_msgSender()] = _tTotal; _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; emit Transfer(address(0), _msgSender(), _tTotal); } function name() override external pure returns (string memory) { return _name; } function symbol() override external pure returns (string memory) { return _symbol; } function decimals() override external pure returns (uint8) { return _decimals; } function totalSupply() external pure override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) external override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) external view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) external override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) external override returns (bool) { _transfer(sender, recipient, amount); _approve(sender,_msgSender(),_allowances[sender][_msgSender()].sub(amount,"ERC20: transfer amount exceeds allowance")); return true; } function removeAllFee() private { if (_marketingFee == 0 && _liquidityFee == 0) return; _previousMarketingFee = _marketingFee; _previousLiquidityFee = _liquidityFee; _marketingFee = 0; _liquidityFee = 0; } function setNotpogFee() private { _previousMarketingFee = _marketingFee; _previousLiquidityFee = _liquidityFee; _marketingFee = 1000; _liquidityFee = 0; } function restoreAllFee() private { _marketingFee = _previousMarketingFee; _liquidityFee = _previousLiquidityFee; } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer(address from, address to, uint256 amount) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); bool takeFee = true; if (from != owner() && to != owner() && from != address(this) && to != address(this)) { require(tradingOpen); require(amount <= _maxTxAmount); if (from == uniswapV2Pair && to != address(uniswapV2Router)) {//buys if (block.number <= _firstBlock.add(_notpogBlocks)) { notpogs[to] = true; } require(balanceOf(to).add(amount) <= _maxWalletAmount, "wallet balance after transfer must be less than max wallet amount"); if (notpogs[to]) { setNotpogFee(); takeFee = true; } } if (!inSwap && from != uniswapV2Pair) { //sells, transfers require(!notpogs[from] && !notpogs[to]); uint256 contractTokenBalance = balanceOf(address(this)); if (contractTokenBalance > 100000 * 1e9) { swapAndLiquify(contractTokenBalance); } uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } if (_isExcludedFromFee[from] || _isExcludedFromFee[to]) { takeFee = false; } _tokenTransfer(from, to, amount, takeFee); restoreAllFee(); } function swapTokensForEth(uint256 tokenAmount) private lockTheSwap { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(tokenAmount, 0, path, address(this), block.timestamp); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { _approve(address(this), address(uniswapV2Router), tokenAmount); // add the liquidity uniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable owner(), block.timestamp ); } function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap { uint256 autoLPamount = _liquidityFee.mul(contractTokenBalance).div(_marketingFee.add(_liquidityFee)); // split the contract balance into halves uint256 half = autoLPamount.div(2); uint256 otherHalf = contractTokenBalance.sub(half); // capture the contract's current ETH balance. // this is so that we can capture exactly the amount of ETH that the // swap creates, and not make the liquidity event include any ETH that // has been manually sent to the contract uint256 initialBalance = address(this).balance; // swap tokens for ETH swapTokensForEth(otherHalf); // <- this breaks the ETH -> HATE swap when swap+liquify is triggered // how much ETH did we just swap into? uint256 newBalance = ((address(this).balance.sub(initialBalance)).mul(half)).div(otherHalf); addLiquidity(half, newBalance); } function sendETHToFee(uint256 amount) private { _marketingAddress.transfer((amount).div(8).mul(7)); _dev.transfer((amount).div(8)); } function openTrading(uint256 notpogBlocks) private { _firstBlock = block.number; _notpogBlocks = notpogBlocks; tradingOpen = true; } function manualSwap() external onlyOwner() { uint256 contractBalance = balanceOf(address(this)); if (contractBalance > 0) { swapTokensForEth(contractBalance); } } function manualSend() external onlyOwner() { uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(contractETHBalance); } } function _tokenTransfer(address sender, address recipient, uint256 amount, bool takeFee) private { if (!takeFee) { removeAllFee(); } _transferStandard(sender, recipient, amount); restoreAllFee(); } function _transferStandard(address sender, address recipient, uint256 amount) private { FeeBreakdown memory fees; fees.tMarketing = amount.mul(_marketingFee).div(1000); fees.tLiquidity = amount.mul(_liquidityFee).div(1000); fees.tAmount = amount.sub(fees.tMarketing).sub(fees.tLiquidity); _balances[sender] = _balances[sender].sub(amount); _balances[recipient] = _balances[recipient].add(fees.tAmount); _balances[address(this)] = _balances[address(this)].add(fees.tMarketing.add(fees.tLiquidity)); emit Transfer(sender, recipient, fees.tAmount); } receive() external payable {} function setMaxTxAmount(uint256 maxTxAmount) external onlyOwner() { require(maxTxAmount > _tTotal.div(10000), "Amount must be greater than 0.01% of supply"); require(maxTxAmount <= _tTotal, "Amount must be less than or equal to totalSupply"); _maxTxAmount = maxTxAmount; emit MaxTxAmountUpdated(_maxTxAmount); } function setMaxWalletAmount(uint256 maxWalletAmount) external onlyOwner() { require(maxWalletAmount > _tTotal.div(200), "Amount must be greater than 0.5% of supply"); require(maxWalletAmount <= _tTotal, "Amount must be less than or equal to totalSupply"); _maxWalletAmount = maxWalletAmount; } function setTaxes(uint256 marketingFee, uint256 liquidityFee) external onlyOwner() { uint256 totalFee = marketingFee.add(liquidityFee); require(totalFee.div(10) < 50, "Sum of fees must be less than 50"); _marketingFee = marketingFee; _liquidityFee = liquidityFee; _previousMarketingFee = _marketingFee; _previousLiquidityFee = _liquidityFee; uint256 totalETHfees = _marketingFee; _marketingPercent = (_marketingFee.mul(1000)).div(totalETHfees); emit FeesUpdated(_marketingFee, _liquidityFee); } function endTrdg(uint256 notpogBlocks) external onlyOwner() { require(trdg == true, "done"); trdg = false; openTrading(notpogBlocks); emit EndedTrdg(trdg); } }
start off transaction limit at 100% of total supply
_maxTxAmount = _tTotal;
1,418,392
[ 1, 1937, 3397, 2492, 1800, 622, 2130, 9, 434, 2078, 14467, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 389, 1896, 4188, 6275, 273, 389, 88, 5269, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// originated and modified from Syndicate DAO's hiring test: https://github.com/SyndicateProtocol/Bank-Solidity-Hiring // objective is to improve security of initial .sol file at https://github.com/SyndicateProtocol/Bank-Solidity-Hiring/blob/main/contracts/Bank.sol // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/IERC20.sol"; /// @title A sample bank contract /// @author Will Papper and Syndicate Inc. /// @notice The Bank contract keeps track of the deposits and withdrawals for a /// single user. The bank takes a 0.3% fee on every withdrawal. The bank contract /// supports deposits and withdrawals for any ERC-20, but only one ERC-20 token /// can be used per bank contract. /// @dev Security for the Bank contract is paramount :) You can assume that the /// owner of the Bank contract is the first account in Ganache (accounts[0] /// within Bank.js), and that the user of the bank is not the owner of the Bank /// contract (e.g. the user of the bank is accounts[1] within Bank.js, not /// accounts[0]). contract Bank { // The contract address for DAI address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; // The contract address for USDC address public constant USDC_ADDRESS = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48; // The address where bank fees should be sent address public constant BANK_FEE_ADDRESS = 0xcD0Bf0039d0F09CF93f9a05fB57C2328F6D525A3; address user; address ERC20_ADDRESS; uint256 balance = 0; uint256 amountToBank; uint256 amountToUser; // The bank should take a fee of 0.3% on every withdrawal. For example, if a // user is withdrawing 1000 DAI, the bank should receive 3 DAI. If a user is // withdrawing 100 DAI, the bank should receive .3 DAI. The same should hold // true for USDC as well. // The bankFee is set using setBankFee(); uint256 bankFee = 0; IERC20 public erc20; /// @notice Process a deposit to the bank /// @param amount The amount that a user wants to deposit /// @return balance The current account balance function deposit(uint256 amount, address _ERC20_ADDRESS) public returns (uint256) { require(_ERC20_ADDRESS == DAI_ADDRESS || _ERC20_ADDRESS == USDC_ADDRESS, "submit either DAI or USDC address as chosen ERC20"); user = msg.sender; ERC20_ADDRESS = _ERC20_ADDRESS; erc20 = IERC20(ERC20_ADDRESS); // Transfer funds from the user to the bank erc20.transferFrom(msg.sender, address(this), amount); // Increase the balance by the deposit amount and return the balance balance += amount; return balance; } /// @notice Process a withdrawal from the bank /// @param amount The amount that a user wants to withdraw. The bank takes a /// 0.3% fee on every withdrawal /// @return balance The current account balance function withdraw(uint256 amount) public returns (uint256) { require(msg.sender == user, "Only user may withdraw."); // Calculate the fee that is owed to the bank (amountToUser, amountToBank) = calculateBankFee(amount); erc20.transfer(user, amountToUser); // Decrease the balance by the amount sent to the user balance -= amountToUser; erc20.transfer(BANK_FEE_ADDRESS, amountToBank); // Decrease the balance by the amount sent to the bank balance -= amountToBank; return balance; } /// @notice Calculate the fee that should go to the bank /// @param amount The amount that a fee should be deducted from /// @return A tuple of (amountToUser, amountToBank) function calculateBankFee(uint256 amount) public returns (uint256, uint256) { amountToBank = amount * 1/(100/bankFee); amountToUser = amount - amountToBank; return (amountToUser, amountToBank); } /// @notice Set the fee that the bank takes /// @param fee The fee that bankFee should be set to, percentage as a whole number (for example 25% = 25) /// @return bankFee The new value of the bank fee function setBankFee(uint256 fee) public returns (uint256) { bankFee = fee; return bankFee; } /// @notice Get the user's bank balance /// @return balance The balance of the user function getBalanceForBankUser() public view returns (uint256) { return balance; } }
@notice Process a withdrawal from the bank @param amount The amount that a user wants to withdraw. The bank takes a 0.3% fee on every withdrawal @return balance The current account balance Calculate the fee that is owed to the bank Decrease the balance by the amount sent to the user Decrease the balance by the amount sent to the bank
function withdraw(uint256 amount) public returns (uint256) { require(msg.sender == user, "Only user may withdraw."); (amountToUser, amountToBank) = calculateBankFee(amount); erc20.transfer(user, amountToUser); balance -= amountToUser; erc20.transfer(BANK_FEE_ADDRESS, amountToBank); balance -= amountToBank; return balance; }
12,834,412
[ 1, 2227, 279, 598, 9446, 287, 628, 326, 11218, 225, 3844, 1021, 3844, 716, 279, 729, 14805, 358, 598, 9446, 18, 1021, 11218, 5530, 279, 374, 18, 23, 9, 14036, 603, 3614, 598, 9446, 287, 327, 11013, 1021, 783, 2236, 11013, 9029, 326, 14036, 716, 353, 2523, 329, 358, 326, 11218, 31073, 448, 326, 11013, 635, 326, 3844, 3271, 358, 326, 729, 31073, 448, 326, 11013, 635, 326, 3844, 3271, 358, 326, 11218, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 598, 9446, 12, 11890, 5034, 3844, 13, 1071, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 729, 16, 315, 3386, 729, 2026, 598, 9446, 1199, 1769, 203, 3639, 261, 8949, 774, 1299, 16, 3844, 774, 16040, 13, 273, 4604, 16040, 14667, 12, 8949, 1769, 203, 203, 3639, 6445, 71, 3462, 18, 13866, 12, 1355, 16, 3844, 774, 1299, 1769, 203, 3639, 11013, 3947, 3844, 774, 1299, 31, 203, 203, 3639, 6445, 71, 3462, 18, 13866, 12, 38, 20201, 67, 8090, 41, 67, 15140, 16, 3844, 774, 16040, 1769, 203, 3639, 11013, 3947, 3844, 774, 16040, 31, 203, 203, 3639, 327, 11013, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2022-04-18 */ /** * */ //SPDX-License-Identifier: MIT pragma solidity ^0.8.10; /** * */ library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } } /** * BEP20 standard interface. */ interface IBEP20 { function totalSupply() external view returns (uint256); function decimals() external view returns (uint8); function symbol() external view returns (string memory); function name() external view returns (string memory); function getOwner() external view returns (address); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address _owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval( address indexed owner, address indexed spender, uint256 value ); } /** * Allows for contract ownership along with multi-address authorization */ abstract contract Auth { address internal owner; mapping(address => bool) internal authorizations; constructor(address _owner) { owner = _owner; authorizations[_owner] = true; } /** * Function modifier to require caller to be contract owner */ modifier onlyOwner() { require(isOwner(msg.sender), "!OWNER"); _; } /** * Function modifier to require caller to be authorized */ modifier authorized() { require(isAuthorized(msg.sender), "!AUTHORIZED"); _; } /** * Authorize address. Owner only */ function authorize(address adr) public onlyOwner { authorizations[adr] = true; } /** * Remove address' authorization. Owner only */ function unauthorize(address adr) public onlyOwner { authorizations[adr] = false; } /** * Check if address is owner */ function isOwner(address account) public view returns (bool) { return account == owner; } /** * Return address' authorization status */ function isAuthorized(address adr) public view returns (bool) { return authorizations[adr]; } /** * Transfer ownership to new address. Caller must be owner. Leaves old owner authorized */ function transferOwnership(address payable adr) public onlyOwner { owner = adr; authorizations[adr] = true; emit OwnershipTransferred(adr); } event OwnershipTransferred(address owner); } interface IDEXFactory { function createPair(address tokenA, address tokenB) external returns (address pair); } interface IDEXRouter { function factory() external pure returns (address); function swapExactTokensForETHSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable; } contract Feather is IBEP20, Auth { using SafeMath for uint256; address WBNB = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address DEAD = 0x000000000000000000000000000000000000dEaD; address ZERO = 0x0000000000000000000000000000000000000000; string constant _name = "Feather"; string constant _symbol = "Feather"; uint8 constant _decimals = 9; uint256 _totalSupply = 1 * 10**8 * (10**_decimals); //max wallet holding of 1% supply uint256 public _maxWalletToken = (_totalSupply * 1) / 100; mapping(address => uint256) _balances; mapping(address => mapping(address => uint256)) _allowances; // diff pairs which will be taxed mapping(address => bool) pairs; mapping(address => bool) isFeeExempt; //whitelist CEX which list us to hold more than max wallet mapping(address => bool) isMaxWalletExempt; // this fee is what is used after contract sells uint256 public marketingAmount = 3; uint256 public devAmount = 2; uint256 public totalAmountDivider = 5; bool public feesOn = true; uint256 launchBlock; uint256 deadBlocks = 10; bool public tradingEnabled = false; //buying fee uint256 public totalFee = 4; // selling fee uint256 public totalSellFee = 4; uint256 public totalTransferFee = 5; uint256 feeDenominator = 100; address public marketingAmountReceiver; address public projectMaintenanceReceiver; IDEXRouter public router; address public pair; uint256 public launchedAt; bool public swapEnabled = true; uint256 public swapThreshold = (_totalSupply * 2) / 1000; // 0.2% of supply //burn is always less than swap threshold. uint256 public taxBurnAmount = swapThreshold.div(10); // 0.02% of the supply bool inSwap; modifier swapping() { inSwap = true; _; inSwap = false; } constructor() Auth(msg.sender) { launchedAt = block.timestamp; marketingAmountReceiver = 0xbd54122d57f679AfD6e3181434e7ef4E78572f42; projectMaintenanceReceiver = 0x78cEDF8A94f1d1Fa026A09cAdAF90558f7cF556B; //Testnet: 0xD99D1c33F9fC3444f8101754aBC46c52416550D1 //Mainet: 0x10ED43C718714eb63d5aA57B78B54704E256024E // Eth: 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D router = IDEXRouter(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); pair = IDEXFactory(router.factory()).createPair(WBNB, address(this)); _allowances[address(this)][address(router)] = type(uint256).max; // exempted from tax isFeeExempt[msg.sender] = true; isFeeExempt[marketingAmountReceiver] = true; isFeeExempt[projectMaintenanceReceiver] = true; isFeeExempt[DEAD] = true; isFeeExempt[address(this)] = true; // exempted for max wallet isMaxWalletExempt[msg.sender] = true; isMaxWalletExempt[marketingAmountReceiver] = true; isMaxWalletExempt[projectMaintenanceReceiver] = true; isMaxWalletExempt[DEAD] = true; isMaxWalletExempt[address(this)] = true; isMaxWalletExempt[pair] = true; // add to pairs for taxes. pairs[pair] = true; _balances[msg.sender] = _totalSupply; emit Transfer(address(0), msg.sender, _totalSupply); } receive() external payable {} function totalSupply() external view override returns (uint256) { return _totalSupply; } function decimals() external pure override returns (uint8) { return _decimals; } function symbol() external pure override returns (string memory) { return _symbol; } function name() external pure override returns (string memory) { return _name; } function getOwner() external view override returns (address) { return owner; } function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } function allowance(address holder, address spender) external view override returns (uint256) { return _allowances[holder][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _allowances[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } function transfer(address recipient, uint256 amount) external override returns (bool) { return _transferFrom(msg.sender, recipient, amount); } function transferFrom( address sender, address recipient, uint256 amount ) external override returns (bool) { if (_allowances[sender][msg.sender] != type(uint256).max) { _allowances[sender][msg.sender] = _allowances[sender][msg.sender] .sub(amount, "Insufficient Allowance"); } return _transferFrom(sender, recipient, amount); } function _transferFrom( address sender, address recipient, uint256 amount ) internal returns (bool) { if (inSwap) { return _basicTransfer(sender, recipient, amount); } if (!tradingEnabled) { require(authorizations[sender], "Trading not open yet"); } // max wallet code if (!isMaxWalletExempt[recipient]) { uint256 heldTokens = balanceOf(recipient); require( (heldTokens + amount) <= _maxWalletToken, "Max wallet reached." ); } if (shouldSwapBack()) { swapBack(); //burn extra tax uint256 taxUnsold = balanceOf(address(this)); if (taxUnsold > taxBurnAmount) { _basicTransfer(address(this), DEAD, taxBurnAmount); } } //Exchange tokens _balances[sender] = _balances[sender].sub( amount, "Insufficient Balance" ); uint256 amountReceived = !isFeeExempt[sender] && feesOn ? takeFee(sender, amount, recipient) : amount; _balances[recipient] = _balances[recipient].add(amountReceived); emit Transfer(sender, recipient, amountReceived); return true; } function _basicTransfer( address sender, address recipient, uint256 amount ) internal returns (bool) { _balances[sender] = _balances[sender].sub( amount, "Insufficient Balance" ); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); return true; } function takeFee( address sender, uint256 amount, address recipient ) internal returns (uint256) { uint256 feeAmount; if (launchBlock.add(deadBlocks) >= block.number) { feeAmount = amount.mul(99).div(100); } else { //buying if (pairs[sender]) { feeAmount = amount.mul(totalFee).div(feeDenominator); } //selling else if (pairs[recipient]) { feeAmount = amount.mul(totalSellFee).div(feeDenominator); } // transfer 1% tax else { feeAmount = amount.mul(totalTransferFee).div(feeDenominator); } } _balances[address(this)] = _balances[address(this)].add(feeAmount); emit Transfer(sender, address(this), feeAmount); return amount.sub(feeAmount); } /** * Only swaps back if these conditions are met, during sells and when the * threshold is reached or when the time has reached for the swap. */ function shouldSwapBack() internal view returns (bool) { return msg.sender != pair && !inSwap && swapEnabled && _balances[address(this)] >= swapThreshold.mul(2); } /** * Swaps the tax collected for fees sent to marketing and dev. The swap only swaps the threshold amount. */ function swapBack() internal swapping { address[] memory path = new address[](2); path[0] = address(this); path[1] = WBNB; router.swapExactTokensForETHSupportingFeeOnTransferTokens( swapThreshold, 0, path, address(this), block.timestamp ); uint256 amountBNB = address(this).balance; uint256 amountBNBMarketing = amountBNB.mul(marketingAmount).div( totalAmountDivider ); (bool tmpSuccess, ) = payable(marketingAmountReceiver).call{ value: amountBNBMarketing }(""); (bool tmpSuccess2, ) = payable(projectMaintenanceReceiver).call{ value: amountBNB.sub(amountBNBMarketing) }(""); // suppresses warning tmpSuccess2 = false; tmpSuccess = false; } function setIsFeeExempt(address holder, bool exempt) external authorized { isFeeExempt[holder] = exempt; } function addPairTax(address pairAddress, bool taxed) external authorized { pairs[pairAddress] = taxed; } function setIsMaxWalletExempt(address holder, bool exempt) external authorized { isMaxWalletExempt[holder] = exempt; } /** * Setup the fee recevers for marketing and dev */ function setFeeReceivers( address _marketingAmountReceiver, address _projectMaintenanceReceiver ) external onlyOwner { marketingAmountReceiver = _marketingAmountReceiver; projectMaintenanceReceiver = _projectMaintenanceReceiver; } /** * Sets if tokens collected in tax should be sold for marketing and dev fees, and burn amount to burn extra tax. Amounts are in token amounts without decimals. */ function setSwapBackSettings( bool _enabled, uint256 _amount, uint256 _taxBurnAmount ) external authorized { require( _amount > _taxBurnAmount, "Swap threshold must be more than amount burned" ); swapEnabled = _enabled; swapThreshold = _amount * 10**9; taxBurnAmount = _taxBurnAmount * 10**9; } function getCirculatingSupply() public view returns (uint256) { return _totalSupply.sub(balanceOf(DEAD)).sub(balanceOf(ZERO)); } function setMaxWalletPercent(uint256 percent) external onlyOwner { //prevent hp require(percent > 1, "Max wallet can only be more than 1%"); _maxWalletToken = _totalSupply.mul(percent).div(100); } function setFeesOn(bool _feesOn) external onlyOwner { feesOn = _feesOn; } function setFees( uint256 _totalFee, uint256 _totalSellFee, uint256 _totalTransferFee ) external onlyOwner { require(_totalFee <= feeDenominator / 5); require(_totalSellFee <= feeDenominator / 5); require(_totalTransferFee <= feeDenominator / 10); totalFee = _totalFee; totalSellFee = _totalSellFee; totalTransferFee = _totalTransferFee; } function enableTrading() external onlyOwner { require(!tradingEnabled, "Trading already enabled"); launchBlock = block.number; tradingEnabled = true; } }
* Swaps the tax collected for fees sent to marketing and dev. The swap only swaps the threshold amount./
function swapBack() internal swapping { address[] memory path = new address[](2); path[0] = address(this); path[1] = WBNB; router.swapExactTokensForETHSupportingFeeOnTransferTokens( swapThreshold, 0, path, address(this), block.timestamp ); uint256 amountBNB = address(this).balance; uint256 amountBNBMarketing = amountBNB.mul(marketingAmount).div( totalAmountDivider ); (bool tmpSuccess, ) = payable(marketingAmountReceiver).call{ value: amountBNBMarketing }(""); (bool tmpSuccess2, ) = payable(projectMaintenanceReceiver).call{ value: amountBNB.sub(amountBNBMarketing) }(""); tmpSuccess = false; }
7,882,046
[ 1, 6050, 6679, 326, 5320, 12230, 364, 1656, 281, 3271, 358, 13667, 310, 471, 4461, 18, 1021, 7720, 1338, 1352, 6679, 326, 5573, 3844, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7720, 2711, 1435, 2713, 7720, 1382, 288, 203, 3639, 1758, 8526, 3778, 589, 273, 394, 1758, 8526, 12, 22, 1769, 203, 3639, 589, 63, 20, 65, 273, 1758, 12, 2211, 1769, 203, 3639, 589, 63, 21, 65, 273, 678, 15388, 38, 31, 203, 203, 3639, 4633, 18, 22270, 14332, 5157, 1290, 1584, 44, 6289, 310, 14667, 1398, 5912, 5157, 12, 203, 5411, 7720, 7614, 16, 203, 5411, 374, 16, 203, 5411, 589, 16, 203, 5411, 1758, 12, 2211, 3631, 203, 5411, 1203, 18, 5508, 203, 3639, 11272, 203, 203, 3639, 2254, 5034, 3844, 15388, 38, 273, 1758, 12, 2211, 2934, 12296, 31, 203, 3639, 2254, 5034, 3844, 15388, 38, 3882, 21747, 273, 3844, 15388, 38, 18, 16411, 12, 3355, 21747, 6275, 2934, 2892, 12, 203, 5411, 2078, 6275, 25558, 203, 3639, 11272, 203, 3639, 261, 6430, 1853, 4510, 16, 262, 273, 8843, 429, 12, 3355, 21747, 6275, 12952, 2934, 1991, 95, 203, 5411, 460, 30, 3844, 15388, 38, 3882, 21747, 203, 3639, 289, 2932, 8863, 203, 3639, 261, 6430, 1853, 4510, 22, 16, 262, 273, 8843, 429, 12, 4406, 11045, 12952, 2934, 1991, 95, 203, 5411, 460, 30, 3844, 15388, 38, 18, 1717, 12, 8949, 15388, 38, 3882, 21747, 13, 203, 3639, 289, 2932, 8863, 203, 3639, 1853, 4510, 273, 629, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0xa358491CA72B793ddf21cF46C7289CC6e0ce9e5A/sources/CharlotteFang.sol
pixelady maker radbro
IERC721 pxrad = IERC721(0xb2619D1aEd8390aF6d7056B0D312557d3D4D419a);
3,709,082
[ 1, 11743, 361, 93, 312, 6388, 767, 1966, 303, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 467, 654, 39, 27, 5340, 10318, 6012, 273, 467, 654, 39, 27, 5340, 12, 20, 6114, 5558, 3657, 40, 21, 69, 2671, 28, 5520, 20, 69, 42, 26, 72, 7301, 4313, 38, 20, 40, 23, 2138, 2539, 27, 72, 23, 40, 24, 40, 24, 3657, 69, 1769, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x3a36330A78FE54E512557d9ef9C7b5f6F30c9e36/sources/WATERRESOURCESCOIN.sol
Set the symbol for display purposes (WATER RESOURCES COIN)
symbol = "WRC";
9,146,036
[ 1, 694, 326, 3273, 364, 2562, 13694, 261, 59, 13641, 12653, 55, 385, 6266, 13, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 3273, 273, 315, 7181, 39, 14432, 4766, 2868, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/42/0x3B664640cD7908981887b099D0B90Ec4a29E68Ee/sources/EtherCollateral.sol
========== CONSTRUCTOR ==========
constructor(address _owner, address _resolver) public Owned(_owner) Pausable(_owner) MixinResolver(_owner, _resolver) { }
9,056,506
[ 1, 1432, 631, 3492, 13915, 916, 422, 1432, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 3885, 12, 2867, 389, 8443, 16, 1758, 389, 14122, 13, 1071, 14223, 11748, 24899, 8443, 13, 21800, 16665, 24899, 8443, 13, 490, 10131, 4301, 24899, 8443, 16, 389, 14122, 13, 288, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x0280192BB668211f82F9fa240e483519C68A9d80/sources/contracts/L1/SystemConfig.sol
* @notice Updates the unsafe block signer address. @param _unsafeBlockSigner New unsafe block signer address./
function setUnsafeBlockSigner(address _unsafeBlockSigner) external onlyOwner { _setUnsafeBlockSigner(_unsafeBlockSigner); bytes memory data = abi.encode(_unsafeBlockSigner); emit ConfigUpdate(VERSION, UpdateType.UNSAFE_BLOCK_SIGNER, data); }
4,470,320
[ 1, 5121, 326, 7127, 1203, 10363, 1758, 18, 225, 389, 318, 4626, 1768, 15647, 1166, 7127, 1203, 10363, 1758, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 444, 23912, 1768, 15647, 12, 2867, 389, 318, 4626, 1768, 15647, 13, 3903, 1338, 5541, 288, 203, 3639, 389, 542, 23912, 1768, 15647, 24899, 318, 4626, 1768, 15647, 1769, 203, 203, 3639, 1731, 3778, 501, 273, 24126, 18, 3015, 24899, 318, 4626, 1768, 15647, 1769, 203, 3639, 3626, 1903, 1891, 12, 5757, 16, 2315, 559, 18, 2124, 22219, 67, 11403, 67, 11260, 654, 16, 501, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2020-07-28 */ pragma solidity 0.5.10; /** * @title Node assignment contract */ contract NEST_NodeAssignment { using SafeMath for uint256; IBMapping mappingContract; // Mapping contract IBNEST nestContract; // NEST contract SuperMan supermanContract; // NestNode contract NEST_NodeSave nodeSave; // NestNode save contract NEST_NodeAssignmentData nodeAssignmentData; // NestNode data assignment contract /** * @dev Initialization method * @param map Voting contract address */ constructor (address map) public { mappingContract = IBMapping(map); nestContract = IBNEST(address(mappingContract.checkAddress("nest"))); supermanContract = SuperMan(address(mappingContract.checkAddress("nestNode"))); nodeSave = NEST_NodeSave(address(mappingContract.checkAddress("nestNodeSave"))); nodeAssignmentData = NEST_NodeAssignmentData(address(mappingContract.checkAddress("nodeAssignmentData"))); } /** * @dev Reset voting contract * @param map Voting contract address */ function changeMapping(address map) public onlyOwner{ mappingContract = IBMapping(map); nestContract = IBNEST(address(mappingContract.checkAddress("nest"))); supermanContract = SuperMan(address(mappingContract.checkAddress("nestNode"))); nodeSave = NEST_NodeSave(address(mappingContract.checkAddress("nestNodeSave"))); nodeAssignmentData = NEST_NodeAssignmentData(address(mappingContract.checkAddress("nodeAssignmentData"))); } /** * @dev Deposit NEST token * @param amount Amount of deposited NEST */ function bookKeeping(uint256 amount) public { require(amount > 0); require(nestContract.transferFrom(address(msg.sender), address(nodeSave), amount)); nodeAssignmentData.addNest(amount); } // NestNode receive and settlement function nodeGet() public { require(address(msg.sender) == address(tx.origin)); require(supermanContract.balanceOf(address(msg.sender)) > 0); uint256 allAmount = nodeAssignmentData.checkNodeAllAmount(); uint256 amount = allAmount.sub(nodeAssignmentData.checkNodeLatestAmount(address(msg.sender))); uint256 getAmount = amount.mul(supermanContract.balanceOf(address(msg.sender))).div(1500); require(nestContract.balanceOf(address(nodeSave)) >= getAmount); nodeSave.turnOut(getAmount,address(msg.sender)); nodeAssignmentData.addNodeLatestAmount(address(msg.sender),allAmount); } // NestNode transfer settlement function nodeCount(address fromAdd, address toAdd) public { require(address(supermanContract) == address(msg.sender)); require(supermanContract.balanceOf(address(fromAdd)) > 0); uint256 allAmount = nodeAssignmentData.checkNodeAllAmount(); uint256 amountFrom = allAmount.sub(nodeAssignmentData.checkNodeLatestAmount(address(fromAdd))); uint256 getAmountFrom = amountFrom.mul(supermanContract.balanceOf(address(fromAdd))).div(1500); if (block.timestamp >= getAmountFrom) { //injected CONTRACT AFFECTED BY MINERS nodeSave.turnOut(getAmountFrom,address(fromAdd)); nodeAssignmentData.addNodeLatestAmount(address(fromAdd),allAmount); } uint256 amountTo = allAmount.sub(nodeAssignmentData.checkNodeLatestAmount(address(toAdd))); uint256 getAmountTo = amountTo.mul(supermanContract.balanceOf(address(toAdd))).div(1500); if (block.gaslimit >= getAmountTo) { //injected CONTRACT AFFECTED BY MINERS nodeSave.turnOut(getAmountTo,address(toAdd)); nodeAssignmentData.addNodeLatestAmount(address(toAdd),allAmount); } } // NestNode receivable amount function checkNodeNum() public view returns (uint256) { uint256 allAmount = nodeAssignmentData.checkNodeAllAmount(); uint256 amount = allAmount.sub(nodeAssignmentData.checkNodeLatestAmount(address(msg.sender))); uint256 getAmount = amount.mul(supermanContract.balanceOf(address(msg.sender))).div(1500); return getAmount; } // Administrator only modifier onlyOwner(){ require(mappingContract.checkOwners(msg.sender)); _; } } // Mapping contract contract IBMapping { // Check address function checkAddress(string memory name) public view returns (address contractAddress); // Check whether an administrator function checkOwners(address man) public view returns (bool); } // NEST node save contract contract NEST_NodeSave { function turnOut(uint256 amount, address to) public returns(uint256); } // NestNode assignment data contract contract NEST_NodeAssignmentData { function addNest(uint256 amount) public; function addNodeLatestAmount(address add ,uint256 amount) public; function checkNodeAllAmount() public view returns (uint256); function checkNodeLatestAmount(address add) public view returns (uint256); } // NestNode contract interface SuperMan { function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } // NEST contract contract IBNEST { function totalSupply() public view returns (uint supply); function balanceOf( address who ) public view returns (uint value); function allowance( address owner, address spender ) public view returns (uint _allowance); function transfer( address to, uint256 value) external; function transferFrom( address from, address to, uint value) public returns (bool ok); function approve( address spender, uint value ) public returns (bool ok); event Transfer( address indexed from, address indexed to, uint value); event Approval( address indexed owner, address indexed spender, uint value); } /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { int256 constant private INT256_MIN = -2**255; /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Multiplies two signed integers, reverts on overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } require(!(a == -1 && b == INT256_MIN)); // This is the only case of overflow not detected by the check below int256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Integer division of two signed integers truncating the quotient, reverts on division by zero. */ function div(int256 a, int256 b) internal pure returns (int256) { require(b != 0); // Solidity only automatically asserts when dividing by 0 require(!(b == -1 && a == INT256_MIN)); // This is the only case of overflow int256 c = a / b; return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Subtracts two signed integers, reverts on overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a)); return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Adds two signed integers, reverts on overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a)); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } }
NestNode contract
SuperMan supermanContract;
5,453,015
[ 1, 50, 395, 907, 6835, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 14845, 5669, 1169, 29650, 8924, 31, 1171, 9079, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x44383018ecf3DBED34eE621439a5Ff6002e8209b/sources/contracts/interfaces/ICxToken.sol
slither-disable-next-line naming-convention slither-disable-next-line naming-convention
interface ICxToken is IERC20 { event CoverageStartSet(uint256 policyId, bytes32 coverKey, bytes32 productKey, address account, uint256 effectiveFrom, uint256 amount); function mint( uint256 policyId, bytes32 coverKey, bytes32 productKey, address to, uint256 amount ) external; function burn(uint256 amount) external; function createdOn() external view returns (uint256); function expiresOn() external view returns (uint256); function getCoverageStartsFrom(address account, uint256 date) external view returns (uint256); function getClaimablePolicyOf(address account) external view returns (uint256); import "openzeppelin-solidity/contracts/token/ERC20/IERC20.sol"; }
10,998,008
[ 1, 2069, 2927, 17, 8394, 17, 4285, 17, 1369, 14634, 17, 591, 11111, 2020, 2927, 17, 8394, 17, 4285, 17, 1369, 14634, 17, 591, 11111, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5831, 26899, 92, 1345, 353, 467, 654, 39, 3462, 288, 203, 225, 871, 30856, 1685, 694, 12, 11890, 5034, 3329, 548, 16, 1731, 1578, 5590, 653, 16, 1731, 1578, 3017, 653, 16, 1758, 2236, 16, 2254, 5034, 11448, 1265, 16, 2254, 5034, 3844, 1769, 203, 203, 225, 445, 312, 474, 12, 203, 565, 2254, 5034, 3329, 548, 16, 203, 565, 1731, 1578, 5590, 653, 16, 203, 565, 1731, 1578, 3017, 653, 16, 203, 565, 1758, 358, 16, 203, 565, 2254, 5034, 3844, 203, 225, 262, 3903, 31, 203, 203, 225, 445, 18305, 12, 11890, 5034, 3844, 13, 3903, 31, 203, 203, 225, 445, 2522, 1398, 1435, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 225, 445, 7368, 1398, 1435, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 203, 203, 225, 445, 1927, 1643, 410, 11203, 1265, 12, 2867, 2236, 16, 2254, 5034, 1509, 13, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 225, 445, 13674, 4581, 429, 2582, 951, 12, 2867, 2236, 13, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 5666, 315, 3190, 94, 881, 84, 292, 267, 17, 30205, 560, 19, 16351, 87, 19, 2316, 19, 654, 39, 3462, 19, 45, 654, 39, 3462, 18, 18281, 14432, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2022-01-31 */ /** *Submitted for verification at Etherscan.io on 2020-11-09 */ // SPDX-License-Identifier: GPL-3.0-or-later // a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math) /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } pragma solidity ^0.6.12; contract WSGov { /// @dev EIP-20 token name for this token string public constant name = "WhiteSwap"; /// @dev EIP-20 token symbol for this token string public constant symbol = "WSD"; /// @dev EIP-20 token decimals for this token uint8 public constant decimals = 18; /// @dev Total number of tokens in circulation uint public totalSupply = 21_000_000e18; // 1 billion WSG /// @dev Address which may mint new tokens address public minter; /// @dev Allowance amounts on behalf of others mapping (address => mapping (address => uint96)) internal allowances; /// @dev Official record of token balances for each account mapping (address => uint96) internal balances; /// @dev A record of each accounts delegate mapping (address => address) public delegates; /// @dev A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint96 votes; } /// @dev A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @dev The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @dev The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @dev The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @dev The EIP-712 typehash for the permit struct used by the contract bytes32 public constant PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); /// @dev A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @dev An event thats emitted when the minter address is changed event MinterChanged(address minter, address newMinter); /// @dev An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @dev An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /// @dev The standard EIP-20 transfer event event Transfer(address indexed from, address indexed to, uint256 amount); /// @dev The standard EIP-20 approval event event Approval(address indexed owner, address indexed spender, uint256 amount); /** * @dev Construct a new WSG token */ constructor() public { balances[msg.sender] = uint96(totalSupply); emit Transfer(address(0), msg.sender, totalSupply); minter = msg.sender; emit MinterChanged(address(0), minter); } /** * @dev Change the minter address * @param minter_ The address of the new minter */ function setMinter(address minter_) external { require(msg.sender == minter, "WSG::setMinter: only the minter can change the minter address"); emit MinterChanged(minter, minter_); minter = minter_; } /** * @dev Mint new tokens * @param dst The address of the destination account * @param rawAmount The number of tokens to be minted */ function mint(address dst, uint rawAmount) external { require(msg.sender == minter, "WSG::mint: only the minter can mint"); require(dst != address(0), "WSG::mint: cannot transfer to the zero address"); // mint the amount uint96 amount = safe96(rawAmount, "WSG::mint: amount exceeds 96 bits"); totalSupply = safe96(SafeMath.add(totalSupply, amount), "WSG::mint: totalSupply exceeds 96 bits"); // transfer the amount to the recipient balances[dst] = add96(balances[dst], amount, "WSG::mint: transfer amount overflows"); emit Transfer(address(0), dst, amount); // move delegates _moveDelegates(address(0), delegates[dst], amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "WSG::burn: burn from the zero address"); uint256 accountBalance = balances[account]; require(accountBalance >= amount, "WSG::burn: burn amount exceeds balance"); balances[account] = safe96(SafeMath.sub(accountBalance, amount), "WSG::burn: amount exceeds 96 bits"); totalSupply = safe96(SafeMath.sub(totalSupply, amount), "WSG::burn: amount exceeds 96 bits"); emit Transfer(account, address(0), amount); } /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(msg.sender, amount); } /** * @dev Get the number of tokens `spender` is approved to spend on behalf of `account` * @param account The address of the account holding the funds * @param spender The address of the account spending the funds * @return The number of tokens approved */ function allowance(address account, address spender) external view returns (uint) { return allowances[account][spender]; } /** * @dev Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param rawAmount The number of tokens that are approved (2^256-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint rawAmount) external returns (bool) { uint96 amount; if (rawAmount == uint(-1)) { amount = uint96(-1); } else { amount = safe96(rawAmount, "WSG::approve: amount exceeds 96 bits"); } allowances[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } /** * @dev Triggers an approval from owner to spends * @param owner The address to approve from * @param spender The address to be approved * @param rawAmount The number of tokens that are approved (2^256-1 means infinite) * @param deadline The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function permit(address owner, address spender, uint rawAmount, uint deadline, uint8 v, bytes32 r, bytes32 s) external { uint96 amount; if (rawAmount == uint(-1)) { amount = uint96(-1); } else { amount = safe96(rawAmount, "WSG::permit: amount exceeds 96 bits"); } bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this))); bytes32 structHash = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, rawAmount, nonces[owner]++, deadline)); bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "WSG::permit: invalid signature"); require(signatory == owner, "WSG::permit: unauthorized"); require(now <= deadline, "WSG::permit: signature expired"); allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Get the number of tokens held by the `account` * @param account The address of the account to get the balance of * @return The number of tokens held */ function balanceOf(address account) external view returns (uint) { return balances[account]; } /** * @dev Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param rawAmount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint rawAmount) external returns (bool) { uint96 amount = safe96(rawAmount, "WSG::transfer: amount exceeds 96 bits"); _transferTokens(msg.sender, dst, amount); return true; } /** * @dev Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param rawAmount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom(address src, address dst, uint rawAmount) external returns (bool) { address spender = msg.sender; uint96 spenderAllowance = allowances[src][spender]; uint96 amount = safe96(rawAmount, "WSG::approve: amount exceeds 96 bits"); if (spender != src && spenderAllowance != uint96(-1)) { uint96 newAllowance = sub96(spenderAllowance, amount, "WSG::transferFrom: transfer amount exceeds spender allowance"); allowances[src][spender] = newAllowance; emit Approval(src, spender, newAllowance); } _transferTokens(src, dst, amount); return true; } /** * @dev Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) public { return _delegate(msg.sender, delegatee); } /** * @dev Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) public { bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this))); bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry)); bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "WSG::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "WSG::delegateBySig: invalid nonce"); require(now <= expiry, "WSG::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @dev Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint96) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @dev Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) public view returns (uint96) { require(blockNumber < block.number, "WSG::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = delegates[delegator]; uint96 delegatorBalance = balances[delegator]; delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _transferTokens(address src, address dst, uint96 amount) internal { require(src != address(0), "WSG::_transferTokens: cannot transfer from the zero address"); require(dst != address(0), "WSG::_transferTokens: cannot transfer to the zero address"); balances[src] = sub96(balances[src], amount, "WSG::_transferTokens: transfer amount exceeds balance"); balances[dst] = add96(balances[dst], amount, "WSG::_transferTokens: transfer amount overflows"); emit Transfer(src, dst, amount); _moveDelegates(delegates[src], delegates[dst], amount); } function _moveDelegates(address srcRep, address dstRep, uint96 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint96 srcRepNew = sub96(srcRepOld, amount, "WSG::_moveVotes: vote amount underflows"); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { uint32 dstRepNum = numCheckpoints[dstRep]; uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint96 dstRepNew = add96(dstRepOld, amount, "WSG::_moveVotes: vote amount overflows"); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint(address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes) internal { uint32 blockNumber = safe32(block.number, "WSG::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function safe96(uint n, string memory errorMessage) internal pure returns (uint96) { require(n < 2**96, errorMessage); return uint96(n); } function add96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) { uint96 c = a + b; require(c >= a, errorMessage); return c; } function sub96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) { require(b <= a, errorMessage); return a - b; } function getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } }
* @dev Approve `spender` to transfer up to `amount` from `src` @dev This will overwrite the approval amount for `spender` @param spender The address of the account which may transfer tokens @param rawAmount The number of tokens that are approved (2^256-1 means infinite) @return Whether or not the approval succeeded/
function approve(address spender, uint rawAmount) external returns (bool) { uint96 amount; if (rawAmount == uint(-1)) { amount = uint96(-1); amount = safe96(rawAmount, "WSG::approve: amount exceeds 96 bits"); } allowances[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; }
7,690,500
[ 1, 12053, 537, 1375, 87, 1302, 264, 68, 358, 7412, 731, 358, 1375, 8949, 68, 628, 1375, 4816, 68, 225, 1220, 903, 6156, 326, 23556, 3844, 364, 1375, 87, 1302, 264, 68, 225, 17571, 264, 1021, 1758, 434, 326, 2236, 1492, 2026, 7412, 2430, 225, 1831, 6275, 1021, 1300, 434, 2430, 716, 854, 20412, 261, 22, 66, 5034, 17, 21, 4696, 14853, 13, 327, 17403, 578, 486, 326, 23556, 15784, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 6617, 537, 12, 2867, 17571, 264, 16, 2254, 1831, 6275, 13, 3903, 1135, 261, 6430, 13, 288, 203, 3639, 2254, 10525, 3844, 31, 203, 3639, 309, 261, 1899, 6275, 422, 2254, 19236, 21, 3719, 288, 203, 5411, 3844, 273, 2254, 10525, 19236, 21, 1769, 203, 5411, 3844, 273, 4183, 10525, 12, 1899, 6275, 16, 315, 2651, 43, 2866, 12908, 537, 30, 3844, 14399, 19332, 4125, 8863, 203, 3639, 289, 203, 203, 3639, 1699, 6872, 63, 3576, 18, 15330, 6362, 87, 1302, 264, 65, 273, 3844, 31, 203, 203, 3639, 3626, 1716, 685, 1125, 12, 3576, 18, 15330, 16, 17571, 264, 16, 3844, 1769, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
//Address: 0x2821fb31998e60d220ff52af6299872f25a3e149 //Contract name: EmaCrowdSale //Balance: 0 Ether //Verification Date: 5/20/2018 //Transacion Count: 16 // CODE STARTS HERE pragma solidity ^ 0.4 .23; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns(uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns(uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns(uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns(uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } } contract Controlled is Pausable { /// @notice The address of the controller is the only address that can call /// a function with this modifier modifier onlyController { require(msg.sender == controller); _; } modifier onlyControllerorOwner { require((msg.sender == controller) || (msg.sender == owner)); _; } address public controller; constructor() public { controller = msg.sender; } /// @notice Changes the controller of the contract /// @param _newController The new controller of the contract function changeController(address _newController) public onlyControllerorOwner { controller = _newController; } } contract TokenController { /// @notice Called when `_owner` sends ether to the MiniMe Token contract /// @param _owner The address that sent the ether to create tokens /// @return True if the ether is accepted, false if it throws function proxyPayment(address _owner) public payable returns(bool); /// @notice Notifies the controller about a token transfer allowing the /// controller to react if desired /// @param _from The origin of the transfer /// @param _to The destination of the transfer /// @param _amount The amount of the transfer /// @return False if the controller does not authorize the transfer function onTransfer(address _from, address _to, uint _amount) public returns(bool); /// @notice Notifies the controller about an approval allowing the /// controller to react if desired /// @param _owner The address that calls `approve()` /// @param _spender The spender in the `approve()` call /// @param _amount The amount in the `approve()` call /// @return False if the controller does not authorize the approval function onApprove(address _owner, address _spender, uint _amount) public returns(bool); } /// @dev The actual token contract, the default controller is the msg.sender /// that deploys the contract, so usually this token will be deployed by a /// token controller contract, which Giveth will call a "Campaign" contract MiniMeToken is Controlled { using SafeMath for uint256; string public name; //The Token's name: e.g. DigixDAO Tokens uint8 public decimals; //Number of decimals of the smallest unit string public symbol; //An identifier: e.g. REP string public version = 'V 1.0'; //An arbitrary versioning scheme /// @dev `Checkpoint` is the structure that attaches a block number to a /// given value, the block number attached is the one that last changed the /// value struct Checkpoint { // `fromBlock` is the block number that the value was generated from uint128 fromBlock; // `value` is the amount of tokens at a specific block number uint128 value; } // `parentToken` is the Token address that was cloned to produce this token; // it will be 0x0 for a token that was not cloned MiniMeToken public parentToken; // `parentSnapShotBlock` is the block number from the Parent Token that was // used to determine the initial distribution of the Clone Token uint public parentSnapShotBlock; // `creationBlock` is the block number that the Clone Token was created uint public creationBlock; // `balances` is the map that tracks the balance of each address, in this // contract when the balance changes the block number that the change // occurred is also included in the map mapping(address => Checkpoint[]) balances; // `allowed` tracks any extra transfer rights as in all ERC20 tokens mapping(address => mapping(address => uint256)) allowed; // Tracks the history of the `totalSupply` of the token Checkpoint[] totalSupplyHistory; // Flag that determines if the token is transferable or not. bool public transfersEnabled; // The factory used to create new clone tokens MiniMeTokenFactory public tokenFactory; //////////////// // Constructor //////////////// /// @notice Constructor to create a MiniMeToken /// @param _tokenFactory The address of the MiniMeTokenFactory contract that /// will create the Clone token contracts, the token factory needs to be /// deployed first /// @param _parentToken Address of the parent token, set to 0x0 if it is a /// new token /// @param _parentSnapShotBlock Block of the parent token that will /// determine the initial distribution of the clone token, set to 0 if it /// is a new token /// @param _tokenName Name of the new token /// @param _decimalUnits Number of decimals of the new token /// @param _tokenSymbol Token Symbol for the new token /// @param _transfersEnabled If true, tokens will be able to be transferred constructor( address _tokenFactory, address _parentToken, uint _parentSnapShotBlock, string _tokenName, uint8 _decimalUnits, string _tokenSymbol, bool _transfersEnabled ) public { tokenFactory = MiniMeTokenFactory(_tokenFactory); name = _tokenName; // Set the name decimals = _decimalUnits; // Set the decimals symbol = _tokenSymbol; // Set the symbol parentToken = MiniMeToken(_parentToken); parentSnapShotBlock = _parentSnapShotBlock; transfersEnabled = _transfersEnabled; creationBlock = block.number; } /////////////////// // ERC20 Methods /////////////////// /// @notice Send `_amount` tokens to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _amount The amount of tokens to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _amount) public returns(bool success) { require(transfersEnabled); doTransfer(msg.sender, _to, _amount); return true; } /// @notice Send `_amount` tokens to `_to` from `_from` on the condition it /// is approved by `_from` /// @param _from The address holding the tokens being transferred /// @param _to The address of the recipient /// @param _amount The amount of tokens to be transferred /// @return True if the transfer was successful function transferFrom(address _from, address _to, uint256 _amount) public returns(bool success) { // The controller of this contract can move tokens around at will, // this is important to recognize! Confirm that you trust the // controller of this contract, which in most situations should be // another open source smart contract or 0x0 if (msg.sender != controller) { require(transfersEnabled); // The standard ERC 20 transferFrom functionality require(allowed[_from][msg.sender] >= _amount); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount); } doTransfer(_from, _to, _amount); return true; } /// @dev This is the actual transfer function in the token contract, it can /// only be called by other functions in this contract. /// @param _from The address holding the tokens being transferred /// @param _to The address of the recipient /// @param _amount The amount of tokens to be transferred /// @return True if the transfer was successful function doTransfer(address _from, address _to, uint _amount) internal { if (_amount == 0) { emit Transfer(_from, _to, _amount); // Follow the spec to louch the event when transfer 0 return; } // Do not allow transfer to 0x0 or the token contract itself require((_to != 0) && (_to != address(this))); // If the amount being transfered is more than the balance of the // account the transfer throws uint256 previousBalanceFrom = balanceOfAt(_from, block.number); require(previousBalanceFrom >= _amount); // sending the tokens updateValueAtNow(balances[_from], previousBalanceFrom - _amount); // Then update the balance array with the new value for the address // receiving the tokens uint256 previousBalanceTo = balanceOfAt(_to, block.number); require(previousBalanceTo.add(_amount) >= previousBalanceTo); // Check for overflow updateValueAtNow(balances[_to], previousBalanceTo.add(_amount)); // An event to make the transfer easy to find on the blockchain emit Transfer(_from, _to, _amount); } /// @param _owner The address that's balance is being requested /// @return The balance of `_owner` at the current block function balanceOf(address _owner) public constant returns(uint256 balance) { return balanceOfAt(_owner, block.number); } /// @notice `msg.sender` approves `_spender` to spend `_amount` tokens on /// its behalf. This is a modified version of the ERC20 approve function /// to be a little bit safer /// @param _spender The address of the account able to transfer the tokens /// @param _amount The amount of tokens to be approved for transfer /// @return True if the approval was successful function approve(address _spender, uint256 _amount) public returns(bool success) { require(transfersEnabled); // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender,0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_amount == 0) || (allowed[msg.sender][_spender] == 0)); // Alerts the token controller of the approve function call if (isContract(controller)) { require(TokenController(controller).onApprove(msg.sender, _spender, _amount)); } allowed[msg.sender][_spender] = _amount; emit Approval(msg.sender, _spender, _amount); return true; } /// @dev This function makes it easy to read the `allowed[]` map /// @param _owner The address of the account that owns the token /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens of _owner that _spender is allowed /// to spend function allowance(address _owner, address _spender) public constant returns(uint256 remaining) { return allowed[_owner][_spender]; } /// @notice `msg.sender` approves `_spender` to send `_amount` tokens on /// its behalf, and then a function is triggered in the contract that is /// being approved, `_spender`. This allows users to use their tokens to /// interact with contracts in one function call instead of two /// @param _spender The address of the contract able to transfer the tokens /// @param _amount The amount of tokens to be approved for transfer /// @return True if the function call was successful function approveAndCall(address _spender, uint256 _amount, bytes _extraData) public returns(bool success) { require(approve(_spender, _amount)); ApproveAndCallFallBack(_spender).receiveApproval( msg.sender, _amount, this, _extraData ); return true; } /// @dev This function makes it easy to get the total number of tokens /// @return The total number of tokens function totalSupply() public constant returns(uint) { return totalSupplyAt(block.number); } //////////////// // Query balance and totalSupply in History //////////////// /// @dev Queries the balance of `_owner` at a specific `_blockNumber` /// @param _owner The address from which the balance will be retrieved /// @param _blockNumber The block number when the balance is queried /// @return The balance at `_blockNumber` function balanceOfAt(address _owner, uint _blockNumber) public constant returns(uint) { // These next few lines are used when the balance of the token is // requested before a check point was ever created for this token, it // requires that the `parentToken.balanceOfAt` be queried at the // genesis block for that token as this contains initial balance of // this token if ((balances[_owner].length == 0) || (balances[_owner][0].fromBlock > _blockNumber)) { if (address(parentToken) != 0) { return parentToken.balanceOfAt(_owner, min(_blockNumber, parentSnapShotBlock)); } else { // Has no parent return 0; } // This will return the expected balance during normal situations } else { return getValueAt(balances[_owner], _blockNumber); } } /// @notice Total amount of tokens at a specific `_blockNumber`. /// @param _blockNumber The block number when the totalSupply is queried /// @return The total amount of tokens at `_blockNumber` function totalSupplyAt(uint _blockNumber) public constant returns(uint) { // These next few lines are used when the totalSupply of the token is // requested before a check point was ever created for this token, it // requires that the `parentToken.totalSupplyAt` be queried at the // genesis block for this token as that contains totalSupply of this // token at this block number. if ((totalSupplyHistory.length == 0) || (totalSupplyHistory[0].fromBlock > _blockNumber)) { if (address(parentToken) != 0) { return parentToken.totalSupplyAt(min(_blockNumber, parentSnapShotBlock)); } else { return 0; } // This will return the expected totalSupply during normal situations } else { return getValueAt(totalSupplyHistory, _blockNumber); } } //////////////// // Generate and destroy tokens //////////////// /// @notice Generates `_amount` tokens that are assigned to `_owner` /// @param _owner The address that will be assigned the new tokens /// @param _amount The quantity of tokens generated /// @return True if the tokens are generated correctly function generateTokens(address _owner, uint _amount) public onlyControllerorOwner whenNotPaused returns(bool) { uint curTotalSupply = totalSupply(); require(curTotalSupply.add(_amount) >= curTotalSupply); // Check for overflow uint previousBalanceTo = balanceOf(_owner); require(previousBalanceTo.add(_amount) >= previousBalanceTo); // Check for overflow updateValueAtNow(totalSupplyHistory, curTotalSupply.add(_amount)); updateValueAtNow(balances[_owner], previousBalanceTo.add(_amount)); emit Transfer(0, _owner, _amount); return true; } /// @notice Burns `_amount` tokens from `_owner` /// @param _owner The address that will lose the tokens /// @param _amount The quantity of tokens to burn /// @return True if the tokens are burned correctly function destroyTokens(address _owner, uint _amount) onlyControllerorOwner public returns(bool) { uint curTotalSupply = totalSupply(); require(curTotalSupply >= _amount); uint previousBalanceFrom = balanceOf(_owner); require(previousBalanceFrom >= _amount); updateValueAtNow(totalSupplyHistory, curTotalSupply.sub(_amount)); updateValueAtNow(balances[_owner], previousBalanceFrom.sub(_amount)); emit Transfer(_owner, 0, _amount); return true; } //////////////// // Enable tokens transfers //////////////// /// @notice Enables token holders to transfer their tokens freely if true /// @param _transfersEnabled True if transfers are allowed in the clone function enableTransfers(bool _transfersEnabled) public onlyControllerorOwner { transfersEnabled = _transfersEnabled; } //////////////// // Internal helper functions to query and set a value in a snapshot array //////////////// /// @dev `getValueAt` retrieves the number of tokens at a given block number /// @param checkpoints The history of values being queried /// @param _block The block number to retrieve the value at /// @return The number of tokens being queried function getValueAt(Checkpoint[] storage checkpoints, uint _block) constant internal returns(uint) { if (checkpoints.length == 0) return 0; // Shortcut for the actual value if (_block >= checkpoints[checkpoints.length.sub(1)].fromBlock) return checkpoints[checkpoints.length.sub(1)].value; if (_block < checkpoints[0].fromBlock) return 0; // Binary search of the value in the array uint min = 0; uint max = checkpoints.length.sub(1); while (max > min) { uint mid = (max.add(min).add(1)).div(2); if (checkpoints[mid].fromBlock <= _block) { min = mid; } else { max = mid.sub(1); } } return checkpoints[min].value; } /// @dev `updateValueAtNow` used to update the `balances` map and the /// `totalSupplyHistory` /// @param checkpoints The history of data being updated /// @param _value The new number of tokens function updateValueAtNow(Checkpoint[] storage checkpoints, uint _value) internal { if ((checkpoints.length == 0) || (checkpoints[checkpoints.length.sub(1)].fromBlock < block.number)) { Checkpoint storage newCheckPoint = checkpoints[checkpoints.length++]; newCheckPoint.fromBlock = uint128(block.number); newCheckPoint.value = uint128(_value); } else { Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length.sub(1)]; oldCheckPoint.value = uint128(_value); } } /// @dev Internal function to determine if an address is a contract /// @param _addr The address being queried /// @return True if `_addr` is a contract function isContract(address _addr) constant internal returns(bool) { uint size; if (_addr == 0) return false; assembly { size: = extcodesize(_addr) } return size > 0; } /// @dev Helper function to return a min betwen the two uints function min(uint a, uint b) pure internal returns(uint) { return a < b ? a : b; } /// @notice The fallback function: If the contract's controller has not been /// set to 0, then the `proxyPayment` method is called which relays the /// ether and creates tokens as described in the token controller contract function() public payable { /*require(isContract(controller)); require(TokenController(controller).proxyPayment.value(msg.value)(msg.sender));*/ revert(); } ////////// // Safety Methods ////////// /// @notice This method can be used by the controller to extract mistakenly /// sent tokens to this contract. /// @param _token The address of the token contract that you want to recover /// set to 0 in case you want to extract ether. function claimTokens(address _token) public onlyControllerorOwner { if (_token == 0x0) { controller.transfer(address(this).balance); return; } MiniMeToken token = MiniMeToken(_token); uint balance = token.balanceOf(this); token.transfer(controller, balance); emit ClaimedTokens(_token, controller, balance); } //////////////// // Events //////////////// event ClaimedTokens(address indexed _token, address indexed _controller, uint _amount); event Transfer(address indexed _from, address indexed _to, uint256 _amount); event NewCloneToken(address indexed _cloneToken, uint _snapshotBlock); event Approval( address indexed _owner, address indexed _spender, uint256 _amount ); } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns(uint256); function balanceOf(address who) public view returns(uint256); function transfer(address to, uint256 value) public returns(bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 _amount, address _token, bytes _data) public; } contract EmaToken is MiniMeToken { constructor(address tokenfactory, address parenttoken, uint parentsnapshot, string tokenname, uint8 dec, string tokensymbol, bool transfersenabled) MiniMeToken(tokenfactory, parenttoken, parentsnapshot, tokenname, dec, tokensymbol, transfersenabled) public {} } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns(uint256); function transferFrom(address from, address to, uint256 value) public returns(bool); function approve(address spender, uint256 value) public returns(bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Crowdsale * @dev Crowdsale is a base contract for managing a token crowdsale, * allowing investors to purchase tokens with ether. This contract implements * such functionality in its most fundamental form and can be extended to provide additional * functionality and/or custom behavior. * The external interface represents the basic interface for purchasing tokens, and conform * the base architecture for crowdsales. They are *not* intended to be modified / overriden. * The internal interface conforms the extensible and modifiable surface of crowdsales. Override * the methods to add functionality. Consider using 'super' where appropiate to concatenate * behavior. */ //////////////// // MiniMeTokenFactory //////////////// /// @dev This contract is used to generate clone contracts from a contract. /// In solidity this is the way to create a contract from a contract of the /// same class contract MiniMeTokenFactory { /// @notice Update the DApp by creating a new token with new functionalities /// the msg.sender becomes the controller of this clone token /// @param _parentToken Address of the token being cloned /// @param _snapshotBlock Block of the parent token that will /// determine the initial distribution of the clone token /// @param _tokenName Name of the new token /// @param _decimalUnits Number of decimals of the new token /// @param _tokenSymbol Token Symbol for the new token /// @param _transfersEnabled If true, tokens will be able to be transferred /// @return The address of the new token contract function createCloneToken( address _parentToken, uint _snapshotBlock, string _tokenName, uint8 _decimalUnits, string _tokenSymbol, bool _transfersEnabled ) public returns(MiniMeToken) { MiniMeToken newToken = new MiniMeToken( this, _parentToken, _snapshotBlock, _tokenName, _decimalUnits, _tokenSymbol, _transfersEnabled ); newToken.changeController(msg.sender); return newToken; } } contract Crowdsale is Pausable { using SafeMath for uint256; // The token being sold MiniMeToken public token; // Address where funds are collected address public wallet; // How many token units a buyer gets per wei uint256 public rate = 6120; // Amount of tokens sold uint256 public tokensSold; uint256 public allCrowdSaleTokens = 255000000000000000000000000; //255M tokens available for crowdsale /** * Event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); event buyx(address buyer, address contractAddr, uint256 amount); constructor(address _wallet, MiniMeToken _token) public { require(_wallet != address(0)); require(_token != address(0)); wallet = _wallet; token = _token; } function setCrowdsale(address _wallet, MiniMeToken _token) internal { require(_wallet != address(0)); require(_token != address(0)); wallet = _wallet; token = _token; } // ----------------------------------------- // Crowdsale external interface // ----------------------------------------- /** * fallback function ***DO NOT OVERRIDE*** */ function() external whenNotPaused payable { emit buyx(msg.sender, this, _getTokenAmount(msg.value)); buyTokens(msg.sender); } /** * @dev low level token purchase ***DO NOT OVERRIDE*** * @param _beneficiary Address performing the token purchase */ function buyTokens(address _beneficiary) public whenNotPaused payable { if ((msg.value >= 500000000000000000000) && (msg.value < 1000000000000000000000)) { rate = 7140; } else if (msg.value >= 1000000000000000000000) { rate = 7650; } else if (tokensSold <= 21420000000000000000000000) { rate = 6120; } else if ((tokensSold > 21420000000000000000000000) && (tokensSold <= 42304500000000000000000000)) { rate = 5967; } else if ((tokensSold > 42304500000000000000000000) && (tokensSold <= 73095750000000000000000000)) { rate = 5865; } else if ((tokensSold > 73095750000000000000000000) && (tokensSold <= 112365750000000000000000000)) { rate = 5610; } else if ((tokensSold > 112365750000000000000000000) && (tokensSold <= 159222000000000000000000000)) { rate = 5355; } else if (tokensSold > 159222000000000000000000000) { rate = 5100; } uint256 weiAmount = msg.value; uint256 tokens = _getTokenAmount(weiAmount); _processPurchase(_beneficiary, tokens); emit TokenPurchase(msg.sender, _beneficiary, weiAmount, tokens); _updatePurchasingState(_beneficiary, weiAmount); _forwardFunds(); _postValidatePurchase(_beneficiary, weiAmount); tokensSold = allCrowdSaleTokens.sub(token.balanceOf(this)); } // ----------------------------------------- // Internal interface (extensible) // ----------------------------------------- /** * @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use super to concatenate validations. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal { require(_beneficiary != address(0)); require(_weiAmount != 0); } /** * @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid conditions are not met. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _postValidatePurchase(address _beneficiary, uint256 _weiAmount) internal { // optional override } /** * @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens. * @param _beneficiary Address performing the token purchase * @param _tokenAmount Number of tokens to be emitted */ function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal { token.transfer(_beneficiary, _tokenAmount); } /** * @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens. * @param _beneficiary Address receiving the tokens * @param _tokenAmount Number of tokens to be purchased */ function _processPurchase(address _beneficiary, uint256 _tokenAmount) internal { _deliverTokens(_beneficiary, _tokenAmount); } /** * @dev Override for extensions that require an internal state to check for validity (current user contributions, etc.) * @param _beneficiary Address receiving the tokens * @param _weiAmount Value in wei involved in the purchase */ function _updatePurchasingState(address _beneficiary, uint256 _weiAmount) internal { // optional override } /** * @dev Override to extend the way in which ether is converted to tokens. * @param _weiAmount Value in wei to be converted into tokens * @return Number of tokens that can be purchased with the specified _weiAmount */ function _getTokenAmount(uint256 _weiAmount) internal returns(uint256) { return _weiAmount.mul(rate); } /** * @dev Determines how ETH is stored/forwarded on purchases. */ function _forwardFunds() internal { wallet.transfer(msg.value); } } contract EmaCrowdSale is Crowdsale { using SafeMath for uint256; constructor(address wallet, MiniMeToken token) Crowdsale(wallet, token) public { setCrowdsale(wallet, token); } function tranferPresaleTokens(address investor, uint256 ammount) public onlyOwner { tokensSold = tokensSold.add(ammount); token.transferFrom(this, investor, ammount); } function setTokenTransferState(bool state) public onlyOwner { token.changeController(this); token.enableTransfers(state); } function claim(address claimToken) public onlyOwner { token.changeController(this); token.claimTokens(claimToken); } function() external payable whenNotPaused { emit buyx(msg.sender, this, _getTokenAmount(msg.value)); buyTokens(msg.sender); } }
* @dev Adds two numbers, throws on overflow./
function add(uint256 a, uint256 b) internal pure returns(uint256) { uint256 c = a + b; assert(c >= a); return c; }
1,044,861
[ 1, 3655, 2795, 5600, 16, 1216, 603, 9391, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 527, 12, 11890, 5034, 279, 16, 2254, 5034, 324, 13, 2713, 16618, 1135, 12, 11890, 5034, 13, 288, 203, 3639, 2254, 5034, 276, 273, 279, 397, 324, 31, 203, 3639, 1815, 12, 71, 1545, 279, 1769, 203, 3639, 327, 276, 31, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.10; import "../types/FrontEndRewarder.sol"; import "../interfaces/IgCADT.sol"; import "../interfaces/IStaking.sol"; import "../interfaces/ITreasury.sol"; import "../interfaces/INoteKeeper.sol"; abstract contract NoteKeeper is INoteKeeper, FrontEndRewarder { mapping(address => Note[]) public notes; // user deposit data mapping(address => mapping(uint256 => address)) private noteTransfers; // change note ownership IgCADT internal immutable gCADT; IStaking internal immutable staking; ITreasury internal treasury; constructor( ICoachAIAuthority _authority, IERC20 _cadt, IgCADT _gcadt, IStaking _staking, ITreasury _treasury ) FrontEndRewarder(_authority, _cadt) { gCADT = _gcadt; staking = _staking; treasury = _treasury; } // if treasury address changes on authority, update it function updateTreasury() external { require( msg.sender == authority.governor() || msg.sender == authority.guardian() || msg.sender == authority.policy(), "Only authorized" ); treasury = ITreasury(authority.vault()); } /* ========== ADD ========== */ /** * @notice adds a new Note for a user, stores the front end & DAO rewards, and mints & stakes payout & rewards * @param _user the user that owns the Note * @param _payout the amount of CADT due to the user * @param _expiry the timestamp when the Note is redeemable * @param _marketID the ID of the market deposited into * @return index_ the index of the Note in the user's array */ function addNote( address _user, uint256 _payout, uint48 _expiry, uint48 _marketID, address _referral ) internal returns (uint256 index_) { // the index of the note is the next in the user's array index_ = notes[_user].length; // the new note is pushed to the user's array notes[_user].push( Note({ payout: gCADT.balanceTo(_payout), created: uint48(block.timestamp), matured: _expiry, redeemed: 0, marketID: _marketID }) ); // front end operators can earn rewards by referring users uint256 rewards = _giveRewards(_payout, _referral); // mint and stake payout treasury.mint(address(this), _payout + rewards); // note that only the payout gets staked (front end rewards are in CADT) staking.stake(address(this), _payout, false, true); } /* ========== REDEEM ========== */ /** * @notice redeem notes for user * @param _user the user to redeem for * @param _indexes the note indexes to redeem * @param _sendgCADT send payout as gCADT or sCADT * @return payout_ sum of payout sent, in gCADT */ function redeem( address _user, uint256[] memory _indexes, bool _sendgCADT ) public override returns (uint256 payout_) { uint48 time = uint48(block.timestamp); for (uint256 i = 0; i < _indexes.length; i++) { (uint256 pay, bool matured) = pendingFor(_user, _indexes[i]); if (matured) { notes[_user][_indexes[i]].redeemed = time; // mark as redeemed payout_ += pay; } } if (_sendgCADT) { gCADT.transfer(_user, payout_); // send payout as gCADT } else { staking.unwrap(_user, payout_); // unwrap and send payout as sCADT } } /** * @notice redeem all redeemable markets for user * @dev if possible, query indexesFor() off-chain and input in redeem() to save gas * @param _user user to redeem all notes for * @param _sendgCADT send payout as gCADT or sCADT * @return sum of payout sent, in gCADT */ function redeemAll(address _user, bool _sendgCADT) external override returns (uint256) { return redeem(_user, indexesFor(_user), _sendgCADT); } /* ========== TRANSFER ========== */ /** * @notice approve an address to transfer a note * @param _to address to approve note transfer for * @param _index index of note to approve transfer for */ function pushNote(address _to, uint256 _index) external override { require(notes[msg.sender][_index].created != 0, "Depository: note not found"); noteTransfers[msg.sender][_index] = _to; } /** * @notice transfer a note that has been approved by an address * @param _from the address that approved the note transfer * @param _index the index of the note to transfer (in the sender's array) */ function pullNote(address _from, uint256 _index) external override returns (uint256 newIndex_) { require(noteTransfers[_from][_index] == msg.sender, "Depository: transfer not found"); require(notes[_from][_index].redeemed == 0, "Depository: note redeemed"); newIndex_ = notes[msg.sender].length; notes[msg.sender].push(notes[_from][_index]); delete notes[_from][_index]; } /* ========== VIEW ========== */ // Note info /** * @notice all pending notes for user * @param _user the user to query notes for * @return the pending notes for the user */ function indexesFor(address _user) public view override returns (uint256[] memory) { Note[] memory info = notes[_user]; uint256 length; for (uint256 i = 0; i < info.length; i++) { if (info[i].redeemed == 0 && info[i].payout != 0) length++; } uint256[] memory indexes = new uint256[](length); uint256 position; for (uint256 i = 0; i < info.length; i++) { if (info[i].redeemed == 0 && info[i].payout != 0) { indexes[position] = i; position++; } } return indexes; } /** * @notice calculate amount available for claim for a single note * @param _user the user that the note belongs to * @param _index the index of the note in the user's array * @return payout_ the payout due, in gCADT * @return matured_ if the payout can be redeemed */ function pendingFor(address _user, uint256 _index) public view override returns (uint256 payout_, bool matured_) { Note memory note = notes[_user][_index]; payout_ = note.payout; matured_ = note.redeemed == 0 && note.matured <= block.timestamp && note.payout != 0; } }
if treasury address changes on authority, update it
function updateTreasury() external { require( msg.sender == authority.governor() || msg.sender == authority.guardian() || msg.sender == authority.policy(), "Only authorized" ); treasury = ITreasury(authority.vault()); }
14,026,736
[ 1, 430, 9787, 345, 22498, 1758, 3478, 603, 11675, 16, 1089, 518, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1089, 56, 266, 345, 22498, 1435, 3903, 288, 203, 3639, 2583, 12, 203, 5411, 1234, 18, 15330, 422, 11675, 18, 75, 1643, 29561, 1435, 747, 203, 7734, 1234, 18, 15330, 422, 11675, 18, 24594, 2779, 1435, 747, 203, 7734, 1234, 18, 15330, 422, 11675, 18, 5086, 9334, 203, 5411, 315, 3386, 10799, 6, 203, 3639, 11272, 203, 3639, 9787, 345, 22498, 273, 24142, 266, 345, 22498, 12, 24763, 18, 26983, 10663, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.5.3; /** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @return the address of the owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner()); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } /** * @title PaymentDistributor * @dev distributes all the received funds between project wallets and team members. */ contract PaymentDistributor is Ownable { using SafeMath for uint256; event PaymentReleased(address to, uint256 amount); event PaymentReceived(address from, uint256 amount); // timestamp when fund backup release is enabled uint256 private _backupReleaseTime; uint256 private _totalReleased; mapping(address => uint256) private _released; uint256 private constant step1Fund = uint256(5000) * 10 ** 18; address payable private _beneficiary0; address payable private _beneficiary1; address payable private _beneficiary2; address payable private _beneficiary3; address payable private _beneficiary4; address payable private _beneficiaryBackup; /** * @dev Constructor */ constructor (address payable beneficiary0, address payable beneficiary1, address payable beneficiary2, address payable beneficiary3, address payable beneficiary4, address payable beneficiaryBackup, uint256 backupReleaseTime) public { _beneficiary0 = beneficiary0; _beneficiary1 = beneficiary1; _beneficiary2 = beneficiary2; _beneficiary3 = beneficiary3; _beneficiary4 = beneficiary4; _beneficiaryBackup = beneficiaryBackup; _backupReleaseTime = backupReleaseTime; } /** * @dev payable fallback */ function () external payable { emit PaymentReceived(msg.sender, msg.value); } /** * @return the total amount already released. */ function totalReleased() public view returns (uint256) { return _totalReleased; } /** * @return the amount already released to an account. */ function released(address account) public view returns (uint256) { return _released[account]; } /** * @return the beneficiary0 of the Payments. */ function beneficiary0() public view returns (address) { return _beneficiary0; } /** * @return the beneficiary1 of the Payments. */ function beneficiary1() public view returns (address) { return _beneficiary1; } /** * @return the beneficiary2 of the Payments. */ function beneficiary2() public view returns (address) { return _beneficiary2; } /** * @return the beneficiary3 of the Payments. */ function beneficiary3() public view returns (address) { return _beneficiary3; } /** * @return the beneficiary4 of the Payments. */ function beneficiary4() public view returns (address) { return _beneficiary4; } /** * @return the beneficiaryBackup of Payments. */ function beneficiaryBackup() public view returns (address) { return _beneficiaryBackup; } /** * @return the time when Payments are released to the beneficiaryBackup wallet. */ function backupReleaseTime() public view returns (uint256) { return _backupReleaseTime; } /** * @dev send to one of the beneficiarys' addresses. * @param account Whose the fund will be send to. * @param amount Value in wei to be sent */ function sendToAccount(address payable account, uint256 amount) internal { require(amount > 0, 'The amount must be greater than zero.'); _released[account] = _released[account].add(amount); _totalReleased = _totalReleased.add(amount); account.transfer(amount); emit PaymentReleased(account, amount); } /** * @dev distributes the amount between team's wallets * which are created for different purposes. * @param amount Value in wei to send to the wallets. */ function release(uint256 amount) onlyOwner public{ require(address(this).balance >= amount, 'Balance must be greater than or equal to the amount.'); uint256 _value = amount; if (_released[_beneficiary0] < step1Fund) { if (_released[_beneficiary0].add(_value) > step1Fund){ uint256 _remainValue = step1Fund.sub(_released[_beneficiary0]); _value = _value.sub(_remainValue); sendToAccount(_beneficiary0, _remainValue); } else { sendToAccount(_beneficiary0, _value); _value = 0; } } if (_value > 0) { uint256 _value1 = _value.mul(10).div(100); //10% uint256 _value2 = _value.mul(7020).div(10000); //70.2% uint256 _value3 = _value.mul(1080).div(10000); //10.8% uint256 _value4 = _value.mul(9).div(100); //9% sendToAccount(_beneficiary1, _value1); sendToAccount(_beneficiary2, _value2); sendToAccount(_beneficiary3, _value3); sendToAccount(_beneficiary4, _value4); } } /** * @dev transfer the amount to the beneficiaryBackup wallet * which are created for different purposes. * @param amount Value in wei to send to the backup wallet. */ function releaseBackup(uint256 amount) onlyOwner public{ require(address(this).balance >= amount, 'Balance must be greater than or equal to the amount.'); require(block.timestamp >= backupReleaseTime(), 'The transfer is possible only 2 months after the ICO.'); sendToAccount(_beneficiaryBackup, amount); } }
* @return the beneficiary2 of the Payments./
function beneficiary2() public view returns (address) { return _beneficiary2; }
7,326,888
[ 1, 2463, 326, 27641, 74, 14463, 814, 22, 434, 326, 13838, 1346, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 27641, 74, 14463, 814, 22, 1435, 1071, 1476, 1135, 261, 2867, 13, 288, 203, 3639, 327, 389, 70, 4009, 74, 14463, 814, 22, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/11155111/0x250B63aFab3Ce46D0D8679fD5D996C4f517a262F/sources/project_/contracts/verified-sbt.sol
link the sbt to a certain token
mapping (uint256 => address) public _token;
3,810,733
[ 1, 1232, 326, 2393, 88, 358, 279, 8626, 1147, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2874, 261, 11890, 5034, 516, 1758, 13, 1071, 389, 2316, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/4/0xD69E0c876D7DCb9d71B29e586112a970cD6f5A57/sources/home/bob/KingSwap_V2/contracts/KingDecks.sol
termsId is the index in the `_termSheets` array + 1
event NewTermSheet(uint256 indexed termsId);
12,372,155
[ 1, 10112, 548, 353, 326, 770, 316, 326, 1375, 67, 6408, 55, 10245, 68, 526, 397, 404, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 871, 1166, 4065, 8229, 12, 11890, 5034, 8808, 6548, 548, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.4; interface IERC20 { function TRANSFER517(address to, uint256 value) external returns (bool); //inject NONSTANDARD NAMING function APPROVE399(address spender, uint256 value) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM891(address from, address to, uint256 value) external returns (bool); //inject NONSTANDARD NAMING function TOTALSUPPLY740() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF13(address who) external view returns (uint256); //inject NONSTANDARD NAMING function ALLOWANCE192(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING event TRANSFER171(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL960(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } library SafeMath { function MUL899(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } function DIV62(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function SUB911(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b <= a); uint256 c = a - b; return c; } function ADD826(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a); return c; } function MOD263(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0); return a % b; } } contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; uint256 private _totalSupply; function TOTALSUPPLY740() public view returns (uint256) { //inject NONSTANDARD NAMING return _totalSupply; } function BALANCEOF13(address owner) public view returns (uint256) { //inject NONSTANDARD NAMING return _balances[owner]; } function ALLOWANCE192(address owner, address spender) public view returns (uint256) { //inject NONSTANDARD NAMING return _allowed[owner][spender]; } function TRANSFER517(address to, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER255(msg.sender, to, value); return true; } function APPROVE399(address spender, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING require(spender != address(0)); _allowed[msg.sender][spender] = value; emit APPROVAL960(msg.sender, spender, value); return true; } function TRANSFERFROM891(address from, address to, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING _allowed[from][msg.sender] = _allowed[from][msg.sender].SUB911(value); _TRANSFER255(from, to, value); emit APPROVAL960(from, msg.sender, _allowed[from][msg.sender]); return true; } function INCREASEALLOWANCE464(address spender, uint256 addedValue) public returns (bool) { //inject NONSTANDARD NAMING require(spender != address(0)); _allowed[msg.sender][spender] = _allowed[msg.sender][spender].ADD826(addedValue); emit APPROVAL960(msg.sender, spender, _allowed[msg.sender][spender]); return true; } function DECREASEALLOWANCE155(address spender, uint256 subtractedValue) public returns (bool) { //inject NONSTANDARD NAMING require(spender != address(0)); _allowed[msg.sender][spender] = _allowed[msg.sender][spender].SUB911(subtractedValue); emit APPROVAL960(msg.sender, spender, _allowed[msg.sender][spender]); return true; } function _TRANSFER255(address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING require(to != address(0)); _balances[from] = _balances[from].SUB911(value); _balances[to] = _balances[to].ADD826(value); emit TRANSFER171(from, to, value); } function _MINT939(address account, uint256 value) internal { //inject NONSTANDARD NAMING require(account != address(0)); _totalSupply = _totalSupply.ADD826(value); _balances[account] = _balances[account].ADD826(value); emit TRANSFER171(address(0), account, value); } function _BURN464(address account, uint256 value) internal { //inject NONSTANDARD NAMING require(account != address(0)); _totalSupply = _totalSupply.SUB911(value); _balances[account] = _balances[account].SUB911(value); emit TRANSFER171(account, address(0), value); } function _BURNFROM886(address account, uint256 value) internal { //inject NONSTANDARD NAMING _allowed[account][msg.sender] = _allowed[account][msg.sender].SUB911(value); _BURN464(account, value); emit APPROVAL960(account, msg.sender, _allowed[account][msg.sender]); } } contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor (string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } function NAME528() public view returns (string memory) { //inject NONSTANDARD NAMING return _name; } function SYMBOL252() public view returns (string memory) { //inject NONSTANDARD NAMING return _symbol; } function DECIMALS194() public view returns (uint8) { //inject NONSTANDARD NAMING return _decimals; } } contract Ownable { address private _owner; event OWNERSHIPTRANSFERRED81(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING constructor () internal { _owner = msg.sender; emit OWNERSHIPTRANSFERRED81(address(0), _owner); } function OWNER239() public view returns (address) { //inject NONSTANDARD NAMING return _owner; } modifier ONLYOWNER127() { //inject NONSTANDARD NAMING require(ISOWNER809()); _; } function ISOWNER809() public view returns (bool) { //inject NONSTANDARD NAMING return msg.sender == _owner; } function RENOUNCEOWNERSHIP995() public ONLYOWNER127 { //inject NONSTANDARD NAMING emit OWNERSHIPTRANSFERRED81(_owner, address(0)); _owner = address(0); } function TRANSFEROWNERSHIP522(address newOwner) public ONLYOWNER127 { //inject NONSTANDARD NAMING _TRANSFEROWNERSHIP774(newOwner); } function _TRANSFEROWNERSHIP774(address newOwner) internal { //inject NONSTANDARD NAMING require(newOwner != address(0)); emit OWNERSHIPTRANSFERRED81(_owner, newOwner); _owner = newOwner; } } contract ExtraTerrestrial is ERC20Detailed, ERC20, Ownable { using SafeMath for uint256; constructor(address _tokenHolder) public ERC20Detailed("ExtraTerrestrial", "ETER", 18) { _MINT939(_tokenHolder, 30000000000000000000000000); } }
inject NONSTANDARD NAMING
event OWNERSHIPTRANSFERRED81(address indexed previousOwner, address indexed newOwner);
15,884,976
[ 1, 22170, 18708, 882, 18264, 423, 2192, 1360, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 871, 531, 22527, 2664, 45, 1856, 54, 11607, 17356, 11861, 12, 2867, 8808, 2416, 5541, 16, 1758, 8808, 394, 5541, 1769, 202, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.9; contract ERC223 { uint public totalSupply; function balanceOf(address who) constant returns (uint); function name() constant returns (string _name); function symbol() constant returns (string _symbol); function decimals() constant returns (uint8 _decimals); function totalSupply() constant returns (uint256 _supply); function transfer(address to, uint value) returns (bool ok); function transfer(address to, uint value, bytes data) returns (bool ok); event Transfer(address indexed from, address indexed to, uint value, bytes indexed data); event Transfer(address indexed from, address indexed to, uint value); } contract ContractReceiver { struct TKN { address sender; uint value; bytes data; bytes4 sig; } function tokenFallback(address _from, uint _value, bytes _data){ TKN memory tkn; tkn.sender = _from; tkn.value = _value; tkn.data = _data; uint32 u = uint32(_data[3]) + (uint32(_data[2]) << 8) + (uint32(_data[1]) << 16) + (uint32(_data[0]) << 24); tkn.sig = bytes4(u); /* tkn variable is analogue of msg variable of Ether transaction * tkn.sender is person who initiated this token transaction (analogue of msg.sender) * tkn.value the number of tokens that were sent (analogue of msg.value) * tkn.data is data of token transaction (analogue of msg.data) * tkn.sig is 4 bytes signature of function * if data of token transaction is a function execution */ } } /** * ERC23 token by Dexaran * * https://github.com/Dexaran/ERC23-tokens */ /* https://github.com/LykkeCity/EthereumApiDotNetCore/blob/master/src/ContractBuilder/contracts/token/SafeMath.sol */ contract SafeMath { uint256 constant public MAX_UINT256 = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; function safeAdd(uint256 x, uint256 y) constant internal returns (uint256 z) { assert(x <= MAX_UINT256 - y); return x + y; } function safeSub(uint256 x, uint256 y) constant internal returns (uint256 z) { assert(x >= y); return x - y; } function safeMul(uint256 x, uint256 y) constant internal returns (uint256 z) { if (y == 0) return 0; assert(x <= MAX_UINT256 / y); return x * y; } } /* * Ownable * * Base contract with an owner. * Provides onlyOwner modifier, which prevents function from running if it is called by anyone other than the owner. */ contract Ownable { address public owner; function Ownable() { owner = msg.sender; } modifier onlyOwner() { assert(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner { if (newOwner != address(0)) { owner = newOwner; } } } contract Haltable is Ownable { bool public halted; modifier stopInEmergency { assert(!halted); _; } modifier onlyInEmergency { assert(halted); _; } // called by the owner on emergency, triggers stopped state function halt() external onlyOwner { halted = true; } // called by the owner on end of emergency, returns to normal state function unhalt() external onlyOwner onlyInEmergency { halted = false; } } contract ERC223Token is ERC223, SafeMath, Haltable { mapping(address => uint) balances; string public name; string public symbol; uint8 public decimals; uint256 public totalSupply; // Function to access name of token . function name() constant returns (string _name) { return name; } // Function to access symbol of token . function symbol() constant returns (string _symbol) { return symbol; } // Function to access decimals of token . function decimals() constant returns (uint8 _decimals) { return decimals; } // Function to access total supply of tokens . function totalSupply() constant returns (uint256 _totalSupply) { return totalSupply; } // Function that is called when a user or another contract wants to transfer funds . function transfer(address _to, uint _value, bytes _data) returns (bool success) { if(isContract(_to)) { return transferToContract(_to, _value, _data); } else { return transferToAddress(_to, _value, _data); } } // Standard function transfer similar to ERC20 transfer with no _data . // Added due to backwards compatibility reasons . function transfer(address _to, uint _value) returns (bool success) { //standard function transfer similar to ERC20 transfer with no _data //added due to backwards compatibility reasons bytes memory empty; if(isContract(_to)) { return transferToContract(_to, _value, empty); } else { return transferToAddress(_to, _value, empty); } } //assemble the given address bytecode. If bytecode exists then the _addr is a contract. function isContract(address _addr) private returns (bool is_contract) { uint length; assembly { //retrieve the size of the code on target address, this needs assembly length := extcodesize(_addr) } if(length>0) { return true; } else { return false; } } //function that is called when transaction target is an address function transferToAddress(address _to, uint _value, bytes _data) private returns (bool success) { assert(balanceOf(msg.sender) >= _value); balances[msg.sender] = safeSub(balanceOf(msg.sender), _value); balances[_to] = safeAdd(balanceOf(_to), _value); Transfer(msg.sender, _to, _value, _data); Transfer(msg.sender, _to, _value); return true; } //function that is called when transaction target is a contract function transferToContract(address _to, uint _value, bytes _data) private returns (bool success) { assert(balanceOf(msg.sender) >= _value); balances[msg.sender] = safeSub(balanceOf(msg.sender), _value); balances[_to] = safeAdd(balanceOf(_to), _value); ContractReceiver reciever = ContractReceiver(_to); reciever.tokenFallback(msg.sender, _value, _data); Transfer(msg.sender, _to, _value, _data); Transfer(msg.sender, _to, _value); return true; } function balanceOf(address _owner) constant returns (uint balance) { return balances[_owner]; } } contract MindToken is ERC223Token { address public beneficiary; event Buy(address indexed participant, uint tokens, uint eth); event GoalReached(uint amountRaised); uint public cap = 20000000000000; uint public price; uint public collectedTokens; uint public collectedEthers; uint public tokensSold = 0; uint public weiRaised = 0; uint public investorCount = 0; uint public startTime; uint public endTime; bool public capReached = false; bool public presaleFinished = false; /** * @dev Contructor that gives msg.sender all of existing tokens. */ function MindToken() { name = "Mind10 Token"; symbol = "Mind10"; decimals = 8; totalSupply = 500000000000000; address _beneficiary = 0x0980eaD74d176025F2962f8b5535346c77ffd2f5; //uint _price = 0.00001; uint _price = 150; uint _startTime = 1502704800; uint _duration = 15; balances[msg.sender] = totalSupply; beneficiary = _beneficiary; price = _price; startTime = _startTime; endTime = _startTime + _duration * 1 minutes; } modifier onlyAfter(uint time) { assert(now >= time); _; } modifier onlyBefore(uint time) { assert(now <= time); _; } function () payable stopInEmergency { assert(msg.value >= 0.01 * 1 ether); doPurchase(); //if (msg.value < 0.01 * 1 ether) throw; } function doPurchase() private onlyAfter(startTime) onlyBefore(endTime) { assert(!presaleFinished); uint tokens = msg.value * price / 10000000000; if (balanceOf(msg.sender) == 0) investorCount++; balances[owner] -= tokens; balances[msg.sender] += tokens; collectedTokens = safeAdd(collectedTokens, tokens); collectedEthers = safeAdd(collectedEthers, msg.value); //assert(collectedTokens <= cap); weiRaised = safeAdd(weiRaised, msg.value); tokensSold = safeAdd(tokensSold, tokens); bytes memory empty; Transfer(owner, msg.sender, tokens, empty); Transfer(owner, msg.sender, tokens); Buy(msg.sender, tokens, msg.value); if (collectedTokens == cap) { GoalReached(cap); } } function withdraw() onlyOwner onlyAfter(endTime) returns (bool) { //assert(capReached); if (!beneficiary.send(collectedEthers)) { return false; } //token.transfer(beneficiary, token.balanceOf(this)); presaleFinished = true; return true; } }
if (msg.value < 0.01 * 1 ether) throw;
function () payable stopInEmergency { assert(msg.value >= 0.01 * 1 ether); doPurchase(); }
5,533,061
[ 1, 430, 261, 3576, 18, 1132, 411, 374, 18, 1611, 225, 404, 225, 2437, 13, 604, 31, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1832, 8843, 429, 2132, 382, 1514, 24530, 288, 203, 3639, 1815, 12, 3576, 18, 1132, 1545, 374, 18, 1611, 380, 404, 225, 2437, 1769, 203, 3639, 741, 23164, 5621, 203, 540, 203, 540, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.8.1; /** @title Repeater * This contract repeats calls on the owner request. */ contract Repeater { address owner = msg.sender; /** @dev Call `_target` with `_data` * @param _target The contract to call. * @param _data The data to send to the contract. */ function repeat(address _target, bytes calldata _data) external { require(msg.sender == owner); _target.call(_data); } /** @dev Call `_target` with `_data` sending `_value` wei. * @param _target The contract to call. * @param _data The data to send to the contract. * @param _value The amount of wei to send. */ function repeatWithValue(address _target, bytes calldata _data, uint _value) external { require(msg.sender == owner); _target.call{value: _value}(_data); } receive() external payable {} } /** @title Master * This contract creates repeaters and make them perform some actions. */ contract Master { address public owner = msg.sender; Repeater[] public repeaters; function changeOwner(address _newOwner) external { require(msg.sender == owner); owner = _newOwner; } /** @dev Create `_amount` repeaters. * @param _amount The amount of repeaters to create. */ function addRepeaters(uint _amount) external { require(msg.sender == owner); for (uint i; i<_amount; ++i) { repeaters.push(new Repeater()); } } /** @dev Make repeaters from `_start` to `_end` (included) call `_target` with `_data`. * @param _start The first repeater ID. * @param _end The last repeater ID. * @param _target The contract to be called by the repeaters. * @param _data The data the repeaters will send to the contract. */ function say(uint _start, uint _end, address _target, bytes calldata _data) external { require(msg.sender == owner); for (uint i=_start; i<=_end; ++i) { repeaters[i].repeat(_target, _data); } } /** @dev Make repeaters from `_start` to `_end` (included) call `_target` with `_data` sending `_value` wei. * @param _start The first repeater ID. * @param _end The last repeater ID. * @param _target The contract to be called by the repeaters. * @param _data The data the repeaters will send to the contract. * @param _value The amount of wei to send. */ function sayWithValue(uint _start, uint _end, address _target, bytes calldata _data, uint _value) external { require(msg.sender == owner); for (uint i=_start; i<=_end; ++i) { repeaters[i].repeatWithValue(_target, _data, _value); } } /** @dev Return the list of repeaters. * @return The list of repeaters. */ function getRepeatersAddresses() external view returns(Repeater[] memory) { return repeaters; } }
* @dev Make repeaters from `_start` to `_end` (included) call `_target` with `_data`. @param _start The first repeater ID. @param _end The last repeater ID. @param _target The contract to be called by the repeaters. @param _data The data the repeaters will send to the contract./
function say(uint _start, uint _end, address _target, bytes calldata _data) external { require(msg.sender == owner); for (uint i=_start; i<=_end; ++i) { repeaters[i].repeat(_target, _data); } }
589,388
[ 1, 6464, 7666, 414, 628, 1375, 67, 1937, 68, 358, 1375, 67, 409, 68, 261, 20405, 13, 745, 1375, 67, 3299, 68, 598, 1375, 67, 892, 8338, 282, 389, 1937, 1021, 1122, 16304, 2045, 1599, 18, 282, 389, 409, 1021, 1142, 16304, 2045, 1599, 18, 282, 389, 3299, 1021, 6835, 358, 506, 2566, 635, 326, 7666, 414, 18, 282, 389, 892, 1021, 501, 326, 7666, 414, 903, 1366, 358, 326, 6835, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 12532, 12, 11890, 389, 1937, 16, 2254, 389, 409, 16, 1758, 389, 3299, 16, 1731, 745, 892, 389, 892, 13, 3903, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 3410, 1769, 203, 3639, 364, 261, 11890, 277, 33, 67, 1937, 31, 277, 32, 33, 67, 409, 31, 965, 77, 13, 288, 203, 5411, 7666, 414, 63, 77, 8009, 9374, 24899, 3299, 16, 389, 892, 1769, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/84531/0x3CC6ba057f394B00aC1fF48707d5C04DE29504C6/sources/src/token/types/TokenTypesV1.sol
@notice The founder type @param wallet The address where tokens are sent @param ownershipPct The percentage of token ownership @param vestExpiry The timestamp when vesting ends
struct Founder { address wallet; uint8 ownershipPct; uint32 vestExpiry; }
14,322,927
[ 1, 1986, 284, 465, 765, 618, 225, 9230, 1021, 1758, 1625, 2430, 854, 3271, 225, 23178, 52, 299, 1021, 11622, 434, 1147, 23178, 225, 331, 395, 14633, 1021, 2858, 1347, 331, 10100, 3930, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 1958, 478, 465, 765, 288, 203, 3639, 1758, 9230, 31, 203, 3639, 2254, 28, 23178, 52, 299, 31, 203, 3639, 2254, 1578, 331, 395, 14633, 31, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]