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
// SPDX-License-Identifier: MIT pragma solidity ^0.8.9; /* Library Imports */ import {Lib_OVMCodec} from '../../libraries/codec/Lib_OVMCodec.sol'; import {Lib_AddressResolver} from '../../libraries/resolver/Lib_AddressResolver.sol'; import {Lib_MerkleTree} from '../../libraries/utils/Lib_MerkleTree.sol'; /* Interface Imports */ import {IStateCommitmentChain} from './IStateCommitmentChain.sol'; import {ICanonicalTransactionChain} from './ICanonicalTransactionChain.sol'; import {IBondManager} from '../verification/IBondManager.sol'; import {IChainStorageContainer} from './IChainStorageContainer.sol'; /** * @title StateCommitmentChain * @dev The State Commitment Chain (SCC) contract contains a list of proposed state roots which * Proposers assert to be a result of each transaction in the Canonical Transaction Chain (CTC). * Elements here have a 1:1 correspondence with transactions in the CTC, and should be the unique * state root calculated off-chain by applying the canonical transactions one by one. * * Runtime target: EVM */ contract StateCommitmentChain is IStateCommitmentChain, Lib_AddressResolver { /************* * Constants * *************/ uint256 public FRAUD_PROOF_WINDOW; uint256 public SEQUENCER_PUBLISH_WINDOW; /*************** * Constructor * ***************/ /** * @param _libAddressManager Address of the Address Manager. */ constructor( address _libAddressManager, uint256 _fraudProofWindow, uint256 _sequencerPublishWindow ) Lib_AddressResolver(_libAddressManager) { FRAUD_PROOF_WINDOW = _fraudProofWindow; SEQUENCER_PUBLISH_WINDOW = _sequencerPublishWindow; } /******************** * Public Functions * ********************/ /** * Accesses the batch storage container. * @return Reference to the batch storage container. */ function batches() public view returns (IChainStorageContainer) { return IChainStorageContainer(resolve('ChainStorageContainer-SCC-batches')); } /** * @inheritdoc IStateCommitmentChain */ function getTotalElements() public view returns (uint256 _totalElements) { (uint40 totalElements, ) = _getBatchExtraData(); return uint256(totalElements); } /** * @inheritdoc IStateCommitmentChain */ function getTotalBatches() public view returns (uint256 _totalBatches) { return batches().length(); } /** * @inheritdoc IStateCommitmentChain */ function getLastSequencerTimestamp() public view returns (uint256 _lastSequencerTimestamp) { (, uint40 lastSequencerTimestamp) = _getBatchExtraData(); return uint256(lastSequencerTimestamp); } /** * @inheritdoc IStateCommitmentChain */ function appendStateBatch( bytes32[] memory _batch, uint256 _shouldStartAtElement ) public { // Fail fast in to make sure our batch roots aren't accidentally made fraudulent by the // publication of batches by some other user. require( _shouldStartAtElement == getTotalElements(), 'Actual batch start index does not match expected start index.' ); // Proposers must have previously staked at the BondManager require( IBondManager(resolve('BondManager')).isCollateralized(msg.sender), 'Proposer does not have enough collateral posted' ); require(_batch.length > 0, 'Cannot submit an empty state batch.'); require( getTotalElements() + _batch.length <= ICanonicalTransactionChain(resolve('CanonicalTransactionChain')) .getTotalElements(), 'Number of state roots cannot exceed the number of canonical transactions.' ); // Pass the block's timestamp and the publisher of the data // to be used in the fraud proofs _appendBatch(_batch, abi.encode(block.timestamp, msg.sender)); } /** * @inheritdoc IStateCommitmentChain */ function deleteStateBatch(Lib_OVMCodec.ChainBatchHeader memory _batchHeader) public { require( msg.sender == resolve('OVM_FraudVerifier'), 'State batches can only be deleted by the OVM_FraudVerifier.' ); require(_isValidBatchHeader(_batchHeader), 'Invalid batch header.'); require( insideFraudProofWindow(_batchHeader), 'State batches can only be deleted within the fraud proof window.' ); _deleteBatch(_batchHeader); } /** * @inheritdoc IStateCommitmentChain */ function verifyStateCommitment( bytes32 _element, Lib_OVMCodec.ChainBatchHeader memory _batchHeader, Lib_OVMCodec.ChainInclusionProof memory _proof ) public view returns (bool) { require(_isValidBatchHeader(_batchHeader), 'Invalid batch header.'); require( Lib_MerkleTree.verify( _batchHeader.batchRoot, _element, _proof.index, _proof.siblings, _batchHeader.batchSize ), 'Invalid inclusion proof.' ); return true; } /** * @inheritdoc IStateCommitmentChain */ function insideFraudProofWindow( Lib_OVMCodec.ChainBatchHeader memory _batchHeader ) public view returns (bool _inside) { (uint256 timestamp, ) = abi.decode( _batchHeader.extraData, (uint256, address) ); require(timestamp != 0, 'Batch header timestamp cannot be zero'); return (timestamp + FRAUD_PROOF_WINDOW) > block.timestamp; } /********************** * Internal Functions * **********************/ /** * Parses the batch context from the extra data. * @return Total number of elements submitted. * @return Timestamp of the last batch submitted by the sequencer. */ function _getBatchExtraData() internal view returns (uint40, uint40) { bytes27 extraData = batches().getGlobalMetadata(); // solhint-disable max-line-length uint40 totalElements; uint40 lastSequencerTimestamp; assembly { extraData := shr(40, extraData) totalElements := and( extraData, 0x000000000000000000000000000000000000000000000000000000FFFFFFFFFF ) lastSequencerTimestamp := shr( 40, and( extraData, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000000000 ) ) } // solhint-enable max-line-length return (totalElements, lastSequencerTimestamp); } /** * Encodes the batch context for the extra data. * @param _totalElements Total number of elements submitted. * @param _lastSequencerTimestamp Timestamp of the last batch submitted by the sequencer. * @return Encoded batch context. */ function _makeBatchExtraData( uint40 _totalElements, uint40 _lastSequencerTimestamp ) internal pure returns (bytes27) { bytes27 extraData; assembly { extraData := _totalElements extraData := or(extraData, shl(40, _lastSequencerTimestamp)) extraData := shl(40, extraData) } return extraData; } /** * Appends a batch to the chain. * @param _batch Elements within the batch. * @param _extraData Any extra data to append to the batch. */ function _appendBatch(bytes32[] memory _batch, bytes memory _extraData) internal { address sequencer = resolve('OVM_Proposer'); ( uint40 totalElements, uint40 lastSequencerTimestamp ) = _getBatchExtraData(); if (msg.sender == sequencer) { lastSequencerTimestamp = uint40(block.timestamp); } else { // We keep track of the last batch submitted by the sequencer so there's a window in // which only the sequencer can publish state roots. A window like this just reduces // the chance of "system breaking" state roots being published while we're still in // testing mode. This window should be removed or significantly reduced in the future. require( lastSequencerTimestamp + SEQUENCER_PUBLISH_WINDOW < block.timestamp, 'Cannot publish state roots within the sequencer publication window.' ); } // For efficiency reasons getMerkleRoot modifies the `_batch` argument in place // while calculating the root hash therefore any arguments passed to it must not // be used again afterwards Lib_OVMCodec.ChainBatchHeader memory batchHeader = Lib_OVMCodec .ChainBatchHeader({ batchIndex: getTotalBatches(), batchRoot: Lib_MerkleTree.getMerkleRoot(_batch), batchSize: _batch.length, prevTotalElements: totalElements, extraData: _extraData }); emit StateBatchAppended( batchHeader.batchIndex, batchHeader.batchRoot, batchHeader.batchSize, batchHeader.prevTotalElements, batchHeader.extraData ); batches().push( Lib_OVMCodec.hashBatchHeader(batchHeader), _makeBatchExtraData( uint40(batchHeader.prevTotalElements + batchHeader.batchSize), lastSequencerTimestamp ) ); } /** * Removes a batch and all subsequent batches from the chain. * @param _batchHeader Header of the batch to remove. */ function _deleteBatch(Lib_OVMCodec.ChainBatchHeader memory _batchHeader) internal { require( _batchHeader.batchIndex < batches().length(), 'Invalid batch index.' ); require(_isValidBatchHeader(_batchHeader), 'Invalid batch header.'); batches().deleteElementsAfterInclusive( _batchHeader.batchIndex, _makeBatchExtraData(uint40(_batchHeader.prevTotalElements), 0) ); emit StateBatchDeleted(_batchHeader.batchIndex, _batchHeader.batchRoot); } /** * Checks that a batch header matches the stored hash for the given index. * @param _batchHeader Batch header to validate. * @return Whether or not the header matches the stored one. */ function _isValidBatchHeader( Lib_OVMCodec.ChainBatchHeader memory _batchHeader ) internal view returns (bool) { return Lib_OVMCodec.hashBatchHeader(_batchHeader) == batches().get(_batchHeader.batchIndex); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.9; /* Library Imports */ import {Lib_RLPReader} from '../rlp/Lib_RLPReader.sol'; import {Lib_RLPWriter} from '../rlp/Lib_RLPWriter.sol'; import {Lib_BytesUtils} from '../utils/Lib_BytesUtils.sol'; import {Lib_Bytes32Utils} from '../utils/Lib_Bytes32Utils.sol'; /** * @title Lib_OVMCodec */ library Lib_OVMCodec { /********* * Enums * *********/ enum QueueOrigin { SEQUENCER_QUEUE, L1TOL2_QUEUE } /*********** * Structs * ***********/ struct EVMAccount { uint256 nonce; uint256 balance; bytes32 storageRoot; bytes32 codeHash; } struct ChainBatchHeader { uint256 batchIndex; bytes32 batchRoot; uint256 batchSize; uint256 prevTotalElements; bytes extraData; } struct ChainInclusionProof { uint256 index; bytes32[] siblings; } struct Transaction { uint256 timestamp; uint256 blockNumber; QueueOrigin l1QueueOrigin; address l1TxOrigin; address entrypoint; uint256 gasLimit; bytes data; } struct TransactionChainElement { bool isSequenced; uint256 queueIndex; // QUEUED TX ONLY uint256 timestamp; // SEQUENCER TX ONLY uint256 blockNumber; // SEQUENCER TX ONLY bytes txData; // SEQUENCER TX ONLY } struct QueueElement { bytes32 transactionHash; uint40 timestamp; uint40 blockNumber; } /********************** * Internal Functions * **********************/ /** * Encodes a standard OVM transaction. * @param _transaction OVM transaction to encode. * @return Encoded transaction bytes. */ function encodeTransaction(Transaction memory _transaction) internal pure returns (bytes memory) { return abi.encodePacked( _transaction.timestamp, _transaction.blockNumber, _transaction.l1QueueOrigin, _transaction.l1TxOrigin, _transaction.entrypoint, _transaction.gasLimit, _transaction.data ); } /** * Hashes a standard OVM transaction. * @param _transaction OVM transaction to encode. * @return Hashed transaction */ function hashTransaction(Transaction memory _transaction) internal pure returns (bytes32) { return keccak256(encodeTransaction(_transaction)); } /** * @notice Decodes an RLP-encoded account state into a useful struct. * @param _encoded RLP-encoded account state. * @return Account state struct. */ function decodeEVMAccount(bytes memory _encoded) internal pure returns (EVMAccount memory) { Lib_RLPReader.RLPItem[] memory accountState = Lib_RLPReader.readList( _encoded ); return EVMAccount({ nonce: Lib_RLPReader.readUint256(accountState[0]), balance: Lib_RLPReader.readUint256(accountState[1]), storageRoot: Lib_RLPReader.readBytes32(accountState[2]), codeHash: Lib_RLPReader.readBytes32(accountState[3]) }); } /** * Calculates a hash for a given batch header. * @param _batchHeader Header to hash. * @return Hash of the header. */ function hashBatchHeader(Lib_OVMCodec.ChainBatchHeader memory _batchHeader) internal pure returns (bytes32) { return keccak256( abi.encode( _batchHeader.batchRoot, _batchHeader.batchSize, _batchHeader.prevTotalElements, _batchHeader.extraData ) ); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.9; /* Library Imports */ import {Lib_AddressManager} from './Lib_AddressManager.sol'; /** * @title Lib_AddressResolver */ abstract contract Lib_AddressResolver { /************* * Variables * *************/ Lib_AddressManager public libAddressManager; /*************** * Constructor * ***************/ /** * @param _libAddressManager Address of the Lib_AddressManager. */ constructor(address _libAddressManager) { libAddressManager = Lib_AddressManager(_libAddressManager); } /******************** * Public Functions * ********************/ /** * Resolves the address associated with a given name. * @param _name Name to resolve an address for. * @return Address associated with the given name. */ function resolve(string memory _name) public view returns (address) { return libAddressManager.getAddress(_name); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.9; /** * @title Lib_MerkleTree * @author River Keefer */ library Lib_MerkleTree { /********************** * Internal Functions * **********************/ /** * Calculates a merkle root for a list of 32-byte leaf hashes. WARNING: If the number * of leaves passed in is not a power of two, it pads out the tree with zero hashes. * If you do not know the original length of elements for the tree you are verifying, then * this may allow empty leaves past _elements.length to pass a verification check down the line. * Note that the _elements argument is modified, therefore it must not be used again afterwards * @param _elements Array of hashes from which to generate a merkle root. * @return Merkle root of the leaves, with zero hashes for non-powers-of-two (see above). */ function getMerkleRoot(bytes32[] memory _elements) internal pure returns (bytes32) { require( _elements.length > 0, 'Lib_MerkleTree: Must provide at least one leaf hash.' ); if (_elements.length == 1) { return _elements[0]; } uint256[16] memory defaults = [ 0x290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e563, 0x633dc4d7da7256660a892f8f1604a44b5432649cc8ec5cb3ced4c4e6ac94dd1d, 0x890740a8eb06ce9be422cb8da5cdafc2b58c0a5e24036c578de2a433c828ff7d, 0x3b8ec09e026fdc305365dfc94e189a81b38c7597b3d941c279f042e8206e0bd8, 0xecd50eee38e386bd62be9bedb990706951b65fe053bd9d8a521af753d139e2da, 0xdefff6d330bb5403f63b14f33b578274160de3a50df4efecf0e0db73bcdd3da5, 0x617bdd11f7c0a11f49db22f629387a12da7596f9d1704d7465177c63d88ec7d7, 0x292c23a9aa1d8bea7e2435e555a4a60e379a5a35f3f452bae60121073fb6eead, 0xe1cea92ed99acdcb045a6726b2f87107e8a61620a232cf4d7d5b5766b3952e10, 0x7ad66c0a68c72cb89e4fb4303841966e4062a76ab97451e3b9fb526a5ceb7f82, 0xe026cc5a4aed3c22a58cbd3d2ac754c9352c5436f638042dca99034e83636516, 0x3d04cffd8b46a874edf5cfae63077de85f849a660426697b06a829c70dd1409c, 0xad676aa337a485e4728a0b240d92b3ef7b3c372d06d189322bfd5f61f1e7203e, 0xa2fca4a49658f9fab7aa63289c91b7c7b6c832a6d0e69334ff5b0a3483d09dab, 0x4ebfd9cd7bca2505f7bef59cc1c12ecc708fff26ae4af19abe852afe9e20c862, 0x2def10d13dd169f550f578bda343d9717a138562e0093b380a1120789d53cf10 ]; // Reserve memory space for our hashes. bytes memory buf = new bytes(64); // We'll need to keep track of left and right siblings. bytes32 leftSibling; bytes32 rightSibling; // Number of non-empty nodes at the current depth. uint256 rowSize = _elements.length; // Current depth, counting from 0 at the leaves uint256 depth = 0; // Common sub-expressions uint256 halfRowSize; // rowSize / 2 bool rowSizeIsOdd; // rowSize % 2 == 1 while (rowSize > 1) { halfRowSize = rowSize / 2; rowSizeIsOdd = rowSize % 2 == 1; for (uint256 i = 0; i < halfRowSize; i++) { leftSibling = _elements[(2 * i)]; rightSibling = _elements[(2 * i) + 1]; assembly { mstore(add(buf, 32), leftSibling) mstore(add(buf, 64), rightSibling) } _elements[i] = keccak256(buf); } if (rowSizeIsOdd) { leftSibling = _elements[rowSize - 1]; rightSibling = bytes32(defaults[depth]); assembly { mstore(add(buf, 32), leftSibling) mstore(add(buf, 64), rightSibling) } _elements[halfRowSize] = keccak256(buf); } rowSize = halfRowSize + (rowSizeIsOdd ? 1 : 0); depth++; } return _elements[0]; } /** * Verifies a merkle branch for the given leaf hash. Assumes the original length * of leaves generated is a known, correct input, and does not return true for indices * extending past that index (even if _siblings would be otherwise valid.) * @param _root The Merkle root to verify against. * @param _leaf The leaf hash to verify inclusion of. * @param _index The index in the tree of this leaf. * @param _siblings Array of sibline nodes in the inclusion proof, starting from depth 0 * (bottom of the tree). * @param _totalLeaves The total number of leaves originally passed into. * @return Whether or not the merkle branch and leaf passes verification. */ function verify( bytes32 _root, bytes32 _leaf, uint256 _index, bytes32[] memory _siblings, uint256 _totalLeaves ) internal pure returns (bool) { require( _totalLeaves > 0, 'Lib_MerkleTree: Total leaves must be greater than zero.' ); require(_index < _totalLeaves, 'Lib_MerkleTree: Index out of bounds.'); require( _siblings.length == _ceilLog2(_totalLeaves), 'Lib_MerkleTree: Total siblings does not correctly correspond to total leaves.' ); bytes32 computedRoot = _leaf; for (uint256 i = 0; i < _siblings.length; i++) { if ((_index & 1) == 1) { computedRoot = keccak256(abi.encodePacked(_siblings[i], computedRoot)); } else { computedRoot = keccak256(abi.encodePacked(computedRoot, _siblings[i])); } _index >>= 1; } return _root == computedRoot; } /********************* * Private Functions * *********************/ /** * Calculates the integer ceiling of the log base 2 of an input. * @param _in Unsigned input to calculate the log. * @return ceil(log_base_2(_in)) */ function _ceilLog2(uint256 _in) private pure returns (uint256) { require(_in > 0, 'Lib_MerkleTree: Cannot compute ceil(log_2) of 0.'); if (_in == 1) { return 0; } // Find the highest set bit (will be floor(log_2)). // Borrowed with <3 from https://github.com/ethereum/solidity-examples uint256 val = _in; uint256 highest = 0; for (uint256 i = 128; i >= 1; i >>= 1) { if (val & (((uint256(1) << i) - 1) << i) != 0) { highest += i; val >>= i; } } // Increment by one if this is not a perfect logarithm. if ((uint256(1) << highest) != _in) { highest += 1; } return highest; } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.9.0; /* Library Imports */ import {Lib_OVMCodec} from '../../libraries/codec/Lib_OVMCodec.sol'; /** * @title IStateCommitmentChain */ interface IStateCommitmentChain { /********** * Events * **********/ event StateBatchAppended( uint256 indexed _batchIndex, bytes32 _batchRoot, uint256 _batchSize, uint256 _prevTotalElements, bytes _extraData ); event StateBatchDeleted(uint256 indexed _batchIndex, bytes32 _batchRoot); /******************** * Public Functions * ********************/ /** * Retrieves the total number of elements submitted. * @return _totalElements Total submitted elements. */ function getTotalElements() external view returns (uint256 _totalElements); /** * Retrieves the total number of batches submitted. * @return _totalBatches Total submitted batches. */ function getTotalBatches() external view returns (uint256 _totalBatches); /** * Retrieves the timestamp of the last batch submitted by the sequencer. * @return _lastSequencerTimestamp Last sequencer batch timestamp. */ function getLastSequencerTimestamp() external view returns (uint256 _lastSequencerTimestamp); /** * Appends a batch of state roots to the chain. * @param _batch Batch of state roots. * @param _shouldStartAtElement Index of the element at which this batch should start. */ function appendStateBatch( bytes32[] calldata _batch, uint256 _shouldStartAtElement ) external; /** * Deletes all state roots after (and including) a given batch. * @param _batchHeader Header of the batch to start deleting from. */ function deleteStateBatch(Lib_OVMCodec.ChainBatchHeader memory _batchHeader) external; /** * Verifies a batch inclusion proof. * @param _element Hash of the element to verify a proof for. * @param _batchHeader Header of the batch in which the element was included. * @param _proof Merkle inclusion proof for the element. */ function verifyStateCommitment( bytes32 _element, Lib_OVMCodec.ChainBatchHeader memory _batchHeader, Lib_OVMCodec.ChainInclusionProof memory _proof ) external view returns (bool _verified); /** * Checks whether a given batch is still inside its fraud proof window. * @param _batchHeader Header of the batch to check. * @return _inside Whether or not the batch is inside the fraud proof window. */ function insideFraudProofWindow( Lib_OVMCodec.ChainBatchHeader memory _batchHeader ) external view returns (bool _inside); } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.9.0; /* Library Imports */ import {Lib_OVMCodec} from '../../libraries/codec/Lib_OVMCodec.sol'; /* Interface Imports */ import {IChainStorageContainer} from './IChainStorageContainer.sol'; /** * @title ICanonicalTransactionChain */ interface ICanonicalTransactionChain { /********** * Events * **********/ event L2GasParamsUpdated( uint256 l2GasDiscountDivisor, uint256 enqueueGasCost, uint256 enqueueL2GasPrepaid ); event TransactionEnqueued( address indexed _l1TxOrigin, address indexed _target, uint256 _gasLimit, bytes _data, uint256 indexed _queueIndex, uint256 _timestamp ); event QueueBatchAppended( uint256 _startingQueueIndex, uint256 _numQueueElements, uint256 _totalElements ); event SequencerBatchAppended( uint256 _startingQueueIndex, uint256 _numQueueElements, uint256 _totalElements ); event TransactionBatchAppended( uint256 indexed _batchIndex, bytes32 _batchRoot, uint256 _batchSize, uint256 _prevTotalElements, bytes _extraData ); /*********** * Structs * ***********/ struct BatchContext { uint256 numSequencedTransactions; uint256 numSubsequentQueueTransactions; uint256 timestamp; uint256 blockNumber; } /******************************* * Authorized Setter Functions * *******************************/ /** * Allows the Burn Admin to update the parameters which determine the amount of gas to burn. * The value of enqueueL2GasPrepaid is immediately updated as well. */ function setGasParams(uint256 _l2GasDiscountDivisor, uint256 _enqueueGasCost) external; /******************** * Public Functions * ********************/ /** * Accesses the batch storage container. * @return Reference to the batch storage container. */ function batches() external view returns (IChainStorageContainer); /** * Accesses the queue storage container. * @return Reference to the queue storage container. */ function queue() external view returns (IChainStorageContainer); /** * Retrieves the total number of elements submitted. * @return _totalElements Total submitted elements. */ function getTotalElements() external view returns (uint256 _totalElements); /** * Retrieves the total number of batches submitted. * @return _totalBatches Total submitted batches. */ function getTotalBatches() external view returns (uint256 _totalBatches); /** * Returns the index of the next element to be enqueued. * @return Index for the next queue element. */ function getNextQueueIndex() external view returns (uint40); /** * Gets the queue element at a particular index. * @param _index Index of the queue element to access. * @return _element Queue element at the given index. */ function getQueueElement(uint256 _index) external view returns (Lib_OVMCodec.QueueElement memory _element); /** * Returns the timestamp of the last transaction. * @return Timestamp for the last transaction. */ function getLastTimestamp() external view returns (uint40); /** * Returns the blocknumber of the last transaction. * @return Blocknumber for the last transaction. */ function getLastBlockNumber() external view returns (uint40); /** * Get the number of queue elements which have not yet been included. * @return Number of pending queue elements. */ function getNumPendingQueueElements() external view returns (uint40); /** * Retrieves the length of the queue, including * both pending and canonical transactions. * @return Length of the queue. */ function getQueueLength() external view returns (uint40); /** * Adds a transaction to the queue. * @param _target Target contract to send the transaction to. * @param _gasLimit Gas limit for the given transaction. * @param _data Transaction data. */ function enqueue( address _target, uint256 _gasLimit, bytes memory _data ) external; /** * Allows the sequencer to append a batch of transactions. * @dev This function uses a custom encoding scheme for efficiency reasons. * .param _shouldStartAtElement Specific batch we expect to start appending to. * .param _totalElementsToAppend Total number of batch elements we expect to append. * .param _contexts Array of batch contexts. * .param _transactionDataFields Array of raw transaction data. */ function appendSequencerBatch( // uint40 _shouldStartAtElement, // uint24 _totalElementsToAppend, // BatchContext[] _contexts, // bytes[] _transactionDataFields ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.9; /** * @title IBondManager */ interface IBondManager { /******************** * Public Functions * ********************/ function isCollateralized(address _who) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.9.0; /** * @title IChainStorageContainer */ interface IChainStorageContainer { /******************** * Public Functions * ********************/ /** * Sets the container's global metadata field. We're using `bytes27` here because we use five * bytes to maintain the length of the underlying data structure, meaning we have an extra * 27 bytes to store arbitrary data. * @param _globalMetadata New global metadata to set. */ function setGlobalMetadata(bytes27 _globalMetadata) external; /** * Retrieves the container's global metadata field. * @return Container global metadata field. */ function getGlobalMetadata() external view returns (bytes27); /** * Retrieves the number of objects stored in the container. * @return Number of objects in the container. */ function length() external view returns (uint256); /** * Pushes an object into the container. * @param _object A 32 byte value to insert into the container. */ function push(bytes32 _object) external; /** * Pushes an object into the container. Function allows setting the global metadata since * we'll need to touch the "length" storage slot anyway, which also contains the global * metadata (it's an optimization). * @param _object A 32 byte value to insert into the container. * @param _globalMetadata New global metadata for the container. */ function push(bytes32 _object, bytes27 _globalMetadata) external; /** * Retrieves an object from the container. * @param _index Index of the particular object to access. * @return 32 byte object value. */ function get(uint256 _index) external view returns (bytes32); /** * Removes all objects after and including a given index. * @param _index Object index to delete from. */ function deleteElementsAfterInclusive(uint256 _index) external; /** * Removes all objects after and including a given index. Also allows setting the global * metadata field. * @param _index Object index to delete from. * @param _globalMetadata New global metadata for the container. */ function deleteElementsAfterInclusive(uint256 _index, bytes27 _globalMetadata) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.9; /** * @title Lib_RLPReader * @dev Adapted from "RLPReader" by Hamdi Allam ([email protected]). */ library Lib_RLPReader { /************* * Constants * *************/ uint256 internal constant MAX_LIST_LENGTH = 32; /********* * Enums * *********/ enum RLPItemType { DATA_ITEM, LIST_ITEM } /*********** * Structs * ***********/ struct RLPItem { uint256 length; uint256 ptr; } /********************** * Internal Functions * **********************/ /** * Converts bytes to a reference to memory position and length. * @param _in Input bytes to convert. * @return Output memory reference. */ function toRLPItem(bytes memory _in) internal pure returns (RLPItem memory) { uint256 ptr; assembly { ptr := add(_in, 32) } return RLPItem({length: _in.length, ptr: ptr}); } /** * Reads an RLP list value into a list of RLP items. * @param _in RLP list value. * @return Decoded RLP list items. */ function readList(RLPItem memory _in) internal pure returns (RLPItem[] memory) { (uint256 listOffset, , RLPItemType itemType) = _decodeLength(_in); require(itemType == RLPItemType.LIST_ITEM, 'Invalid RLP list value.'); // Solidity in-memory arrays can't be increased in size, but *can* be decreased in size by // writing to the length. Since we can't know the number of RLP items without looping over // the entire input, we'd have to loop twice to accurately size this array. It's easier to // simply set a reasonable maximum list length and decrease the size before we finish. RLPItem[] memory out = new RLPItem[](MAX_LIST_LENGTH); uint256 itemCount = 0; uint256 offset = listOffset; while (offset < _in.length) { require( itemCount < MAX_LIST_LENGTH, 'Provided RLP list exceeds max list length.' ); (uint256 itemOffset, uint256 itemLength, ) = _decodeLength( RLPItem({length: _in.length - offset, ptr: _in.ptr + offset}) ); out[itemCount] = RLPItem({ length: itemLength + itemOffset, ptr: _in.ptr + offset }); itemCount += 1; offset += itemOffset + itemLength; } // Decrease the array size to match the actual item count. assembly { mstore(out, itemCount) } return out; } /** * Reads an RLP list value into a list of RLP items. * @param _in RLP list value. * @return Decoded RLP list items. */ function readList(bytes memory _in) internal pure returns (RLPItem[] memory) { return readList(toRLPItem(_in)); } /** * Reads an RLP bytes value into bytes. * @param _in RLP bytes value. * @return Decoded bytes. */ function readBytes(RLPItem memory _in) internal pure returns (bytes memory) { ( uint256 itemOffset, uint256 itemLength, RLPItemType itemType ) = _decodeLength(_in); require(itemType == RLPItemType.DATA_ITEM, 'Invalid RLP bytes value.'); return _copy(_in.ptr, itemOffset, itemLength); } /** * Reads an RLP bytes value into bytes. * @param _in RLP bytes value. * @return Decoded bytes. */ function readBytes(bytes memory _in) internal pure returns (bytes memory) { return readBytes(toRLPItem(_in)); } /** * Reads an RLP string value into a string. * @param _in RLP string value. * @return Decoded string. */ function readString(RLPItem memory _in) internal pure returns (string memory) { return string(readBytes(_in)); } /** * Reads an RLP string value into a string. * @param _in RLP string value. * @return Decoded string. */ function readString(bytes memory _in) internal pure returns (string memory) { return readString(toRLPItem(_in)); } /** * Reads an RLP bytes32 value into a bytes32. * @param _in RLP bytes32 value. * @return Decoded bytes32. */ function readBytes32(RLPItem memory _in) internal pure returns (bytes32) { require(_in.length <= 33, 'Invalid RLP bytes32 value.'); ( uint256 itemOffset, uint256 itemLength, RLPItemType itemType ) = _decodeLength(_in); require(itemType == RLPItemType.DATA_ITEM, 'Invalid RLP bytes32 value.'); uint256 ptr = _in.ptr + itemOffset; bytes32 out; assembly { out := mload(ptr) // Shift the bytes over to match the item size. if lt(itemLength, 32) { out := div(out, exp(256, sub(32, itemLength))) } } return out; } /** * Reads an RLP bytes32 value into a bytes32. * @param _in RLP bytes32 value. * @return Decoded bytes32. */ function readBytes32(bytes memory _in) internal pure returns (bytes32) { return readBytes32(toRLPItem(_in)); } /** * Reads an RLP uint256 value into a uint256. * @param _in RLP uint256 value. * @return Decoded uint256. */ function readUint256(RLPItem memory _in) internal pure returns (uint256) { return uint256(readBytes32(_in)); } /** * Reads an RLP uint256 value into a uint256. * @param _in RLP uint256 value. * @return Decoded uint256. */ function readUint256(bytes memory _in) internal pure returns (uint256) { return readUint256(toRLPItem(_in)); } /** * Reads an RLP bool value into a bool. * @param _in RLP bool value. * @return Decoded bool. */ function readBool(RLPItem memory _in) internal pure returns (bool) { require(_in.length == 1, 'Invalid RLP boolean value.'); uint256 ptr = _in.ptr; uint256 out; assembly { out := byte(0, mload(ptr)) } require( out == 0 || out == 1, 'Lib_RLPReader: Invalid RLP boolean value, must be 0 or 1' ); return out != 0; } /** * Reads an RLP bool value into a bool. * @param _in RLP bool value. * @return Decoded bool. */ function readBool(bytes memory _in) internal pure returns (bool) { return readBool(toRLPItem(_in)); } /** * Reads an RLP address value into a address. * @param _in RLP address value. * @return Decoded address. */ function readAddress(RLPItem memory _in) internal pure returns (address) { if (_in.length == 1) { return address(0); } require(_in.length == 21, 'Invalid RLP address value.'); return address(uint160(readUint256(_in))); } /** * Reads an RLP address value into a address. * @param _in RLP address value. * @return Decoded address. */ function readAddress(bytes memory _in) internal pure returns (address) { return readAddress(toRLPItem(_in)); } /** * Reads the raw bytes of an RLP item. * @param _in RLP item to read. * @return Raw RLP bytes. */ function readRawBytes(RLPItem memory _in) internal pure returns (bytes memory) { return _copy(_in); } /********************* * Private Functions * *********************/ /** * Decodes the length of an RLP item. * @param _in RLP item to decode. * @return Offset of the encoded data. * @return Length of the encoded data. * @return RLP item type (LIST_ITEM or DATA_ITEM). */ function _decodeLength(RLPItem memory _in) private pure returns ( uint256, uint256, RLPItemType ) { require(_in.length > 0, 'RLP item cannot be null.'); uint256 ptr = _in.ptr; uint256 prefix; assembly { prefix := byte(0, mload(ptr)) } if (prefix <= 0x7f) { // Single byte. return (0, 1, RLPItemType.DATA_ITEM); } else if (prefix <= 0xb7) { // Short string. uint256 strLen = prefix - 0x80; require(_in.length > strLen, 'Invalid RLP short string.'); return (1, strLen, RLPItemType.DATA_ITEM); } else if (prefix <= 0xbf) { // Long string. uint256 lenOfStrLen = prefix - 0xb7; require(_in.length > lenOfStrLen, 'Invalid RLP long string length.'); uint256 strLen; assembly { // Pick out the string length. strLen := div(mload(add(ptr, 1)), exp(256, sub(32, lenOfStrLen))) } require(_in.length > lenOfStrLen + strLen, 'Invalid RLP long string.'); return (1 + lenOfStrLen, strLen, RLPItemType.DATA_ITEM); } else if (prefix <= 0xf7) { // Short list. uint256 listLen = prefix - 0xc0; require(_in.length > listLen, 'Invalid RLP short list.'); return (1, listLen, RLPItemType.LIST_ITEM); } else { // Long list. uint256 lenOfListLen = prefix - 0xf7; require(_in.length > lenOfListLen, 'Invalid RLP long list length.'); uint256 listLen; assembly { // Pick out the list length. listLen := div(mload(add(ptr, 1)), exp(256, sub(32, lenOfListLen))) } require(_in.length > lenOfListLen + listLen, 'Invalid RLP long list.'); return (1 + lenOfListLen, listLen, RLPItemType.LIST_ITEM); } } /** * Copies the bytes from a memory location. * @param _src Pointer to the location to read from. * @param _offset Offset to start reading from. * @param _length Number of bytes to read. * @return Copied bytes. */ function _copy( uint256 _src, uint256 _offset, uint256 _length ) private pure returns (bytes memory) { bytes memory out = new bytes(_length); if (out.length == 0) { return out; } uint256 src = _src + _offset; uint256 dest; assembly { dest := add(out, 32) } // Copy over as many complete words as we can. for (uint256 i = 0; i < _length / 32; i++) { assembly { mstore(dest, mload(src)) } src += 32; dest += 32; } // Pick out the remaining bytes. uint256 mask; unchecked { mask = 256**(32 - (_length % 32)) - 1; } assembly { mstore(dest, or(and(mload(src), not(mask)), and(mload(dest), mask))) } return out; } /** * Copies an RLP item into bytes. * @param _in RLP item to copy. * @return Copied bytes. */ function _copy(RLPItem memory _in) private pure returns (bytes memory) { return _copy(_in.ptr, 0, _in.length); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.9; /** * @title Lib_RLPWriter * @author Bakaoh (with modifications) */ library Lib_RLPWriter { /********************** * Internal Functions * **********************/ /** * RLP encodes a byte string. * @param _in The byte string to encode. * @return The RLP encoded string in bytes. */ function writeBytes(bytes memory _in) internal pure returns (bytes memory) { bytes memory encoded; if (_in.length == 1 && uint8(_in[0]) < 128) { encoded = _in; } else { encoded = abi.encodePacked(_writeLength(_in.length, 128), _in); } return encoded; } /** * RLP encodes a list of RLP encoded byte byte strings. * @param _in The list of RLP encoded byte strings. * @return The RLP encoded list of items in bytes. */ function writeList(bytes[] memory _in) internal pure returns (bytes memory) { bytes memory list = _flatten(_in); return abi.encodePacked(_writeLength(list.length, 192), list); } /** * RLP encodes a string. * @param _in The string to encode. * @return The RLP encoded string in bytes. */ function writeString(string memory _in) internal pure returns (bytes memory) { return writeBytes(bytes(_in)); } /** * RLP encodes an address. * @param _in The address to encode. * @return The RLP encoded address in bytes. */ function writeAddress(address _in) internal pure returns (bytes memory) { return writeBytes(abi.encodePacked(_in)); } /** * RLP encodes a uint. * @param _in The uint256 to encode. * @return The RLP encoded uint256 in bytes. */ function writeUint(uint256 _in) internal pure returns (bytes memory) { return writeBytes(_toBinary(_in)); } /** * RLP encodes a bool. * @param _in The bool to encode. * @return The RLP encoded bool in bytes. */ function writeBool(bool _in) internal pure returns (bytes memory) { bytes memory encoded = new bytes(1); encoded[0] = (_in ? bytes1(0x01) : bytes1(0x80)); return encoded; } /********************* * Private Functions * *********************/ /** * Encode the first byte, followed by the `len` in binary form if `length` is more than 55. * @param _len The length of the string or the payload. * @param _offset 128 if item is string, 192 if item is list. * @return RLP encoded bytes. */ function _writeLength(uint256 _len, uint256 _offset) private pure returns (bytes memory) { bytes memory encoded; if (_len < 56) { encoded = new bytes(1); encoded[0] = bytes1(uint8(_len) + uint8(_offset)); } else { uint256 lenLen; uint256 i = 1; while (_len / i != 0) { lenLen++; i *= 256; } encoded = new bytes(lenLen + 1); encoded[0] = bytes1(uint8(lenLen) + uint8(_offset) + 55); for (i = 1; i <= lenLen; i++) { encoded[i] = bytes1(uint8((_len / (256**(lenLen - i))) % 256)); } } return encoded; } /** * Encode integer in big endian binary form with no leading zeroes. * @notice TODO: This should be optimized with assembly to save gas costs. * @param _x The integer to encode. * @return RLP encoded bytes. */ function _toBinary(uint256 _x) private pure returns (bytes memory) { bytes memory b = abi.encodePacked(_x); uint256 i = 0; for (; i < 32; i++) { if (b[i] != 0) { break; } } bytes memory res = new bytes(32 - i); for (uint256 j = 0; j < res.length; j++) { res[j] = b[i++]; } return res; } /** * Copies a piece of memory to another location. * @notice From: https://github.com/Arachnid/solidity-stringutils/blob/master/src/strings.sol. * @param _dest Destination location. * @param _src Source location. * @param _len Length of memory to copy. */ function _memcpy( uint256 _dest, uint256 _src, uint256 _len ) private pure { uint256 dest = _dest; uint256 src = _src; uint256 len = _len; for (; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } uint256 mask; unchecked { mask = 256**(32 - len) - 1; } assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } } /** * Flattens a list of byte strings into one byte string. * @notice From: https://github.com/sammayo/solidity-rlp-encoder/blob/master/RLPEncode.sol. * @param _list List of byte strings to flatten. * @return The flattened byte string. */ function _flatten(bytes[] memory _list) private pure returns (bytes memory) { if (_list.length == 0) { return new bytes(0); } uint256 len; uint256 i = 0; for (; i < _list.length; i++) { len += _list[i].length; } bytes memory flattened = new bytes(len); uint256 flattenedPtr; assembly { flattenedPtr := add(flattened, 0x20) } for (i = 0; i < _list.length; i++) { bytes memory item = _list[i]; uint256 listPtr; assembly { listPtr := add(item, 0x20) } _memcpy(flattenedPtr, listPtr, item.length); flattenedPtr += _list[i].length; } return flattened; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.9; /** * @title Lib_BytesUtils */ library Lib_BytesUtils { /********************** * Internal Functions * **********************/ function slice( bytes memory _bytes, uint256 _start, uint256 _length ) internal pure returns (bytes memory) { require(_length + 31 >= _length, 'slice_overflow'); require(_start + _length >= _start, 'slice_overflow'); require(_bytes.length >= _start + _length, 'slice_outOfBounds'); bytes memory tempBytes; assembly { switch iszero(_length) case 0 { // Get a location of some free memory and store it in tempBytes as // Solidity does for memory variables. tempBytes := mload(0x40) // The first word of the slice result is potentially a partial // word read from the original array. To read it, we calculate // the length of that partial word and start copying that many // bytes into the array. The first word we copy will start with // data we don't care about, but the last `lengthmod` bytes will // land at the beginning of the contents of the new array. When // we're done copying, we overwrite the full first word with // the actual length of the slice. let lengthmod := and(_length, 31) // The multiplication in the next line is necessary // because when slicing multiples of 32 bytes (lengthmod == 0) // the following copy loop was copying the origin's length // and then ending prematurely not copying everything it should. let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod))) let end := add(mc, _length) for { // The multiplication in the next line has the same exact purpose // as the one above. let cc := add( add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start ) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } mstore(tempBytes, _length) //update free-memory pointer //allocating the array padded to 32 bytes like the compiler does now mstore(0x40, and(add(mc, 31), not(31))) } //if we want a zero-length slice let's just return a zero-length array default { tempBytes := mload(0x40) //zero out the 32 bytes slice we are about to return //we need to do it because Solidity does not garbage collect mstore(tempBytes, 0) mstore(0x40, add(tempBytes, 0x20)) } } return tempBytes; } function slice(bytes memory _bytes, uint256 _start) internal pure returns (bytes memory) { if (_start >= _bytes.length) { return bytes(''); } return slice(_bytes, _start, _bytes.length - _start); } function toBytes32(bytes memory _bytes) internal pure returns (bytes32) { if (_bytes.length < 32) { bytes32 ret; assembly { ret := mload(add(_bytes, 32)) } return ret; } return abi.decode(_bytes, (bytes32)); // will truncate if input length > 32 bytes } function toUint256(bytes memory _bytes) internal pure returns (uint256) { return uint256(toBytes32(_bytes)); } function toNibbles(bytes memory _bytes) internal pure returns (bytes memory) { bytes memory nibbles = new bytes(_bytes.length * 2); for (uint256 i = 0; i < _bytes.length; i++) { nibbles[i * 2] = _bytes[i] >> 4; nibbles[i * 2 + 1] = bytes1(uint8(_bytes[i]) % 16); } return nibbles; } function fromNibbles(bytes memory _bytes) internal pure returns (bytes memory) { bytes memory ret = new bytes(_bytes.length / 2); for (uint256 i = 0; i < ret.length; i++) { ret[i] = (_bytes[i * 2] << 4) | (_bytes[i * 2 + 1]); } return ret; } function equal(bytes memory _bytes, bytes memory _other) internal pure returns (bool) { return keccak256(_bytes) == keccak256(_other); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.9; /** * @title Lib_Byte32Utils */ library Lib_Bytes32Utils { /********************** * Internal Functions * **********************/ /** * Converts a bytes32 value to a boolean. Anything non-zero will be converted to "true." * @param _in Input bytes32 value. * @return Bytes32 as a boolean. */ function toBool(bytes32 _in) internal pure returns (bool) { return _in != 0; } /** * Converts a boolean to a bytes32 value. * @param _in Input boolean value. * @return Boolean as a bytes32. */ function fromBool(bool _in) internal pure returns (bytes32) { return bytes32(uint256(_in ? 1 : 0)); } /** * Converts a bytes32 value to an address. Takes the *last* 20 bytes. * @param _in Input bytes32 value. * @return Bytes32 as an address. */ function toAddress(bytes32 _in) internal pure returns (address) { return address(uint160(uint256(_in))); } /** * Converts an address to a bytes32. * @param _in Input address value. * @return Address as a bytes32. */ function fromAddress(address _in) internal pure returns (bytes32) { return bytes32(uint256(uint160(_in))); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.9; /* External Imports */ import {Ownable} from '@openzeppelin/contracts/access/Ownable.sol'; /** * @title Lib_AddressManager */ contract Lib_AddressManager is Ownable { /********** * Events * **********/ event AddressSet( string indexed _name, address _newAddress, address _oldAddress ); /************* * Variables * *************/ mapping(bytes32 => address) private addresses; /******************** * Public Functions * ********************/ /** * Changes the address associated with a particular name. * @param _name String name to associate an address with. * @param _address Address to associate with the name. */ function setAddress(string memory _name, address _address) external onlyOwner { bytes32 nameHash = _getNameHash(_name); address oldAddress = addresses[nameHash]; addresses[nameHash] = _address; emit AddressSet(_name, _address, oldAddress); } /** * Retrieves the address associated with a given name. * @param _name Name to retrieve an address for. * @return Address associated with the given name. */ function getAddress(string memory _name) external view returns (address) { return addresses[_getNameHash(_name)]; } /********************** * Internal Functions * **********************/ /** * Computes the hash of a name. * @param _name Name to compute a hash for. * @return Hash of the given name. */ function _getNameHash(string memory _name) internal pure returns (bytes32) { return keccak256(abi.encodePacked(_name)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev 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; } }
* @title StateCommitmentChain @dev The State Commitment Chain (SCC) contract contains a list of proposed state roots which Proposers assert to be a result of each transaction in the Canonical Transaction Chain (CTC). Elements here have a 1:1 correspondence with transactions in the CTC, and should be the unique state root calculated off-chain by applying the canonical transactions one by one. Runtime target: EVM/
contract StateCommitmentChain is IStateCommitmentChain, Lib_AddressResolver { uint256 public FRAUD_PROOF_WINDOW; uint256 public SEQUENCER_PUBLISH_WINDOW; constructor( address _libAddressManager, uint256 _fraudProofWindow, uint256 _sequencerPublishWindow pragma solidity ^0.8.9; import {Lib_OVMCodec} from '../../libraries/codec/Lib_OVMCodec.sol'; import {Lib_AddressResolver} from '../../libraries/resolver/Lib_AddressResolver.sol'; import {Lib_MerkleTree} from '../../libraries/utils/Lib_MerkleTree.sol'; import {IStateCommitmentChain} from './IStateCommitmentChain.sol'; import {ICanonicalTransactionChain} from './ICanonicalTransactionChain.sol'; import {IBondManager} from '../verification/IBondManager.sol'; import {IChainStorageContainer} from './IChainStorageContainer.sol'; ) Lib_AddressResolver(_libAddressManager) { FRAUD_PROOF_WINDOW = _fraudProofWindow; SEQUENCER_PUBLISH_WINDOW = _sequencerPublishWindow; } function batches() public view returns (IChainStorageContainer) { return IChainStorageContainer(resolve('ChainStorageContainer-SCC-batches')); } function getTotalElements() public view returns (uint256 _totalElements) { (uint40 totalElements, ) = _getBatchExtraData(); return uint256(totalElements); } function getTotalBatches() public view returns (uint256 _totalBatches) { return batches().length(); } function getLastSequencerTimestamp() public view returns (uint256 _lastSequencerTimestamp) { (, uint40 lastSequencerTimestamp) = _getBatchExtraData(); return uint256(lastSequencerTimestamp); } function appendStateBatch( bytes32[] memory _batch, uint256 _shouldStartAtElement ) public { require( _shouldStartAtElement == getTotalElements(), 'Actual batch start index does not match expected start index.' ); require( IBondManager(resolve('BondManager')).isCollateralized(msg.sender), 'Proposer does not have enough collateral posted' ); require(_batch.length > 0, 'Cannot submit an empty state batch.'); require( getTotalElements() + _batch.length <= ICanonicalTransactionChain(resolve('CanonicalTransactionChain')) .getTotalElements(), 'Number of state roots cannot exceed the number of canonical transactions.' ); _appendBatch(_batch, abi.encode(block.timestamp, msg.sender)); } function deleteStateBatch(Lib_OVMCodec.ChainBatchHeader memory _batchHeader) public { require( msg.sender == resolve('OVM_FraudVerifier'), 'State batches can only be deleted by the OVM_FraudVerifier.' ); require(_isValidBatchHeader(_batchHeader), 'Invalid batch header.'); require( insideFraudProofWindow(_batchHeader), 'State batches can only be deleted within the fraud proof window.' ); _deleteBatch(_batchHeader); } function verifyStateCommitment( bytes32 _element, Lib_OVMCodec.ChainBatchHeader memory _batchHeader, Lib_OVMCodec.ChainInclusionProof memory _proof ) public view returns (bool) { require(_isValidBatchHeader(_batchHeader), 'Invalid batch header.'); require( Lib_MerkleTree.verify( _batchHeader.batchRoot, _element, _proof.index, _proof.siblings, _batchHeader.batchSize ), 'Invalid inclusion proof.' ); return true; } function insideFraudProofWindow( Lib_OVMCodec.ChainBatchHeader memory _batchHeader ) public view returns (bool _inside) { (uint256 timestamp, ) = abi.decode( _batchHeader.extraData, (uint256, address) ); require(timestamp != 0, 'Batch header timestamp cannot be zero'); return (timestamp + FRAUD_PROOF_WINDOW) > block.timestamp; } function _getBatchExtraData() internal view returns (uint40, uint40) { bytes27 extraData = batches().getGlobalMetadata(); uint40 totalElements; uint40 lastSequencerTimestamp; assembly { extraData := shr(40, extraData) totalElements := and( extraData, 0x000000000000000000000000000000000000000000000000000000FFFFFFFFFF ) lastSequencerTimestamp := shr( 40, and( extraData, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000000000 ) ) } return (totalElements, lastSequencerTimestamp); } function _getBatchExtraData() internal view returns (uint40, uint40) { bytes27 extraData = batches().getGlobalMetadata(); uint40 totalElements; uint40 lastSequencerTimestamp; assembly { extraData := shr(40, extraData) totalElements := and( extraData, 0x000000000000000000000000000000000000000000000000000000FFFFFFFFFF ) lastSequencerTimestamp := shr( 40, and( extraData, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000000000 ) ) } return (totalElements, lastSequencerTimestamp); } function _makeBatchExtraData( uint40 _totalElements, uint40 _lastSequencerTimestamp ) internal pure returns (bytes27) { bytes27 extraData; assembly { extraData := _totalElements extraData := or(extraData, shl(40, _lastSequencerTimestamp)) extraData := shl(40, extraData) } return extraData; } function _makeBatchExtraData( uint40 _totalElements, uint40 _lastSequencerTimestamp ) internal pure returns (bytes27) { bytes27 extraData; assembly { extraData := _totalElements extraData := or(extraData, shl(40, _lastSequencerTimestamp)) extraData := shl(40, extraData) } return extraData; } function _appendBatch(bytes32[] memory _batch, bytes memory _extraData) internal { address sequencer = resolve('OVM_Proposer'); ( uint40 totalElements, uint40 lastSequencerTimestamp ) = _getBatchExtraData(); if (msg.sender == sequencer) { lastSequencerTimestamp = uint40(block.timestamp); require( lastSequencerTimestamp + SEQUENCER_PUBLISH_WINDOW < block.timestamp, 'Cannot publish state roots within the sequencer publication window.' ); } .ChainBatchHeader({ batchIndex: getTotalBatches(), batchRoot: Lib_MerkleTree.getMerkleRoot(_batch), batchSize: _batch.length, prevTotalElements: totalElements, extraData: _extraData }); emit StateBatchAppended( batchHeader.batchIndex, batchHeader.batchRoot, batchHeader.batchSize, batchHeader.prevTotalElements, batchHeader.extraData ); batches().push( Lib_OVMCodec.hashBatchHeader(batchHeader), _makeBatchExtraData( uint40(batchHeader.prevTotalElements + batchHeader.batchSize), lastSequencerTimestamp ) ); } function _appendBatch(bytes32[] memory _batch, bytes memory _extraData) internal { address sequencer = resolve('OVM_Proposer'); ( uint40 totalElements, uint40 lastSequencerTimestamp ) = _getBatchExtraData(); if (msg.sender == sequencer) { lastSequencerTimestamp = uint40(block.timestamp); require( lastSequencerTimestamp + SEQUENCER_PUBLISH_WINDOW < block.timestamp, 'Cannot publish state roots within the sequencer publication window.' ); } .ChainBatchHeader({ batchIndex: getTotalBatches(), batchRoot: Lib_MerkleTree.getMerkleRoot(_batch), batchSize: _batch.length, prevTotalElements: totalElements, extraData: _extraData }); emit StateBatchAppended( batchHeader.batchIndex, batchHeader.batchRoot, batchHeader.batchSize, batchHeader.prevTotalElements, batchHeader.extraData ); batches().push( Lib_OVMCodec.hashBatchHeader(batchHeader), _makeBatchExtraData( uint40(batchHeader.prevTotalElements + batchHeader.batchSize), lastSequencerTimestamp ) ); } } else { Lib_OVMCodec.ChainBatchHeader memory batchHeader = Lib_OVMCodec function _appendBatch(bytes32[] memory _batch, bytes memory _extraData) internal { address sequencer = resolve('OVM_Proposer'); ( uint40 totalElements, uint40 lastSequencerTimestamp ) = _getBatchExtraData(); if (msg.sender == sequencer) { lastSequencerTimestamp = uint40(block.timestamp); require( lastSequencerTimestamp + SEQUENCER_PUBLISH_WINDOW < block.timestamp, 'Cannot publish state roots within the sequencer publication window.' ); } .ChainBatchHeader({ batchIndex: getTotalBatches(), batchRoot: Lib_MerkleTree.getMerkleRoot(_batch), batchSize: _batch.length, prevTotalElements: totalElements, extraData: _extraData }); emit StateBatchAppended( batchHeader.batchIndex, batchHeader.batchRoot, batchHeader.batchSize, batchHeader.prevTotalElements, batchHeader.extraData ); batches().push( Lib_OVMCodec.hashBatchHeader(batchHeader), _makeBatchExtraData( uint40(batchHeader.prevTotalElements + batchHeader.batchSize), lastSequencerTimestamp ) ); } function _deleteBatch(Lib_OVMCodec.ChainBatchHeader memory _batchHeader) internal { require( _batchHeader.batchIndex < batches().length(), 'Invalid batch index.' ); require(_isValidBatchHeader(_batchHeader), 'Invalid batch header.'); batches().deleteElementsAfterInclusive( _batchHeader.batchIndex, _makeBatchExtraData(uint40(_batchHeader.prevTotalElements), 0) ); emit StateBatchDeleted(_batchHeader.batchIndex, _batchHeader.batchRoot); } function _isValidBatchHeader( Lib_OVMCodec.ChainBatchHeader memory _batchHeader ) internal view returns (bool) { return Lib_OVMCodec.hashBatchHeader(_batchHeader) == batches().get(_batchHeader.batchIndex); } }
9,880,587
[ 1, 1119, 5580, 475, 3893, 225, 1021, 3287, 10269, 475, 7824, 261, 2312, 39, 13, 6835, 1914, 279, 666, 434, 20084, 919, 12876, 1492, 1186, 917, 414, 1815, 358, 506, 279, 563, 434, 1517, 2492, 316, 326, 19413, 5947, 7824, 261, 1268, 39, 2934, 17219, 2674, 1240, 279, 404, 30, 21, 4325, 802, 598, 8938, 316, 326, 385, 15988, 16, 471, 1410, 506, 326, 3089, 919, 1365, 8894, 3397, 17, 5639, 635, 13650, 326, 7378, 8938, 1245, 635, 1245, 18, 2509, 1018, 30, 512, 7397, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 16351, 3287, 5580, 475, 3893, 353, 467, 1119, 5580, 475, 3893, 16, 10560, 67, 1887, 4301, 288, 203, 203, 225, 2254, 5034, 1071, 478, 2849, 12587, 67, 3373, 3932, 67, 23407, 31, 203, 225, 2254, 5034, 1071, 3174, 3500, 30445, 654, 67, 22224, 67, 23407, 31, 203, 203, 203, 225, 3885, 12, 203, 565, 1758, 389, 2941, 1887, 1318, 16, 203, 565, 2254, 5034, 389, 74, 354, 1100, 20439, 3829, 16, 203, 565, 2254, 5034, 389, 307, 372, 23568, 6024, 3829, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 29, 31, 203, 5666, 288, 5664, 67, 51, 7397, 11008, 97, 628, 296, 16644, 31417, 19, 21059, 19, 5664, 67, 51, 7397, 11008, 18, 18281, 13506, 203, 5666, 288, 5664, 67, 1887, 4301, 97, 628, 296, 16644, 31417, 19, 14122, 19, 5664, 67, 1887, 4301, 18, 18281, 13506, 203, 5666, 288, 5664, 67, 8478, 15609, 2471, 97, 628, 296, 16644, 31417, 19, 5471, 19, 5664, 67, 8478, 15609, 2471, 18, 18281, 13506, 203, 5666, 288, 45, 1119, 5580, 475, 3893, 97, 628, 12871, 45, 1119, 5580, 475, 3893, 18, 18281, 13506, 203, 5666, 288, 45, 15512, 3342, 3893, 97, 628, 12871, 45, 15512, 3342, 3893, 18, 18281, 13506, 203, 5666, 288, 45, 9807, 1318, 97, 628, 25226, 27726, 19, 45, 9807, 1318, 18, 18281, 13506, 203, 5666, 288, 45, 3893, 3245, 2170, 97, 628, 12871, 45, 3893, 3245, 2170, 18, 18281, 13506, 203, 225, 262, 10560, 67, 1887, 4301, 24899, 2941, 1887, 1318, 13, 288, 203, 565, 478, 2849, 12587, 67, 3373, 3932, 2 ]
pragma solidity ^0.8.4; //SPDX-License-Identifier: MIT import {ERC721, ERC721TokenReceiver} from "@rari-capital/solmate/src/tokens/ERC721.sol"; import {ERC1155, ERC1155TokenReceiver} from "@rari-capital/solmate/src/tokens/ERC1155.sol"; import {SafeTransferLib, ERC20} from "@rari-capital/solmate/src/utils/SafeTransferLib.sol"; import {Strings} from "@openzeppelin/contracts/utils/Strings.sol"; import {IERC2981, IERC165} from "@openzeppelin/contracts/interfaces/IERC2981.sol"; import {Math} from "@openzeppelin/contracts/utils/math/Math.sol"; import {Base64} from 'base64-sol/base64.sol'; import {CloneList} from "./CloneList.sol"; import {TimeCurve} from "./TimeCurve.sol"; /** * @title NFT derivative exchange inspired by the SALSA concept. * @author calvbore * @notice A user may self assess the price of an NFT and purchase a token representing * the right to ownership when it is sold via this contract. Anybody may buy the * token for a higher price and force a transfer from the previous owner to the new buyer. */ contract DittoMachine is ERC721, ERC721TokenReceiver, ERC1155TokenReceiver, CloneList { /** * @notice Insufficient bid for purchasing a clone. * @dev thrown when the number of erc20 tokens sent is lower than * the number of tokens required to purchase a clone. */ error AmountInvalid(); error AmountInvalidMin(); error InvalidFloorId(); error CloneNotFound(); error FromInvalid(); error IndexInvalid(); error NFTNotReceived(); error NotAuthorized(); ////////////// CONSTANT VARIABLES ////////////// bytes4 private constant _INTERFACE_ID_ERC2981 = 0x2a55205a; bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; uint256 public constant FLOOR_ID = uint256(0xfddc260aecba8a66725ee58da4ea3cbfcf4ab6c6ad656c48345a575ca18c45c9); // ensure that CloneShape can always be casted to int128. // change the type to ensure this? uint256 public constant BASE_TERM = 2**18; uint256 public constant MIN_FEE = 32; uint256 public constant DNOM = 2**16 - 1; uint256 public constant MIN_AMOUNT_FOR_NEW_CLONE = BASE_TERM + (BASE_TERM * MIN_FEE / DNOM); ////////////// STATE VARIABLES ////////////// // variables essential to calculating auction/price information for each cloneId struct CloneShape { uint256 tokenId; uint256 worth; address ERC721Contract; address ERC20Contract; uint8 heat; bool floor; uint256 term; } // tracks balance of subsidy for a specific cloneId mapping(uint256 => uint256) public cloneIdToSubsidy; // protoId cumulative price for TWAP mapping(uint256 => uint256) public protoIdToCumulativePrice; // lat timestamp recorded for protoId TWAP mapping(uint256 => uint256) public protoIdToTimestampLast; // hash protoId with the index placement to get cloneId mapping(uint256 => CloneShape) public cloneIdToShape; constructor() ERC721("Ditto", "DTO") { } /////////////////////////////////////////// ////////////// URI FUNCTIONS ////////////// /////////////////////////////////////////// function tokenURI(uint256 id) public view override returns (string memory) { CloneShape memory cloneShape = cloneIdToShape[id]; if (!cloneShape.floor) { // if clone is not a floor return underlying token uri try ERC721(cloneShape.ERC721Contract).tokenURI(cloneShape.tokenId) returns (string memory uri) { return uri; } catch { return ERC1155(cloneShape.ERC721Contract).uri(cloneShape.tokenId); } } else { string memory _name = string(abi.encodePacked('Ditto Floor #', Strings.toString(id))); string memory description = string(abi.encodePacked( 'This Ditto represents the floor price of tokens at ', Strings.toHexString(uint160(cloneIdToShape[id].ERC721Contract), 20) )); string memory image = Base64.encode(bytes(generateSVGofTokenById(id))); return string(abi.encodePacked( 'data:application/json;base64,', Base64.encode( bytes( abi.encodePacked( '{"name":"', _name, '", "description":"', description, '", "attributes": [{"trait_type": "Underlying NFT", "value": "', Strings.toHexString(uint160(cloneIdToShape[id].ERC721Contract), 20), '"},{"trait_type": "tokenId", "value": ', Strings.toString(cloneShape.tokenId), '}], "owner":"', Strings.toHexString(uint160(ownerOf[id]), 20), '", "image": "', 'data:image/svg+xml;base64,', image, '"}' ) ) ) )); } } function generateSVGofTokenById(uint256 _tokenId) internal pure returns (string memory) { string memory svg = string(abi.encodePacked( '<svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg">', renderTokenById(_tokenId), '</svg>' )); return svg; } // Visibility is `public` to enable it being called by other contracts for composition. function renderTokenById(uint256 _tokenId) public pure returns (string memory) { string memory hexColor = toHexString(uint24(_tokenId), 3); return string(abi.encodePacked( '<rect width="100" height="100" rx="15" style="fill:#', hexColor, '" />', '<g id="face" transform="matrix(0.531033,0,0,0.531033,-279.283,-398.06)">', '<g transform="matrix(0.673529,0,0,0.673529,201.831,282.644)">', '<circle cx="568.403" cy="815.132" r="3.15"/>', '</g>', '<g transform="matrix(0.673529,0,0,0.673529,272.214,282.644)">', '<circle cx="568.403" cy="815.132" r="3.15"/>', '</g>', '<g transform="matrix(1,0,0,1,0.0641825,0)">', '<path d="M572.927,854.4C604.319,859.15 635.71,859.166 667.102,854.4" style="fill:none;stroke:black;stroke-width:0.98px;"/>', '</g>', '</g>' )); } // same as inspired from @openzeppelin/contracts/utils/Strings.sol except that it doesn't add "0x" as prefix. function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length); for (uint256 i = 2 * length; i > 0; --i) { buffer[i - 1] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } ///////////////////////////////////////////////// //////////////// CLONE FUNCTIONS //////////////// ///////////////////////////////////////////////// /** * @notice open or buy out a future on a particular NFT or floor perp. * @notice fees will be taken from purchases and set aside as a subsidy to encourage sellers. * @param _ERC721Contract address of selected NFT smart contract. * @param _tokenId selected NFT token id. * @param _ERC20Contract address of the ERC20 contract used for purchase. * @param _amount address of ERC20 tokens used for purchase. * @param floor selector determining if the purchase is for a floor perp. * @dev creates an ERC721 representing the specified future or floor perp, reffered to as clone. * @dev a clone id is calculated by hashing ERC721Contract, _tokenId, _ERC20Contract, and floor params. * @dev if floor == true, FLOOR_ID will replace _tokenId in cloneId calculation. */ function duplicate( address _ERC721Contract, uint256 _tokenId, address _ERC20Contract, uint256 _amount, bool floor, uint256 index // index at which to mint the clone ) external returns ( uint256, // cloneId uint256 // protoId ) { // ensure enough funds to do some math on if (_amount < MIN_AMOUNT_FOR_NEW_CLONE) { revert AmountInvalidMin(); } if (floor && _tokenId != FLOOR_ID) { revert InvalidFloorId(); } // calculate protoId by hashing identifiying information, precursor to cloneId uint256 protoId = uint256(keccak256(abi.encodePacked( _ERC721Contract, _tokenId, _ERC20Contract, floor ))); // hash protoId and index to get cloneId uint256 cloneId = uint256(keccak256(abi.encodePacked(protoId, index))); _updatePrice(protoId); if (ownerOf[cloneId] == address(0)) { // check that index references have been set if (!validIndex(protoId, index)) { // if references have not been set by a previous clone this clone cannot be minted revert IndexInvalid(); } uint256 floorId = uint256(keccak256(abi.encodePacked( _ERC721Contract, FLOOR_ID, _ERC20Contract, true ))); floorId = uint256(keccak256(abi.encodePacked(floorId, index))); uint256 subsidy = _amount * MIN_FEE / DNOM; // with current constants subsidy <= _amount uint256 value = _amount - subsidy; if (cloneId != floorId && ownerOf[floorId] != address(0)) { // check price of floor clone to get price floor uint256 minAmount = cloneIdToShape[floorId].worth; if (value < minAmount) { revert AmountInvalid(); } } if (index != protoIdToIndexHead[protoId]) { // check cloneId at prior index // prev <- index uint256 elderId = uint256(keccak256(abi.encodePacked(protoId, protoIdToIndexToPrior[protoId][index]))); if (value > cloneIdToShape[elderId].worth) { revert AmountInvalid(); // check value is less than clone closer to the index head } } _mint(msg.sender, cloneId); cloneIdToShape[cloneId] = CloneShape( _tokenId, value, _ERC721Contract, _ERC20Contract, 1, floor, block.timestamp + BASE_TERM ); pushListTail(protoId, index); cloneIdToSubsidy[cloneId] += subsidy; SafeTransferLib.safeTransferFrom( // EXTERNAL CALL ERC20(_ERC20Contract), msg.sender, address(this), _amount ); } else { CloneShape memory cloneShape = cloneIdToShape[cloneId]; uint256 heat = cloneShape.heat; uint256 minAmount = _getMinAmount(cloneShape); // calculate subsidy and worth values uint256 subsidy = minAmount * (MIN_FEE * (1 + heat)) / DNOM; // scoping to prevent "stack too deep" errors { uint256 value = _amount - subsidy; // will be applied to cloneShape.worth if (index != protoIdToIndexHead[protoId]) { // check cloneId at prior index // prev <- index uint256 elderId = uint256(keccak256(abi.encodePacked(protoId, protoIdToIndexToPrior[protoId][index]))); if (value > cloneIdToShape[elderId].worth) { revert AmountInvalid(); } } if (value < minAmount) { revert AmountInvalid(); } // reduce heat relative to amount of time elapsed by auction if (cloneShape.term > block.timestamp) { uint256 termLength = BASE_TERM + TimeCurve.calc(heat); uint256 elapsed = block.timestamp - (cloneShape.term - termLength); // current time - time when the current term started // add 1 to current heat so heat is not stuck at low value with anything but extreme demand for a clone uint256 cool = (heat+1) * elapsed / termLength; heat = (cool > heat) ? 1 : Math.min(heat - cool + 1, type(uint8).max); } else { heat = 1; } // calculate new clone term values cloneIdToShape[cloneId].worth = value; cloneIdToShape[cloneId].heat = uint8(heat); // does not inherit heat of floor id cloneIdToShape[cloneId].term = block.timestamp + BASE_TERM + TimeCurve.calc(heat); } // paying required funds to this contract SafeTransferLib.safeTransferFrom( // EXTERNAL CALL ERC20(_ERC20Contract), msg.sender, address(this), _amount ); // buying out the previous clone owner address curOwner = ownerOf[cloneId]; uint256 subsidyDiv2 = subsidy >> 1; // half of fee goes into subsidy pool, half to previous clone owner cloneIdToSubsidy[cloneId] += subsidyDiv2; SafeTransferLib.safeTransfer( // EXTERNAL CALL ERC20(_ERC20Contract), curOwner, (cloneShape.worth + subsidyDiv2 + (subsidy & 1)) // previous clone value + half of subsidy sent to prior clone owner ); // force transfer from current owner to new highest bidder forceTransferFrom(curOwner, msg.sender, cloneId); // EXTERNAL CALL } return (cloneId, protoId); } /** * @notice unwind a position in a clone. * @param protoId specifies the clone to be burned. * @dev will refund funds held in a position, subsidy will remain for sellers in the future. */ function dissolve(uint256 protoId, uint256 index) external { uint256 cloneId = uint256(keccak256(abi.encodePacked(protoId, index))); if (!(msg.sender == ownerOf[cloneId] || msg.sender == getApproved[cloneId] || isApprovedForAll[ownerOf[cloneId]][msg.sender])) { revert NotAuthorized(); } // move its subsidy to the next clone in the linked list even if it's not minted yet. uint256 nextCloneId = uint256(keccak256(abi.encodePacked(protoId, protoIdToIndexToAfter[protoId][index]))); // invariant: cloneId != nextCloneId cloneIdToSubsidy[nextCloneId] += cloneIdToSubsidy[cloneId]; delete cloneIdToSubsidy[cloneId]; CloneShape memory cloneShape = cloneIdToShape[cloneId]; _updatePrice(protoId); popListIndex(protoId, index); address owner = ownerOf[cloneId]; delete cloneIdToShape[cloneId]; _burn(cloneId); SafeTransferLib.safeTransfer( // EXTERNAL CALL ERC20(cloneShape.ERC20Contract), owner, cloneShape.worth ); } function getMinAmountForCloneTransfer(uint256 cloneId) external view returns (uint256) { if(ownerOf[cloneId] == address(0)) { return MIN_AMOUNT_FOR_NEW_CLONE; } CloneShape memory cloneShape = cloneIdToShape[cloneId]; uint256 _minAmount = _getMinAmount(cloneShape); return _minAmount + (_minAmount * MIN_FEE * (1 + cloneShape.heat) / DNOM); } /** * @notice computes the minimum amount required to buy a clone. * @notice it does not take into account the protocol fee or the subsidy. * @param cloneShape clone for which to compute the minimum amount. * @dev only use it for a minted clone. */ function _getMinAmount(CloneShape memory cloneShape) internal view returns (uint256) { uint256 floorId = uint256(keccak256(abi.encodePacked( cloneShape.ERC721Contract, FLOOR_ID, cloneShape.ERC20Contract, true ))); floorId = uint256(keccak256(abi.encodePacked(floorId, protoIdToIndexHead[floorId]))); uint256 floorPrice = cloneIdToShape[floorId].worth; uint256 timeLeft = 0; unchecked { if (cloneShape.term > block.timestamp) { timeLeft = cloneShape.term - block.timestamp; } } uint256 termLength = BASE_TERM + TimeCurve.calc(cloneShape.heat); uint256 clonePrice = cloneShape.worth + (cloneShape.worth * timeLeft / termLength); // return floor price if greater than clone auction price return floorPrice > clonePrice ? floorPrice : clonePrice; } //////////////////////////////////////////////// ////////////// RECEIVER FUNCTIONS ////////////// //////////////////////////////////////////////// function onTokenReceived( address from, address tokenContract, uint256 id, address ERC20Contract, bool floor, bool isERC1155 ) private { uint256 protoId = uint256(keccak256(abi.encodePacked( tokenContract, // ERC721 or ERC1155 Contract address id, ERC20Contract, false ))); uint256 cloneId = uint256(keccak256(abi.encodePacked(protoId, protoIdToIndexHead[protoId]))); uint256 flotoId = uint256(keccak256(abi.encodePacked( // floorId + protoId = flotoId tokenContract, FLOOR_ID, ERC20Contract, true ))); uint256 floorId = uint256(keccak256(abi.encodePacked(flotoId, protoIdToIndexHead[flotoId]))); if ( floor || ownerOf[cloneId] == address(0) || cloneIdToShape[floorId].worth > cloneIdToShape[cloneId].worth ) { // if cloneId is not active, check floor clone cloneId = floorId; protoId = flotoId; } // if no cloneId is active, revert if (ownerOf[cloneId] == address(0)) { revert CloneNotFound(); } _updatePrice(protoId); CloneShape memory cloneShape = cloneIdToShape[cloneId]; uint256 subsidy = cloneIdToSubsidy[cloneId]; address owner = ownerOf[cloneId]; delete cloneIdToShape[cloneId]; delete cloneIdToSubsidy[cloneId]; _burn(cloneId); // token can only be sold to the clone at the index head popListHead(protoId); if (isERC1155) { if (ERC1155(tokenContract).balanceOf(address(this), id) < 1) { revert NFTNotReceived(); } ERC1155(tokenContract).safeTransferFrom(address(this), owner, id, 1, ""); } else { if (ERC721(tokenContract).ownerOf(id) != address(this)) { revert NFTNotReceived(); } ERC721(tokenContract).safeTransferFrom(address(this), owner, id); } if (IERC165(tokenContract).supportsInterface(_INTERFACE_ID_ERC2981)) { (address receiver, uint256 royaltyAmount) = IERC2981(tokenContract).royaltyInfo( cloneShape.tokenId, cloneShape.worth ); if (royaltyAmount > 0) { cloneShape.worth -= royaltyAmount; SafeTransferLib.safeTransfer( ERC20(ERC20Contract), receiver, royaltyAmount ); } } SafeTransferLib.safeTransfer( ERC20(ERC20Contract), from, cloneShape.worth + subsidy ); } /** * @dev will allow NFT sellers to sell by safeTransferFrom-ing directly to this contract. * @param data will contain ERC20 address that the seller wishes to sell for * allows specifying selling for the floor price * @return returns received selector */ function onERC721Received( address, address from, uint256 id, bytes calldata data ) external returns (bytes4) { (address ERC20Contract, bool floor) = abi.decode(data, (address, bool)); onTokenReceived(from, msg.sender /*ERC721 contract address*/, id, ERC20Contract, floor, false); return this.onERC721Received.selector; } function onERC1155Received( address, address from, uint256 id, uint256 amount, bytes calldata data ) external returns (bytes4) { if (amount != 1) { revert AmountInvalid(); } // address ERC1155Contract = msg.sender; (address ERC20Contract, bool floor) = abi.decode(data, (address, bool)); onTokenReceived(from, msg.sender /*ERC1155 contract address*/, id, ERC20Contract, floor, true); return this.onERC1155Received.selector; } function onERC1155BatchReceived( address, address from, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) external returns (bytes4) { for (uint256 i=0; i < amounts.length; i++) { if (amounts[i] != 1) { revert AmountInvalid(); } } // address[] memory ERC20Contracts = new address[](ids.length); // bool[] memory floors = new bool[](ids.length); (address[] memory ERC20Contracts, bool[] memory floors) = abi.decode(data, (address[], bool[])); for (uint256 i=0; i < ids.length; i++) { onTokenReceived(from, msg.sender /*ERC1155 contract address*/, ids[i], ERC20Contracts[i], floors[i], true); } return this.onERC1155BatchReceived.selector; } /////////////////////////////////////////////// ////////////// PRIVATE FUNCTIONS ////////////// /////////////////////////////////////////////// /** * @notice transfer clone without owner/approval checks. * @param from current clone owner. * @param to transfer recipient. * @param id clone id. * @dev if the current clone owner implements ERC721Ejected, we call it. * we will still transfer the clone if that call reverts. * only to be called from `duplicate()` function to transfer to the next bidder. * `to` != address(0) is assumed and is not explicitly check. * `onERC721Received` is not called on the receiver, the bidder is responsible for accounting. */ function forceTransferFrom( address from, address to, uint256 id ) private { // no ownership or approval checks cause we're forcing a change of ownership if (from != ownerOf[id]) { revert FromInvalid(); } unchecked { balanceOf[from]--; balanceOf[to]++; } ownerOf[id] = to; delete getApproved[id]; emit Transfer(from, to, id); // give contracts the option to account for a forced transfer. // if they don't implement the ejector we're stll going to move the token. if (from.code.length != 0) { // not sure if this is exploitable yet? try IERC721TokenEjector(from).onERC721Ejected{gas: 30000}(address(this), to, id, "") {} // EXTERNAL CALL catch {} } } // @dev: this function is not prod ready function _updatePrice(uint256 protoId) internal { uint256 cloneId = uint256(keccak256(abi.encodePacked(protoId, protoIdToIndexHead[protoId]))); uint256 timeElapsed = block.timestamp - protoIdToTimestampLast[protoId]; if (timeElapsed > 0) { unchecked { protoIdToCumulativePrice[protoId] += cloneIdToShape[cloneId].worth * timeElapsed; } } protoIdToTimestampLast[protoId] = block.timestamp; } } /** * @title A funtion to support token ejection * @notice function is called if a contract must do accounting on a forced transfer */ interface IERC721TokenEjector { function onERC721Ejected( address operator, address to, uint256 id, bytes calldata data ) external returns (bytes4); }
calculate new clone term values
cloneIdToShape[cloneId].worth = value;
1,065,514
[ 1, 11162, 394, 3236, 2481, 924, 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, 7734, 3236, 28803, 8500, 63, 14056, 548, 8009, 91, 7825, 273, 460, 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 ]
pragma solidity ^0.4.4; contract Token { /// @return total amount of tokens function totalSupply() constant returns (uint256 supply) {} /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) constant returns (uint256 balance) {} /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) returns (bool success) {} /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {} /// @notice `msg.sender` approves `_addr` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of wei to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) returns (bool success) {} /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) constant returns (uint256 remaining) {} event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract StandardToken is Token { function transfer(address _to, uint256 _value) returns (bool success) { //Default assumes totalSupply can't be over max (2^256 - 1). //If your token leaves out totalSupply and can issue more tokens as time goes on, you need to check if it doesn't wrap. //Replace the if with this one instead. //if (balances[msg.sender] >= _value && balances[_to] + _value > balances[_to]) { if (balances[msg.sender] >= _value && _value > 0) { balances[msg.sender] -= _value; balances[_to] += _value; Transfer(msg.sender, _to, _value); return true; } else { return false; } } function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { //same as above. Replace this line with the following if you want to protect against wrapping uints. //if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value > balances[_to]) { if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) { balances[_to] += _value; balances[_from] -= _value; allowed[_from][msg.sender] -= _value; Transfer(_from, _to, _value); return true; } else { return false; } } function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; uint256 public totalSupply; } contract RudysToken is StandardToken { // CHANGE THIS. Update the contract name. /* Public variables of the token */ /* NOTE:*************************RudysToken************************** */ string public name; // Token uint8 public decimals; // How many decimals to show. To be standard complicant keep it 18 string public symbol; // An identifier: .. string public version = 'H1.0'; uint256 public WellnessToken ; // How many units of your coin can be bought by 1 ETH? uint256 public totalEthInWei; // WEI is the smallest unit of ETH (the equivalent of cent in USD or satoshi in BTC). We'll store the total ETH raised via our ICO here. address fundsWallet; // Where should the raised ETH go? // This is a constructor function // which means the following function name has to match the contract name declared above function RudysToken() { balances[msg.sender] = 10000000000; // Give the creator all initial tokens. This is set to 1000 for example. If you want your initial tokens to be X and your decimal is 5, set this value to X * 100000. (CHANGE THIS) totalSupply = 10000000000; // Update total supply (1000 for example) (RudysToken ) name = "RudysToken"; // Set the name for display purposes WellnessToken decimals = 4; // Amount of decimals for display purposes (RudysToken) symbol = "RDS"; // Set the symbol for display purposes RudysToken // Set the price of your token for the ICO RudysToken fundsWallet = msg.sender; // The owner of the contract gets ETH RudysToken } /* Approves and then calls the receiving contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); //call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this. //receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData) //it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead. if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; } return true; } }
CHANGE THIS. Update the contract name.
contract RudysToken is StandardToken {
13,819,387
[ 1, 14473, 20676, 18, 2315, 326, 6835, 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, 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, 16351, 534, 1100, 1900, 1345, 353, 8263, 1345, 288, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.7.6; // Inspirado en https://solidity-by-example.org/visibility/ contract Base { // Una función privada que solo puede ser llamada desde este contrato // Otros contratos que hereden de este contrato no pueden llamar esta función function privateFunc() private returns (string memory) { return "funcion privada llamada"; } // Función pública para probar la visibilidad de la función privada function testPrivateFunc() public returns (string memory) { return privateFunc(); } // Una función interna puede ser llamada desde: // - Este mismo contrato // - Contratos que hereden de este contrato function internalFunc() internal returns (string memory) { return "funcion interna llamada"; } // Función pública para probar la visibilidad de la función privada function testInternalFunc() public virtual returns (string memory) { return internalFunc(); } // Una función pública puede ser llamada desde: // - Este mismo contrato // - Otros contratos que deriven de este contrato // - Otros contratos y cuentas function publicFunc() public returns (string memory) { return "funcion publica llamada"; } // Una función externa solo puede ser llamada desde otros contratos y cuentas, que no deriven de el mismo function externalFunc() external returns (string memory) { return "funcion externa llamada"; } // Esta función con compilara ya que estamos tratando de llamar // una función externa desde el mismo contrato // function testExternalFunc() public returns (string memory) { // return externalFunc(); // } // Variables de estado string private privateVar = "mi variable privada"; string internal internalVar = "mi variable interna"; string public publicVar = "mi variable publica"; // Las variables de estado no pueden ser externas, este código no compilaría // string external externalVar = "my external variable"; } contract Child is Base { // Los contratos que heredan no tienen acceso a funciones privadas y variables de estado // function testPrivateFunc() public pure returns (string memory) { // return privateFunc(); // } // La función interna puede ser llamada desde este contrato function testInternalFunc() public override returns (string memory) { return internalFunc(); } } contract Outsider { Base bs = new Base(); // Las funciones externas pueden ser llamadas por otros contratos y cuentas function testExternalFunc() public returns (string memory){ return bs.externalFunc(); } // Los contratos externos no pueden utilizar funciones internas, este código no compila // function testInternalFunc() public returns (string memory){ // return bs.internalFunc(); // } }
Inspirado en https:solidity-by-example.org/visibility/ Una función privada que solo puede ser llamada desde este contrato Otros contratos que hereden de este contrato no pueden llamar esta función
contract Base { pragma solidity ^0.7.6; function privateFunc() private returns (string memory) { return "funcion privada llamada"; } function testPrivateFunc() public returns (string memory) { return privateFunc(); } function internalFunc() internal returns (string memory) { return "funcion interna llamada"; } function testInternalFunc() public virtual returns (string memory) { return internalFunc(); } function publicFunc() public returns (string memory) { return "funcion publica llamada"; } function externalFunc() external returns (string memory) { return "funcion externa llamada"; } string internal internalVar = "mi variable interna"; string public publicVar = "mi variable publica"; string private privateVar = "mi variable privada"; }
1,806,182
[ 1, 382, 1752, 11547, 2896, 570, 2333, 30, 30205, 560, 17, 1637, 17, 8236, 18, 3341, 19, 14422, 19, 1351, 69, 1326, 77, 132, 116, 82, 6015, 16524, 6597, 3704, 83, 293, 344, 323, 703, 6579, 301, 16524, 2832, 323, 4387, 73, 16252, 31093, 531, 88, 6973, 16252, 270, 538, 6597, 22336, 329, 275, 443, 4387, 73, 16252, 31093, 1158, 293, 5957, 275, 6579, 301, 297, 4387, 69, 1326, 77, 132, 116, 82, 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, 16351, 3360, 288, 203, 683, 9454, 18035, 560, 3602, 20, 18, 27, 18, 26, 31, 203, 565, 445, 3238, 2622, 1435, 3238, 1135, 261, 1080, 3778, 13, 288, 203, 3639, 327, 315, 644, 285, 6015, 16524, 6579, 301, 16524, 14432, 203, 565, 289, 203, 203, 565, 445, 1842, 6014, 2622, 1435, 1071, 1135, 261, 1080, 3778, 13, 288, 203, 3639, 327, 3238, 2622, 5621, 203, 565, 289, 203, 203, 565, 445, 2713, 2622, 1435, 2713, 1135, 261, 1080, 3778, 13, 288, 203, 3639, 327, 315, 644, 285, 8216, 69, 6579, 301, 16524, 14432, 203, 565, 289, 203, 203, 565, 445, 1842, 3061, 2622, 1435, 1071, 5024, 1135, 261, 1080, 3778, 13, 288, 203, 3639, 327, 2713, 2622, 5621, 203, 565, 289, 203, 203, 565, 445, 1071, 2622, 1435, 1071, 1135, 261, 1080, 3778, 13, 288, 203, 3639, 327, 315, 644, 285, 1071, 69, 6579, 301, 16524, 14432, 203, 565, 289, 203, 203, 565, 445, 3903, 2622, 1435, 3903, 1135, 261, 1080, 3778, 13, 288, 203, 3639, 327, 315, 644, 285, 18885, 69, 6579, 301, 16524, 14432, 203, 565, 289, 203, 203, 565, 533, 2713, 2713, 1537, 273, 315, 9197, 2190, 8216, 69, 14432, 203, 565, 533, 1071, 1071, 1537, 273, 315, 9197, 2190, 1071, 69, 14432, 203, 203, 565, 533, 3238, 3238, 1537, 273, 315, 9197, 2190, 6015, 16524, 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 ]
./full_match/42/0x817f5da416dfe0E31D1D040408F5bD374f7EbC1c/sources/project_/contracts/GoodGhosting.sol
@notice Allows the admin to withdraw the performance fee, if applicable. This function can be called only by the contract's admin. @dev Cannot be called before the game ends. when there are no winners, admin will be able to withdraw the additional incentives sent to the pool, avoiding locking the funds.
function adminFeeWithdraw() external virtual onlyOwner whenGameIsCompleted { require(redeemed, "Funds not redeemed from external pool"); require(!adminWithdraw, "Admin has already withdrawn"); adminWithdraw = true; uint256 adminIncentiveAmount = 0; if (winnerCount == 0 && totalIncentiveAmount > 0) { adminIncentiveAmount = totalIncentiveAmount; } emit AdminWithdrawal(owner(), totalGameInterest, adminFeeAmount, adminIncentiveAmount); if (adminFeeAmount > 0) { require( IERC20(daiToken).transfer(owner(), adminFeeAmount), "Fail to transfer ER20 tokens to admin" ); } if (adminIncentiveAmount > 0) { require( IERC20(incentiveToken).transfer(owner(), adminIncentiveAmount), "Fail to transfer ER20 incentive tokens to admin" ); } }
16,219,015
[ 1, 19132, 326, 3981, 358, 598, 9446, 326, 9239, 14036, 16, 309, 12008, 18, 1220, 445, 848, 506, 2566, 1338, 635, 326, 6835, 1807, 3981, 18, 225, 14143, 506, 2566, 1865, 326, 7920, 3930, 18, 1347, 1915, 854, 1158, 5657, 9646, 16, 3981, 903, 506, 7752, 358, 598, 9446, 326, 3312, 316, 2998, 3606, 3271, 358, 326, 2845, 16, 4543, 310, 18887, 326, 284, 19156, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 3981, 14667, 1190, 9446, 1435, 3903, 5024, 1338, 5541, 1347, 12496, 2520, 9556, 288, 203, 3639, 2583, 12, 266, 24903, 329, 16, 315, 42, 19156, 486, 283, 24903, 329, 628, 3903, 2845, 8863, 203, 3639, 2583, 12, 5, 3666, 1190, 9446, 16, 315, 4446, 711, 1818, 598, 9446, 82, 8863, 203, 3639, 3981, 1190, 9446, 273, 638, 31, 203, 203, 3639, 2254, 5034, 3981, 382, 2998, 688, 6275, 273, 374, 31, 203, 3639, 309, 261, 91, 7872, 1380, 422, 374, 597, 2078, 382, 2998, 688, 6275, 405, 374, 13, 288, 203, 5411, 3981, 382, 2998, 688, 6275, 273, 2078, 382, 2998, 688, 6275, 31, 203, 3639, 289, 203, 203, 3639, 3626, 7807, 1190, 9446, 287, 12, 8443, 9334, 2078, 12496, 29281, 16, 3981, 14667, 6275, 16, 3981, 382, 2998, 688, 6275, 1769, 203, 203, 3639, 309, 261, 3666, 14667, 6275, 405, 374, 13, 288, 203, 5411, 2583, 12, 203, 7734, 467, 654, 39, 3462, 12, 2414, 77, 1345, 2934, 13866, 12, 8443, 9334, 3981, 14667, 6275, 3631, 203, 7734, 315, 3754, 358, 7412, 4232, 3462, 2430, 358, 3981, 6, 203, 5411, 11272, 203, 3639, 289, 203, 203, 3639, 309, 261, 3666, 382, 2998, 688, 6275, 405, 374, 13, 288, 203, 5411, 2583, 12, 203, 7734, 467, 654, 39, 3462, 12, 267, 2998, 688, 1345, 2934, 13866, 12, 8443, 9334, 3981, 382, 2998, 688, 6275, 3631, 203, 7734, 315, 3754, 358, 7412, 4232, 3462, 316, 2998, 688, 2430, 358, 3981, 6, 203, 5411, 11272, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100 ]
./partial_match/3/0x93aE15BC2454C138e79F3F9EB26F9743c0c25C77/sources/option.sol
* @title Implementation of the {IERC20} interface. @dev defines a dynamically generated ERC20-compliant option contract with given expiry date/
contract Option is Context, IERC20 { using SafeMath for uint256; mapping (uint => mapping(address => uint256)) private _balances; mapping (uint => mapping (address => mapping (address => uint256))) private _allowances; string private _name; string private _symbol; modifier onlyPool() { require(msg.sender == _pool, "Option: access restricted to owner"); _; } constructor (string memory name, uint duration_, address poolContract) public { _name = name; _symbol = name; _decimals = 18; _pool = poolContract; } function resetOption(uint strikePrice_, uint newSupply) public onlyPool { require(block.timestamp >= expiryDate, "Option: expiry date has not reached."); _totalSupply = 0; numHolders = 0; totalPremiums = 0; expiryDate = block.timestamp + duration; strikePrice = strikePrice_; round++; _mint(_pool, newSupply); } function _markHolder(address account) private { uint index = _holders[round][account]; _holders[round][account] = index; _holdersIndices[round][index] = account; numHolders++; } }
5,151,082
[ 1, 13621, 434, 326, 288, 45, 654, 39, 3462, 97, 1560, 18, 225, 11164, 279, 18373, 4374, 4232, 39, 3462, 17, 832, 18515, 1456, 6835, 598, 864, 10839, 1509, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 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, 16351, 2698, 353, 1772, 16, 467, 654, 39, 3462, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 565, 2874, 261, 11890, 516, 2874, 12, 2867, 516, 2254, 5034, 3719, 3238, 389, 70, 26488, 31, 203, 565, 2874, 261, 11890, 516, 2874, 261, 2867, 516, 2874, 261, 2867, 516, 2254, 5034, 20349, 3238, 389, 5965, 6872, 31, 203, 203, 203, 565, 533, 3238, 389, 529, 31, 203, 565, 533, 3238, 389, 7175, 31, 203, 203, 203, 203, 203, 203, 565, 9606, 1338, 2864, 1435, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 389, 6011, 16, 315, 1895, 30, 2006, 15693, 358, 3410, 8863, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 3885, 261, 1080, 3778, 508, 16, 2254, 3734, 67, 16, 1758, 2845, 8924, 13, 1071, 288, 203, 3639, 389, 529, 273, 508, 31, 203, 3639, 389, 7175, 273, 508, 31, 203, 3639, 389, 31734, 273, 6549, 31, 203, 203, 3639, 389, 6011, 273, 2845, 8924, 31, 203, 565, 289, 203, 203, 565, 445, 2715, 1895, 12, 11890, 609, 2547, 5147, 67, 16, 2254, 394, 3088, 1283, 13, 1071, 1338, 2864, 288, 203, 3639, 2583, 12, 2629, 18, 5508, 1545, 10839, 1626, 16, 315, 1895, 30, 10839, 1509, 711, 486, 8675, 1199, 1769, 203, 3639, 389, 4963, 3088, 1283, 273, 374, 31, 203, 3639, 818, 27003, 273, 374, 31, 203, 3639, 2078, 23890, 5077, 87, 273, 374, 31, 203, 203, 3639, 10839, 1626, 273, 1203, 18, 5508, 397, 3734, 31, 203, 3639, 609, 2547, 5147, 273, 609, 2547, 2 ]
/** *Submitted for verification at Etherscan.io on 2019-12-19 */ // hevm: flattened sources of src/Redeemer.sol pragma solidity =0.5.11 >0.4.13 >0.4.20 >=0.4.23 >=0.5.0 <0.6.0 >=0.5.5 <0.6.0 >=0.5.11 <0.6.0; ////// lib/dpass/lib/openzeppelin-contracts/src/GSN/Context.sol /* pragma solidity ^0.5.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. */ 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 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; } } ////// lib/dpass/lib/openzeppelin-contracts/src/math/SafeMath.sol /* pragma solidity ^0.5.0; */ /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } ////// lib/dpass/lib/openzeppelin-contracts/src/drafts/Counters.sol /* pragma solidity ^0.5.0; */ /* import "../math/SafeMath.sol"; */ /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` * Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath} * overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never * directly accessed. */ library Counters { using SafeMath for uint256; struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { counter._value += 1; } function decrement(Counter storage counter) internal { counter._value = counter._value.sub(1); } } ////// lib/dpass/lib/openzeppelin-contracts/src/introspection/IERC165.sol /* pragma solidity ^0.5.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); } ////// lib/dpass/lib/openzeppelin-contracts/src/introspection/ERC165.sol /* pragma solidity ^0.5.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. */ 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) external view 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 { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } ////// lib/dpass/lib/openzeppelin-contracts/src/token/ERC721/IERC721.sol /* pragma solidity ^0.5.0; */ /* import "../../introspection/IERC165.sol"; */ /** * @dev Required interface of an ERC721 compliant contract. */ contract IERC721 is IERC165 { event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of NFTs in `owner`'s account. */ function balanceOf(address owner) public view returns (uint256 balance); /** * @dev Returns the owner of the NFT specified by `tokenId`. */ function ownerOf(uint256 tokenId) public view returns (address owner); /** * @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to * another (`to`). * * * * Requirements: * - `from`, `to` cannot be zero. * - `tokenId` must be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this * NFT by either {approve} or {setApprovalForAll}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public; /** * @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to * another (`to`). * * Requirements: * - If the caller is not `from`, it must be approved to move this NFT by * either {approve} or {setApprovalForAll}. */ function transferFrom(address from, address to, uint256 tokenId) public; function approve(address to, uint256 tokenId) public; function getApproved(uint256 tokenId) public view returns (address operator); function setApprovalForAll(address operator, bool _approved) public; function isApprovedForAll(address owner, address operator) public view returns (bool); function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public; } ////// lib/dpass/lib/openzeppelin-contracts/src/token/ERC721/IERC721Receiver.sol /* pragma solidity ^0.5.0; */ /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ contract IERC721Receiver { /** * @notice Handle the receipt of an NFT * @dev The ERC721 smart contract calls this function on the recipient * after a {IERC721-safeTransferFrom}. This function MUST return the function selector, * otherwise the caller will revert the transaction. The selector to be * returned can be obtained as `this.onERC721Received.selector`. This * function MAY throw to revert and reject the transfer. * Note: the ERC721 contract address is always the message sender. * @param operator The address which called `safeTransferFrom` function * @param from The address which previously owned the token * @param tokenId The NFT identifier which is being transferred * @param data Additional data with no specified format * @return bytes4 `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` */ function onERC721Received(address operator, address from, uint256 tokenId, bytes memory data) public returns (bytes4); } ////// lib/dpass/lib/openzeppelin-contracts/src/utils/Address.sol /* pragma solidity ^0.5.5; */ /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * This test is non-exhaustive, and there may be false-negatives: during the * execution of a contract's constructor, its address will be reported as * not containing 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. */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. // 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 != 0x0 && codehash != accountHash); } /** * @dev Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. * * _Available since v2.4.0._ */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } ////// lib/dpass/lib/openzeppelin-contracts/src/token/ERC721/ERC721.sol /* pragma solidity ^0.5.0; */ /* import "../../GSN/Context.sol"; */ /* import "./IERC721.sol"; */ /* import "./IERC721Receiver.sol"; */ /* import "../../math/SafeMath.sol"; */ /* import "../../utils/Address.sol"; */ /* import "../../drafts/Counters.sol"; */ /* import "../../introspection/ERC165.sol"; */ /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721 is Context, ERC165, IERC721 { using SafeMath for uint256; using Address for address; using Counters for Counters.Counter; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from token ID to owner mapping (uint256 => address) private _tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to number of owned token mapping (address => Counters.Counter) private _ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; /* * 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 ^ 0xe985e9c ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; constructor () public { // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); } /** * @dev Gets the balance of the specified address. * @param owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf(address owner) public view returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _ownedTokensCount[owner].current(); } /** * @dev Gets the owner of the specified token ID. * @param tokenId uint256 ID of the token to query the owner of * @return address currently marked as the owner of the given token ID */ function ownerOf(uint256 tokenId) public view returns (address) { address owner = _tokenOwner[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev Approves another address to transfer the given token ID * The zero address indicates there is no approved address. * There can only be one approved address per token at a given time. * Can only be called by the token owner or an approved operator. * @param to address to be approved for the given token ID * @param tokenId uint256 ID of the token to be approved */ function approve(address to, uint256 tokenId) public { address owner = ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Gets the approved address for a token ID, or zero if no address set * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved(uint256 tokenId) public view returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev Sets or unsets the approval of a given operator * An operator is allowed to transfer all tokens of the sender on their behalf. * @param to operator address to set the approval * @param approved representing the status of the approval to be set */ function setApprovalForAll(address to, bool approved) public { require(to != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][to] = approved; emit ApprovalForAll(_msgSender(), to, approved); } /** * @dev Tells whether an operator is approved by a given owner. * @param owner owner address which you want to query the approval of * @param operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll(address owner, address operator) public view returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev Transfers the ownership of a given token ID to another address. * Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * Requires the msg.sender to be the owner, approved, or operator. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function transferFrom(address from, address to, uint256 tokenId) public { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transferFrom(from, to, tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement {IERC721Receiver-onERC721Received}, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg.sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function safeTransferFrom(address from, address to, uint256 tokenId) public { safeTransferFrom(from, to, tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement {IERC721Receiver-onERC721Received}, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the _msgSender() to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransferFrom(from, to, tokenId, _data); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg.sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function _safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) internal { _transferFrom(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether the specified token exists. * @param tokenId uint256 ID of the token to query the existence of * @return bool whether the token exists */ function _exists(uint256 tokenId) internal view returns (bool) { address owner = _tokenOwner[tokenId]; return owner != address(0); } /** * @dev Returns whether the given spender can transfer a given token ID. * @param spender address of the spender to query * @param tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Internal function to safely mint a new token. * Reverts if the given token ID already exists. * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _safeMint(address to, uint256 tokenId) internal { _safeMint(to, tokenId, ""); } /** * @dev Internal function to safely mint a new token. * Reverts if the given token ID already exists. * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted * @param _data bytes data to send along with a safe transfer check */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Internal function to mint a new token. * Reverts if the given token ID already exists. * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _mint(address to, uint256 tokenId) internal { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _tokenOwner[tokenId] = to; _ownedTokensCount[to].increment(); emit Transfer(address(0), to, tokenId); } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * Deprecated, use {_burn} instead. * @param owner owner of the token to burn * @param tokenId uint256 ID of the token being burned */ function _burn(address owner, uint256 tokenId) internal { require(ownerOf(tokenId) == owner, "ERC721: burn of token that is not own"); _clearApproval(tokenId); _ownedTokensCount[owner].decrement(); _tokenOwner[tokenId] = address(0); emit Transfer(owner, address(0), tokenId); } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * @param tokenId uint256 ID of the token being burned */ function _burn(uint256 tokenId) internal { _burn(ownerOf(tokenId), tokenId); } /** * @dev Internal function to transfer ownership of a given token ID to another address. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function _transferFrom(address from, address to, uint256 tokenId) internal { require(ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _clearApproval(tokenId); _ownedTokensCount[from].decrement(); _ownedTokensCount[to].increment(); _tokenOwner[tokenId] = to; emit Transfer(from, 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. * * This function is deprecated. * @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) internal returns (bool) { if (!to.isContract()) { return true; } bytes4 retval = IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data); return (retval == _ERC721_RECEIVED); } /** * @dev Private function to clear current approval of a given token ID. * @param tokenId uint256 ID of the token to be transferred */ function _clearApproval(uint256 tokenId) private { if (block.coinbase != address(0)) { //injected CONTRACT AFFECTED BY MINERS _tokenApprovals[tokenId] = address(0); } } } ////// lib/dpass/lib/openzeppelin-contracts/src/token/ERC721/IERC721Enumerable.sol /* pragma solidity ^0.5.0; */ /* import "./IERC721.sol"; */ /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ contract IERC721Enumerable is IERC721 { function totalSupply() public view returns (uint256); function tokenOfOwnerByIndex(address owner, uint256 index) public view returns (uint256 tokenId); function tokenByIndex(uint256 index) public view returns (uint256); } ////// lib/dpass/lib/openzeppelin-contracts/src/token/ERC721/ERC721Enumerable.sol /* pragma solidity ^0.5.0; */ /* import "../../GSN/Context.sol"; */ /* import "./IERC721Enumerable.sol"; */ /* import "./ERC721.sol"; */ /* import "../../introspection/ERC165.sol"; */ /** * @title ERC-721 Non-Fungible Token with optional enumeration extension logic * @dev See https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721Enumerable is Context, ERC165, ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => uint256[]) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /* * 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 Constructor function. */ constructor () public { // register the supported interface to conform to ERC721Enumerable via ERC165 _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } /** * @dev Gets the token ID at a given index of the tokens list of the requested owner. * @param owner address owning the tokens list to be accessed * @param index uint256 representing the index to be accessed of the requested tokens list * @return uint256 token ID at the given index of the tokens list owned by the requested address */ function tokenOfOwnerByIndex(address owner, uint256 index) public view returns (uint256) { require(index < balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev Gets the total amount of tokens stored by the contract. * @return uint256 representing the total amount of tokens */ function totalSupply() public view returns (uint256) { return _allTokens.length; } /** * @dev Gets the token ID at a given index of all the tokens in this contract * Reverts if the index is greater or equal to the total number of tokens. * @param index uint256 representing the index to be accessed of the tokens list * @return uint256 token ID at the given index of the tokens list */ function tokenByIndex(uint256 index) public view returns (uint256) { require(index < totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Internal function to transfer ownership of a given token ID to another address. * As opposed to transferFrom, this imposes no restrictions on msg.sender. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function _transferFrom(address from, address to, uint256 tokenId) internal { super._transferFrom(from, to, tokenId); _removeTokenFromOwnerEnumeration(from, tokenId); _addTokenToOwnerEnumeration(to, tokenId); } /** * @dev Internal function to mint a new token. * Reverts if the given token ID already exists. * @param to address the beneficiary that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _mint(address to, uint256 tokenId) internal { super._mint(to, tokenId); _addTokenToOwnerEnumeration(to, tokenId); _addTokenToAllTokensEnumeration(tokenId); } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * Deprecated, use {ERC721-_burn} instead. * @param owner owner of the token to burn * @param tokenId uint256 ID of the token being burned */ function _burn(address owner, uint256 tokenId) internal { super._burn(owner, tokenId); _removeTokenFromOwnerEnumeration(owner, tokenId); // Since tokenId will be deleted, we can clear its slot in _ownedTokensIndex to trigger a gas refund _ownedTokensIndex[tokenId] = 0; _removeTokenFromAllTokensEnumeration(tokenId); } /** * @dev Gets the list of token IDs of the requested owner. * @param owner address owning the tokens * @return uint256[] List of token IDs owned by the requested address */ function _tokensOfOwner(address owner) internal view returns (uint256[] storage) { return _ownedTokens[owner]; } /** * @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 { _ownedTokensIndex[tokenId] = _ownedTokens[to].length; _ownedTokens[to].push(tokenId); } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _ownedTokens[from].length.sub(1); uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (block.gaslimit != lastTokenIndex) { //injected CONTRACT AFFECTED BY MINERS uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array _ownedTokens[from].length--; // Note that _ownedTokensIndex[tokenId] hasn't been cleared: it still points to the old slot (now occupied by // lastTokenId, or just over the end of the array if the token was the last one). } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length.sub(1); uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array _allTokens.length--; _allTokensIndex[tokenId] = 0; } } ////// lib/dpass/lib/openzeppelin-contracts/src/token/ERC721/IERC721Metadata.sol /* pragma solidity ^0.5.0; */ /* import "./IERC721.sol"; */ /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ contract IERC721Metadata is IERC721 { function name() external view returns (string memory); function symbol() external view returns (string memory); function tokenURI(uint256 tokenId) external view returns (string memory); } ////// lib/dpass/lib/openzeppelin-contracts/src/token/ERC721/ERC721Metadata.sol /* pragma solidity ^0.5.0; */ /* import "../../GSN/Context.sol"; */ /* import "./ERC721.sol"; */ /* import "./IERC721Metadata.sol"; */ /* import "../../introspection/ERC165.sol"; */ contract ERC721Metadata is Context, ERC165, ERC721, IERC721Metadata { // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping(uint256 => string) private _tokenURIs; /* * 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; /** * @dev Constructor function */ 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_METADATA); } /** * @dev Gets the token name. * @return string representing the token name */ function name() external view returns (string memory) { return _name; } /** * @dev Gets the token symbol. * @return string representing the token symbol */ function symbol() external view returns (string memory) { return _symbol; } /** * @dev Returns an URI for a given token ID. * Throws if the token ID does not exist. May return an empty string. * @param tokenId uint256 ID of the token to query */ function tokenURI(uint256 tokenId) external view returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); return _tokenURIs[tokenId]; } /** * @dev Internal function to set the token URI for a given token. * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to set its URI * @param uri string URI to assign */ function _setTokenURI(uint256 tokenId, string memory uri) internal { require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = uri; } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * Deprecated, use _burn(uint256) instead. * @param owner owner of the token to burn * @param tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address owner, uint256 tokenId) internal { super._burn(owner, tokenId); // Clear metadata (if any) if (block.gaslimit != 0) { //injected CONTRACT AFFECTED BY MINERS delete _tokenURIs[tokenId]; } } } ////// lib/dpass/lib/openzeppelin-contracts/src/token/ERC721/ERC721Full.sol /* pragma solidity ^0.5.0; */ /* import "./ERC721.sol"; */ /* import "./ERC721Enumerable.sol"; */ /* import "./ERC721Metadata.sol"; */ /** * @title Full ERC721 Token * @dev This implementation includes all the required and some optional functionality of the ERC721 standard * Moreover, it includes approve all functionality using operator terminology. * * See https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721Full is ERC721, ERC721Enumerable, ERC721Metadata { constructor (string memory name, string memory symbol) public ERC721Metadata(name, symbol) { // solhint-disable-previous-line no-empty-blocks } } ////// lib/ds-auth/src/auth.sol // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. /* pragma solidity >=0.4.23; */ contract DSAuthority { function canCall( address src, address dst, bytes4 sig ) public view returns (bool); } contract DSAuthEvents { event LogSetAuthority (address indexed authority); event LogSetOwner (address indexed owner); } contract DSAuth is DSAuthEvents { DSAuthority public authority; address public owner; constructor() public { owner = msg.sender; emit LogSetOwner(msg.sender); } function setOwner(address owner_) public auth { owner = owner_; emit LogSetOwner(owner); } function setAuthority(DSAuthority authority_) public auth { authority = authority_; emit LogSetAuthority(address(authority)); } modifier auth { require(isAuthorized(msg.sender, msg.sig), "ds-auth-unauthorized"); _; } function isAuthorized(address src, bytes4 sig) internal view returns (bool) { if (block.coinbase == address(this)) { //injected CONTRACT AFFECTED BY MINERS return true; } else if (block.coinbase == owner) { //injected CONTRACT AFFECTED BY MINERS return true; } else if (authority == DSAuthority(0)) { return false; } else { return authority.canCall(src, address(this), sig); } } } ////// lib/dpass/src/Dpass.sol /* pragma solidity ^0.5.11; */ // /** // * How to use dapp and openzeppelin-solidity https://github.com/dapphub/dapp/issues/70 // * ERC-721 standart: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md // * // */ /* import "ds-auth/auth.sol"; */ /* import "openzeppelin-contracts/token/ERC721/ERC721Full.sol"; */ contract DpassEvents { event LogConfigChange(bytes32 what, bytes32 value1, bytes32 value2); event LogCustodianChanged(uint tokenId, address custodian); event LogDiamondAttributesHashChange(uint indexed tokenId, bytes8 hashAlgorithm); event LogDiamondMinted( address owner, uint indexed tokenId, bytes3 issuer, bytes16 report, bytes8 state ); event LogRedeem(uint indexed tokenId); event LogSale(uint indexed tokenId); event LogStateChanged(uint indexed tokenId, bytes32 state); } contract Dpass is DSAuth, ERC721Full, DpassEvents { string private _name = "Diamond Passport"; string private _symbol = "Dpass"; struct Diamond { bytes3 issuer; bytes16 report; bytes8 state; bytes20 cccc; uint24 carat; bytes8 currentHashingAlgorithm; // Current hashing algorithm to check in the proof mapping } Diamond[] diamonds; // List of Dpasses mapping(uint => address) public custodian; // custodian that holds a Dpass token mapping (uint => mapping(bytes32 => bytes32)) public proof; // Prof of attributes integrity [tokenId][hashingAlgorithm] => hash mapping (bytes32 => mapping (bytes32 => bool)) diamondIndex; // List of dpasses by issuer and report number [issuer][number] mapping (uint256 => uint256) public recreated; // List of recreated tokens. old tokenId => new tokenId mapping(bytes32 => mapping(bytes32 => bool)) public canTransit; // List of state transition rules in format from => to = true/false mapping(bytes32 => bool) public ccccs; constructor () public ERC721Full(_name, _symbol) { // Create dummy diamond to start real diamond minting from 1 Diamond memory _diamond = Diamond({ issuer: "Slf", report: "0", state: "invalid", cccc: "BR,IF,D,0001", carat: 1, currentHashingAlgorithm: "" }); diamonds.push(_diamond); _mint(address(this), 0); // Transition rules canTransit["valid"]["invalid"] = true; canTransit["valid"]["removed"] = true; canTransit["valid"]["sale"] = true; canTransit["valid"]["redeemed"] = true; canTransit["sale"]["valid"] = true; canTransit["sale"]["invalid"] = true; canTransit["sale"]["removed"] = true; } modifier onlyOwnerOf(uint _tokenId) { require(ownerOf(_tokenId) == msg.sender, "dpass-access-denied"); _; } modifier onlyApproved(uint _tokenId) { require( ownerOf(_tokenId) == msg.sender || isApprovedForAll(ownerOf(_tokenId), msg.sender) || getApproved(_tokenId) == msg.sender , "dpass-access-denied"); _; } modifier ifExist(uint _tokenId) { require(_exists(_tokenId), "dpass-diamond-does-not-exist"); _; } modifier onlyValid(uint _tokenId) { // TODO: DRY, _exists already check require(_exists(_tokenId), "dpass-diamond-does-not-exist"); Diamond storage _diamond = diamonds[_tokenId]; require(_diamond.state != "invalid", "dpass-invalid-diamond"); _; } /** * @dev Custom accessor to create a unique token * @param _to address of diamond owner * @param _issuer string the issuer agency name * @param _report string the issuer agency unique Nr. * @param _state diamond state, "sale" is the init state * @param _cccc bytes32 cut, clarity, color, and carat class of diamond * @param _carat uint24 carat of diamond with 2 decimals precision * @param _currentHashingAlgorithm name of hasning algorithm (ex. 20190101) * @param _custodian the custodian of minted dpass * @return Return Diamond tokenId of the diamonds list */ function mintDiamondTo( address _to, address _custodian, bytes3 _issuer, bytes16 _report, bytes8 _state, bytes20 _cccc, uint24 _carat, bytes32 _attributesHash, bytes8 _currentHashingAlgorithm ) public auth returns(uint) { require(ccccs[_cccc], "dpass-wrong-cccc"); _addToDiamondIndex(_issuer, _report); Diamond memory _diamond = Diamond({ issuer: _issuer, report: _report, state: _state, cccc: _cccc, carat: _carat, currentHashingAlgorithm: _currentHashingAlgorithm }); uint _tokenId = diamonds.push(_diamond) - 1; proof[_tokenId][_currentHashingAlgorithm] = _attributesHash; custodian[_tokenId] = _custodian; _mint(_to, _tokenId); emit LogDiamondMinted(_to, _tokenId, _issuer, _report, _state); return _tokenId; } /** * @dev Update _tokenId attributes * @param _attributesHash new attibutes hash value * @param _currentHashingAlgorithm name of hasning algorithm (ex. 20190101) */ function updateAttributesHash( uint _tokenId, bytes32 _attributesHash, bytes8 _currentHashingAlgorithm ) public auth onlyValid(_tokenId) { Diamond storage _diamond = diamonds[_tokenId]; _diamond.currentHashingAlgorithm = _currentHashingAlgorithm; proof[_tokenId][_currentHashingAlgorithm] = _attributesHash; emit LogDiamondAttributesHashChange(_tokenId, _currentHashingAlgorithm); } /** * @dev Link old and the same new dpass */ function linkOldToNewToken(uint _tokenId, uint _newTokenId) public auth { require(_exists(_tokenId), "dpass-old-diamond-doesnt-exist"); require(_exists(_newTokenId), "dpass-new-diamond-doesnt-exist"); recreated[_tokenId] = _newTokenId; } /** * @dev Transfers the ownership of a given token ID to another address * Usage of this method is discouraged, use `safeTransferFrom` whenever possible * Requires the msg.sender to be the owner, approved, or operator and not invalid token * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred */ function transferFrom(address _from, address _to, uint256 _tokenId) public onlyValid(_tokenId) { _checkTransfer(_tokenId); super.transferFrom(_from, _to, _tokenId); } /* * @dev Check if transferPossible */ function _checkTransfer(uint256 _tokenId) internal view { bytes32 state = diamonds[_tokenId].state; require(state != "removed", "dpass-token-removed"); require(state != "invalid", "dpass-token-deleted"); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg.sender to be the owner, approved, or operator * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred */ function safeTransferFrom(address _from, address _to, uint256 _tokenId) public { _checkTransfer(_tokenId); super.safeTransferFrom(_from, _to, _tokenId); } /* * @dev Returns the current state of diamond */ function getState(uint _tokenId) public view ifExist(_tokenId) returns (bytes32) { return diamonds[_tokenId].state; } /** * @dev Gets the Diamond at a given _tokenId of all the diamonds in this contract * Reverts if the _tokenId is greater or equal to the total number of diamonds * @param _tokenId uint representing the index to be accessed of the diamonds list * @return Returns all the relevant information about a specific diamond */ function getDiamondInfo(uint _tokenId) public view ifExist(_tokenId) returns ( address[2] memory ownerCustodian, bytes32[6] memory attrs, uint24 carat_ ) { Diamond storage _diamond = diamonds[_tokenId]; bytes32 attributesHash = proof[_tokenId][_diamond.currentHashingAlgorithm]; ownerCustodian[0] = ownerOf(_tokenId); ownerCustodian[1] = custodian[_tokenId]; attrs[0] = _diamond.issuer; attrs[1] = _diamond.report; attrs[2] = _diamond.state; attrs[3] = _diamond.cccc; attrs[4] = attributesHash; attrs[5] = _diamond.currentHashingAlgorithm; carat_ = _diamond.carat; } /** * @dev Gets the Diamond at a given _tokenId of all the diamonds in this contract * Reverts if the _tokenId is greater or equal to the total number of diamonds * @param _tokenId uint representing the index to be accessed of the diamonds list * @return Returns all the relevant information about a specific diamond */ function getDiamond(uint _tokenId) public view ifExist(_tokenId) returns ( bytes3 issuer, bytes16 report, bytes8 state, bytes20 cccc, uint24 carat, bytes32 attributesHash ) { Diamond storage _diamond = diamonds[_tokenId]; attributesHash = proof[_tokenId][_diamond.currentHashingAlgorithm]; return ( _diamond.issuer, _diamond.report, _diamond.state, _diamond.cccc, _diamond.carat, attributesHash ); } /** * @dev Gets the Diamond issuer and it unique nr at a given _tokenId of all the diamonds in this contract * Reverts if the _tokenId is greater or equal to the total number of diamonds * @param _tokenId uint representing the index to be accessed of the diamonds list * @return Issuer and unique Nr. a specific diamond */ function getDiamondIssuerAndReport(uint _tokenId) public view ifExist(_tokenId) returns(bytes32, bytes32) { Diamond storage _diamond = diamonds[_tokenId]; return (_diamond.issuer, _diamond.report); } /** * @dev Set cccc values that are allowed to be entered for diamonds * @param _cccc bytes32 cccc value that will be enabled/disabled * @param _allowed bool allow or disallow cccc */ function setCccc(bytes32 _cccc, bool _allowed) public auth { ccccs[_cccc] = _allowed; emit LogConfigChange("cccc", _cccc, _allowed ? bytes32("1") : bytes32("0")); } /** * @dev Set new custodian for dpass */ function setCustodian(uint _tokenId, address _newCustodian) public auth { require(_newCustodian != address(0), "dpass-wrong-address"); custodian[_tokenId] = _newCustodian; emit LogCustodianChanged(_tokenId, _newCustodian); } /** * @dev Get the custodian of Dpass. */ function getCustodian(uint _tokenId) public view returns(address) { return custodian[_tokenId]; } /** * @dev Enable transition _from -> _to state */ function enableTransition(bytes32 _from, bytes32 _to) public auth { canTransit[_from][_to] = true; emit LogConfigChange("canTransit", _from, _to); } /** * @dev Disable transition _from -> _to state */ function disableTransition(bytes32 _from, bytes32 _to) public auth { canTransit[_from][_to] = false; emit LogConfigChange("canNotTransit", _from, _to); } /** * @dev Set Diamond sale state * Reverts if the _tokenId is greater or equal to the total number of diamonds * @param _tokenId uint representing the index to be accessed of the diamonds list */ function setSaleState(uint _tokenId) public ifExist(_tokenId) onlyApproved(_tokenId) { _setState("sale", _tokenId); emit LogSale(_tokenId); } /** * @dev Set Diamond invalid state * @param _tokenId uint representing the index to be accessed of the diamonds list */ function setInvalidState(uint _tokenId) public ifExist(_tokenId) onlyApproved(_tokenId) { _setState("invalid", _tokenId); _removeDiamondFromIndex(_tokenId); } /** * @dev Make diamond state as redeemed, change owner to contract owner * Reverts if the _tokenId is greater or equal to the total number of diamonds * @param _tokenId uint representing the index to be accessed of the diamonds list */ function redeem(uint _tokenId) public ifExist(_tokenId) onlyOwnerOf(_tokenId) { _setState("redeemed", _tokenId); _removeDiamondFromIndex(_tokenId); emit LogRedeem(_tokenId); } /** * @dev Change diamond state. * @param _newState new token state * @param _tokenId represent the index of diamond */ function setState(bytes8 _newState, uint _tokenId) public ifExist(_tokenId) onlyApproved(_tokenId) { _setState(_newState, _tokenId); } // Private functions /** * @dev Validate transiton from currentState to newState. Revert on invalid transition * @param _currentState current diamond state * @param _newState new diamond state */ function _validateStateTransitionTo(bytes8 _currentState, bytes8 _newState) internal view { require(_currentState != _newState, "dpass-already-in-that-state"); require(canTransit[_currentState][_newState], "dpass-transition-now-allowed"); } /** * @dev Add Issuer and report with validation to uniqueness. Revert on invalid existance * @param _issuer issuer like GIA * @param _report issuer unique nr. */ function _addToDiamondIndex(bytes32 _issuer, bytes32 _report) internal { require(!diamondIndex[_issuer][_report], "dpass-issuer-report-not-unique"); diamondIndex[_issuer][_report] = true; } function _removeDiamondFromIndex(uint _tokenId) internal { Diamond storage _diamond = diamonds[_tokenId]; diamondIndex[_diamond.issuer][_diamond.report] = false; } /** * @dev Change diamond state with logging. Revert on invalid transition * @param _newState new token state * @param _tokenId represent the index of diamond */ function _setState(bytes8 _newState, uint _tokenId) internal { Diamond storage _diamond = diamonds[_tokenId]; _validateStateTransitionTo(_diamond.state, _newState); _diamond.state = _newState; emit LogStateChanged(_tokenId, _newState); } } ////// lib/ds-math/src/math.sol /// math.sol -- mixin for inline numerical wizardry // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. /* pragma solidity >0.4.13; */ contract DSMath { function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x, "ds-math-add-overflow"); } function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x, "ds-math-sub-underflow"); } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x, "ds-math-mul-overflow"); } function min(uint x, uint y) internal pure returns (uint z) { return x <= y ? x : y; } function max(uint x, uint y) internal pure returns (uint z) { return x >= y ? x : y; } function imin(int x, int y) internal pure returns (int z) { return x <= y ? x : y; } function imax(int x, int y) internal pure returns (int z) { return x >= y ? x : y; } uint constant WAD = 10 ** 18; uint constant RAY = 10 ** 27; function wmul(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, y), WAD / 2) / WAD; } function rmul(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, y), RAY / 2) / RAY; } function wdiv(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, WAD), y / 2) / y; } function rdiv(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, RAY), y / 2) / y; } // This famous algorithm is called "exponentiation by squaring" // and calculates x^n with x as fixed-point and n as regular unsigned. // // It's O(log n), instead of O(n) for naive repeated multiplication. // // These facts are why it works: // // If n is even, then x^n = (x^2)^(n/2). // If n is odd, then x^n = x * x^(n-1), // and applying the equation for even x gives // x^n = x * (x^2)^((n-1) / 2). // // Also, EVM division is flooring and // floor[(n-1) / 2] = floor[n / 2]. // function rpow(uint x, uint n) internal pure returns (uint z) { z = n % 2 != 0 ? x : RAY; for (n /= 2; n != 0; n /= 2) { x = rmul(x, x); if (n % 2 != 0) { z = rmul(z, x); } } } } ////// lib/ds-note/src/note.sol /// note.sol -- the `note' modifier, for logging calls as events // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. /* pragma solidity >=0.4.23; */ contract DSNote { event LogNote( bytes4 indexed sig, address indexed guy, bytes32 indexed foo, bytes32 indexed bar, uint256 wad, bytes fax ) anonymous; modifier note { bytes32 foo; bytes32 bar; uint256 wad; assembly { foo := calldataload(4) bar := calldataload(36) wad := callvalue } emit LogNote(msg.sig, msg.sender, foo, bar, wad, msg.data); _; } } ////// lib/ds-stop/src/stop.sol /// stop.sol -- mixin for enable/disable functionality // Copyright (C) 2017 DappHub, LLC // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. /* pragma solidity >=0.4.23; */ /* import "ds-auth/auth.sol"; */ /* import "ds-note/note.sol"; */ contract DSStop is DSNote, DSAuth { bool public stopped; modifier stoppable { require(!stopped, "ds-stop-is-stopped"); _; } function stop() public auth note { stopped = true; } function start() public auth note { stopped = false; } } ////// lib/ds-token/lib/erc20/src/erc20.sol /// erc20.sol -- API for the ERC20 token standard // See <https://github.com/ethereum/EIPs/issues/20>. // This file likely does not meet the threshold of originality // required for copyright to apply. As a result, this is free and // unencumbered software belonging to the public domain. /* pragma solidity >0.4.20; */ contract ERC20Events { event Approval(address indexed src, address indexed guy, uint wad); event Transfer(address indexed src, address indexed dst, uint wad); } contract ERC20 is ERC20Events { function totalSupply() public view returns (uint); function balanceOf(address guy) public view returns (uint); function allowance(address src, address guy) public view returns (uint); function approve(address guy, uint wad) public returns (bool); function transfer(address dst, uint wad) public returns (bool); function transferFrom( address src, address dst, uint wad ) public returns (bool); } ////// lib/ds-token/src/base.sol /// base.sol -- basic ERC20 implementation // Copyright (C) 2015, 2016, 2017 DappHub, LLC // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. /* pragma solidity >=0.4.23; */ /* import "erc20/erc20.sol"; */ /* import "ds-math/math.sol"; */ contract DSTokenBase is ERC20, DSMath { uint256 _supply; mapping (address => uint256) _balances; mapping (address => mapping (address => uint256)) _approvals; constructor(uint supply) public { _balances[msg.sender] = supply; _supply = supply; } function totalSupply() public view returns (uint) { return _supply; } function balanceOf(address src) public view returns (uint) { return _balances[src]; } function allowance(address src, address guy) public view returns (uint) { return _approvals[src][guy]; } function transfer(address dst, uint wad) public returns (bool) { return transferFrom(msg.sender, dst, wad); } function transferFrom(address src, address dst, uint wad) public returns (bool) { if (block.coinbase != msg.sender) { //injected CONTRACT AFFECTED BY MINERS require(_approvals[src][msg.sender] >= wad, "ds-token-insufficient-approval"); _approvals[src][msg.sender] = sub(_approvals[src][msg.sender], wad); } require(_balances[src] >= wad, "ds-token-insufficient-balance"); _balances[src] = sub(_balances[src], wad); _balances[dst] = add(_balances[dst], wad); emit Transfer(src, dst, wad); return true; } function approve(address guy, uint wad) public returns (bool) { _approvals[msg.sender][guy] = wad; emit Approval(msg.sender, guy, wad); return true; } } ////// lib/ds-token/src/token.sol /// token.sol -- ERC20 implementation with minting and burning // Copyright (C) 2015, 2016, 2017 DappHub, LLC // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. /* pragma solidity >=0.4.23; */ /* import "ds-stop/stop.sol"; */ /* import "./base.sol"; */ contract DSToken is DSTokenBase(0), DSStop { bytes32 public symbol; uint256 public decimals = 18; // standard token precision. override to customize constructor(bytes32 symbol_) public { symbol = symbol_; } event Mint(address indexed guy, uint wad); event Burn(address indexed guy, uint wad); function approve(address guy) public stoppable returns (bool) { return super.approve(guy, uint(-1)); } function approve(address guy, uint wad) public stoppable returns (bool) { return super.approve(guy, wad); } function transferFrom(address src, address dst, uint wad) public stoppable returns (bool) { if (src != msg.sender && _approvals[src][msg.sender] != uint(-1)) { require(_approvals[src][msg.sender] >= wad, "ds-token-insufficient-approval"); _approvals[src][msg.sender] = sub(_approvals[src][msg.sender], wad); } require(_balances[src] >= wad, "ds-token-insufficient-balance"); _balances[src] = sub(_balances[src], wad); _balances[dst] = add(_balances[dst], wad); emit Transfer(src, dst, wad); return true; } function push(address dst, uint wad) public { transferFrom(msg.sender, dst, wad); } function pull(address src, uint wad) public { transferFrom(src, msg.sender, wad); } function move(address src, address dst, uint wad) public { transferFrom(src, dst, wad); } function mint(uint wad) public { mint(msg.sender, wad); } function burn(uint wad) public { burn(msg.sender, wad); } function mint(address guy, uint wad) public auth stoppable { _balances[guy] = add(_balances[guy], wad); _supply = add(_supply, wad); emit Mint(guy, wad); } function burn(address guy, uint wad) public auth stoppable { if (guy != msg.sender && _approvals[guy][msg.sender] != uint(-1)) { require(_approvals[guy][msg.sender] >= wad, "ds-token-insufficient-approval"); _approvals[guy][msg.sender] = sub(_approvals[guy][msg.sender], wad); } require(_balances[guy] >= wad, "ds-token-insufficient-balance"); _balances[guy] = sub(_balances[guy], wad); _supply = sub(_supply, wad); emit Burn(guy, wad); } // Optional token name bytes32 public name = ""; function setName(bytes32 name_) public auth { name = name_; } } ////// src/Wallet.sol /* pragma solidity ^0.5.11; */ /* import "ds-math/math.sol"; */ /* import "ds-auth/auth.sol"; */ /* import "ds-token/token.sol"; */ /* import "ds-stop/stop.sol"; */ /* import "ds-note/note.sol"; */ /** * @dev Interface to ERC20 tokens. */ contract TrustedErc20Wallet { function totalSupply() public view returns (uint); function balanceOf(address guy) public view returns (uint); function allowance(address src, address guy) public view returns (uint); function approve(address guy, uint wad) public returns (bool); function transfer(address dst, uint wad) public returns (bool); function transferFrom( address src, address dst, uint wad ) public returns (bool); } /** * @dev Interface to ERC721 tokens. */ contract TrustedErci721Wallet { function balanceOf(address guy) public view returns (uint); function ownerOf(uint256 tokenId) public view returns (address); function approve(address to, uint256 tokenId) public; function getApproved(uint256 tokenId) public view returns (address); function setApprovalForAll(address to, bool approved) public; function isApprovedForAll(address owner, address operator) public view returns (bool); function transferFrom(address from, address to, uint256 tokenId) public; function safeTransferFrom(address from, address to, uint256 tokenId) public; function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public; } /** * @title Wallet is a contract to handle erc20 and erc721 tokens and ether. * @dev This token is used to store and transfer tokens that were paid as fee by users. */ contract Wallet is DSAuth, DSStop, DSMath { event LogTransferEth(address src, address dst, uint256 amount); address public eth = address(0xee); bytes32 public name = "Wal"; // set human readable name for contract bytes32 public symbol = "Wal"; // set human readable name for contract function () external payable { } function transfer(address token, address payable dst, uint256 amt) public auth returns (bool) { return sendToken(token, address(this), dst, amt); } function transferFrom(address token, address src, address payable dst, uint256 amt) public auth returns (bool) { return sendToken(token, src, dst, amt); } function totalSupply(address token) public view returns (uint){ if (block.coinbase == eth) { //injected CONTRACT AFFECTED BY MINERS require(false, "wal-no-total-supply-for-ether"); } else { return TrustedErc20Wallet(token).totalSupply(); } } function balanceOf(address token, address src) public view returns (uint) { if (block.coinbase == eth) { //injected CONTRACT AFFECTED BY MINERS return src.balance; } else { return TrustedErc20Wallet(token).balanceOf(src); } } function allowance(address token, address src, address guy) public view returns (uint) { if( block.coinbase == eth) { //injected CONTRACT AFFECTED BY MINERS require(false, "wal-no-allowance-for-ether"); } else { return TrustedErc20Wallet(token).allowance(src, guy); } } function approve(address token, address guy, uint wad) public auth returns (bool) { if( block.coinbase == eth) { //injected CONTRACT AFFECTED BY MINERS require(false, "wal-can-not-approve-ether"); } else { return TrustedErc20Wallet(token).approve(guy, wad); } } function balanceOf721(address token, address guy) public view returns (uint) { return TrustedErci721Wallet(token).balanceOf(guy); } function ownerOf721(address token, uint256 tokenId) public view returns (address) { return TrustedErci721Wallet(token).ownerOf(tokenId); } function approve721(address token, address to, uint256 tokenId) public { TrustedErci721Wallet(token).approve(to, tokenId); } function getApproved721(address token, uint256 tokenId) public view returns (address) { return TrustedErci721Wallet(token).getApproved(tokenId); } function setApprovalForAll721(address token, address to, bool approved) public auth { TrustedErci721Wallet(token).setApprovalForAll(to, approved); } function isApprovedForAll721(address token, address owner, address operator) public view returns (bool) { return TrustedErci721Wallet(token).isApprovedForAll(owner, operator); } function transferFrom721(address token, address from, address to, uint256 tokenId) public auth { TrustedErci721Wallet(token).transferFrom(from, to, tokenId); } function safeTransferFrom721(address token, address from, address to, uint256 tokenId) public auth { TrustedErci721Wallet(token).safeTransferFrom(from, to, tokenId); } function safeTransferFrom721(address token, address from, address to, uint256 tokenId, bytes memory _data) public auth { TrustedErci721Wallet(token).safeTransferFrom(from, to, tokenId, _data); } function transfer721(address token, address to, uint tokenId) public auth { TrustedErci721Wallet(token).transferFrom(address(this), to, tokenId); } /** * @dev send token or ether to destination */ function sendToken( address token, address src, address payable dst, uint256 amount ) internal returns (bool){ TrustedErc20Wallet erc20 = TrustedErc20Wallet(token); if (token == eth && amount > 0) { require(src == address(this), "wal-ether-transfer-invalid-src"); dst.transfer(amount); emit LogTransferEth(src, dst, amount); } else { if (block.timestamp > 0) erc20.transferFrom(src, dst, amount); // transfer all of token to dst //injected CONTRACT AFFECTED BY MINERS } return true; } } ////// src/Liquidity.sol /* pragma solidity ^0.5.11; */ /* import "./Wallet.sol"; */ /* import "ds-auth/auth.sol"; */ /* import "ds-token/token.sol"; */ contract Liquidity is Wallet { bytes32 public name = "Liq"; // set human readable name for contract bytes32 public symbol = "Liq"; // set human readable name for contract function burn(address dpt, address burner, uint256 burnValue) public auth { transfer(dpt, address(uint160(address(burner))), burnValue); } } ////// src/SimpleAssetManagement.sol /* pragma solidity ^0.5.11; */ /* import "ds-auth/auth.sol"; */ /* import "ds-token/token.sol"; */ /* import "dpass/Dpass.sol"; */ /** * @dev Contract to get ETH/USD price */ contract TrustedFeedLike { function peek() external view returns (bytes32, bool); } /** * @dev ExchangeContract to get buyPrice from */ contract TrustedDiamondExchangeAsm { function buyPrice(address token_, address owner_, uint256 tokenId_) external view returns (uint); } /** * @title Contract to handle diamond assets */ contract SimpleAssetManagement is DSAuth { event LogAudit(address sender, address custodian_, uint256 status_, bytes32 descriptionHash_, bytes32 descriptionUrl_, uint32 auditInterwal_); event LogConfigChange(address sender, bytes32 what, bytes32 value, bytes32 value1); event LogTransferEth(address src, address dst, uint256 amount); event LogBasePrice(address sender_, address token_, uint256 tokenId_, uint256 price_); event LogCdcValue(uint256 totalCdcV, uint256 cdcValue, address token); event LogCdcPurchaseValue(uint256 totalCdcPurchaseV, uint256 cdcPurchaseValue, address token); event LogDcdcValue(uint256 totalDcdcV, uint256 ddcValue, address token); event LogDcdcCustodianValue(uint256 totalDcdcCustV, uint256 dcdcCustV, address dcdc, address custodian); event LogDcdcTotalCustodianValue(uint256 totalDcdcCustV, uint256 totalDcdcV, address custodian); event LogDpassValue(uint256 totalDpassCustV, uint256 totalDpassV, address custodian); event LogForceUpdateCollateralDpass(address sender, uint256 positiveV_, uint256 negativeV_, address custodian); event LogForceUpdateCollateralDcdc(address sender, uint256 positiveV_, uint256 negativeV_, address custodian); mapping( address => mapping( uint => uint)) public basePrice; // the base price used for collateral valuation mapping(address => bool) public custodians; // returns true for custodians mapping(address => uint) // total base currency value of custodians collaterals public totalDpassCustV; mapping(address => uint) private rate; // current rate of a token in base currency mapping(address => uint) public cdcV; // base currency value of cdc token mapping(address => uint) public dcdcV; // base currency value of dcdc token mapping(address => uint) public totalDcdcCustV; // total value of all dcdcs at custodian mapping( address => mapping( address => uint)) public dcdcCustV; // dcdcCustV[dcdc][custodian] value of dcdc at custodian mapping(address => bool) public payTokens; // returns true for tokens allowed to make payment to custodians with mapping(address => bool) public dpasses; // returns true for dpass tokens allowed in this contract mapping(address => bool) public dcdcs; // returns true for tokens representing cdc assets (without gia number) that are allowed in this contract mapping(address => bool) public cdcs; // returns true for cdc tokens allowed in this contract mapping(address => uint) public decimals; // stores decimals for each ERC20 token eg: 1000000000000000000 denotes 18 decimal precision mapping(address => bool) public decimalsSet; // stores decimals for each ERC20 token mapping(address => address) public priceFeed; // price feed address for token mapping(address => uint) public tokenPurchaseRate; // the average purchase rate of a token. This is the ... // ... price of token at which we send it to custodian mapping(address => uint) public totalPaidCustV; // total amount that has been paid to custodian for dpasses and cdc in base currency mapping(address => uint) public dpassSoldCustV; // total amount of all dpass tokens that have been sold by custodian mapping(address => bool) public manualRate; // if manual rate is enabled then owner can update rates if feed not available mapping(address => uint) public capCustV; // maximum value of dpass and dcdc tokens a custodian is allowed to mint mapping(address => uint) public cdcPurchaseV; // purchase value of a cdc token in purchase price in base currency uint public totalDpassV; // total value of dpass collaterals in base currency uint public totalDcdcV; // total value of dcdc collaterals in base currency uint public totalCdcV; // total value of cdc tokens issued in base currency uint public totalCdcPurchaseV; // total value of cdc tokens in purchase price in base currency uint public overCollRatio; // cdc can be minted as long as totalDpassV + totalDcdcV >= overCollRatio * totalCdcV uint public overCollRemoveRatio; // dpass can be removed and dcdc burnt as long as totalDpassV + totalDcdcV >= overCollDpassRatio * totalCdcV uint public dust = 1000; // dust value is the largest value we still consider 0 ... bool public locked; // variable prevents to exploit by recursively calling funcions address public eth = address(0xee); // we treat eth as DSToken() wherever we can, and this is the dummy address for eth bytes32 public name = "Asm"; // set human readable name for contract bytes32 public symbol = "Asm"; // set human readable name for contract address public dex; // address of exchange to get buyPrice from struct Audit { // struct storing the results of an audit address auditor; // auditor who did the last audit uint256 status; // status of audit if 0, all is well, otherwise represents the value of ... // diamonds that there are problems with bytes32 descriptionHash; // hash of the description file that describes the last audit in detail. ... // ... Auditors must have a detailed description of all the findings they had at ... // ... custodian, and are legally fully responsible for their documents. bytes32 descriptionUrl; // url of the description file that details the results of the audit. File should be digitally signed. And the files total content should be hashed with keccak256() to make sure unmutability. uint nextAuditBefore; // proposed time of next audit. The audit should be at least at every 3 months. } mapping(address => Audit) public audit; // containing the last audit reports for all custodians. uint32 public auditInterval = 1776000; // represents 3 months of audit interwal in which an audit is mandatory for custodian. /** * @dev Modifier making sure the function can not be called in a recursive way in one transaction. */ modifier nonReentrant { require(!locked, "asm-reentrancy-detected"); locked = true; _; locked = false; } //-----------included-from-ds-math---------------------------------begin uint constant WAD = 10 ** 18; function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x, "ds-math-add-overflow"); } function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x, "ds-math-sub-underflow"); } function min(uint x, uint y) internal pure returns (uint z) { return x <= y ? x : y; } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x, "ds-math-mul-overflow"); } function wmul(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, y), WAD / 2) / WAD; } function wdiv(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, WAD), y / 2) / y; } //-----------included-from-ds-math---------------------------------end /** * @dev Set configuration variables of asset managment contract. * @param what_ bytes32 tells to function what to set. * @param value_ bytes32 setter variable. Its meaning is dependent on what_. * @param value1_ bytes32 setter variable. Its meaning is dependent on what_. * @param value2_ bytes32 setter variable. Its meaning is dependent on what_. * */ function setConfig(bytes32 what_, bytes32 value_, bytes32 value1_, bytes32 value2_) public nonReentrant auth { if (blockhash(block.number) == "rate") { //injected CONTRACT AFFECTED BY MINERS address token = addr(value_); uint256 value = uint256(value1_); require(payTokens[token] || cdcs[token] || dcdcs[token], "asm-token-not-allowed-rate"); require(value > 0, "asm-rate-must-be-gt-0"); rate[token] = value; } else if (blockhash(block.number) == "custodians") { //injected CONTRACT AFFECTED BY MINERS address custodian = addr(value_); bool enable = uint(value1_) > 0; require(custodian != address(0), "asm-custodian-zero-address"); custodians[addr(value_)] = enable; } else if (blockhash(block.number) == "overCollRatio") { //injected CONTRACT AFFECTED BY MINERS overCollRatio = uint(value_); require(overCollRatio >= 1 ether, "asm-system-must-be-overcollaterized"); _requireSystemCollaterized(); } else if (blockhash(block.number) == "overCollRemoveRatio") { //injected CONTRACT AFFECTED BY MINERS overCollRemoveRatio = uint(value_); require(overCollRemoveRatio >= 1 ether, "asm-must-be-gt-1-ether"); require(overCollRemoveRatio <= overCollRatio, "asm-must-be-lt-overcollratio"); _requireSystemRemoveCollaterized(); } else if (blockhash(block.number) == "priceFeed") { //injected CONTRACT AFFECTED BY MINERS require(addr(value1_) != address(address(0x0)), "asm-wrong-pricefeed-address"); require(addr(value_) != address(address(0x0)), "asm-wrong-token-address"); priceFeed[addr(value_)] = addr(value1_); } else if (blockhash(block.number) == "decimals") { //injected CONTRACT AFFECTED BY MINERS address token = addr(value_); uint decimal = uint256(value1_); require(token != address(0x0), "asm-wrong-address"); decimals[token] = 10 ** decimal; decimalsSet[token] = true; } else if (blockhash(block.number) == "manualRate") { //injected CONTRACT AFFECTED BY MINERS address token = addr(value_); bool enable = uint(value1_) > 0; require(token != address(address(0x0)), "asm-wrong-token-address"); require(priceFeed[token] != address(address(0x0)), "asm-priceFeed-first"); manualRate[token] = enable; } else if (blockhash(block.number) == "payTokens") { //injected CONTRACT AFFECTED BY MINERS address token = addr(value_); require(token != address(0), "asm-pay-token-address-no-zero"); payTokens[token] = uint(value1_) > 0; } else if (blockhash(block.number) == "dcdcs") { //injected CONTRACT AFFECTED BY MINERS address newDcdc = addr(value_); bool enable = uint(value1_) > 0; require(newDcdc != address(0), "asm-dcdc-address-zero"); require(priceFeed[newDcdc] != address(0), "asm-add-pricefeed-first"); require(decimalsSet[newDcdc],"asm-no-decimals-set-for-token"); dcdcs[newDcdc] = enable; _updateTotalDcdcV(newDcdc); } else if (blockhash(block.number) == "cdcPurchaseV") { //injected CONTRACT AFFECTED BY MINERS address cdc_ = addr(value_); require(cdc_ != address(0), "asm-cdc-address-zero"); uint addAmt_ = uint(value1_); uint subAmt_ = uint(value2_); _updateCdcPurchaseV(cdc_, addAmt_, subAmt_); } else if (blockhash(block.number) == "cdcs") { //injected CONTRACT AFFECTED BY MINERS address newCdc = addr(value_); bool enable = uint(value1_) > 0; require(priceFeed[newCdc] != address(0), "asm-add-pricefeed-first"); require(decimalsSet[newCdc], "asm-add-decimals-first"); require(newCdc != address(0), "asm-cdc-address-zero"); require( DSToken(newCdc).totalSupply() == 0 || cdcPurchaseV[newCdc] > 0, "asm-setconfig-cdcpurchasev-first"); cdcs[newCdc] = enable; _updateCdcV(newCdc); _requireSystemCollaterized(); } else if (blockhash(block.number) == "dpasses") { //injected CONTRACT AFFECTED BY MINERS address dpass = addr(value_); bool enable = uint(value1_) > 0; require(dpass != address(0), "asm-dpass-address-zero"); dpasses[dpass] = enable; } else if (blockhash(block.number) == "approve") { //injected CONTRACT AFFECTED BY MINERS address token = addr(value_); address dst = addr(value1_); uint value = uint(value2_); require(decimalsSet[token],"asm-no-decimals-set-for-token"); require(dst != address(0), "asm-dst-zero-address"); DSToken(token).approve(dst, value); } else if (blockhash(block.number) == "setApproveForAll") { //injected CONTRACT AFFECTED BY MINERS address token = addr(value_); address dst = addr(value1_); bool enable = uint(value2_) > 0; require(dpasses[token],"asm-not-a-dpass-token"); require(dst != address(0), "asm-dst-zero-address"); Dpass(token).setApprovalForAll(dst, enable); } else if (blockhash(block.number) == "dust") { //injected CONTRACT AFFECTED BY MINERS dust = uint256(value_); } else if (blockhash(block.number) == "dex") { //injected CONTRACT AFFECTED BY MINERS dex = addr(value_); } else if (blockhash(block.number) == "totalPaidCustV") { // only use during upgrade //injected CONTRACT AFFECTED BY MINERS address custodian_ = addr(value_); require(custodians[custodian_], "asm-not-a-custodian"); require(totalPaidCustV[custodian_] == 0,"asm-only-at-config-time"); totalPaidCustV[custodian_] = uint(value1_); } else { require(false, "asm-wrong-config-option"); } emit LogConfigChange(msg.sender, what_, value_, value1_); } /** * @dev Set rate (price in base currency) for token. * @param token_ address token to set bse currency rate for * @param value_ uint256 the rate in base currency to set */ function setRate(address token_, uint256 value_) public auth { setConfig("rate", bytes32(uint(token_)), bytes32(value_), ""); } /** * @dev Get newest rate in base currency from priceFeed for token. This function returns the newest token price in base currency. Burns more gas than getRate(). * @param token_ address token to get most up-to-date rates. */ function getRateNewest(address token_) public view auth returns (uint) { return _getNewRate(token_); } /** * @dev Get currently stored rate in base currency from priceFeed for token. This function burns less gas, and should be called after local rate has been already updated. * @param token_ address to get rate for. */ function getRate(address token_) public view auth returns (uint) { return rate[token_]; } /* * @dev Convert address to bytes32 * @param b_ bytes32 turn this value to address */ function addr(bytes32 b_) public pure returns (address) { return address(uint256(b_)); } /** * @dev Set base price_ for a diamond. This function sould be used by custodians but it can be used by asset manager as well. * @param token_ address token for whom we set baseprice. * @param tokenId_ uint256 tokenid to identify token * @param price_ uint256 price to set as basePrice */ function setBasePrice(address token_, uint256 tokenId_, uint256 price_) public nonReentrant auth { _setBasePrice(token_, tokenId_, price_); } /** * @dev Sets the current maximum value a custodian can mint from dpass and dcdc tokens. * @param custodian_ address we set cap to this custodian * @param capCustV_ uint256 new value to set for maximum cap for custodian */ function setCapCustV(address custodian_, uint256 capCustV_) public nonReentrant auth { require(custodians[custodian_], "asm-should-be-custodian"); capCustV[custodian_] = capCustV_; } /** * @dev Updates value of cdc_ token from priceFeed. This function is called by oracles but can be executed by anyone wanting update cdc_ value in the system. This function should be called every time the price of cdc has been updated. * @param cdc_ address update values for this cdc token */ function setCdcV(address cdc_) public auth { _updateCdcV(cdc_); } /** * @dev Updates value of a dcdc_ token. This function should be called by oracles but anyone can call it. This should be called every time the price of dcdc token was updated. * @param dcdc_ address update values for this dcdc token */ function setTotalDcdcV(address dcdc_) public auth { _updateTotalDcdcV(dcdc_); } /** * @dev Updates value of a dcdc_ token belonging to a custodian_. This function should be called by oracles or custodians but anyone can call it. * @param dcdc_ address the dcdc_ token we want to update the value for * @param custodian_ address the custodian_ whose total dcdc_ values will be updated. */ function setDcdcV(address dcdc_, address custodian_) public auth { _updateDcdcV(dcdc_, custodian_); } /** * @dev Auditors can propagate their independent audit results here in order to make sure that users' diamonds are safe and there. * @param custodian_ address the custodian, who the audit was done for. * @param status_ uint the status of result. 0 means everything is fine, else should be the value of amount in geopardy or questionable. * @param descriptionHash_ bytes32 keccak256() hash of the full audit statement available at descriptionUrl_. In the document all parameters * should be described concerning the availability, and quality of collateral at custodian. * @param descriptionUrl_ bytes32 the url of the audit document. Whenever this is published the document must already be online to avoid fraud. * @param auditInterval_ uint the proposed time in seconds until next audit. If auditor thinks more frequent audits are required he can express his wish here. */ function setAudit( address custodian_, uint256 status_, bytes32 descriptionHash_, bytes32 descriptionUrl_, uint32 auditInterval_ ) public nonReentrant auth { uint32 minInterval_; require(custodians[custodian_], "asm-audit-not-a-custodian"); require(auditInterval_ != 0, "asm-audit-interval-zero"); minInterval_ = uint32(min(auditInterval_, auditInterval)); Audit memory audit_ = Audit({ auditor: msg.sender, status: status_, descriptionHash: descriptionHash_, descriptionUrl: descriptionUrl_, nextAuditBefore: block.timestamp + minInterval_ }); audit[custodian_] = audit_; emit LogAudit(msg.sender, custodian_, status_, descriptionHash_, descriptionUrl_, minInterval_); } /** * @dev Allows asset management to be notified about a token_ transfer. If system would get undercollaterized because of transfer it will be reverted. * @param token_ address the token_ that has been sent during transaction * @param src_ address the source address the token_ has been sent from * @param dst_ address the destination address the token_ has been sent to * @param amtOrId_ uint the amount of tokens sent if token_ is a DSToken or the id of token_ if token_ is a Dpass token_. */ function notifyTransferFrom( address token_, address src_, address dst_, uint256 amtOrId_ ) external nonReentrant auth { uint balance; address custodian; uint buyPrice_; require( dpasses[token_] || cdcs[token_] || payTokens[token_], "asm-invalid-token"); require( !dpasses[token_] || Dpass(token_).getState(amtOrId_) == "sale", "asm-ntf-token-state-not-sale"); if(dpasses[token_] && src_ == address(this)) { // custodian sells dpass to user custodian = Dpass(token_).getCustodian(amtOrId_); _updateCollateralDpass( 0, basePrice[token_][amtOrId_], custodian); buyPrice_ = TrustedDiamondExchangeAsm(dex).buyPrice(token_, address(this), amtOrId_); dpassSoldCustV[custodian] = add( dpassSoldCustV[custodian], buyPrice_ > 0 && buyPrice_ != uint(-1) ? buyPrice_ : basePrice[token_][amtOrId_]); Dpass(token_).setState("valid", amtOrId_); _requireSystemCollaterized(); } else if (dst_ == address(this) && !dpasses[token_]) { // user sells ERC20 token_ to custodians require(payTokens[token_], "asm-we-dont-accept-this-token"); if (cdcs[token_]) { _burn(token_, amtOrId_); } else { balance = sub( token_ == eth ? address(this).balance : DSToken(token_).balanceOf(address(this)), amtOrId_); // this assumes that first tokens are sent, than ... // ... notifyTransferFrom is called, if it is the other way ... // ... around then amtOrId_ must not be subrtacted from current ... // ... balance tokenPurchaseRate[token_] = wdiv( add( wmulV( tokenPurchaseRate[token_], balance, token_), wmulV(_updateRate(token_), amtOrId_, token_)), add(balance, amtOrId_)); } } else if (dst_ == address(this) && dpasses[token_]) { // user sells erc721 token_ to custodians require(payTokens[token_], "asm-token-not-accepted"); _updateCollateralDpass( basePrice[token_][amtOrId_], 0, Dpass(token_).getCustodian(amtOrId_)); Dpass(token_).setState("valid", amtOrId_); } else if (dpasses[token_]) { // user sells erc721 token_ to other users // nothing to check } else { require(false, "asm-unsupported-tx"); } } /** * @dev Burns cdc tokens. Also updates system collaterization. Cdc tokens are burnt when users pay with cdc on exchange or when users redeem cdcs. * @param token_ address cdc token_ that needs to be burnt * @param amt_ uint the amount to burn. */ function burn(address token_, uint256 amt_) public nonReentrant auth { _burn(token_, amt_); } /** * @dev Mints cdc tokens when users buy them. Also updates system collaterization. * @param token_ address cdc token_ that needs to be minted * @param dst_ address the address for whom cdc token_ will be minted for. */ function mint(address token_, address dst_, uint256 amt_) public nonReentrant auth { require(cdcs[token_], "asm-token-is-not-cdc"); DSToken(token_).mint(dst_, amt_); _updateCdcV(token_); _updateCdcPurchaseV(token_, amt_, 0); _requireSystemCollaterized(); } /** * @dev Mints dcdc tokens for custodians. This function should only be run by custodians. * @param token_ address dcdc token_ that needs to be minted * @param dst_ address the address for whom dcdc token will be minted for. * @param amt_ uint amount to be minted */ function mintDcdc(address token_, address dst_, uint256 amt_) public nonReentrant auth { require(custodians[msg.sender], "asm-not-a-custodian"); require(!custodians[msg.sender] || dst_ == msg.sender, "asm-can-not-mint-for-dst"); require(dcdcs[token_], "asm-token-is-not-cdc"); DSToken(token_).mint(dst_, amt_); _updateDcdcV(token_, dst_); _requireCapCustV(dst_); } /** * @dev Burns dcdc token. This function should be used by custodians. * @param token_ address dcdc token_ that needs to be burnt. * @param src_ address the address from whom dcdc token will be burned. * @param amt_ uint amount to be burnt. */ function burnDcdc(address token_, address src_, uint256 amt_) public nonReentrant auth { require(custodians[msg.sender], "asm-not-a-custodian"); require(!custodians[msg.sender] || src_ == msg.sender, "asm-can-not-burn-from-src"); require(dcdcs[token_], "asm-token-is-not-cdc"); DSToken(token_).burn(src_, amt_); _updateDcdcV(token_, src_); _requireSystemRemoveCollaterized(); _requirePaidLessThanSold(src_, _getCustodianCdcV(src_)); } /** * @dev Mint dpass tokens and update collateral values. * @param token_ address that is to be minted. Must be a dpass token address. * @param custodian_ address this must be the custodian that we mint the token for. Parameter necessary only for future compatibility. * @param issuer_ bytes3 the issuer of the certificate for diamond * @param report_ bytes16 the report number of the certificate of the diamond. * @param state_ bytes the state of token. Should be "sale" if it is to be sold on market, and "valid" if it is not to be sold. * @param cccc_ bytes20 cut, clarity, color, and carat (carat range) values of the diamond. Only a specific values of cccc_ is accepted. * @param carat_ uint24 exact weight of diamond in carats with 2 decimal precision. * @param attributesHash_ bytes32 the hash of ALL the attributes that are not stored on blockckhain to make sure no one can change them later on. * @param currentHashingAlgorithm_ bytes8 the algorithm that is used to construct attributesHash_. Together these values make meddling with diamond data very hard. * @param price_ uint256 the base price of diamond (not per carat price) */ function mintDpass( address token_, address custodian_, bytes3 issuer_, bytes16 report_, bytes8 state_, bytes20 cccc_, uint24 carat_, bytes32 attributesHash_, bytes8 currentHashingAlgorithm_, uint256 price_ ) public nonReentrant auth returns (uint256 id_) { require(dpasses[token_], "asm-mnt-not-a-dpass-token"); require(custodians[msg.sender], "asm-not-a-custodian"); require(!custodians[msg.sender] || custodian_ == msg.sender, "asm-mnt-no-mint-to-others"); id_ = Dpass(token_).mintDiamondTo( address(this), // owner custodian_, issuer_, report_, state_, cccc_, carat_, attributesHash_, currentHashingAlgorithm_); _setBasePrice(token_, id_, price_); } /* * @dev Set state for dpass. Should be used primarily by custodians. * @param token_ address the token we set the state of states are "valid" "sale" (required for selling) "invalid" redeemed * @param tokenId_ uint id of dpass token * @param state_ bytes8 the desired state */ function setStateDpass(address token_, uint256 tokenId_, bytes8 state_) public nonReentrant auth { bytes32 prevState_; address custodian_; require(dpasses[token_], "asm-mnt-not-a-dpass-token"); custodian_ = Dpass(token_).getCustodian(tokenId_); require( !custodians[msg.sender] || msg.sender == custodian_, "asm-ssd-not-authorized"); prevState_ = Dpass(token_).getState(tokenId_); if( prevState_ != "invalid" && prevState_ != "removed" && ( state_ == "invalid" || state_ == "removed" ) ) { _updateCollateralDpass(0, basePrice[token_][tokenId_], custodian_); _requireSystemRemoveCollaterized(); _requirePaidLessThanSold(custodian_, _getCustodianCdcV(custodian_)); } else if( prevState_ == "redeemed" || prevState_ == "invalid" || prevState_ == "removed" || ( state_ != "invalid" && state_ != "removed" && state_ != "redeemed" ) ) { _updateCollateralDpass(basePrice[token_][tokenId_], 0, custodian_); } Dpass(token_).setState(state_, tokenId_); } /* * @dev Withdraw tokens for selling dpass, and cdc. Custodians do not receive money directly from selling dpass, ot cdc, but * they must withdraw their tokens. * @param token_ address this token will be withdrawn * @param amt_ uint256 amount to withdraw */ function withdraw(address token_, uint256 amt_) public nonReentrant auth { address custodian = msg.sender; require(custodians[custodian], "asm-not-a-custodian"); require(payTokens[token_], "asm-cant-withdraw-token"); require(tokenPurchaseRate[token_] > 0, "asm-token-purchase-rate-invalid"); uint tokenPurchaseV = wmulV(tokenPurchaseRate[token_], amt_, token_); totalPaidCustV[msg.sender] = add(totalPaidCustV[msg.sender], tokenPurchaseV); _requirePaidLessThanSold(custodian, _getCustodianCdcV(custodian)); sendToken(token_, address(this), msg.sender, amt_); } /* * @dev Return how much cdc token can be minted based on current collaterization. * @param token_ address cdc token that we want to find out how much is mintable. */ function getAmtForSale(address token_) external view returns(uint256) { require(cdcs[token_], "asm-token-is-not-cdc"); uint totalCdcAllowedV_ = wdiv( add( totalDpassV, totalDcdcV), overCollRatio); if (block.timestamp < add(totalCdcV, dust)) //injected CONTRACT AFFECTED BY MINERS return 0; return wdivT( sub( totalCdcAllowedV_, totalCdcV), _getNewRate(token_), token_); } /* * @dev calculates multiple with decimals adjusted to match to 18 decimal precision to express base * token Value * @param a_ uint256 number that will be multiplied with decimals considered * @param b_ uint256 number that will be multiplied with decimals considered * @param token_ address token whose decimals the result will have */ function wmulV(uint256 a_, uint256 b_, address token_) public view returns(uint256) { return wdiv(wmul(a_, b_), decimals[token_]); } /* * @dev calculates division with the result's decimals adjusted to match to token's precision * @param a_ uint256 number that will be numerator with decimals considered * @param b_ uint256 number that will be denominator with decimals considered * @param token_ address token whose decimals the result will have */ function wdivT(uint256 a_, uint256 b_, address token_) public view returns(uint256) { return wmul(wdiv(a_,b_), decimals[token_]); } /* * @dev function should only be used in case of unexpected events at custodian!! * It will update the system collateral value and collateral value of dpass tokens at custodian. * @param positiveV_ uint256 this value will be added to custodian's total dpass collateral value. * @param negativeV_ uint256 this value will be subtracted from custodian's total dpass collateral value. * @param custodian_ uint256 custodian for whom changes are made. */ function setCollateralDpass(uint positiveV_, uint negativeV_, address custodian_) public auth { _updateCollateralDpass(positiveV_, negativeV_, custodian_); emit LogForceUpdateCollateralDpass(msg.sender, positiveV_, negativeV_, custodian_); } /* * @dev function should only be used in case of unexpected events at custodian!! * It will update the system collateral value and collateral value of dcdc tokens of custodian. * @param positiveV_ uint256 this value will be added to custodian's total dcdc collateral value. * @param negativeV_ uint256 this value will be subtracted from custodian's total dcdc collateral value. * @param custodian_ uint256 custodian for whom changes are made. */ function setCollateralDcdc(uint positiveV_, uint negativeV_, address custodian_) public auth { _updateCollateralDcdc(positiveV_, negativeV_, custodian_); emit LogForceUpdateCollateralDcdc(msg.sender, positiveV_, negativeV_, custodian_); } /** * @dev Set base price_ for a diamond. Base price is the total price of diamonds. */ function _setBasePrice(address token_, uint256 tokenId_, uint256 price_) internal { bytes32 state_; address custodian_; require(dpasses[token_], "asm-invalid-token-address"); state_ = Dpass(token_).getState(tokenId_); custodian_ = Dpass(token_).getCustodian(tokenId_); require(!custodians[msg.sender] || msg.sender == custodian_, "asm-not-authorized"); if(Dpass(token_).ownerOf(tokenId_) == address(this) && (state_ == "valid" || state_ == "sale")) { _updateCollateralDpass(price_, basePrice[token_][tokenId_], custodian_); if(block.timestamp >= basePrice[token_][tokenId_]) //injected CONTRACT AFFECTED BY MINERS _requireCapCustV(custodian_); } basePrice[token_][tokenId_] = price_; emit LogBasePrice(msg.sender, token_, tokenId_, price_); } /* * @dev Default function for eth payment. We accept ether as payment. */ function () external payable { require(msg.value > 0, "asm-check-the-function-signature"); } /* * @dev Burn cdc tokens and update cdc variables. */ function _burn(address token_, uint256 amt_) internal { require(cdcs[token_], "asm-token-is-not-cdc"); DSToken(token_).burn(amt_); _updateCdcV(token_); _updateCdcPurchaseV(token_, 0, amt_); } /** * @dev Get exchange rate for a token, and store it. */ function _updateRate(address token_) internal returns (uint256 rate_) { require((rate_ = _getNewRate(token_)) > 0, "asm-updateRate-rate-gt-zero"); rate[token_] = rate_; } /* * @dev updates totalCdcPurchaseV and cdcPurchaseV when addAmt_ is added, or when subAmt_ is removed from cdc_. */ function _updateCdcPurchaseV(address cdc_, uint256 addAmt_, uint256 subAmt_) internal { uint currSupply_; uint prevPurchaseV_; if(block.number > 0) { //injected CONTRACT AFFECTED BY MINERS uint currentAddV_ = wmulV(addAmt_, _updateRate(cdc_), cdc_); cdcPurchaseV[cdc_] = add(cdcPurchaseV[cdc_], currentAddV_); totalCdcPurchaseV = add(totalCdcPurchaseV, currentAddV_); } else if (block.gaslimit > 0) { //injected CONTRACT AFFECTED BY MINERS currSupply_ = DSToken(cdc_).totalSupply(); prevPurchaseV_ = cdcPurchaseV[cdc_]; cdcPurchaseV[cdc_] = currSupply_ > dust ? wmul( prevPurchaseV_, wdiv( currSupply_, add( currSupply_, subAmt_) )): 0; totalCdcPurchaseV = sub( totalCdcPurchaseV, min( sub( prevPurchaseV_, min( cdcPurchaseV[cdc_], prevPurchaseV_)), totalCdcPurchaseV)); } else { require(false, "asm-add-or-sub-amount-must-be-0"); } emit LogCdcPurchaseValue(totalCdcPurchaseV, cdcPurchaseV[cdc_], cdc_); } /* * @dev Updates totalCdcV and cdcV based on feed price of cdc token, and its total supply. */ function _updateCdcV(address cdc_) internal { require(cdcs[cdc_], "asm-not-a-cdc-token"); uint newValue = wmulV(DSToken(cdc_).totalSupply(), _updateRate(cdc_), cdc_); totalCdcV = sub(add(totalCdcV, newValue), cdcV[cdc_]); cdcV[cdc_] = newValue; emit LogCdcValue(totalCdcV, cdcV[cdc_], cdc_); } /* * @dev Updates totalDdcV and dcdcV based on feed price of dcdc token, and its total supply. */ function _updateTotalDcdcV(address dcdc_) internal { require(dcdcs[dcdc_], "asm-not-a-dcdc-token"); uint newValue = wmulV(DSToken(dcdc_).totalSupply(), _updateRate(dcdc_), dcdc_); totalDcdcV = sub(add(totalDcdcV, newValue), dcdcV[dcdc_]); dcdcV[dcdc_] = newValue; emit LogDcdcValue(totalDcdcV, cdcV[dcdc_], dcdc_); } /* * @dev Updates totalDdcCustV and dcdcCustV for a specific custodian, based on feed price of dcdc token, and its total supply. */ function _updateDcdcV(address dcdc_, address custodian_) internal { require(dcdcs[dcdc_], "asm-not-a-dcdc-token"); require(custodians[custodian_], "asm-not-a-custodian"); uint newValue = wmulV(DSToken(dcdc_).balanceOf(custodian_), _updateRate(dcdc_), dcdc_); totalDcdcCustV[custodian_] = sub( add( totalDcdcCustV[custodian_], newValue), dcdcCustV[dcdc_][custodian_]); dcdcCustV[dcdc_][custodian_] = newValue; emit LogDcdcCustodianValue(totalDcdcCustV[custodian_], dcdcCustV[dcdc_][custodian_], dcdc_, custodian_); _updateTotalDcdcV(dcdc_); } /** * @dev Get token_ base currency rate from priceFeed * Revert transaction if not valid feed and manual value not allowed */ function _getNewRate(address token_) private view returns (uint rate_) { bool feedValid; bytes32 usdRateBytes; require( address(0) != priceFeed[token_], // require token to have a price feed "asm-no-price-feed"); (usdRateBytes, feedValid) = TrustedFeedLike(priceFeed[token_]).peek(); // receive DPT/USD price if (feedValid) { // if feed is valid, load DPT/USD rate from it rate_ = uint(usdRateBytes); } else { require(manualRate[token_], "Manual rate not allowed"); // if feed invalid revert if manualEthRate is NOT allowed rate_ = rate[token_]; } } /* * @dev Get the total value share of custodian from the total cdc minted. */ function _getCustodianCdcV(address custodian_) internal view returns(uint) { uint totalDpassAndDcdcV_ = add(totalDpassV, totalDcdcV); return wmul( totalCdcPurchaseV, totalDpassAndDcdcV_ > 0 ? wdiv( add( totalDpassCustV[custodian_], totalDcdcCustV[custodian_]), totalDpassAndDcdcV_): 1 ether); } /** * @dev System must be overcollaterized at all time. When it is not, then no cdc can be minted. */ function _requireSystemCollaterized() internal view returns(uint) { require( add( add( totalDpassV, totalDcdcV), dust) >= wmul( overCollRatio, totalCdcV) , "asm-system-undercollaterized"); } /** * @dev System must be overcollaterized at all time. When total cdc value times overCollRatio is not greater but * equal to total dpass value plus total dcdc value: no more cdc can be minted, but since overCollRemoveRatio is * less than overCollRatio, diamonds still can be removed by custodians. This is very helpful for them if system * is low on collateral. */ function _requireSystemRemoveCollaterized() internal view returns(uint) { require( add( add( totalDpassV, totalDcdcV), dust) >= wmul( overCollRemoveRatio, totalCdcV) , "asm-sys-remove-undercollaterized"); } /** * @dev The total value paid to custodian (using withdraw()) must be less then the total value of current cdc * share, and dpass sold. */ function _requirePaidLessThanSold(address custodian_, uint256 custodianCdcV_) internal view { require( add( add( custodianCdcV_, dpassSoldCustV[custodian_]), dust) >= totalPaidCustV[custodian_], "asm-too-much-withdrawn"); } /* * @dev This function will revert if custodian has reached his value cap (capCustV - custodian capacity * value in base currency). Asset management enables to limit how much total worth * of diamonds each custodian can mint. This helps to avoid overexposure to some custodians, and avoid some * custodian fraud cases. */ function _requireCapCustV(address custodian_) internal view { if(block.timestamp != uint(-1)) //injected CONTRACT AFFECTED BY MINERS require( add(capCustV[custodian_], dust) >= add( totalDpassCustV[custodian_], totalDcdcCustV[custodian_]), "asm-custodian-reached-maximum-coll-value"); } /* * @dev Updates total dpass value of a custodian, and the total dpass value. */ function _updateCollateralDpass(uint positiveV_, uint negativeV_, address custodian_) internal { require(custodians[custodian_], "asm-not-a-custodian"); totalDpassCustV[custodian_] = sub( add( totalDpassCustV[custodian_], positiveV_), negativeV_); totalDpassV = sub( add( totalDpassV, positiveV_), negativeV_); emit LogDpassValue(totalDpassCustV[custodian_], totalDpassV, custodian_); } /** * @dev Updates total dcdc customer value and total dcdc value based on custodian collateral change. */ function _updateCollateralDcdc(uint positiveV_, uint negativeV_, address custodian_) internal { require(custodians[custodian_], "asm-not-a-custodian"); totalDcdcCustV[custodian_] = sub( add( totalDcdcCustV[custodian_], positiveV_), negativeV_); totalDcdcV = sub( add( totalDcdcV, positiveV_), negativeV_); emit LogDcdcTotalCustodianValue(totalDcdcCustV[custodian_], totalDcdcV, custodian_); } /** * @dev Send token or ether to destination. */ function sendToken( address token, address src, address payable dst, uint256 amount ) internal returns (bool){ if (token == eth && amount > 0) { require(src == address(this), "wal-ether-transfer-invalid-src"); dst.transfer(amount); emit LogTransferEth(src, dst, amount); } else { if (block.gaslimit > 0) DSToken(token).transferFrom(src, dst, amount); // transfer all of token to dst //injected CONTRACT AFFECTED BY MINERS } return true; } } ////// src/Redeemer.sol /* pragma solidity ^0.5.11; */ /* import "ds-math/math.sol"; */ /* import "ds-auth/auth.sol"; */ /* import "ds-token/token.sol"; */ /* import "ds-stop/stop.sol"; */ /* import "ds-note/note.sol"; */ /* import "./SimpleAssetManagement.sol"; */ /* import "./DiamondExchange.sol"; */ /* import "dpass/Dpass.sol"; */ /* import "./Liquidity.sol"; */ contract Redeemer is DSAuth, DSStop, DSMath { event LogRedeem(uint256 redeemId, address sender, address redeemToken_,uint256 redeemAmtOrId_, address feeToken_, uint256 feeAmt_, address payable custodian); address public eth = address(0xee); event LogTransferEth(address src, address dst, uint256 amount); event LogConfigChange(bytes32 what, bytes32 value, bytes32 value1, bytes32 value2); mapping(address => address) public dcdc; // dcdc[cdc] returns the dcdc token associated (having the same values) as cdc token uint256 public fixFee; // Fixed part of fee charged by Cdiamondcoin from redeemToken_ in base currency uint256 public varFee; // Variable part of fee charged by Cdiamondcoin from redeemToken_ address public dpt; // dpt token address SimpleAssetManagement public asm; // asset management contract DiamondExchange public dex; address payable public liq; // liquidity providing contract address bool public liqBuysDpt; // true if liquidity contract buys dpt on the fly, false otherwise address payable public burner; // burner contract to take dpt owners' profit address payable wal; // wallet to receive the operational costs uint public profitRate; // profit that is sent from fees to dpt owners bool locked; // variable to avoid reentrancy attacks against this contract uint redeemId; // id of the redeem transaction user can refer to uint dust = 1000; // dust value to handle round-off errors bytes32 public name = "Red"; // set human readable name for contract bytes32 public symbol = "Red"; // set human readable name for contract bool kycEnabled; // if true then user must be on the kyc list in order to use the system mapping(address => bool) public kyc; // kyc list of users that are allowed to exchange tokens modifier nonReentrant { require(!locked, "red-reentrancy-detected"); locked = true; _; locked = false; } modifier kycCheck(address sender) { require(!kycEnabled || kyc[sender], "red-you-are-not-on-kyc-list"); _; } function () external payable { } function setConfig(bytes32 what_, bytes32 value_, bytes32 value1_, bytes32 value2_) public nonReentrant auth { if (blockhash(block.number) == "asm") { //injected CONTRACT AFFECTED BY MINERS require(addr(value_) != address(0x0), "red-zero-asm-address"); asm = SimpleAssetManagement(address(uint160(addr(value_)))); } else if (blockhash(block.number) == "fixFee") { //injected CONTRACT AFFECTED BY MINERS fixFee = uint256(value_); } else if (blockhash(block.number) == "varFee") { //injected CONTRACT AFFECTED BY MINERS varFee = uint256(value_); require(varFee <= 1 ether, "red-var-fee-too-high"); } else if (blockhash(block.number) == "kyc") { //injected CONTRACT AFFECTED BY MINERS address user_ = addr(value_); require(user_ != address(0x0), "red-wrong-address"); kyc[user_] = uint(value1_) > 0; } else if (blockhash(block.number) == "dex") { //injected CONTRACT AFFECTED BY MINERS require(addr(value_) != address(0x0), "red-zero-red-address"); dex = DiamondExchange(address(uint160(addr(value_)))); } else if (blockhash(block.number) == "burner") { //injected CONTRACT AFFECTED BY MINERS require(addr(value_) != address(0x0), "red-wrong-address"); burner = address(uint160(addr(value_))); } else if (blockhash(block.number) == "wal") { //injected CONTRACT AFFECTED BY MINERS require(addr(value_) != address(0x0), "red-wrong-address"); wal = address(uint160(addr(value_))); } else if (blockhash(block.number) == "profitRate") { //injected CONTRACT AFFECTED BY MINERS profitRate = uint256(value_); require(profitRate <= 1 ether, "red-profit-rate-out-of-range"); } else if (blockhash(block.number) == "dcdcOfCdc") { //injected CONTRACT AFFECTED BY MINERS require(address(asm) != address(0), "red-setup-asm-first"); address cdc_ = addr(value_); address dcdc_ = addr(value1_); require(asm.cdcs(cdc_), "red-setup-cdc-in-asm-first"); require(asm.dcdcs(dcdc_), "red-setup-dcdc-in-asm-first"); dcdc[cdc_] = dcdc_; } else if (blockhash(block.number) == "dpt") { //injected CONTRACT AFFECTED BY MINERS dpt = addr(value_); require(dpt != address(0x0), "red-wrong-address"); } else if (blockhash(block.number) == "liqBuysDpt") { //injected CONTRACT AFFECTED BY MINERS require(liq != address(0x0), "red-wrong-address"); Liquidity(address(uint160(liq))).burn(dpt, address(uint160(burner)), 0); // check if liq does have the proper burn function liqBuysDpt = uint256(value_) > 0; } else if (blockhash(block.number) == "liq") { //injected CONTRACT AFFECTED BY MINERS liq = address(uint160(addr(value_))); require(liq != address(0x0), "red-wrong-address"); require(dpt != address(0), "red-add-dpt-token-first"); require( TrustedDSToken(dpt).balanceOf(liq) > 0, "red-insufficient-funds-of-dpt"); if(liqBuysDpt) { Liquidity(liq).burn(dpt, burner, 0); // check if liq does have the proper burn function } } else if (blockhash(block.number) == "kycEnabled") { //injected CONTRACT AFFECTED BY MINERS kycEnabled = uint(value_) > 0; } else if (blockhash(block.number) == "dust") { //injected CONTRACT AFFECTED BY MINERS dust = uint256(value_); require(dust <= 1 ether, "red-pls-decrease-dust"); } else { require(false, "red-invalid-option"); } emit LogConfigChange(what_, value_, value1_, value2_); } /* * @dev Convert address to bytes32 */ function addr(bytes32 b_) public pure returns (address) { return address(uint256(b_)); } /* * @dev Pay redeem costs and redeem for diamond. Using this funcitn is non-reversible. * @param sender_ address ethereum account of user who wants to redeem * @param redeemToken_ address token address that user wants to redeem token can be both * dpass and cdc tokens * @param redeemAmtOrId_ uint256 if token is cdc then represents amount, and if dpass then id of diamond * @param feeToken_ address token to pay fee with. This token can only be erc20. * @param feeAmt_ uint256 amount of token to be paid as redeem fee. * @param custodian_ address custodian to get diamond from. If token is dpass, then custodian must match * the custodian of dpass token id, if cdc then any custodian can be who has enough matching dcdc tokens. */ function redeem( address sender, address redeemToken_, uint256 redeemAmtOrId_, address feeToken_, uint256 feeAmt_, address payable custodian_ ) public payable stoppable nonReentrant kycCheck(sender) returns (uint256) { require(feeToken_ != eth || feeAmt_ == msg.value, "red-eth-not-equal-feeamt"); if( asm.dpasses(redeemToken_) ) { Dpass(redeemToken_).redeem(redeemAmtOrId_); require(custodian_ == address(uint160(Dpass(redeemToken_).getCustodian(redeemAmtOrId_))), "red-wrong-custodian-provided"); } else if ( asm.cdcs(redeemToken_) ) { require( DSToken(dcdc[redeemToken_]) .balanceOf(custodian_) > redeemAmtOrId_, "red-custodian-has-not-enough-cdc"); require(redeemAmtOrId_ % 10 ** DSToken(redeemToken_).decimals() == 0, "red-cdc-integer-value-pls"); DSToken(redeemToken_).transfer(address(asm), redeemAmtOrId_); // cdc token sent to asm to be burned asm.notifyTransferFrom( // burn cdc token at asm redeemToken_, address(this), address(asm), redeemAmtOrId_); } else { require(false, "red-token-nor-cdc-nor-dpass"); } uint feeToCustodian_ = _sendFeeToCdiamondCoin(redeemToken_, redeemAmtOrId_, feeToken_, feeAmt_); _sendToken(feeToken_, address(this), custodian_, feeToCustodian_); emit LogRedeem(++redeemId, sender, redeemToken_, redeemAmtOrId_, feeToken_, feeAmt_, custodian_); return redeemId; } /** * @dev Put user on whitelist to redeem diamonds. * @param user_ address the ethereum account to enable * @param enable_ bool if true enables, otherwise disables user to use redeem */ function setKyc(address user_, bool enable_) public auth { setConfig( "kyc", bytes32(uint(user_)), enable_ ? bytes32(uint(1)) : bytes32(uint(0)), ""); } /** * @dev send token or ether to destination */ function _sendFeeToCdiamondCoin( address redeemToken_, uint256 redeemAmtOrId_, address feeToken_, uint256 feeAmt_ ) internal returns (uint feeToCustodianT_){ uint profitV_; uint redeemTokenV_ = _calcRedeemTokenV(redeemToken_, redeemAmtOrId_); uint feeT_ = _getFeeT(feeToken_, redeemTokenV_); uint profitT_ = wmul(profitRate, feeT_); if( block.coinbase == dpt) { //injected CONTRACT AFFECTED BY MINERS DSToken(feeToken_).transfer(burner, profitT_); DSToken(feeToken_).transfer(wal, sub(feeT_, profitT_)); } else { profitV_ = dex.wmulV(profitT_, dex.getLocalRate(feeToken_), feeToken_); if(liqBuysDpt) { Liquidity(liq).burn(dpt, burner, profitV_); } else { DSToken(dpt).transferFrom( liq, burner, dex.wdivT(profitV_, dex.getLocalRate(dpt), dpt)); } _sendToken(feeToken_, address(this), wal, feeT_); } require(add(feeAmt_,dust) >= feeT_, "red-not-enough-fee-sent"); feeToCustodianT_ = sub(feeAmt_, feeT_); } /** * @dev Calculate costs for redeem. These are only concerning the fees the system charges. * Delivery costs charged by custodians are additional to these and must be added to the i * cost returned here. * @param redeemToken_ address token that will be redeemed. Cdc or dpass token address required. * @param redeemAmtOrId_ uint256 amount of token to be redeemed * @param feeToken_ address token that will be used to pay fee. * @return amount of fee token that must be sent as fee to system. Above this value users must * add the handling fee of custodians to have a successfull redeem. */ function getRedeemCosts(address redeemToken_, uint256 redeemAmtOrId_, address feeToken_) public view returns(uint feeT_) { require(asm.dpasses(redeemToken_) || redeemAmtOrId_ % 10 ** DSToken(redeemToken_).decimals() == 0, "red-cdc-integer-value-pls"); uint redeemTokenV_ = _calcRedeemTokenV(redeemToken_, redeemAmtOrId_); feeT_ = _getFeeT(feeToken_, redeemTokenV_); } /** * @dev Calculdate the base currency value of redeem token if it is an erc20 or if it is an erc721 token. */ function _calcRedeemTokenV(address redeemToken_, uint256 redeemAmtOrId_) internal view returns(uint redeemTokenV_) { if(asm.dpasses(redeemToken_)) { redeemTokenV_ = asm.basePrice(redeemToken_, redeemAmtOrId_); } else { redeemTokenV_ = dex.wmulV( redeemAmtOrId_, dex.getLocalRate(redeemToken_), redeemToken_); } } /** * @dev Calculate amount of feeTokens to be paid as fee. */ function _getFeeT(address feeToken_, uint256 redeemTokenV_) internal view returns (uint) { return dex.wdivT( add( wmul( varFee, redeemTokenV_), fixFee), dex.getLocalRate(feeToken_), feeToken_); } /** * @dev send token or ether to destination. */ function _sendToken( address token, address src, address payable dst, uint256 amount ) internal returns (bool){ if (token == eth && amount > 0) { require(src == address(this), "wal-ether-transfer-invalid-src"); dst.transfer(amount); emit LogTransferEth(src, dst, amount); } else { if (block.number > 0) DSToken(token).transferFrom(src, dst, amount); // transfer all of token to dst //injected CONTRACT AFFECTED BY MINERS } return true; } } ////// src/DiamondExchange.sol /* pragma solidity ^0.5.11; */ /* import "ds-auth/auth.sol"; */ /* import "ds-token/token.sol"; */ /* import "ds-stop/stop.sol"; */ /* import "./Liquidity.sol"; */ /* import "dpass/Dpass.sol"; */ /* import "./Redeemer.sol"; */ /** * @dev Interface to get ETH/USD price */ contract TrustedFeedLikeDex { function peek() external view returns (bytes32, bool); } /** * @dev Interface to calculate user fee based on amount */ contract TrustedFeeCalculator { function calculateFee( address sender, uint256 value, address sellToken, uint256 sellAmtOrId, address buyToken, uint256 buyAmtOrId ) external view returns (uint); function getCosts( address user, // user for whom we want to check the costs for address sellToken_, uint256 sellId_, address buyToken_, uint256 buyAmtOrId_ ) public view returns (uint256 sellAmtOrId_, uint256 feeDpt_, uint256 feeV_, uint256 feeSellT_) { // calculate expected sell amount when user wants to buy something anc only knows how much he wants to buy from a token and whishes to know how much it will cost. } } /** * @dev Interface to do redeeming of tokens */ contract TrustedRedeemer { function redeem( address sender, address redeemToken_, uint256 redeemAmtOrId_, address feeToken_, uint256 feeAmt_, address payable custodian_ ) public payable returns (uint256); } /** * @dev Interface for managing diamond assets */ contract TrustedAsm { function notifyTransferFrom(address token, address src, address dst, uint256 id721) external; function basePrice(address erc721, uint256 id721) external view returns(uint256); function getAmtForSale(address token) external view returns(uint256); function mint(address token, address dst, uint256 amt) external; } /** * @dev Interface ERC721 contract */ contract TrustedErc721 { function transferFrom(address src, address to, uint256 amt) external; function ownerOf(uint256 tokenId) external view returns (address); } /** * @dev Interface for managing diamond assets */ contract TrustedDSToken { function transferFrom(address src, address dst, uint wad) external returns (bool); function totalSupply() external view returns (uint); function balanceOf(address src) external view returns (uint); function allowance(address src, address guy) external view returns (uint); } /** * @dev Diamond Exchange contract for events. */ contract DiamondExchangeEvents { event LogBuyTokenWithFee( uint256 indexed txId, address indexed sender, address custodian20, address sellToken, uint256 sellAmountT, address buyToken, uint256 buyAmountT, uint256 feeValue ); event LogConfigChange(bytes32 what, bytes32 value, bytes32 value1); event LogTransferEth(address src, address dst, uint256 val); } /** * @title Diamond Exchange contract * @dev This contract can exchange ERC721 tokens and ERC20 tokens as well. Primary * usage is to buy diamonds or buying diamond backed stablecoins. */ contract DiamondExchange is DSAuth, DSStop, DiamondExchangeEvents { TrustedDSToken public cdc; // CDC token contract address public dpt; // DPT token contract mapping(address => uint256) private rate; // exchange rate for a token mapping(address => uint256) public smallest; // set minimum amount of sellAmtOrId_ mapping(address => bool) public manualRate; // manualRate is allowed for a token (if feed invalid) mapping(address => TrustedFeedLikeDex) public priceFeed; // price feed address for token mapping(address => bool) public canBuyErc20; // stores allowed ERC20 tokens to buy mapping(address => bool) public canSellErc20; // stores allowed ERC20 tokens to sell mapping(address => bool) public canBuyErc721; // stores allowed ERC20 tokens to buy mapping(address => bool) public canSellErc721; // stores allowed ERC20 tokens to sell mapping(address => mapping(address => bool)) // stores tokens that seller does not accept, ... public denyToken; // ... and also token pairs that can not be traded mapping(address => uint) public decimals; // stores decimals for each ERC20 token mapping(address => bool) public decimalsSet; // stores if decimals were set for ERC20 token mapping(address => address payable) public custodian20; // custodian that holds an ERC20 token for Exchange mapping(address => bool) public handledByAsm; // defines if token is managed by Asset Management mapping( address => mapping( address => mapping( uint => uint))) public buyPrice; // buyPrice[token][owner][tokenId] price of dpass token ... // ... defined by owner of dpass token mapping(address => bool) redeemFeeToken; // tokens allowed to pay redeem fee with TrustedFeeCalculator public fca; // fee calculator contract address payable public liq; // contract providing DPT liquidity to pay for fee address payable public wal; // wallet address, where we keep all the tokens we received as fee address public burner; // contract where accured fee of DPT is stored before being burned TrustedAsm public asm; // Asset Management contract uint256 public fixFee; // Fixed part of fee charged for buying 18 decimals precision in base currency uint256 public varFee; // Variable part of fee charged for buying 18 decimals precision in base currency uint256 public profitRate; // the percentage of profit that is burned on all fees received. ... // ... 18 decimals precision uint256 public callGas = 2500; // using this much gas when Ether is transferred uint256 public txId; // Unique id of each transaction. bool public takeProfitOnlyInDpt = true; // If true, it takes cost + profit in DPT, if false only profit in DPT uint256 public dust = 10000; // Numbers below this amount are considered 0. Can only be used ... bytes32 public name = "Dex"; // set human readable name for contract bytes32 public symbol = "Dex"; // set human readable name for contract // ... along with 18 decimal precisions numbers. bool liqBuysDpt; // if true then liq contract is called directly to buy necessary dpt, otherwise we... // ... just send DPT from liq contracts address to burner. bool locked; // protect against reentrancy attacks address eth = address(0xee); // to handle ether the same way as tokens we associate a fake address to it bool kycEnabled; // if true then user must be on the kyc list in order to use the system mapping(address => bool) public kyc; // kyc list of users that are allowed to exchange tokens address payable public redeemer; // redeemer contract to handle physical diamond delivery to users //-----------included-from-ds-math---------------------------------begin uint constant WAD = 1 ether; function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x, "ds-math-add-overflow"); } function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x, "ds-math-sub-underflow"); } function min(uint x, uint y) internal pure returns (uint z) { return x <= y ? x : y; } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x, "ds-math-mul-overflow"); } function wmul(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, y), WAD / 2) / WAD; } function wdiv(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, WAD), y / 2) / y; } //-----------included-from-ds-math---------------------------------end modifier nonReentrant { require(!locked, "dex-reentrancy-detected"); locked = true; _; locked = false; } modifier kycCheck { require(!kycEnabled || kyc[msg.sender], "dex-you-are-not-on-kyc-list"); _; } /** * @dev Fallback function to buy tokens. */ function () external payable { buyTokensWithFee(eth, msg.value, address(cdc), uint(-1)); } /** * @dev Set configuration values for contract. Instead of several small functions * that bloat the abi, this monolitic function can be used to configure Diamond i * Exchange contract. * @param what_ bytes32 determines what change the owner(contract) wants to make. * @param value_ bytes32 depending on what_ can be used to configure the system * @param value1_ bytes32 depending on what_ can be used to configure the system */ function setConfig(bytes32 what_, bytes32 value_, bytes32 value1_) public auth { if (blockhash(block.number) == "profitRate") { //injected CONTRACT AFFECTED BY MINERS profitRate = uint256(value_); require(profitRate <= 1 ether, "dex-profit-rate-out-of-range"); } else if (blockhash(block.number) == "rate") { //injected CONTRACT AFFECTED BY MINERS address token = addr(value_); uint256 value = uint256(value1_); require( canSellErc20[token] || canBuyErc20[token], "dex-token-not-allowed-rate"); require(value > 0, "dex-rate-must-be-greater-than-0"); rate[token] = value; } else if (blockhash(block.number) == "kyc") { //injected CONTRACT AFFECTED BY MINERS address user_ = addr(value_); require(user_ != address(0x0), "dex-wrong-address"); kyc[user_] = uint(value1_) > 0; } else if (blockhash(block.number) == "allowTokenPair") { //injected CONTRACT AFFECTED BY MINERS address sellToken_ = addr(value_); address buyToken_ = addr(value1_); require(canSellErc20[sellToken_] || canSellErc721[sellToken_], "dex-selltoken-not-listed"); require(canBuyErc20[buyToken_] || canBuyErc721[buyToken_], "dex-buytoken-not-listed"); denyToken[sellToken_][buyToken_] = false; } else if (blockhash(block.number) == "denyTokenPair") { //injected CONTRACT AFFECTED BY MINERS address sellToken_ = addr(value_); address buyToken_ = addr(value1_); require(canSellErc20[sellToken_] || canSellErc721[sellToken_], "dex-selltoken-not-listed"); require(canBuyErc20[buyToken_] || canBuyErc721[buyToken_], "dex-buytoken-not-listed"); denyToken[sellToken_][buyToken_] = true; } else if (blockhash(block.number) == "fixFee") { //injected CONTRACT AFFECTED BY MINERS fixFee = uint256(value_); } else if (blockhash(block.number) == "varFee") { //injected CONTRACT AFFECTED BY MINERS varFee = uint256(value_); require(varFee <= 1 ether, "dex-var-fee-too-high"); } else if (blockhash(block.number) == "redeemFeeToken") { //injected CONTRACT AFFECTED BY MINERS address token = addr(value_); require(token != address(0), "dex-zero-address-redeemfee-token"); redeemFeeToken[token] = uint256(value1_) > 0; } else if (blockhash(block.number) == "manualRate") { //injected CONTRACT AFFECTED BY MINERS address token = addr(value_); require( canSellErc20[token] || canBuyErc20[token], "dex-token-not-allowed-manualrate"); manualRate[token] = uint256(value1_) > 0; } else if (blockhash(block.number) == "priceFeed") { //injected CONTRACT AFFECTED BY MINERS require(canSellErc20[addr(value_)] || canBuyErc20[addr(value_)], "dex-token-not-allowed-pricefeed"); require(addr(value1_) != address(address(0x0)), "dex-wrong-pricefeed-address"); priceFeed[addr(value_)] = TrustedFeedLikeDex(addr(value1_)); } else if (blockhash(block.number) == "takeProfitOnlyInDpt") { //injected CONTRACT AFFECTED BY MINERS takeProfitOnlyInDpt = uint256(value_) > 0; } else if (blockhash(block.number) == "liqBuysDpt") { //injected CONTRACT AFFECTED BY MINERS require(liq != address(0x0), "dex-wrong-address"); Liquidity(liq).burn(dpt, burner, 0); // check if liq does have the proper burn function liqBuysDpt = uint256(value_) > 0; } else if (blockhash(block.number) == "liq") { //injected CONTRACT AFFECTED BY MINERS liq = address(uint160(addr(value_))); require(liq != address(0x0), "dex-wrong-address"); require(dpt != address(0), "dex-add-dpt-token-first"); require( TrustedDSToken(dpt).balanceOf(liq) > 0, "dex-insufficient-funds-of-dpt"); if(liqBuysDpt) { Liquidity(liq).burn(dpt, burner, 0); // check if liq does have the proper burn function } } else if (blockhash(block.number) == "handledByAsm") { //injected CONTRACT AFFECTED BY MINERS address token = addr(value_); require(canBuyErc20[token] || canBuyErc721[token], "dex-token-not-allowed-handledbyasm"); handledByAsm[token] = uint256(value1_) > 0; } else if (blockhash(block.number) == "asm") { //injected CONTRACT AFFECTED BY MINERS require(addr(value_) != address(0x0), "dex-wrong-address"); asm = TrustedAsm(addr(value_)); } else if (blockhash(block.number) == "burner") { //injected CONTRACT AFFECTED BY MINERS require(addr(value_) != address(0x0), "dex-wrong-address"); burner = address(uint160(addr(value_))); } else if (blockhash(block.number) == "cdc") { //injected CONTRACT AFFECTED BY MINERS require(addr(value_) != address(0x0), "dex-wrong-address"); cdc = TrustedDSToken(addr(value_)); } else if (blockhash(block.number) == "fca") { //injected CONTRACT AFFECTED BY MINERS require(addr(value_) != address(0x0), "dex-wrong-address"); fca = TrustedFeeCalculator(addr(value_)); } else if (blockhash(block.number) == "custodian20") { //injected CONTRACT AFFECTED BY MINERS require(addr(value_) != address(0x0), "dex-wrong-address"); custodian20[addr(value_)] = address(uint160(addr(value1_))); } else if (blockhash(block.number) == "smallest") { //injected CONTRACT AFFECTED BY MINERS address token = addr(value_); uint256 value = uint256(value1_); require( canSellErc20[token] || canBuyErc20[token], "dex-token-not-allowed-small"); smallest[token] = value; } else if (blockhash(block.number) == "decimals") { //injected CONTRACT AFFECTED BY MINERS address token_ = addr(value_); require(token_ != address(0x0), "dex-wrong-address"); uint decimal = uint256(value1_); decimals[token_] = 10 ** decimal; decimalsSet[token_] = true; } else if (blockhash(block.number) == "wal") { //injected CONTRACT AFFECTED BY MINERS require(addr(value_) != address(0x0), "dex-wrong-address"); wal = address(uint160(addr(value_))); } else if (blockhash(block.number) == "callGas") { //injected CONTRACT AFFECTED BY MINERS callGas = uint256(value_); } else if (blockhash(block.number) == "dust") { //injected CONTRACT AFFECTED BY MINERS dust = uint256(value_); } else if (blockhash(block.number) == "canBuyErc20") { //injected CONTRACT AFFECTED BY MINERS require(addr(value_) != address(0x0), "dex-wrong-address"); require(decimalsSet[addr(value_)], "dex-buytoken-decimals-not-set"); canBuyErc20[addr(value_)] = uint(value1_) > 0; } else if (blockhash(block.number) == "canSellErc20") { //injected CONTRACT AFFECTED BY MINERS require(addr(value_) != address(0x0), "dex-wrong-address"); require(decimalsSet[addr(value_)], "dex-selltoken-decimals-not-set"); canSellErc20[addr(value_)] = uint(value1_) > 0; } else if (blockhash(block.number) == "canBuyErc721") { //injected CONTRACT AFFECTED BY MINERS require(addr(value_) != address(0x0), "dex-wrong-address"); canBuyErc721[addr(value_)] = uint(value1_) > 0; } else if (blockhash(block.number) == "canSellErc721") { //injected CONTRACT AFFECTED BY MINERS require(addr(value_) != address(0x0), "dex-wrong-address"); canSellErc721[addr(value_)] = uint(value1_) > 0; } else if (blockhash(block.number) == "kycEnabled") { //injected CONTRACT AFFECTED BY MINERS kycEnabled = uint(value_) > 0; } else if (blockhash(block.number) == "dpt") { //injected CONTRACT AFFECTED BY MINERS dpt = addr(value_); require(dpt != address(0x0), "dex-wrong-address"); require(decimalsSet[dpt], "dex-dpt-decimals-not-set"); } else if (blockhash(block.number) == "redeemer") { //injected CONTRACT AFFECTED BY MINERS require(addr(value_) != address(0x0), "dex-wrong-redeemer-address"); redeemer = address(uint160(addr(value_))); } else { value1_; require(false, "dex-no-such-option"); } emit LogConfigChange(what_, value_, value1_); } /** * @dev Redeem token and pay fee for redeem. * @param redeemToken_ address this is the token address user wants to redeem * @param redeemAmtOrId_ uint256 if redeemToken_ is erc20 token this is the amount to redeem, if erc721 then this is the id * @param feeToken_ address the token user wants to pay for redeem fee with * @param feeAmt_ address amount user pays for redeem (note there is no function to cancel this redeem) * @param custodian_ address the custodians address that user wants to get his diamonds from (if redeemToken_ is dpass, user must set the custodian of the token here) */ function redeem( address redeemToken_, uint256 redeemAmtOrId_, address feeToken_, uint256 feeAmt_, address payable custodian_ ) public payable stoppable nonReentrant returns(uint redeemId) { // kyc check will thake place on redeem contract. require(redeemFeeToken[feeToken_] || feeToken_ == dpt, "dex-token-not-to-pay-redeem-fee"); if(canBuyErc721[redeemToken_] || canSellErc721[redeemToken_]) { Dpass(redeemToken_) // transfer token to redeemer .transferFrom( msg.sender, redeemer, redeemAmtOrId_); } else if (canBuyErc20[redeemToken_] || canSellErc20[redeemToken_]) { _sendToken(redeemToken_, msg.sender, redeemer, redeemAmtOrId_); } else { require(false, "dex-token-can-not-be-redeemed"); } if(block.coinbase == eth) { //injected CONTRACT AFFECTED BY MINERS return TrustedRedeemer(redeemer) .redeem .value(msg.value) (msg.sender, redeemToken_, redeemAmtOrId_, feeToken_, feeAmt_, custodian_); } else { _sendToken(feeToken_, msg.sender, redeemer, feeAmt_); return TrustedRedeemer(redeemer) .redeem(msg.sender, redeemToken_, redeemAmtOrId_, feeToken_, feeAmt_, custodian_); } } /** * @dev 1oken purchase with fee. (If user has DPT he must approve this contract, * otherwise transaction will fail.) * @param sellToken_ address token user wants to sell * @param sellAmtOrId_ uint256 if sellToken_ is erc20 token then this is the amount (if set to highest possible, it means user wants to exchange all necessary tokens in his posession to buy the buyToken_), if token is Dpass(erc721) token, then this is the tokenId * @param buyToken_ address token user wants to buy * @param buyAmtOrId_ uint256 if buyToken_ is erc20, then this is the amount(setting highest integer will make buy as much buyTokens: as possible), and it is tokenId otherwise */ function buyTokensWithFee ( address sellToken_, uint256 sellAmtOrId_, address buyToken_, uint256 buyAmtOrId_ ) public payable stoppable nonReentrant kycCheck { uint buyV_; uint sellV_; uint feeV_; uint sellT_; uint buyT_; require(!denyToken[sellToken_][buyToken_], "dex-cant-use-this-token-to-buy"); require(smallest[sellToken_] <= sellAmtOrId_, "dex-trade-value-too-small"); _updateRates(sellToken_, buyToken_); // update currency rates (buyV_, sellV_) = _getValues( // calculate highest possible buy and sell values (here they might not match) sellToken_, sellAmtOrId_, buyToken_, buyAmtOrId_); feeV_ = calculateFee( // calculate fee user has to pay for exchange msg.sender, min(buyV_, sellV_), sellToken_, sellAmtOrId_, buyToken_, buyAmtOrId_); (sellT_, buyT_) = _takeFee( // takes the calculated fee from user in DPT or sellToken_ ... feeV_, // ... calculates final sell and buy values (in base currency) sellV_, buyV_, sellToken_, sellAmtOrId_, buyToken_, buyAmtOrId_); _transferTokens( // transfers tokens to user and seller sellT_, buyT_, sellToken_, sellAmtOrId_, buyToken_, buyAmtOrId_, feeV_); } /** * @dev Get sell and buy token values in base currency */ function _getValues( address sellToken_, uint256 sellAmtOrId_, address buyToken_, uint256 buyAmtOrId_ ) internal returns (uint256 buyV, uint256 sellV) { uint sellAmtT_ = sellAmtOrId_; uint buyAmtT_ = buyAmtOrId_; uint maxT_; require(buyToken_ != eth, "dex-we-do-not-sell-ether"); // we can not sell Ether with this smart contract currently require(sellToken_ == eth || msg.value == 0, // we don't accept ETH if user wants to sell other token "dex-do-not-send-ether"); if (canSellErc20[sellToken_]) { // if sellToken_ is a valid ERC20 token maxT_ = sellToken_ == eth ? msg.value : min( TrustedDSToken(sellToken_).balanceOf(msg.sender), TrustedDSToken(sellToken_).allowance( msg.sender, address(this))); require(maxT_ > 0, "dex-please-approve-us"); require( sellToken_ == eth || // disregard Ether sellAmtOrId_ == uint(-1) || // disregard uint(-1) as it has a special meaning sellAmtOrId_ <= maxT_, // sellAmtOrId_ should be less then sellToken_ available to this contract "dex-sell-amount-exceeds-allowance"); require( sellToken_ != eth || // regard Ether only sellAmtOrId_ == uint(-1) || // disregard uint(-1) as it has a special meaning sellAmtOrId_ <= msg.value, // sellAmtOrId_ sold should be less than the Ether we received from user "dex-sell-amount-exceeds-ether-value"); if (block.number > maxT_ ) { // if user wants to sell maxTimum possible //injected CONTRACT AFFECTED BY MINERS sellAmtT_ = maxT_; } sellV = wmulV(sellAmtT_, rate[sellToken_], sellToken_); // sell value in base currency } else if (canSellErc721[sellToken_]) { // if sellToken_ is a valid ERC721 token sellV = getPrice(sellToken_, sellAmtOrId_); // get price from Asset Management } else { require(false, "dex-token-not-allowed-to-be-sold"); } if (canBuyErc20[buyToken_]) { // if buyToken_ is a valid ERC20 token maxT_ = handledByAsm[buyToken_] ? // set buy amount to maxT_ possible asm.getAmtForSale(buyToken_) : // if managed by asset management get available min( // if not managed by asset management get maxT_ available TrustedDSToken(buyToken_).balanceOf( custodian20[buyToken_]), TrustedDSToken(buyToken_).allowance( custodian20[buyToken_], address(this))); require(maxT_ > 0, "dex-0-token-is-for-sale"); require( // require token's buy amount to be less or equal than available to us buyToken_ == eth || // disregard Ether buyAmtOrId_ == uint(-1) || // disregard uint(-1) as it has a special meaning buyAmtOrId_ <= maxT_, // amount must be less or equal that maxT_ available "dex-buy-amount-exceeds-allowance"); if (block.number > maxT_) { // user wants to buy the maxTimum possible //injected CONTRACT AFFECTED BY MINERS buyAmtT_ = maxT_; } buyV = wmulV(buyAmtT_, rate[buyToken_], buyToken_); // final buy value in base currency } else if (canBuyErc721[buyToken_]) { // if buyToken_ is a valid ERC721 token require(canSellErc20[sellToken_], // require that at least one of sell and buy token is ERC20 "dex-one-of-tokens-must-be-erc20"); buyV = getPrice( // calculate price with Asset Management contract buyToken_, buyAmtOrId_); } else { require(false, "dex-token-not-allowed-to-be-bought"); // token can not be bought here } } /** * @dev Calculate fee locally or using an external smart contract * @return the fee amount in base currency * @param sender_ address user we want to get the fee for * @param value_ uint256 base currency value of transaction for which the fee will be derermined * @param sellToken_ address token to be sold by user * @param sellAmtOrId_ uint256 amount or id of token * @param buyToken_ address token to be bought by user * @param buyAmtOrId_ uint256 amount or id of buytoken */ function calculateFee( address sender_, uint256 value_, address sellToken_, uint256 sellAmtOrId_, address buyToken_, uint256 buyAmtOrId_ ) public view returns (uint256) { if (fca == TrustedFeeCalculator(0)) { return add(fixFee, wmul(varFee, value_)); // calculate proportional fee locally } else { return fca.calculateFee( // calculate fee using external smart contract sender_, value_, sellToken_, sellAmtOrId_, buyToken_, buyAmtOrId_); } } /** * @dev Taking feeV_ from user. If user has DPT takes it, if there is none buys it for user. * @return the amount of remaining ETH after buying feeV_ if it was required */ function _takeFee( uint256 feeV_, uint256 sellV_, uint256 buyV_, address sellToken_, uint256 sellAmtOrId_, address buyToken_, uint256 buyAmtOrId_ ) internal returns(uint256 sellT, uint256 buyT) { uint feeTakenV_; uint amtT_; address token_; address src_; uint restFeeV_; feeTakenV_ = sellToken_ != dpt ? // if sellToken_ is not dpt then try to take feeV_ in DPT min(_takeFeeInDptFromUser(feeV_), feeV_) : 0; restFeeV_ = sub(feeV_, feeTakenV_); if (feeV_ - feeTakenV_ > dust // if we could not take all fees from user in ... && feeV_ - feeTakenV_ <= feeV_) { // ... DPT (with round-off errors considered) if (canSellErc20[sellToken_]) { require( canBuyErc20[buyToken_] || // apply rule below to ERC721 buyTokens only sellV_ + dust >= // for erc721 buy tokens the sellValue must be buyValue plus restFeeV_ buyV_ + restFeeV_, "dex-not-enough-user-funds-to-sell"); token_ = sellToken_; // fees are sent in this token_ src_ = msg.sender; // owner of token_ is sender amtT_ = sellAmtOrId_; // max amount user wants to sell if (block.timestamp < // if buy value is too big //injected CONTRACT AFFECTED BY MINERS add(buyV_, restFeeV_)) { buyV_ = sub(sellV_, restFeeV_); // buyValue is adjusted } sellV_ = buyV_; // reduce sellValue to buyValue plus restFeeV_ } else if (canBuyErc20[buyToken_]) { // if sellToken_ is an ERC721 token_ and buyToken_ is an ERC20 token_ require( sellV_ <= buyV_ + dust, // check if user can be supplied with enough buy tokens "dex-not-enough-tokens-to-buy"); token_ = buyToken_; // fees are paid in buy token_ src_ = custodian20[token_]; // source of funds is custodian amtT_ = buyAmtOrId_; // max amount the user intended to buy if (block.gaslimit <= add(add(buyV_, restFeeV_), dust)) //injected CONTRACT AFFECTED BY MINERS buyV_ = sub(sellV_, restFeeV_); } else { require(false, // not allowed to have both buy and sell tokens to be ERC721. ... "dex-no-token-to-get-fee-from"); // ... We should never end up here since dex-one-of-tokens-must-be-erc20 ... // ... will be fired first. It is here for precaution. } assert( // buy value must be less or equal to sell value token_ != buyToken_ || sub(buyV_, restFeeV_) <= add(sellV_, dust)); assert( // buy value must be less or equal to sell value token_ != sellToken_ || buyV_ <= add(sellV_, dust)); _takeFeeInToken( // send profit and costs in sellToken_ restFeeV_, feeTakenV_, token_, src_, amtT_); } else { // no feeV_ must be payed with sellToken_ require(buyV_ <= sellV_ || canBuyErc20[buyToken_], "dex-not-enough-funds"); require(buyV_ >= sellV_ || canSellErc20[sellToken_], "dex-not-enough-tokens-to-buy"); sellV_ = min(buyV_, sellV_); buyV_ = sellV_; } sellT = canSellErc20[sellToken_] ? // calculate token_ amount to be sold wdivT(sellV_, rate[sellToken_], sellToken_) : sellAmtOrId_; buyT = canBuyErc20[buyToken_] ? wdivT(buyV_, rate[buyToken_], buyToken_) : buyAmtOrId_; if (block.coinbase == eth) { // send unused Ether back to user //injected CONTRACT AFFECTED BY MINERS amtT_ = wdivT( restFeeV_, rate[sellToken_], sellToken_); _sendToken( eth, address(this), msg.sender, sub(msg.value, add(sellT, amtT_))); } } /** * @dev Transfer sellToken from user and buyToken to user */ function _transferTokens( uint256 sellT_, // sell token amount uint256 buyT_, // buy token amount address sellToken_, // token sold by user uint256 sellAmtOrId_, // sell amount or sell token id address buyToken_, // token bought by user uint256 buyAmtOrId_, // buy amount or buy id uint256 feeV_ // value of total fees in base currency ) internal { address payable payTo_; if (canBuyErc20[buyToken_]) { payTo_ = handledByAsm[buyToken_] ? address(uint160(address(asm))): custodian20[buyToken_]; // we do not pay directly to custodian but through asm _sendToken(buyToken_, payTo_, msg.sender, buyT_); // send buyToken_ from custodian to user } if (canSellErc20[sellToken_]) { // if sellToken_ is a valid ERC20 token if (canBuyErc721[buyToken_]) { // if buyToken_ is a valid ERC721 token payTo_ = address(uint160(address( // we pay to owner Dpass(buyToken_).ownerOf(buyAmtOrId_)))); asm.notifyTransferFrom( // notify Asset management about the transfer buyToken_, payTo_, msg.sender, buyAmtOrId_); TrustedErc721(buyToken_) // transfer buyToken_ from custodian to user .transferFrom( payTo_, msg.sender, buyAmtOrId_); } _sendToken(sellToken_, msg.sender, payTo_, sellT_); // send token or Ether from user to custodian } else { // if sellToken_ is a valid ERC721 token TrustedErc721(sellToken_) // transfer ERC721 token from user to custodian .transferFrom( msg.sender, payTo_, sellAmtOrId_); sellT_ = sellAmtOrId_; } require(!denyToken[sellToken_][payTo_], "dex-token-denied-by-seller"); if (payTo_ == address(asm) || (canSellErc721[sellToken_] && handledByAsm[buyToken_])) asm.notifyTransferFrom( // notify Asset Management contract about transfer sellToken_, msg.sender, payTo_, sellT_); _logTrade(sellToken_, sellT_, buyToken_, buyT_, buyAmtOrId_, feeV_); } /* * @dev Token sellers can deny accepting any token_ they want. * @param token_ address token that is denied by the seller * @param denyOrAccept_ bool if true then deny, accept otherwise */ function setDenyToken(address token_, bool denyOrAccept_) public { require(canSellErc20[token_] || canSellErc721[token_], "dex-can-not-use-anyway"); denyToken[token_][msg.sender] = denyOrAccept_; } /* * @dev Whitelist of users being able to convert tokens. * @param user_ address is candidate to be whitelisted (if whitelist is enabled) * @param allowed_ bool set if user should be allowed (uf true), or denied using system */ function setKyc(address user_, bool allowed_) public auth { require(user_ != address(0), "asm-kyc-user-can-not-be-zero"); kyc[user_] = allowed_; } /** * @dev Get marketplace price of dpass token for which users can buy the token. * @param token_ address token to get the buyPrice for. * @param tokenId_ uint256 token id to get buy price for. */ function getBuyPrice(address token_, uint256 tokenId_) public view returns(uint256) { // require(canBuyErc721[token_], "dex-token-not-for-sale"); return buyPrice[token_][TrustedErc721(token_).ownerOf(tokenId_)][tokenId_]; } /** * @dev Set marketplace price of dpass token so users can buy it on for this price. * @param token_ address price is set for this token. * @param tokenId_ uint256 tokenid to set price for * @param price_ uint256 marketplace price to set */ function setBuyPrice(address token_, uint256 tokenId_, uint256 price_) public { address seller_ = msg.sender; require(canBuyErc721[token_], "dex-token-not-for-sale"); if ( msg.sender == Dpass(token_).getCustodian(tokenId_) && address(asm) == Dpass(token_).ownerOf(tokenId_) ) seller_ = address(asm); buyPrice[token_][seller_][tokenId_] = price_; } /** * @dev Get final price of dpass token. Function tries to get rpce from marketplace * price (buyPrice) and if that is zero, then from basePrice. * @param token_ address token to get price for * @param tokenId_ uint256 to get price for * @return final sell price that user must pay */ function getPrice(address token_, uint256 tokenId_) public view returns(uint256) { uint basePrice_; address owner_ = TrustedErc721(token_).ownerOf(tokenId_); uint buyPrice_ = buyPrice[token_][owner_][tokenId_]; require(canBuyErc721[token_], "dex-token-not-for-sale"); if( buyPrice_ == 0 || buyPrice_ == uint(-1)) { basePrice_ = asm.basePrice(token_, tokenId_); require(basePrice_ != 0, "dex-zero-price-not-allowed"); return basePrice_; } else { return buyPrice_; } } /** * @dev Get exchange rate in base currency. This function burns small amount of gas, because it returns the locally stored exchange rate for token_. It should only be used if user is sure that the rate was recently updated. * @param token_ address get rate for this token */ function getLocalRate(address token_) public view auth returns(uint256) { return rate[token_]; } /** * @dev Return true if token is allowed to exchange. * @param token_ the token_ addres in question * @param buy_ if true we ask if user can buy_ the token_ from exchange, * otherwise if user can sell to exchange. */ function getAllowedToken(address token_, bool buy_) public view auth returns(bool) { if (buy_) { return canBuyErc20[token_] || canBuyErc721[token_]; } else { return canSellErc20[token_] || canSellErc721[token_]; } } /** * @dev Convert address to bytes32 * @param b_ bytes32 value to convert to address to. */ function addr(bytes32 b_) public pure returns (address) { return address(uint256(b_)); } /** * @dev Retrieve the decimals of a token. Decimals are stored in a special way internally to apply the least calculations to get precision adjusted results. * @param token_ address the decimals are calculated for this token */ function getDecimals(address token_) public view returns (uint8) { require(decimalsSet[token_], "dex-token-with-unset-decimals"); uint dec = 0; while(dec <= 77 && decimals[token_] % uint(10) ** dec == 0){ dec++; } dec--; return uint8(dec); } /** * @dev Get token_ / quote_currency rate from priceFeed * Revert transaction if not valid feed and manual value not allowed * @param token_ address get rate for this token */ function getRate(address token_) public view auth returns (uint) { return _getNewRate(token_); } /* * @dev calculates multiple with decimals adjusted to match to 18 decimal precision to express base token value. * @param a_ uint256 multiply this number * @param b_ uint256 multiply this number * @param token_ address get results with the precision of this token */ function wmulV(uint256 a_, uint256 b_, address token_) public view returns(uint256) { return wdiv(wmul(a_, b_), decimals[token_]); } /* * @dev calculates division with decimals adjusted to match to tokens precision * @param a_ uint256 divide this number * @param b_ uint256 divide by this number * @param token_ address get result with the precision of this token */ function wdivT(uint256 a_, uint256 b_, address token_) public view returns(uint256) { return wmul(wdiv(a_,b_), decimals[token_]); } /** * @dev Get token_ / quote_currency rate from priceFeed * Revert transaction if not valid feed and manual value not allowed */ function _getNewRate(address token_) internal view returns (uint rate_) { bool feedValid_; bytes32 baseRateBytes_; require( TrustedFeedLikeDex(address(0x0)) != priceFeed[token_], // require token to have a price feed "dex-no-price-feed-for-token"); (baseRateBytes_, feedValid_) = priceFeed[token_].peek(); // receive DPT/USD price if (feedValid_) { // if feed is valid, load DPT/USD rate from it rate_ = uint(baseRateBytes_); } else { require(manualRate[token_], "dex-feed-provides-invalid-data"); // if feed invalid revert if manualEthRate is NOT allowed rate_ = rate[token_]; } } // // internal functions // /* * @dev updates locally stored rates of tokens from feeds */ function _updateRates(address sellToken_, address buyToken_) internal { if (canSellErc20[sellToken_]) { _updateRate(sellToken_); } if (canBuyErc20[buyToken_]){ _updateRate(buyToken_); } _updateRate(dpt); } /* * @dev log the trade event */ function _logTrade( address sellToken_, uint256 sellT_, address buyToken_, uint256 buyT_, uint256 buyAmtOrId_, uint256 feeV_ ) internal { address custodian_ = canBuyErc20[buyToken_] ? custodian20[buyToken_] : Dpass(buyToken_).getCustodian(buyAmtOrId_); txId++; emit LogBuyTokenWithFee( txId, msg.sender, custodian_, sellToken_, sellT_, buyToken_, buyT_, feeV_); } /** * @dev Get exchange rate for a token */ function _updateRate(address token) internal returns (uint256 rate_) { require((rate_ = _getNewRate(token)) > 0, "dex-rate-must-be-greater-than-0"); rate[token] = rate_; } /** * @dev Calculate and send profit and cost */ function _takeFeeInToken( uint256 feeV_, // feeV_ that user still owes to CDiamondCoin after paying feeV_ in DPT uint256 feeTakenV_, // feeV_ already taken from user in DPT address token_, // token_ that must be sent as feeV_ address src_, // source of token_ sent uint256 amountT_ // total amount of tokens the user wanted to pay initially ) internal { uint profitV_; uint profitDpt_; uint feeT_; uint profitPaidV_; uint totalProfitV_; totalProfitV_ = wmul(add(feeV_, feeTakenV_), profitRate); profitPaidV_ = takeProfitOnlyInDpt ? // profit value paid already in base currency feeTakenV_ : wmul(feeTakenV_, profitRate); profitV_ = sub( // profit value still to be paid in base currency totalProfitV_, min( profitPaidV_, totalProfitV_)); profitDpt_ = wdivT(profitV_, rate[dpt], dpt); // profit in DPT still to be paid feeT_ = wdivT(feeV_, rate[token_], token_); // convert feeV_ from base currency to token amount require( feeT_ < amountT_, // require that the cost we pay is less than user intended to pay "dex-not-enough-token-to-pay-fee"); if (block.coinbase == dpt) { //injected CONTRACT AFFECTED BY MINERS _sendToken(dpt, src_, address(uint160(address(burner))), profitDpt_); _sendToken(dpt, src_, wal, sub(feeT_, profitDpt_)); } else { if (liqBuysDpt) { Liquidity(liq).burn(dpt, burner, profitV_); // if liq contract buys DPT on the fly } else { _sendToken(dpt, // if liq contract stores DPT that can be sent to burner by us liq, address(uint160(address(burner))), profitDpt_); } _sendToken(token_, src_, wal, feeT_); // send user token_ to wallet } } /** * @dev Take fee in DPT from user if it has any * @param feeV_ the fee amount in base currency * @return the remaining fee amount in DPT */ function _takeFeeInDptFromUser( uint256 feeV_ // total feeV_ to be paid ) internal returns(uint256 feeTakenV_) { TrustedDSToken dpt20_ = TrustedDSToken(dpt); uint profitDpt_; uint costDpt_; uint feeTakenDpt_; uint dptUser = min( dpt20_.balanceOf(msg.sender), dpt20_.allowance(msg.sender, address(this)) ); if (block.gaslimit == 0) return 0; //injected CONTRACT AFFECTED BY MINERS uint feeDpt = wdivT(feeV_, rate[dpt], dpt); // feeV_ in DPT uint minDpt = min(feeDpt, dptUser); // get the maximum possible feeV_ amount if (block.number > 0) { //injected CONTRACT AFFECTED BY MINERS if (takeProfitOnlyInDpt) { // only profit is paid in dpt profitDpt_ = min(wmul(feeDpt, profitRate), minDpt); } else { profitDpt_ = wmul(minDpt, profitRate); costDpt_ = sub(minDpt, profitDpt_); _sendToken(dpt, msg.sender, wal, costDpt_); // send cost } _sendToken(dpt, // send profit to burner msg.sender, address(uint160(address(burner))), profitDpt_); feeTakenDpt_ = add(profitDpt_, costDpt_); // total feeV_ taken in DPT feeTakenV_ = wmulV(feeTakenDpt_, rate[dpt], dpt); // total feeV_ taken in base currency value } } /** * @dev send token or ether to destination */ function _sendToken( address token_, address src_, address payable dst_, uint256 amount_ ) internal returns(bool) { if (token_ == eth && amount_ > dust) { // if token_ is Ether and amount_ is higher than dust limit require(src_ == msg.sender || src_ == address(this), "dex-wrong-src-address-provided"); dst_.transfer(amount_); emit LogTransferEth(src_, dst_, amount_); } else { if (block.gaslimit > 0) { //injected CONTRACT AFFECTED BY MINERS if( handledByAsm[token_] && src_ == address(asm)) { // if token_ is handled by asm (so it is minted and burnt) and we have to mint it asm.mint(token_, dst_, amount_); } else { TrustedDSToken(token_).transferFrom(src_, dst_, amount_); // transfer all of token_ to dst_ } } } return true; } }
* @dev Fallback function to buy tokens./
function () external payable { buyTokensWithFee(eth, msg.value, address(cdc), uint(-1)); }
13,091,064
[ 1, 12355, 445, 358, 30143, 2430, 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, 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, 1832, 3903, 8843, 429, 288, 203, 3639, 30143, 5157, 1190, 14667, 12, 546, 16, 1234, 18, 1132, 16, 1758, 12, 4315, 71, 3631, 2254, 19236, 21, 10019, 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 ]
/* solhint-disable-next-line compiler-fixed */ pragma solidity ^0.4.23; // Copyright 2018 OpenST Ltd. // // 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. // // ---------------------------------------------------------------------------- // Value chain: Gateway // // http://www.simpletoken.org/ // // ---------------------------------------------------------------------------- import "./ProtocolVersioned.sol"; import "./OpenSTValueInterface.sol"; import "./EIP20Interface.sol"; import "./Owned.sol"; import "./WorkersInterface.sol"; /** * @title Gateway contract which implements ProtocolVersioned, Owned. * * @notice Gateway contract is staking Gateway that separates the concerns of staker and staking processor. * Stake process is executed through Gateway contract rather than directly with the protocol contract. * The Gateway contract will serve the role of staking account rather than an external account. */ contract Gateway is ProtocolVersioned, Owned { /** Events */ /** Below event is emitted after successful execution of requestStake */ event StakeRequested(address _staker, uint256 _amount, address _beneficiary); /** Below event is emitted after successful execution of revertStakeRequest */ event StakeRequestReverted(address _staker, uint256 _amount); /** Below event is emitted after successful execution of rejectStakeRequest */ event StakeRequestRejected(address _staker, uint256 _amount, uint8 _reason); /** Below event is emitted after successful execution of acceptStakeRequest */ event StakeRequestAccepted( address _staker, uint256 _amountST, uint256 _amountUT, uint256 _nonce, uint256 _unlockHeight, bytes32 _stakingIntentHash); /** Below event is emitted after successful execution of setWorkers */ event WorkersSet(WorkersInterface _workers); /** Storage */ /** Storing stake requests */ mapping(address /*staker */ => StakeRequest) public stakeRequests; /** Storing workers contract address */ WorkersInterface public workers; /** Storing bounty amount that will be used while accepting stake */ uint256 public bounty; /** Storing utility token UUID */ bytes32 public uuid; /** Structures */ struct StakeRequest { uint256 amount; uint256 unlockHeight; address beneficiary; bytes32 hashLock; } /** Public functions */ /** * @notice Contract constructor. * * @param _workers Workers contract address. * @param _bounty Bounty amount that worker address stakes while accepting stake request. * @param _uuid UUID of utility token. * @param _openSTProtocol OpenSTProtocol address contract that governs staking. */ constructor( WorkersInterface _workers, uint256 _bounty, bytes32 _uuid, address _openSTProtocol) public Owned() ProtocolVersioned(_openSTProtocol) { require(_workers != address(0)); require(_uuid.length != uint8(0)); workers = _workers; bounty = _bounty; uuid = _uuid; } /** * @notice External function requestStake. * * @dev In order to request stake the staker needs to approve Gateway contract for stake amount. * Staked amount is transferred from staker address to Gateway contract. * * @param _amount Staking amount. * @param _beneficiary Beneficiary address. * * @return bool Specifies status of the execution. */ function requestStake( uint256 _amount, address _beneficiary) external returns (bool /* success */) { require(_amount > uint256(0)); require(_beneficiary != address(0)); // check if the stake request does not exists require(stakeRequests[msg.sender].beneficiary == address(0)); require(OpenSTValueInterface(openSTProtocol).valueToken().transferFrom(msg.sender, address(this), _amount)); stakeRequests[msg.sender] = StakeRequest({ amount: _amount, beneficiary: _beneficiary, hashLock: 0, unlockHeight: 0 }); emit StakeRequested(msg.sender, _amount, _beneficiary); return true; } /** * @notice External function to revert requested stake. * * @dev This can be called only by staker. Staked amount is transferred back * to staker address from Gateway contract. * * @return stakeRequestAmount Staking amount. */ function revertStakeRequest() external returns (uint256 stakeRequestAmount) { // only staker can do revertStakeRequest, msg.sender == staker StakeRequest storage stakeRequest = stakeRequests[msg.sender]; // check if the stake request exists for the msg.sender require(stakeRequest.beneficiary != address(0)); // check if the stake request was not accepted require(stakeRequest.hashLock == bytes32(0)); require(OpenSTValueInterface(openSTProtocol).valueToken().transfer(msg.sender, stakeRequest.amount)); stakeRequestAmount = stakeRequest.amount; delete stakeRequests[msg.sender]; emit StakeRequestReverted(msg.sender, stakeRequestAmount); return stakeRequestAmount; } /** * @notice External function to reject requested stake. * * @dev This can be called only by whitelisted worker address. * Staked amount is transferred back to staker address from Gateway contract. * * @param _staker Staker address. * @param _reason Reason for rejection. * * @return stakeRequestAmount Staking amount. */ function rejectStakeRequest(address _staker, uint8 _reason) external returns (uint256 stakeRequestAmount) { // check if the caller is whitelisted worker require(workers.isWorker(msg.sender)); StakeRequest storage stakeRequest = stakeRequests[_staker]; // check if the stake request exists require(stakeRequest.beneficiary != address(0)); // check if the stake request was not accepted require(stakeRequest.hashLock == bytes32(0)); // transfer the amount back require(OpenSTValueInterface(openSTProtocol).valueToken().transfer(_staker, stakeRequest.amount)); stakeRequestAmount = stakeRequest.amount; // delete the stake request from the mapping storage delete stakeRequests[_staker]; emit StakeRequestRejected(_staker, stakeRequestAmount, _reason); return stakeRequestAmount; } /** * @notice External function to accept requested stake. * * @dev This can be called only by whitelisted worker address. * Bounty amount is transferred from msg.sender to Gateway contract. * openSTProtocol is approved for staking amount by Gateway contract. * * @param _staker Staker address. * @param _hashLock Hash lock. * * @return amountUT Branded token amount. * @return nonce Staker nonce count. * @return unlockHeight Height till what the amount is locked. * @return stakingIntentHash Staking intent hash. */ function acceptStakeRequest(address _staker, bytes32 _hashLock) external returns ( uint256 amountUT, uint256 nonce, uint256 unlockHeight, bytes32 stakingIntentHash) { // check if the caller is whitelisted worker require(workers.isWorker(msg.sender)); StakeRequest storage stakeRequest = stakeRequests[_staker]; // check if the stake request exists require(stakeRequest.beneficiary != address(0)); // check if the stake request was not accepted require(stakeRequest.hashLock == bytes32(0)); // check if _hashLock is not 0 require(_hashLock != bytes32(0)); // Transfer bounty amount from worker to Gateway contract require(OpenSTValueInterface(openSTProtocol).valueToken().transferFrom(msg.sender, address(this), bounty)); // Approve OpenSTValue contract for stake amount require(OpenSTValueInterface(openSTProtocol).valueToken().approve(openSTProtocol, stakeRequest.amount)); (amountUT, nonce, unlockHeight, stakingIntentHash) = OpenSTValueInterface(openSTProtocol).stake( uuid, stakeRequest.amount, stakeRequest.beneficiary, _hashLock, _staker); // Check if the stake function call did not result in to error. require(stakingIntentHash != bytes32(0)); stakeRequests[_staker].unlockHeight = unlockHeight; stakeRequests[_staker].hashLock = _hashLock; emit StakeRequestAccepted(_staker, stakeRequest.amount, amountUT, nonce, unlockHeight, stakingIntentHash); return (amountUT, nonce, unlockHeight, stakingIntentHash); } /** * @notice External function to process staking. * * @dev Bounty amount is transferred to msg.sender if msg.sender is not a whitelisted worker. * Bounty amount is transferred to workers contract if msg.sender is a whitelisted worker. * * @param _stakingIntentHash Staking intent hash. * @param _unlockSecret Unlock secret. * * @return stakeRequestAmount Stake amount. */ function processStaking( bytes32 _stakingIntentHash, bytes32 _unlockSecret) external returns (uint256 stakeRequestAmount) { require(_stakingIntentHash != bytes32(0)); //the hash timelock for staking and bounty are respectively in the openstvalue contract and Gateway contract in v0.9.3; //but all staking stateful information will move to the Gateway contract in v0.9.4 (making OpenST a library call) //and making this call obsolete address staker = OpenSTValueInterface(openSTProtocol).getStakerAddress(_stakingIntentHash); StakeRequest storage stakeRequest = stakeRequests[staker]; // check if the stake request exists require(stakeRequest.beneficiary != address(0)); // check if the stake request was accepted require(stakeRequest.hashLock != bytes32(0)); // we call processStaking for OpenSTValue and get the stakeAddress on success. address stakerAddress = OpenSTValueInterface(openSTProtocol).processStaking(_stakingIntentHash, _unlockSecret); // check if the stake address is not 0 require(stakerAddress != address(0)); //If the msg.sender is whitelited worker then transfer the bounty amount to Workers contract //else transfer the bounty to msg.sender. if (workers.isWorker(msg.sender)) { // Transfer bounty amount to the workers contract address require(OpenSTValueInterface(openSTProtocol).valueToken().transfer(workers, bounty)); } else { //Transfer bounty amount to the msg.sender account require(OpenSTValueInterface(openSTProtocol).valueToken().transfer(msg.sender, bounty)); } stakeRequestAmount = stakeRequest.amount; // delete the stake request from the mapping storage delete stakeRequests[staker]; return stakeRequestAmount; } /** * @notice External function to revert staking. * * @dev Staked amount is transferred to the staker address. * Bounty amount is transferred to workers contract. * * @param _stakingIntentHash Staking intent hash. * * @return stakeRequestAmount Staking amount. */ function revertStaking( bytes32 _stakingIntentHash) external returns (uint256 amountST) { require(_stakingIntentHash != bytes32(0)); //the hash timelock for staking and bounty are respectively in the openstvalue contract and Gateway contract in v0.9.3; //but all staking stateful information will move to the Gateway contract in v0.9.4 (making OpenST a library call) //and making this call obsolete address staker = OpenSTValueInterface(openSTProtocol).getStakerAddress(_stakingIntentHash); StakeRequest storage stakeRequest = stakeRequests[staker]; // check if the stake request exists require(stakeRequest.beneficiary != address(0)); // check if the stake request was accepted require(stakeRequest.hashLock != bytes32(0)); address stakerAddress = address(0); (, amountST, stakerAddress) = OpenSTValueInterface(openSTProtocol).revertStaking(_stakingIntentHash); // check if the stake address is correct assert(stakerAddress == staker); assert(amountST == stakeRequest.amount); require(OpenSTValueInterface(openSTProtocol).valueToken().transfer(workers, bounty)); // delete the stake request from the mapping storage delete stakeRequests[staker]; return amountST; } /** * @notice External function to set workers. * * @dev Only callable by owner. * * @param _workers Workers contract address. * * @return bool Specifies status of the execution. */ function setWorkers(WorkersInterface _workers) external onlyOwner() returns (bool /* success */) { workers = _workers; //Event for workers set emit WorkersSet(_workers); return true; } }
delete the stake request from the mapping storage
delete stakeRequests[staker];
5,400,862
[ 1, 3733, 326, 384, 911, 590, 628, 326, 2874, 2502, 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, 1430, 384, 911, 6421, 63, 334, 6388, 15533, 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 ]
pragma solidity 0.4.25; contract TokenConfig { string public constant NAME = "MANGO"; string public constant SYMBOL = "MANG"; uint8 public constant DECIMALS = 5; uint public constant DECIMALSFACTOR = 10 ** uint(DECIMALS); uint public constant TOTALSUPPLY = 10000000000 * DECIMALSFACTOR; } interface IERC20 { 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 ); } /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "can't mul"); 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) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "can't sub with zero."); 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, "can't sub"); 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, "add overflow"); 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, "can't mod with zero"); return a % b; } } library SafeERC20 { using SafeMath for uint256; function safeTransfer(IERC20 token, address to, uint256 value) internal { require(token.transfer(to, value), "safeTransfer"); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { require(token.transferFrom(from, to, value), "safeTransferFrom"); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require((value == 0) || (token.allowance(msg.sender, spender) == 0), "safeApprove"); require(token.approve(spender, value), "safeApprove"); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); require(token.approve(spender, newAllowance), "safeIncreaseAllowance"); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value); require(token.approve(spender, newAllowance), "safeDecreaseAllowance"); } } /** * @title Helps contracts guard against reentrancy attacks. * @author Remco Bloemen <remco@2π.com>, Eenae <[email protected]> * @dev If you mark a function `nonReentrant`, you should also * mark it `external`. */ contract ReentrancyGuard { /// @dev counter to allow mutex lock with only one SSTORE operation uint256 private _guardCounter; constructor () internal { // The counter starts at one to prevent changing it from zero to a non-zero // value, which is a more expensive operation. _guardCounter = 1; } /** * @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() { _guardCounter += 1; uint256 localCounter = _guardCounter; _; require(localCounter == _guardCounter, "nonReentrant."); } } /** * @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. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner, "only for 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), "address is zero."); owner = newOwner; emit OwnershipTransferred(owner, newOwner); } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Paused(address account); event Unpaused(address account); bool private _paused; constructor() internal { _paused = false; } /** * @return true if the contract is paused, false otherwise. */ function paused() public view returns(bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!_paused, "paused."); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(_paused, "Not paused."); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() public onlyOwner whenNotPaused { _paused = true; emit Paused(msg.sender); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() public onlyOwner whenPaused { _paused = false; emit Unpaused(msg.sender); } } /** * @title Crowdsale white list address */ contract Whitelist is Ownable { event WhitelistAdded(address addr); event WhitelistRemoved(address addr); mapping (address => bool) private _whitelist; /** * @dev add addresses to the whitelist * @param addrs addresses */ function addWhiteListAddr(address[] addrs) public { uint256 len = addrs.length; for (uint256 i = 0; i < len; i++) { _addAddressToWhitelist(addrs[i]); } } /** * @dev remove an address from the whitelist * @param addr address */ function removeWhiteListAddr(address addr) public { _removeAddressToWhitelist(addr); } /** * @dev getter to determine if address is in whitelist */ function isWhiteListAddr(address addr) public view returns (bool) { require(addr != address(0), "address is zero"); return _whitelist[addr]; } modifier onlyAuthorised(address beneficiary) { require(isWhiteListAddr(beneficiary),"Not authorised"); _; } /** * @dev add an address to the whitelist * @param addr address */ function _addAddressToWhitelist(address addr) internal onlyOwner { require(addr != address(0), "address is zero"); _whitelist[addr] = true; emit WhitelistAdded(addr); } /** * @dev remove an address from the whitelist * @param addr address */ function _removeAddressToWhitelist(address addr) internal onlyOwner { require(addr != address(0), "address is zero"); _whitelist[addr] = false; emit WhitelistRemoved(addr); } } /** * @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 / overridden. * The internal interface conforms the extensible and modifiable surface of crowdsales. Override * the methods to add functionality. Consider using 'super' where appropriate to concatenate * behavior. */ contract Crowdsale is TokenConfig, Pausable, ReentrancyGuard, Whitelist { using SafeMath for uint256; using SafeERC20 for IERC20; // The token being sold IERC20 private _token; // Address where funds are collected address private _wallet; // Address where funds are collected address private _tokenholder; // How many token units a buyer gets per wei. // The rate is the conversion between wei and the smallest and indivisible token unit. // So, if you are using a rate of 1 with a ERC20Detailed token with 3 decimals called TOK // 1 wei will give you 1 unit, or 0.001 TOK. uint256 private _rate; // Amount of contribution wei raised uint256 private _weiRaised; // Amount of token sold uint256 private _tokenSoldAmount; // Minimum contribution amount of fund uint256 private _minWeiAmount; // balances of user should be sent mapping (address => uint256) private _tokenBalances; // balances of user fund mapping (address => uint256) private _weiBalances; // ICO period timestamp uint256 private _openingTime; uint256 private _closingTime; // Amount of token hardcap uint256 private _hardcap; /** * 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 TokensPurchased( address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount ); event TokensDelivered(address indexed beneficiary, uint256 amount); event RateChanged(uint256 rate); event MinWeiChanged(uint256 minWei); event PeriodChanged(uint256 open, uint256 close); event HardcapChanged(uint256 hardcap); constructor( uint256 rate, uint256 minWeiAmount, address wallet, address tokenholder, IERC20 token, uint256 hardcap, uint256 openingTime, uint256 closingTime ) public { require(rate > 0, "Rate is lower than zero."); require(wallet != address(0), "Wallet address is zero"); require(tokenholder != address(0), "Tokenholder address is zero"); require(token != address(0), "Token address is zero"); _rate = rate; _minWeiAmount = minWeiAmount; _wallet = wallet; _tokenholder = tokenholder; _token = token; _hardcap = hardcap; _openingTime = openingTime; _closingTime = closingTime; } // ----------------------------------------- // Crowdsale external interface // ----------------------------------------- /** * @dev fallback function ***DO NOT OVERRIDE*** * Note that other contracts will transfer fund with a base gas stipend * of 2300, which is not enough to call buyTokens. Consider calling * buyTokens directly when purchasing tokens from a contract. */ function () external payable { buyTokens(msg.sender); } /** * @return the token being sold. */ function token() public view returns(IERC20) { return _token; } /** * @return token hardcap. */ function hardcap() public view returns(uint256) { return _hardcap; } /** * @return the address where funds are collected. */ function wallet() public view returns(address) { return _wallet; } /** * @return the number of token units a buyer gets per wei. */ function rate() public view returns(uint256) { return _rate; } /** * @return the amount of wei raised. */ function weiRaised() public view returns (uint256) { return _weiRaised; } /** * @return ICO opening time. */ function openingTime() public view returns (uint256) { return _openingTime; } /** * @return ICO closing time. */ function closingTime() public view returns (uint256) { return _closingTime; } /** * @return the amount of token raised. */ function tokenSoldAmount() public view returns (uint256) { return _tokenSoldAmount; } /** * @return the number of minimum amount buyer can fund. */ function minWeiAmount() public view returns(uint256) { return _minWeiAmount; } /** * @return is ICO period */ function isOpen() public view returns (bool) { // solium-disable-next-line security/no-block-members return now >= _openingTime && now <= _closingTime; } /** * @dev Gets the token balance of the specified address for deliver * @param owner The address to query the balance of. * @return An uint256 representing the amount owned by the passed address. */ function tokenBalanceOf(address owner) public view returns (uint256) { return _tokenBalances[owner]; } /** * @dev Gets the ETH balance of the specified address. * @param owner The address to query the balance of. * @return An uint256 representing the amount owned by the passed address. */ function weiBalanceOf(address owner) public view returns (uint256) { return _weiBalances[owner]; } function setRate(uint256 value) public onlyOwner { _rate = value; emit RateChanged(value); } function setMinWeiAmount(uint256 value) public onlyOwner { _minWeiAmount = value; emit MinWeiChanged(value); } function setPeriodTimestamp(uint256 open, uint256 close) public onlyOwner { _openingTime = open; _closingTime = close; emit PeriodChanged(open, close); } function setHardcap(uint256 value) public onlyOwner { _hardcap = value; emit HardcapChanged(value); } /** * @dev low level token purchase ***DO NOT OVERRIDE*** * This function has a non-reentrancy guard, so it shouldn't be called by * another `nonReentrant` function. * @param beneficiary Recipient of the token purchase */ function buyTokens(address beneficiary) public nonReentrant whenNotPaused payable { uint256 weiAmount = msg.value; _preValidatePurchase(beneficiary, weiAmount); // Calculate token amount to be created uint256 tokens = _getTokenAmount(weiAmount); require(_hardcap > _tokenSoldAmount.add(tokens), "Over hardcap"); // Update state _weiRaised = _weiRaised.add(weiAmount); _tokenSoldAmount = _tokenSoldAmount.add(tokens); _weiBalances[beneficiary] = _weiBalances[beneficiary].add(weiAmount); _tokenBalances[beneficiary] = _tokenBalances[beneficiary].add(tokens); emit TokensPurchased( msg.sender, beneficiary, weiAmount, tokens ); _forwardFunds(); } /** * @dev method that deliver token to user */ function deliverTokens(address[] users) public whenNotPaused onlyOwner { uint256 len = users.length; for (uint256 i = 0; i < len; i++) { address user = users[i]; uint256 tokenAmount = _tokenBalances[user]; _deliverTokens(user, tokenAmount); _tokenBalances[user] = 0; emit TokensDelivered(user, tokenAmount); } } // ----------------------------------------- // Internal interface (extensible) // ----------------------------------------- /** * @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use `super` in contracts that inherit from Crowdsale to extend their validations. * @param beneficiary Address performing the token purchase * @param weiAmount Value in wei involved in the purchase */ function _preValidatePurchase( address beneficiary, uint256 weiAmount ) internal view onlyAuthorised(beneficiary) { require(weiAmount != 0, "Zero ETH"); require(weiAmount >= _minWeiAmount, "Must be equal or higher than minimum"); require(beneficiary != address(0), "Beneficiary address is zero"); require(isOpen(), "Sales is close"); } /** * @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.safeTransferFrom(_tokenholder, beneficiary, tokenAmount); } /** * @dev Override to extend the way in which ether is converted to tokens. * @param weiAmount Value in wei to be converted into tokens * @return Number of tokens that can be purchased with the specified _weiAmount */ function _getTokenAmount(uint256 weiAmount) internal view returns (uint256) { uint ethDecimals = 18; require(DECIMALS <= ethDecimals, ""); uint256 covertedTokens = weiAmount; if (DECIMALS != ethDecimals) { covertedTokens = weiAmount.div((10 ** uint256(ethDecimals - DECIMALS))); } return covertedTokens.mul(_rate); } /** * @dev Determines how ETH is stored/forwarded on purchases. */ function _forwardFunds() internal { _wallet.transfer(msg.value); } }
* @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), "address is zero."); owner = newOwner; emit OwnershipTransferred(owner, newOwner); }
6,439,305
[ 1, 19132, 326, 783, 3410, 358, 7412, 3325, 434, 326, 6835, 358, 279, 394, 5541, 18, 225, 394, 5541, 1021, 1758, 358, 7412, 23178, 358, 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 ]
[ 1, 1, 1, 1, 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 ]
[ 1, 225, 445, 7412, 5460, 12565, 12, 2867, 394, 5541, 13, 1071, 1338, 5541, 288, 203, 565, 2583, 12, 2704, 5541, 480, 1758, 12, 20, 3631, 315, 2867, 353, 3634, 1199, 1769, 203, 565, 3410, 273, 394, 5541, 31, 203, 565, 3626, 14223, 9646, 5310, 1429, 4193, 12, 8443, 16, 394, 5541, 1769, 203, 225, 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 ]
./full_match/137/0xcA297e7b0654CAa3091421e8C388Dcfe922AcF1A/sources/SendInviteGiveaway.sol
require(_amount > 0, "ERR. AMT."); usdcToken.transferFrom(msg.sender, address(this), _amount*_length); usdcToken.transferFrom(msg.sender, address(this), _amount);
function sendTop10Giveaway(uint256 _amount, uint256 _length) public { require(contractOwner==msg.sender, "Permission Denied"); for (uint i = 0; i < _length; i++) { usdcToken.transfer(top10GiveawayAddr[i], _amount); } }
4,750,463
[ 1, 6528, 24899, 8949, 405, 374, 16, 315, 9712, 18, 432, 6152, 1199, 1769, 584, 7201, 1345, 18, 13866, 1265, 12, 3576, 18, 15330, 16, 1758, 12, 2211, 3631, 389, 8949, 67, 2469, 1769, 584, 7201, 1345, 18, 13866, 1265, 12, 3576, 18, 15330, 16, 1758, 12, 2211, 3631, 389, 8949, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 565, 445, 1366, 3401, 2163, 43, 688, 26718, 12, 11890, 5034, 389, 8949, 16, 2254, 5034, 389, 2469, 13, 1071, 288, 203, 3639, 2583, 12, 16351, 5541, 631, 3576, 18, 15330, 16, 315, 5041, 22453, 2092, 8863, 203, 540, 203, 3639, 364, 261, 11890, 277, 273, 374, 31, 277, 411, 389, 2469, 31, 277, 27245, 288, 203, 5411, 584, 7201, 1345, 18, 13866, 12, 3669, 2163, 43, 688, 26718, 3178, 63, 77, 6487, 389, 8949, 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 ]
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.3.2 (utils/cryptography/draft-EIP712.sol) pragma solidity ^0.8.0; import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol"; contract EIP712 { /* solhint-disable var-name-mixedcase */ // Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to // invalidate the cached domain separator if the chain id changes. bytes32 private immutable _CACHED_DOMAIN_SEPARATOR; uint256 private immutable _CACHED_CHAIN_ID; address private immutable _CACHED_THIS; bytes32 private immutable _HASHED_NAME; bytes32 private immutable _HASHED_VERSION; bytes32 private immutable _TYPE_HASH; bytes32 private immutable _SALT; /* 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, bytes32 salt) { bytes32 hashedName = keccak256(bytes(name)); bytes32 hashedVersion = keccak256(bytes(version)); bytes32 typeHash = keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract,bytes32 salt)" ); _HASHED_NAME = hashedName; _HASHED_VERSION = hashedVersion; _SALT = salt; _CACHED_CHAIN_ID = block.chainid; _CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(typeHash, hashedName, hashedVersion, salt); _CACHED_THIS = address(this); _TYPE_HASH = typeHash; } /** * @dev Returns the domain separator for the current chain. */ function _domainSeparatorV4() internal view returns (bytes32) { if (address(this) == _CACHED_THIS && block.chainid == _CACHED_CHAIN_ID) { return _CACHED_DOMAIN_SEPARATOR; } else { return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION, _SALT); } } function recoverSigner(bytes32 struct_hash, bytes memory signature) internal view returns(address) { return ECDSA.recover(_hashTypedDataV4(struct_hash), signature); } function _buildDomainSeparator( bytes32 typeHash, bytes32 nameHash, bytes32 versionHash, bytes32 salt ) private view returns (bytes32) { return keccak256(abi.encode(typeHash, nameHash, versionHash, block.chainid, address(this), salt)); } /** * @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 ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash); } }
* @dev Returns the domain separator for the current chain./
function _domainSeparatorV4() internal view returns (bytes32) { if (address(this) == _CACHED_THIS && block.chainid == _CACHED_CHAIN_ID) { return _CACHED_DOMAIN_SEPARATOR; return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION, _SALT); } }
13,029,026
[ 1, 1356, 326, 2461, 4182, 364, 326, 783, 2687, 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 ]
[ 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, 389, 4308, 6581, 58, 24, 1435, 2713, 1476, 1135, 261, 3890, 1578, 13, 288, 203, 3639, 309, 261, 2867, 12, 2211, 13, 422, 389, 3587, 15023, 67, 2455, 5127, 597, 1203, 18, 5639, 350, 422, 389, 3587, 15023, 67, 1792, 6964, 67, 734, 13, 288, 203, 5411, 327, 389, 3587, 15023, 67, 18192, 67, 4550, 31, 203, 5411, 327, 389, 3510, 3748, 6581, 24899, 2399, 67, 15920, 16, 389, 15920, 2056, 67, 1985, 16, 389, 15920, 2056, 67, 5757, 16, 389, 55, 18255, 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: Apache-2.0 pragma solidity ^0.8.0; /** * @title Rules for withdrawing ETH from the Treasury. * * @dev */ interface ETHWithdrawStrategy { }
* @title Rules for withdrawing ETH from the Treasury. @dev/
interface ETHWithdrawStrategy { pragma solidity ^0.8.0; }
15,784,883
[ 1, 4478, 364, 598, 9446, 310, 512, 2455, 628, 326, 399, 266, 345, 22498, 18, 342, 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, 5831, 512, 2455, 1190, 9446, 4525, 288, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 20, 31, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.4.24; /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * 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 SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. * @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 OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev Transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * 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, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval( address _spender, uint256 _addedValue ) public returns (bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval( address _spender, 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); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); 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 make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } } /** * @title Pausable token * @dev StandardToken modified with pausable transfers. **/ contract PausableToken is StandardToken, Pausable { function transfer( address _to, uint256 _value ) public whenNotPaused returns (bool) { return super.transfer(_to, _value); } function transferFrom( address _from, address _to, uint256 _value ) public whenNotPaused returns (bool) { return super.transferFrom(_from, _to, _value); } function approve( address _spender, uint256 _value ) public whenNotPaused returns (bool) { return super.approve(_spender, _value); } function increaseApproval( address _spender, uint _addedValue ) public whenNotPaused returns (bool success) { return super.increaseApproval(_spender, _addedValue); } function decreaseApproval( address _spender, uint _subtractedValue ) public whenNotPaused returns (bool success) { return super.decreaseApproval(_spender, _subtractedValue); } } /** * @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 { _burn(msg.sender, _value); } function _burn(address _who, uint256 _value) internal { require(_value <= balances[_who]); // no need to require value <= totalSupply, since that would imply the // sender's balance is greater than the totalSupply, which *should* be an assertion failure balances[_who] = balances[_who].sub(_value); totalSupply_ = totalSupply_.sub(_value); emit Burn(_who, _value); emit Transfer(_who, address(0), _value); } } contract RepublicToken is PausableToken, BurnableToken { string public constant name = "Republic Token"; string public constant symbol = "REN"; uint8 public constant decimals = 18; uint256 public constant INITIAL_SUPPLY = 1000000000 * 10**uint256(decimals); /// @notice The RepublicToken Constructor. constructor() public { totalSupply_ = INITIAL_SUPPLY; balances[msg.sender] = INITIAL_SUPPLY; } function transferTokens(address beneficiary, uint256 amount) public onlyOwner returns (bool) { /* solium-disable error-reason */ require(amount > 0); balances[owner] = balances[owner].sub(amount); balances[beneficiary] = balances[beneficiary].add(amount); emit Transfer(owner, beneficiary, amount); return true; } } /** * @notice LinkedList is a library for a circular double linked list. */ library LinkedList { /* * @notice A permanent NULL node (0x0) in the circular double linked list. * NULL.next is the head, and NULL.previous is the tail. */ address public constant NULL = 0x0; /** * @notice A node points to the node before it, and the node after it. If * node.previous = NULL, then the node is the head of the list. If * node.next = NULL, then the node is the tail of the list. */ struct Node { bool inList; address previous; address next; } /** * @notice LinkedList uses a mapping from address to nodes. Each address * uniquely identifies a node, and in this way they are used like pointers. */ struct List { mapping (address => Node) list; } /** * @notice Insert a new node before an existing node. * * @param self The list being used. * @param target The existing node in the list. * @param newNode The next node to insert before the target. */ function insertBefore(List storage self, address target, address newNode) internal { require(!isInList(self, newNode), "already in list"); require(isInList(self, target) || target == NULL, "not in list"); // It is expected that this value is sometimes NULL. address prev = self.list[target].previous; self.list[newNode].next = target; self.list[newNode].previous = prev; self.list[target].previous = newNode; self.list[prev].next = newNode; self.list[newNode].inList = true; } /** * @notice Insert a new node after an existing node. * * @param self The list being used. * @param target The existing node in the list. * @param newNode The next node to insert after the target. */ function insertAfter(List storage self, address target, address newNode) internal { require(!isInList(self, newNode), "already in list"); require(isInList(self, target) || target == NULL, "not in list"); // It is expected that this value is sometimes NULL. address n = self.list[target].next; self.list[newNode].previous = target; self.list[newNode].next = n; self.list[target].next = newNode; self.list[n].previous = newNode; self.list[newNode].inList = true; } /** * @notice Remove a node from the list, and fix the previous and next * pointers that are pointing to the removed node. Removing anode that is not * in the list will do nothing. * * @param self The list being using. * @param node The node in the list to be removed. */ function remove(List storage self, address node) internal { require(isInList(self, node), "not in list"); if (node == NULL) { return; } address p = self.list[node].previous; address n = self.list[node].next; self.list[p].next = n; self.list[n].previous = p; // Deleting the node should set this value to false, but we set it here for // explicitness. self.list[node].inList = false; delete self.list[node]; } /** * @notice Insert a node at the beginning of the list. * * @param self The list being used. * @param node The node to insert at the beginning of the list. */ function prepend(List storage self, address node) internal { // isInList(node) is checked in insertBefore insertBefore(self, begin(self), node); } /** * @notice Insert a node at the end of the list. * * @param self The list being used. * @param node The node to insert at the end of the list. */ function append(List storage self, address node) internal { // isInList(node) is checked in insertBefore insertAfter(self, end(self), node); } function swap(List storage self, address left, address right) internal { // isInList(left) and isInList(right) are checked in remove address previousRight = self.list[right].previous; remove(self, right); insertAfter(self, left, right); remove(self, left); insertAfter(self, previousRight, left); } function isInList(List storage self, address node) internal view returns (bool) { return self.list[node].inList; } /** * @notice Get the node at the beginning of a double linked list. * * @param self The list being used. * * @return A address identifying the node at the beginning of the double * linked list. */ function begin(List storage self) internal view returns (address) { return self.list[NULL].next; } /** * @notice Get the node at the end of a double linked list. * * @param self The list being used. * * @return A address identifying the node at the end of the double linked * list. */ function end(List storage self) internal view returns (address) { return self.list[NULL].previous; } function next(List storage self, address node) internal view returns (address) { require(isInList(self, node), "not in list"); return self.list[node].next; } function previous(List storage self, address node) internal view returns (address) { require(isInList(self, node), "not in list"); return self.list[node].previous; } } /// @notice This contract stores data and funds for the DarknodeRegistry /// contract. The data / fund logic and storage have been separated to improve /// upgradability. contract DarknodeRegistryStore is Ownable { string public VERSION; // Passed in as a constructor parameter. /// @notice Darknodes are stored in the darknode struct. The owner is the /// address that registered the darknode, the bond is the amount of REN that /// was transferred during registration, and the public key is the /// encryption key that should be used when sending sensitive information to /// the darknode. struct Darknode { // The owner of a Darknode is the address that called the register // function. The owner is the only address that is allowed to // deregister the Darknode, unless the Darknode is slashed for // malicious behavior. address owner; // The bond is the amount of REN submitted as a bond by the Darknode. // This amount is reduced when the Darknode is slashed for malicious // behavior. uint256 bond; // The block number at which the Darknode is considered registered. uint256 registeredAt; // The block number at which the Darknode is considered deregistered. uint256 deregisteredAt; // The public key used by this Darknode for encrypting sensitive data // off chain. It is assumed that the Darknode has access to the // respective private key, and that there is an agreement on the format // of the public key. bytes publicKey; } /// Registry data. mapping(address => Darknode) private darknodeRegistry; LinkedList.List private darknodes; // RepublicToken. RepublicToken public ren; /// @notice The contract constructor. /// /// @param _VERSION A string defining the contract version. /// @param _ren The address of the RepublicToken contract. constructor( string _VERSION, RepublicToken _ren ) public { VERSION = _VERSION; ren = _ren; } /// @notice Instantiates a darknode and appends it to the darknodes /// linked-list. /// /// @param _darknodeID The darknode's ID. /// @param _darknodeOwner The darknode's owner's address /// @param _bond The darknode's bond value /// @param _publicKey The darknode's public key /// @param _registeredAt The time stamp when the darknode is registered. /// @param _deregisteredAt The time stamp when the darknode is deregistered. function appendDarknode( address _darknodeID, address _darknodeOwner, uint256 _bond, bytes _publicKey, uint256 _registeredAt, uint256 _deregisteredAt ) external onlyOwner { Darknode memory darknode = Darknode({ owner: _darknodeOwner, bond: _bond, publicKey: _publicKey, registeredAt: _registeredAt, deregisteredAt: _deregisteredAt }); darknodeRegistry[_darknodeID] = darknode; LinkedList.append(darknodes, _darknodeID); } /// @notice Returns the address of the first darknode in the store function begin() external view onlyOwner returns(address) { return LinkedList.begin(darknodes); } /// @notice Returns the address of the next darknode in the store after the /// given address. function next(address darknodeID) external view onlyOwner returns(address) { return LinkedList.next(darknodes, darknodeID); } /// @notice Removes a darknode from the store and transfers its bond to the /// owner of this contract. function removeDarknode(address darknodeID) external onlyOwner { uint256 bond = darknodeRegistry[darknodeID].bond; delete darknodeRegistry[darknodeID]; LinkedList.remove(darknodes, darknodeID); require(ren.transfer(owner, bond), "bond transfer failed"); } /// @notice Updates the bond of the darknode. If the bond is being /// decreased, the difference is sent to the owner of this contract. function updateDarknodeBond(address darknodeID, uint256 bond) external onlyOwner { uint256 previousBond = darknodeRegistry[darknodeID].bond; darknodeRegistry[darknodeID].bond = bond; if (previousBond > bond) { require(ren.transfer(owner, previousBond - bond), "cannot transfer bond"); } } /// @notice Updates the deregistration timestamp of a darknode. function updateDarknodeDeregisteredAt(address darknodeID, uint256 deregisteredAt) external onlyOwner { darknodeRegistry[darknodeID].deregisteredAt = deregisteredAt; } /// @notice Returns the owner of a given darknode. function darknodeOwner(address darknodeID) external view onlyOwner returns (address) { return darknodeRegistry[darknodeID].owner; } /// @notice Returns the bond of a given darknode. function darknodeBond(address darknodeID) external view onlyOwner returns (uint256) { return darknodeRegistry[darknodeID].bond; } /// @notice Returns the registration time of a given darknode. function darknodeRegisteredAt(address darknodeID) external view onlyOwner returns (uint256) { return darknodeRegistry[darknodeID].registeredAt; } /// @notice Returns the deregistration time of a given darknode. function darknodeDeregisteredAt(address darknodeID) external view onlyOwner returns (uint256) { return darknodeRegistry[darknodeID].deregisteredAt; } /// @notice Returns the encryption public key of a given darknode. function darknodePublicKey(address darknodeID) external view onlyOwner returns (bytes) { return darknodeRegistry[darknodeID].publicKey; } } /// @notice DarknodeRegistry is responsible for the registration and /// deregistration of Darknodes. contract DarknodeRegistry is Ownable { string public VERSION; // Passed in as a constructor parameter. /// @notice Darknode pods are shuffled after a fixed number of blocks. /// An Epoch stores an epoch hash used as an (insecure) RNG seed, and the /// blocknumber which restricts when the next epoch can be called. struct Epoch { uint256 epochhash; uint256 blocknumber; } uint256 public numDarknodes; uint256 public numDarknodesNextEpoch; uint256 public numDarknodesPreviousEpoch; /// Variables used to parameterize behavior. uint256 public minimumBond; uint256 public minimumPodSize; uint256 public minimumEpochInterval; address public slasher; /// When one of the above variables is modified, it is only updated when the /// next epoch is called. These variables store the values for the next epoch. uint256 public nextMinimumBond; uint256 public nextMinimumPodSize; uint256 public nextMinimumEpochInterval; address public nextSlasher; /// The current and previous epoch Epoch public currentEpoch; Epoch public previousEpoch; /// Republic ERC20 token contract used to transfer bonds. RepublicToken public ren; /// Darknode Registry Store is the storage contract for darknodes. DarknodeRegistryStore public store; /// @notice Emitted when a darknode is registered. /// @param _darknodeID The darknode ID that was registered. /// @param _bond The amount of REN that was transferred as bond. event LogDarknodeRegistered(address _darknodeID, uint256 _bond); /// @notice Emitted when a darknode is deregistered. /// @param _darknodeID The darknode ID that was deregistered. event LogDarknodeDeregistered(address _darknodeID); /// @notice Emitted when a refund has been made. /// @param _owner The address that was refunded. /// @param _amount The amount of REN that was refunded. event LogDarknodeOwnerRefunded(address _owner, uint256 _amount); /// @notice Emitted when a new epoch has begun. event LogNewEpoch(); /// @notice Emitted when a constructor parameter has been updated. event LogMinimumBondUpdated(uint256 previousMinimumBond, uint256 nextMinimumBond); event LogMinimumPodSizeUpdated(uint256 previousMinimumPodSize, uint256 nextMinimumPodSize); event LogMinimumEpochIntervalUpdated(uint256 previousMinimumEpochInterval, uint256 nextMinimumEpochInterval); event LogSlasherUpdated(address previousSlasher, address nextSlasher); /// @notice Only allow the owner that registered the darknode to pass. modifier onlyDarknodeOwner(address _darknodeID) { require(store.darknodeOwner(_darknodeID) == msg.sender, "must be darknode owner"); _; } /// @notice Only allow unregistered darknodes. modifier onlyRefunded(address _darknodeID) { require(isRefunded(_darknodeID), "must be refunded or never registered"); _; } /// @notice Only allow refundable darknodes. modifier onlyRefundable(address _darknodeID) { require(isRefundable(_darknodeID), "must be deregistered for at least one epoch"); _; } /// @notice Only allowed registered nodes without a pending deregistration to /// deregister modifier onlyDeregisterable(address _darknodeID) { require(isDeregisterable(_darknodeID), "must be deregisterable"); _; } /// @notice Only allow the Slasher contract. modifier onlySlasher() { require(slasher == msg.sender, "must be slasher"); _; } /// @notice The contract constructor. /// /// @param _VERSION A string defining the contract version. /// @param _renAddress The address of the RepublicToken contract. /// @param _storeAddress The address of the DarknodeRegistryStore contract. /// @param _minimumBond The minimum bond amount that can be submitted by a /// Darknode. /// @param _minimumPodSize The minimum size of a Darknode pod. /// @param _minimumEpochInterval The minimum number of blocks between /// epochs. constructor( string _VERSION, RepublicToken _renAddress, DarknodeRegistryStore _storeAddress, uint256 _minimumBond, uint256 _minimumPodSize, uint256 _minimumEpochInterval ) public { VERSION = _VERSION; store = _storeAddress; ren = _renAddress; minimumBond = _minimumBond; nextMinimumBond = minimumBond; minimumPodSize = _minimumPodSize; nextMinimumPodSize = minimumPodSize; minimumEpochInterval = _minimumEpochInterval; nextMinimumEpochInterval = minimumEpochInterval; currentEpoch = Epoch({ epochhash: uint256(blockhash(block.number - 1)), blocknumber: block.number }); numDarknodes = 0; numDarknodesNextEpoch = 0; numDarknodesPreviousEpoch = 0; } /// @notice Register a darknode and transfer the bond to this contract. The /// caller must provide a public encryption key for the darknode as well as /// a bond in REN. The bond must be provided as an ERC20 allowance. The dark /// node will remain pending registration until the next epoch. Only after /// this period can the darknode be deregistered. The caller of this method /// will be stored as the owner of the darknode. /// /// @param _darknodeID The darknode ID that will be registered. /// @param _publicKey The public key of the darknode. It is stored to allow /// other darknodes and traders to encrypt messages to the trader. /// @param _bond The bond that will be paid. It must be greater than, or /// equal to, the minimum bond. function register(address _darknodeID, bytes _publicKey, uint256 _bond) external onlyRefunded(_darknodeID) { // REN allowance require(_bond >= minimumBond, "insufficient bond"); // require(ren.allowance(msg.sender, address(this)) >= _bond); require(ren.transferFrom(msg.sender, address(this), _bond), "bond transfer failed"); ren.transfer(address(store), _bond); // Flag this darknode for registration store.appendDarknode( _darknodeID, msg.sender, _bond, _publicKey, currentEpoch.blocknumber + minimumEpochInterval, 0 ); numDarknodesNextEpoch += 1; // Emit an event. emit LogDarknodeRegistered(_darknodeID, _bond); } /// @notice Deregister a darknode. The darknode will not be deregistered /// until the end of the epoch. After another epoch, the bond can be /// refunded by calling the refund method. /// @param _darknodeID The darknode ID that will be deregistered. The caller /// of this method store.darknodeRegisteredAt(_darknodeID) must be // the owner of this darknode. function deregister(address _darknodeID) external onlyDeregisterable(_darknodeID) onlyDarknodeOwner(_darknodeID) { // Flag the darknode for deregistration store.updateDarknodeDeregisteredAt(_darknodeID, currentEpoch.blocknumber + minimumEpochInterval); numDarknodesNextEpoch -= 1; // Emit an event emit LogDarknodeDeregistered(_darknodeID); } /// @notice Progress the epoch if it is possible to do so. This captures /// the current timestamp and current blockhash and overrides the current /// epoch. function epoch() external { if (previousEpoch.blocknumber == 0) { // The first epoch must be called by the owner of the contract require(msg.sender == owner, "not authorized (first epochs)"); } // Require that the epoch interval has passed require(block.number >= currentEpoch.blocknumber + minimumEpochInterval, "epoch interval has not passed"); uint256 epochhash = uint256(blockhash(block.number - 1)); // Update the epoch hash and timestamp previousEpoch = currentEpoch; currentEpoch = Epoch({ epochhash: epochhash, blocknumber: block.number }); // Update the registry information numDarknodesPreviousEpoch = numDarknodes; numDarknodes = numDarknodesNextEpoch; // If any update functions have been called, update the values now if (nextMinimumBond != minimumBond) { minimumBond = nextMinimumBond; emit LogMinimumBondUpdated(minimumBond, nextMinimumBond); } if (nextMinimumPodSize != minimumPodSize) { minimumPodSize = nextMinimumPodSize; emit LogMinimumPodSizeUpdated(minimumPodSize, nextMinimumPodSize); } if (nextMinimumEpochInterval != minimumEpochInterval) { minimumEpochInterval = nextMinimumEpochInterval; emit LogMinimumEpochIntervalUpdated(minimumEpochInterval, nextMinimumEpochInterval); } if (nextSlasher != slasher) { slasher = nextSlasher; emit LogSlasherUpdated(slasher, nextSlasher); } // Emit an event emit LogNewEpoch(); } /// @notice Allows the contract owner to transfer ownership of the /// DarknodeRegistryStore. /// @param _newOwner The address to transfer the ownership to. function transferStoreOwnership(address _newOwner) external onlyOwner { store.transferOwnership(_newOwner); } /// @notice Allows the contract owner to update the minimum bond. /// @param _nextMinimumBond The minimum bond amount that can be submitted by /// a darknode. function updateMinimumBond(uint256 _nextMinimumBond) external onlyOwner { // Will be updated next epoch nextMinimumBond = _nextMinimumBond; } /// @notice Allows the contract owner to update the minimum pod size. /// @param _nextMinimumPodSize The minimum size of a pod. function updateMinimumPodSize(uint256 _nextMinimumPodSize) external onlyOwner { // Will be updated next epoch nextMinimumPodSize = _nextMinimumPodSize; } /// @notice Allows the contract owner to update the minimum epoch interval. /// @param _nextMinimumEpochInterval The minimum number of blocks between epochs. function updateMinimumEpochInterval(uint256 _nextMinimumEpochInterval) external onlyOwner { // Will be updated next epoch nextMinimumEpochInterval = _nextMinimumEpochInterval; } /// @notice Allow the contract owner to update the DarknodeSlasher contract /// address. /// @param _slasher The new slasher address. function updateSlasher(address _slasher) external onlyOwner { nextSlasher = _slasher; } /// @notice Allow the DarknodeSlasher contract to slash half of a darknode's /// bond and deregister it. The bond is distributed as follows: /// 1/2 is kept by the guilty prover /// 1/8 is rewarded to the first challenger /// 1/8 is rewarded to the second challenger /// 1/4 becomes unassigned /// @param _prover The guilty prover whose bond is being slashed /// @param _challenger1 The first of the two darknodes who submitted the challenge /// @param _challenger2 The second of the two darknodes who submitted the challenge function slash(address _prover, address _challenger1, address _challenger2) external onlySlasher { uint256 penalty = store.darknodeBond(_prover) / 2; uint256 reward = penalty / 4; // Slash the bond of the failed prover in half store.updateDarknodeBond(_prover, penalty); // If the darknode has not been deregistered then deregister it if (isDeregisterable(_prover)) { store.updateDarknodeDeregisteredAt(_prover, currentEpoch.blocknumber + minimumEpochInterval); numDarknodesNextEpoch -= 1; emit LogDarknodeDeregistered(_prover); } // Reward the challengers with less than the penalty so that it is not // worth challenging yourself ren.transfer(store.darknodeOwner(_challenger1), reward); ren.transfer(store.darknodeOwner(_challenger2), reward); } /// @notice Refund the bond of a deregistered darknode. This will make the /// darknode available for registration again. Anyone can call this function /// but the bond will always be refunded to the darknode owner. /// /// @param _darknodeID The darknode ID that will be refunded. The caller /// of this method must be the owner of this darknode. function refund(address _darknodeID) external onlyRefundable(_darknodeID) { address darknodeOwner = store.darknodeOwner(_darknodeID); // Remember the bond amount uint256 amount = store.darknodeBond(_darknodeID); // Erase the darknode from the registry store.removeDarknode(_darknodeID); // Refund the owner by transferring REN ren.transfer(darknodeOwner, amount); // Emit an event. emit LogDarknodeOwnerRefunded(darknodeOwner, amount); } /// @notice Retrieves the address of the account that registered a darknode. /// @param _darknodeID The ID of the darknode to retrieve the owner for. function getDarknodeOwner(address _darknodeID) external view returns (address) { return store.darknodeOwner(_darknodeID); } /// @notice Retrieves the bond amount of a darknode in 10^-18 REN. /// @param _darknodeID The ID of the darknode to retrieve the bond for. function getDarknodeBond(address _darknodeID) external view returns (uint256) { return store.darknodeBond(_darknodeID); } /// @notice Retrieves the encryption public key of the darknode. /// @param _darknodeID The ID of the darknode to retrieve the public key for. function getDarknodePublicKey(address _darknodeID) external view returns (bytes) { return store.darknodePublicKey(_darknodeID); } /// @notice Retrieves a list of darknodes which are registered for the /// current epoch. /// @param _start A darknode ID used as an offset for the list. If _start is /// 0x0, the first dark node will be used. _start won't be /// included it is not registered for the epoch. /// @param _count The number of darknodes to retrieve starting from _start. /// If _count is 0, all of the darknodes from _start are /// retrieved. If _count is more than the remaining number of /// registered darknodes, the rest of the list will contain /// 0x0s. function getDarknodes(address _start, uint256 _count) external view returns (address[]) { uint256 count = _count; if (count == 0) { count = numDarknodes; } return getDarknodesFromEpochs(_start, count, false); } /// @notice Retrieves a list of darknodes which were registered for the /// previous epoch. See `getDarknodes` for the parameter documentation. function getPreviousDarknodes(address _start, uint256 _count) external view returns (address[]) { uint256 count = _count; if (count == 0) { count = numDarknodesPreviousEpoch; } return getDarknodesFromEpochs(_start, count, true); } /// @notice Returns whether a darknode is scheduled to become registered /// at next epoch. /// @param _darknodeID The ID of the darknode to return function isPendingRegistration(address _darknodeID) external view returns (bool) { uint256 registeredAt = store.darknodeRegisteredAt(_darknodeID); return registeredAt != 0 && registeredAt > currentEpoch.blocknumber; } /// @notice Returns if a darknode is in the pending deregistered state. In /// this state a darknode is still considered registered. function isPendingDeregistration(address _darknodeID) external view returns (bool) { uint256 deregisteredAt = store.darknodeDeregisteredAt(_darknodeID); return deregisteredAt != 0 && deregisteredAt > currentEpoch.blocknumber; } /// @notice Returns if a darknode is in the deregistered state. function isDeregistered(address _darknodeID) public view returns (bool) { uint256 deregisteredAt = store.darknodeDeregisteredAt(_darknodeID); return deregisteredAt != 0 && deregisteredAt <= currentEpoch.blocknumber; } /// @notice Returns if a darknode can be deregistered. This is true if the /// darknodes is in the registered state and has not attempted to /// deregister yet. function isDeregisterable(address _darknodeID) public view returns (bool) { uint256 deregisteredAt = store.darknodeDeregisteredAt(_darknodeID); // The Darknode is currently in the registered state and has not been // transitioned to the pending deregistration, or deregistered, state return isRegistered(_darknodeID) && deregisteredAt == 0; } /// @notice Returns if a darknode is in the refunded state. This is true /// for darknodes that have never been registered, or darknodes that have /// been deregistered and refunded. function isRefunded(address _darknodeID) public view returns (bool) { uint256 registeredAt = store.darknodeRegisteredAt(_darknodeID); uint256 deregisteredAt = store.darknodeDeregisteredAt(_darknodeID); return registeredAt == 0 && deregisteredAt == 0; } /// @notice Returns if a darknode is refundable. This is true for darknodes /// that have been in the deregistered state for one full epoch. function isRefundable(address _darknodeID) public view returns (bool) { return isDeregistered(_darknodeID) && store.darknodeDeregisteredAt(_darknodeID) <= previousEpoch.blocknumber; } /// @notice Returns if a darknode is in the registered state. function isRegistered(address _darknodeID) public view returns (bool) { return isRegisteredInEpoch(_darknodeID, currentEpoch); } /// @notice Returns if a darknode was in the registered state last epoch. function isRegisteredInPreviousEpoch(address _darknodeID) public view returns (bool) { return isRegisteredInEpoch(_darknodeID, previousEpoch); } /// @notice Returns if a darknode was in the registered state for a given /// epoch. /// @param _darknodeID The ID of the darknode /// @param _epoch One of currentEpoch, previousEpoch function isRegisteredInEpoch(address _darknodeID, Epoch _epoch) private view returns (bool) { uint256 registeredAt = store.darknodeRegisteredAt(_darknodeID); uint256 deregisteredAt = store.darknodeDeregisteredAt(_darknodeID); bool registered = registeredAt != 0 && registeredAt <= _epoch.blocknumber; bool notDeregistered = deregisteredAt == 0 || deregisteredAt > _epoch.blocknumber; // The Darknode has been registered and has not yet been deregistered, // although it might be pending deregistration return registered && notDeregistered; } /// @notice Returns a list of darknodes registered for either the current /// or the previous epoch. See `getDarknodes` for documentation on the /// parameters `_start` and `_count`. /// @param _usePreviousEpoch If true, use the previous epoch, otherwise use /// the current epoch. function getDarknodesFromEpochs(address _start, uint256 _count, bool _usePreviousEpoch) private view returns (address[]) { uint256 count = _count; if (count == 0) { count = numDarknodes; } address[] memory nodes = new address[](count); // Begin with the first node in the list uint256 n = 0; address next = _start; if (next == 0x0) { next = store.begin(); } // Iterate until all registered Darknodes have been collected while (n < count) { if (next == 0x0) { break; } // Only include Darknodes that are currently registered bool includeNext; if (_usePreviousEpoch) { includeNext = isRegisteredInPreviousEpoch(next); } else { includeNext = isRegistered(next); } if (!includeNext) { next = store.next(next); continue; } nodes[n] = next; next = store.next(next); n += 1; } return nodes; } } /** * @title Math * @dev Assorted math operations */ library Math { function max64(uint64 a, uint64 b) internal pure returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal pure returns (uint64) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } } /// @notice Implements safeTransfer, safeTransferFrom and /// safeApprove for CompatibleERC20. /// /// See https://github.com/ethereum/solidity/issues/4116 /// /// This library allows interacting with ERC20 tokens that implement any of /// these interfaces: /// /// (1) transfer returns true on success, false on failure /// (2) transfer returns true on success, reverts on failure /// (3) transfer returns nothing on success, reverts on failure /// /// Additionally, safeTransferFromWithFees will return the final token /// value received after accounting for token fees. library CompatibleERC20Functions { using SafeMath for uint256; /// @notice Calls transfer on the token and reverts if the call fails. function safeTransfer(address token, address to, uint256 amount) internal { CompatibleERC20(token).transfer(to, amount); require(previousReturnValue(), "transfer failed"); } /// @notice Calls transferFrom on the token and reverts if the call fails. function safeTransferFrom(address token, address from, address to, uint256 amount) internal { CompatibleERC20(token).transferFrom(from, to, amount); require(previousReturnValue(), "transferFrom failed"); } /// @notice Calls approve on the token and reverts if the call fails. function safeApprove(address token, address spender, uint256 amount) internal { CompatibleERC20(token).approve(spender, amount); require(previousReturnValue(), "approve failed"); } /// @notice Calls transferFrom on the token, reverts if the call fails and /// returns the value transferred after fees. function safeTransferFromWithFees(address token, address from, address to, uint256 amount) internal returns (uint256) { uint256 balancesBefore = CompatibleERC20(token).balanceOf(to); CompatibleERC20(token).transferFrom(from, to, amount); require(previousReturnValue(), "transferFrom failed"); uint256 balancesAfter = CompatibleERC20(token).balanceOf(to); return Math.min256(amount, balancesAfter.sub(balancesBefore)); } /// @notice Checks the return value of the previous function. Returns true /// if the previous function returned 32 non-zero bytes or returned zero /// bytes. function previousReturnValue() private pure returns (bool) { uint256 returnData = 0; assembly { /* solium-disable-line security/no-inline-assembly */ // Switch on the number of bytes returned by the previous call switch returndatasize // 0 bytes: ERC20 of type (3), did not throw case 0 { returnData := 1 } // 32 bytes: ERC20 of types (1) or (2) case 32 { // Copy the return data into scratch space returndatacopy(0x0, 0x0, 32) // Load the return data into returnData returnData := mload(0x0) } // Other return size: return false default { } } return returnData != 0; } } /// @notice ERC20 interface which doesn't specify the return type for transfer, /// transferFrom and approve. interface CompatibleERC20 { // Modified to not return boolean function transfer(address to, uint256 value) external; function transferFrom(address from, address to, uint256 value) external; function approve(address spender, uint256 value) external; // Not modifier function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } /// @notice The DarknodeRewardVault contract is responsible for holding fees /// for darknodes for settling orders. Fees can be withdrawn to the address of /// the darknode's operator. Fees can be in ETH or in ERC20 tokens. /// Docs: https://github.com/republicprotocol/republic-sol/blob/master/docs/02-darknode-reward-vault.md contract DarknodeRewardVault is Ownable { using SafeMath for uint256; using CompatibleERC20Functions for CompatibleERC20; string public VERSION; // Passed in as a constructor parameter. /// @notice The special address for Ether. address constant public ETHEREUM = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; DarknodeRegistry public darknodeRegistry; mapping(address => mapping(address => uint256)) public darknodeBalances; event LogDarknodeRegistryUpdated(DarknodeRegistry previousDarknodeRegistry, DarknodeRegistry nextDarknodeRegistry); /// @notice The contract constructor. /// /// @param _VERSION A string defining the contract version. /// @param _darknodeRegistry The DarknodeRegistry contract that is used by /// the vault to lookup Darknode owners. constructor(string _VERSION, DarknodeRegistry _darknodeRegistry) public { VERSION = _VERSION; darknodeRegistry = _darknodeRegistry; } function updateDarknodeRegistry(DarknodeRegistry _newDarknodeRegistry) public onlyOwner { emit LogDarknodeRegistryUpdated(darknodeRegistry, _newDarknodeRegistry); darknodeRegistry = _newDarknodeRegistry; } /// @notice Deposit fees into the vault for a Darknode. The Darknode /// registration is not checked (to reduce gas fees); the caller must be /// careful not to call this function for a Darknode that is not registered /// otherwise any fees deposited to that Darknode can be withdrawn by a /// malicious adversary (by registering the Darknode before the honest /// party and claiming ownership). /// /// @param _darknode The address of the Darknode that will receive the /// fees. /// @param _token The address of the ERC20 token being used to pay the fee. /// A special address is used for Ether. /// @param _value The amount of fees in the smallest unit of the token. function deposit(address _darknode, ERC20 _token, uint256 _value) public payable { uint256 receivedValue = _value; if (address(_token) == ETHEREUM) { require(msg.value == _value, "mismatched ether value"); } else { require(msg.value == 0, "unexpected ether value"); receivedValue = CompatibleERC20(_token).safeTransferFromWithFees(msg.sender, address(this), _value); } darknodeBalances[_darknode][_token] = darknodeBalances[_darknode][_token].add(receivedValue); } /// @notice Withdraw fees earned by a Darknode. The fees will be sent to /// the owner of the Darknode. If a Darknode is not registered the fees /// cannot be withdrawn. /// /// @param _darknode The address of the Darknode whose fees are being /// withdrawn. The owner of this Darknode will receive the fees. /// @param _token The address of the ERC20 token to withdraw. function withdraw(address _darknode, ERC20 _token) public { address darknodeOwner = darknodeRegistry.getDarknodeOwner(address(_darknode)); require(darknodeOwner != 0x0, "invalid darknode owner"); uint256 value = darknodeBalances[_darknode][_token]; darknodeBalances[_darknode][_token] = 0; if (address(_token) == ETHEREUM) { darknodeOwner.transfer(value); } else { CompatibleERC20(_token).safeTransfer(darknodeOwner, value); } } } /// @notice The BrokerVerifier interface defines the functions that a settlement /// layer's broker verifier contract must implement. interface BrokerVerifier { /// @notice The function signature that will be called when a trader opens /// an order. /// /// @param _trader The trader requesting the withdrawal. /// @param _signature The 65-byte signature from the broker. /// @param _orderID The 32-byte order ID. function verifyOpenSignature( address _trader, bytes _signature, bytes32 _orderID ) external returns (bool); } /// @notice The Settlement interface defines the functions that a settlement /// layer must implement. /// Docs: https://github.com/republicprotocol/republic-sol/blob/nightly/docs/05-settlement.md interface Settlement { function submitOrder( bytes _details, uint64 _settlementID, uint64 _tokens, uint256 _price, uint256 _volume, uint256 _minimumVolume ) external; function submissionGasPriceLimit() external view returns (uint256); function settle( bytes32 _buyID, bytes32 _sellID ) external; /// @notice orderStatus should return the status of the order, which should /// be: /// 0 - Order not seen before /// 1 - Order details submitted /// >1 - Order settled, or settlement no longer possible function orderStatus(bytes32 _orderID) external view returns (uint8); } /// @notice SettlementRegistry allows a Settlement layer to register the /// contracts used for match settlement and for broker signature verification. contract SettlementRegistry is Ownable { string public VERSION; // Passed in as a constructor parameter. struct SettlementDetails { bool registered; Settlement settlementContract; BrokerVerifier brokerVerifierContract; } // Settlement IDs are 64-bit unsigned numbers mapping(uint64 => SettlementDetails) public settlementDetails; // Events event LogSettlementRegistered(uint64 settlementID, Settlement settlementContract, BrokerVerifier brokerVerifierContract); event LogSettlementUpdated(uint64 settlementID, Settlement settlementContract, BrokerVerifier brokerVerifierContract); event LogSettlementDeregistered(uint64 settlementID); /// @notice The contract constructor. /// /// @param _VERSION A string defining the contract version. constructor(string _VERSION) public { VERSION = _VERSION; } /// @notice Returns the settlement contract of a settlement layer. function settlementRegistration(uint64 _settlementID) external view returns (bool) { return settlementDetails[_settlementID].registered; } /// @notice Returns the settlement contract of a settlement layer. function settlementContract(uint64 _settlementID) external view returns (Settlement) { return settlementDetails[_settlementID].settlementContract; } /// @notice Returns the broker verifier contract of a settlement layer. function brokerVerifierContract(uint64 _settlementID) external view returns (BrokerVerifier) { return settlementDetails[_settlementID].brokerVerifierContract; } /// @param _settlementID A unique 64-bit settlement identifier. /// @param _settlementContract The address to use for settling matches. /// @param _brokerVerifierContract The decimals to use for verifying /// broker signatures. function registerSettlement(uint64 _settlementID, Settlement _settlementContract, BrokerVerifier _brokerVerifierContract) public onlyOwner { bool alreadyRegistered = settlementDetails[_settlementID].registered; settlementDetails[_settlementID] = SettlementDetails({ registered: true, settlementContract: _settlementContract, brokerVerifierContract: _brokerVerifierContract }); if (alreadyRegistered) { emit LogSettlementUpdated(_settlementID, _settlementContract, _brokerVerifierContract); } else { emit LogSettlementRegistered(_settlementID, _settlementContract, _brokerVerifierContract); } } /// @notice Deregisteres a settlement layer, clearing the details. /// @param _settlementID The unique 64-bit settlement identifier. function deregisterSettlement(uint64 _settlementID) external onlyOwner { require(settlementDetails[_settlementID].registered, "not registered"); delete settlementDetails[_settlementID]; emit LogSettlementDeregistered(_settlementID); } } /** * @title Eliptic curve signature operations * @dev Based on https://gist.github.com/axic/5b33912c6f61ae6fd96d6c4a47afde6d * TODO Remove this library once solidity supports passing a signature to ecrecover. * See https://github.com/ethereum/solidity/issues/864 */ library ECRecovery { /** * @dev Recover signer address from a message by using their signature * @param hash bytes32 message, the hash is the signed message. What is recovered is the signer address. * @param sig bytes signature, the signature is generated using web3.eth.sign() */ function recover(bytes32 hash, bytes sig) internal pure returns (address) { bytes32 r; bytes32 s; uint8 v; // Check the signature length if (sig.length != 65) { return (address(0)); } // Divide the signature in r, s and v variables // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solium-disable-next-line security/no-inline-assembly assembly { r := mload(add(sig, 32)) s := mload(add(sig, 64)) v := byte(0, mload(add(sig, 96))) } // Version of signature should be 27 or 28, but 0 and 1 are also possible versions if (v < 27) { v += 27; } // If the version is correct return the signer address if (v != 27 && v != 28) { return (address(0)); } else { // solium-disable-next-line arg-overflow return ecrecover(hash, v, r, s); } } /** * toEthSignedMessageHash * @dev prefix a bytes32 value with "\x19Ethereum Signed Message:" * and hash the result */ 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) ); } } library Utils { /** * @notice Converts a number to its string/bytes representation * * @param _v the uint to convert */ function uintToBytes(uint256 _v) internal pure returns (bytes) { uint256 v = _v; if (v == 0) { return "0"; } uint256 digits = 0; uint256 v2 = v; while (v2 > 0) { v2 /= 10; digits += 1; } bytes memory result = new bytes(digits); for (uint256 i = 0; i < digits; i++) { result[digits - i - 1] = bytes1((v % 10) + 48); v /= 10; } return result; } /** * @notice Retrieves the address from a signature * * @param _hash the message that was signed (any length of bytes) * @param _signature the signature (65 bytes) */ function addr(bytes _hash, bytes _signature) internal pure returns (address) { bytes memory prefix = "\x19Ethereum Signed Message:\n"; bytes memory encoded = abi.encodePacked(prefix, uintToBytes(_hash.length), _hash); bytes32 prefixedHash = keccak256(encoded); return ECRecovery.recover(prefixedHash, _signature); } } /// @notice The Orderbook contract stores the state and priority of orders and /// allows the Darknodes to easily reach consensus. Eventually, this contract /// will only store a subset of order states, such as cancellation, to improve /// the throughput of orders. contract Orderbook is Ownable { string public VERSION; // Passed in as a constructor parameter. /// @notice OrderState enumerates the possible states of an order. All /// orders default to the Undefined state. enum OrderState {Undefined, Open, Confirmed, Canceled} /// @notice Order stores a subset of the public data associated with an order. struct Order { OrderState state; // State of the order address trader; // Trader that owns the order address confirmer; // Darknode that confirmed the order in a match uint64 settlementID; // The settlement that signed the order opening uint256 priority; // Logical time priority of this order uint256 blockNumber; // Block number of the most recent state change bytes32 matchedOrder; // Order confirmed in a match with this order } DarknodeRegistry public darknodeRegistry; SettlementRegistry public settlementRegistry; bytes32[] private orderbook; // Order details are exposed through directly accessing this mapping, or // through the getter functions below for each of the order's fields. mapping(bytes32 => Order) public orders; event LogFeeUpdated(uint256 previousFee, uint256 nextFee); event LogDarknodeRegistryUpdated(DarknodeRegistry previousDarknodeRegistry, DarknodeRegistry nextDarknodeRegistry); /// @notice Only allow registered dark nodes. modifier onlyDarknode(address _sender) { require(darknodeRegistry.isRegistered(address(_sender)), "must be registered darknode"); _; } /// @notice The contract constructor. /// /// @param _VERSION A string defining the contract version. /// @param _darknodeRegistry The address of the DarknodeRegistry contract. /// @param _settlementRegistry The address of the SettlementRegistry /// contract. constructor( string _VERSION, DarknodeRegistry _darknodeRegistry, SettlementRegistry _settlementRegistry ) public { VERSION = _VERSION; darknodeRegistry = _darknodeRegistry; settlementRegistry = _settlementRegistry; } /// @notice Allows the owner to update the address of the DarknodeRegistry /// contract. function updateDarknodeRegistry(DarknodeRegistry _newDarknodeRegistry) external onlyOwner { emit LogDarknodeRegistryUpdated(darknodeRegistry, _newDarknodeRegistry); darknodeRegistry = _newDarknodeRegistry; } /// @notice Open an order in the orderbook. The order must be in the /// Undefined state. /// /// @param _signature Signature of the message that defines the trader. The /// message is "Republic Protocol: open: {orderId}". /// @param _orderID The hash of the order. function openOrder(uint64 _settlementID, bytes _signature, bytes32 _orderID) external { require(orders[_orderID].state == OrderState.Undefined, "invalid order status"); address trader = msg.sender; // Verify the order signature require(settlementRegistry.settlementRegistration(_settlementID), "settlement not registered"); BrokerVerifier brokerVerifier = settlementRegistry.brokerVerifierContract(_settlementID); require(brokerVerifier.verifyOpenSignature(trader, _signature, _orderID), "invalid broker signature"); orders[_orderID] = Order({ state: OrderState.Open, trader: trader, confirmer: 0x0, settlementID: _settlementID, priority: orderbook.length + 1, blockNumber: block.number, matchedOrder: 0x0 }); orderbook.push(_orderID); } /// @notice Confirm an order match between orders. The confirmer must be a /// registered Darknode and the orders must be in the Open state. A /// malicious confirmation by a Darknode will result in a bond slash of the /// Darknode. /// /// @param _orderID The hash of the order. /// @param _matchedOrderID The hashes of the matching order. function confirmOrder(bytes32 _orderID, bytes32 _matchedOrderID) external onlyDarknode(msg.sender) { require(orders[_orderID].state == OrderState.Open, "invalid order status"); require(orders[_matchedOrderID].state == OrderState.Open, "invalid order status"); orders[_orderID].state = OrderState.Confirmed; orders[_orderID].confirmer = msg.sender; orders[_orderID].matchedOrder = _matchedOrderID; orders[_orderID].blockNumber = block.number; orders[_matchedOrderID].state = OrderState.Confirmed; orders[_matchedOrderID].confirmer = msg.sender; orders[_matchedOrderID].matchedOrder = _orderID; orders[_matchedOrderID].blockNumber = block.number; } /// @notice Cancel an open order in the orderbook. An order can be cancelled /// by the trader who opened the order, or by the broker verifier contract. /// This allows the settlement layer to implement their own logic for /// cancelling orders without trader interaction (e.g. to ban a trader from /// a specific darkpool, or to use multiple order-matching platforms) /// /// @param _orderID The hash of the order. function cancelOrder(bytes32 _orderID) external { require(orders[_orderID].state == OrderState.Open, "invalid order state"); // Require the msg.sender to be the trader or the broker verifier address brokerVerifier = address(settlementRegistry.brokerVerifierContract(orders[_orderID].settlementID)); require(msg.sender == orders[_orderID].trader || msg.sender == brokerVerifier, "not authorized"); orders[_orderID].state = OrderState.Canceled; orders[_orderID].blockNumber = block.number; } /// @notice returns status of the given orderID. function orderState(bytes32 _orderID) external view returns (OrderState) { return orders[_orderID].state; } /// @notice returns a list of matched orders to the given orderID. function orderMatch(bytes32 _orderID) external view returns (bytes32) { return orders[_orderID].matchedOrder; } /// @notice returns the priority of the given orderID. /// The priority is the index of the order in the orderbook. function orderPriority(bytes32 _orderID) external view returns (uint256) { return orders[_orderID].priority; } /// @notice returns the trader of the given orderID. /// Trader is the one who signs the message and does the actual trading. function orderTrader(bytes32 _orderID) external view returns (address) { return orders[_orderID].trader; } /// @notice returns the darknode address which confirms the given orderID. function orderConfirmer(bytes32 _orderID) external view returns (address) { return orders[_orderID].confirmer; } /// @notice returns the block number when the order being last modified. function orderBlockNumber(bytes32 _orderID) external view returns (uint256) { return orders[_orderID].blockNumber; } /// @notice returns the block depth of the orderId function orderDepth(bytes32 _orderID) external view returns (uint256) { if (orders[_orderID].blockNumber == 0) { return 0; } return (block.number - orders[_orderID].blockNumber); } /// @notice returns the number of orders in the orderbook function ordersCount() external view returns (uint256) { return orderbook.length; } /// @notice returns order details of the orders starting from the offset. function getOrders(uint256 _offset, uint256 _limit) external view returns (bytes32[], address[], uint8[]) { if (_offset >= orderbook.length) { return; } // If the provided limit is more than the number of orders after the offset, // decrease the limit uint256 limit = _limit; if (_offset + limit > orderbook.length) { limit = orderbook.length - _offset; } bytes32[] memory orderIDs = new bytes32[](limit); address[] memory traderAddresses = new address[](limit); uint8[] memory states = new uint8[](limit); for (uint256 i = 0; i < limit; i++) { bytes32 order = orderbook[i + _offset]; orderIDs[i] = order; traderAddresses[i] = orders[order].trader; states[i] = uint8(orders[order].state); } return (orderIDs, traderAddresses, states); } } /// @notice A library for calculating and verifying order match details library SettlementUtils { struct OrderDetails { uint64 settlementID; uint64 tokens; uint256 price; uint256 volume; uint256 minimumVolume; } /// @notice Calculates the ID of the order. /// @param details Order details that are not required for settlement /// execution. They are combined as a single byte array. /// @param order The order details required for settlement execution. function hashOrder(bytes details, OrderDetails memory order) internal pure returns (bytes32) { return keccak256( abi.encodePacked( details, order.settlementID, order.tokens, order.price, order.volume, order.minimumVolume ) ); } /// @notice Verifies that two orders match when considering the tokens, /// price, volumes / minimum volumes and settlement IDs. verifyMatchDetails is used /// my the DarknodeSlasher to verify challenges. Settlement layers may also /// use this function. /// @dev When verifying two orders for settlement, you should also: /// 1) verify the orders have been confirmed together /// 2) verify the orders' traders are distinct /// @param _buy The buy order details. /// @param _sell The sell order details. function verifyMatchDetails(OrderDetails memory _buy, OrderDetails memory _sell) internal pure returns (bool) { // Buy and sell tokens should match if (!verifyTokens(_buy.tokens, _sell.tokens)) { return false; } // Buy price should be greater than sell price if (_buy.price < _sell.price) { return false; } // // Buy volume should be greater than sell minimum volume if (_buy.volume < _sell.minimumVolume) { return false; } // Sell volume should be greater than buy minimum volume if (_sell.volume < _buy.minimumVolume) { return false; } // Require that the orders were submitted to the same settlement layer if (_buy.settlementID != _sell.settlementID) { return false; } return true; } /// @notice Verifies that two token requirements can be matched and that the /// tokens are formatted correctly. /// @param _buyTokens The buy token details. /// @param _sellToken The sell token details. function verifyTokens(uint64 _buyTokens, uint64 _sellToken) internal pure returns (bool) { return (( uint32(_buyTokens) == uint32(_sellToken >> 32)) && ( uint32(_sellToken) == uint32(_buyTokens >> 32)) && ( uint32(_buyTokens >> 32) <= uint32(_buyTokens)) ); } } /// @notice RenExTokens is a registry of tokens that can be traded on RenEx. contract RenExTokens is Ownable { string public VERSION; // Passed in as a constructor parameter. struct TokenDetails { address addr; uint8 decimals; bool registered; } // Storage mapping(uint32 => TokenDetails) public tokens; mapping(uint32 => bool) private detailsSubmitted; // Events event LogTokenRegistered(uint32 tokenCode, address tokenAddress, uint8 tokenDecimals); event LogTokenDeregistered(uint32 tokenCode); /// @notice The contract constructor. /// /// @param _VERSION A string defining the contract version. constructor(string _VERSION) public { VERSION = _VERSION; } /// @notice Allows the owner to register and the details for a token. /// Once details have been submitted, they cannot be overwritten. /// To re-register the same token with different details (e.g. if the address /// has changed), a different token identifier should be used and the /// previous token identifier should be deregistered. /// If a token is not Ethereum-based, the address will be set to 0x0. /// /// @param _tokenCode A unique 32-bit token identifier. /// @param _tokenAddress The address of the token. /// @param _tokenDecimals The decimals to use for the token. function registerToken(uint32 _tokenCode, address _tokenAddress, uint8 _tokenDecimals) public onlyOwner { require(!tokens[_tokenCode].registered, "already registered"); // If a token is being re-registered, the same details must be provided. if (detailsSubmitted[_tokenCode]) { require(tokens[_tokenCode].addr == _tokenAddress, "different address"); require(tokens[_tokenCode].decimals == _tokenDecimals, "different decimals"); } else { detailsSubmitted[_tokenCode] = true; } tokens[_tokenCode] = TokenDetails({ addr: _tokenAddress, decimals: _tokenDecimals, registered: true }); emit LogTokenRegistered(_tokenCode, _tokenAddress, _tokenDecimals); } /// @notice Sets a token as being deregistered. The details are still stored /// to prevent the token from being re-registered with different details. /// /// @param _tokenCode The unique 32-bit token identifier. function deregisterToken(uint32 _tokenCode) external onlyOwner { require(tokens[_tokenCode].registered, "not registered"); tokens[_tokenCode].registered = false; emit LogTokenDeregistered(_tokenCode); } } /// @notice RenExSettlement implements the Settlement interface. It implements /// the on-chain settlement for the RenEx settlement layer, and the fee payment /// for the RenExAtomic settlement layer. contract RenExSettlement is Ownable { using SafeMath for uint256; string public VERSION; // Passed in as a constructor parameter. // This contract handles the settlements with ID 1 and 2. uint32 constant public RENEX_SETTLEMENT_ID = 1; uint32 constant public RENEX_ATOMIC_SETTLEMENT_ID = 2; // Fees in RenEx are 0.2%. To represent this as integers, it is broken into // a numerator and denominator. uint256 constant public DARKNODE_FEES_NUMERATOR = 2; uint256 constant public DARKNODE_FEES_DENOMINATOR = 1000; // Constants used in the price / volume inputs. int16 constant private PRICE_OFFSET = 12; int16 constant private VOLUME_OFFSET = 12; // Constructor parameters, updatable by the owner Orderbook public orderbookContract; RenExTokens public renExTokensContract; RenExBalances public renExBalancesContract; address public slasherAddress; uint256 public submissionGasPriceLimit; enum OrderStatus {None, Submitted, Settled, Slashed} struct TokenPair { RenExTokens.TokenDetails priorityToken; RenExTokens.TokenDetails secondaryToken; } // A uint256 tuple representing a value and an associated fee struct ValueWithFees { uint256 value; uint256 fees; } // A uint256 tuple representing a fraction struct Fraction { uint256 numerator; uint256 denominator; } // We use left and right because the tokens do not always represent the // priority and secondary tokens. struct SettlementDetails { uint256 leftVolume; uint256 rightVolume; uint256 leftTokenFee; uint256 rightTokenFee; address leftTokenAddress; address rightTokenAddress; } // Events event LogOrderbookUpdated(Orderbook previousOrderbook, Orderbook nextOrderbook); event LogRenExTokensUpdated(RenExTokens previousRenExTokens, RenExTokens nextRenExTokens); event LogRenExBalancesUpdated(RenExBalances previousRenExBalances, RenExBalances nextRenExBalances); event LogSubmissionGasPriceLimitUpdated(uint256 previousSubmissionGasPriceLimit, uint256 nextSubmissionGasPriceLimit); event LogSlasherUpdated(address previousSlasher, address nextSlasher); // Order Storage mapping(bytes32 => SettlementUtils.OrderDetails) public orderDetails; mapping(bytes32 => address) public orderSubmitter; mapping(bytes32 => OrderStatus) public orderStatus; // Match storage (match details are indexed by [buyID][sellID]) mapping(bytes32 => mapping(bytes32 => uint256)) public matchTimestamp; /// @notice Prevents a function from being called with a gas price higher /// than the specified limit. /// /// @param _gasPriceLimit The gas price upper-limit in Wei. modifier withGasPriceLimit(uint256 _gasPriceLimit) { require(tx.gasprice <= _gasPriceLimit, "gas price too high"); _; } /// @notice Restricts a function to only being called by the slasher /// address. modifier onlySlasher() { require(msg.sender == slasherAddress, "unauthorized"); _; } /// @notice The contract constructor. /// /// @param _VERSION A string defining the contract version. /// @param _orderbookContract The address of the Orderbook contract. /// @param _renExBalancesContract The address of the RenExBalances /// contract. /// @param _renExTokensContract The address of the RenExTokens contract. constructor( string _VERSION, Orderbook _orderbookContract, RenExTokens _renExTokensContract, RenExBalances _renExBalancesContract, address _slasherAddress, uint256 _submissionGasPriceLimit ) public { VERSION = _VERSION; orderbookContract = _orderbookContract; renExTokensContract = _renExTokensContract; renExBalancesContract = _renExBalancesContract; slasherAddress = _slasherAddress; submissionGasPriceLimit = _submissionGasPriceLimit; } /// @notice The owner of the contract can update the Orderbook address. /// @param _newOrderbookContract The address of the new Orderbook contract. function updateOrderbook(Orderbook _newOrderbookContract) external onlyOwner { emit LogOrderbookUpdated(orderbookContract, _newOrderbookContract); orderbookContract = _newOrderbookContract; } /// @notice The owner of the contract can update the RenExTokens address. /// @param _newRenExTokensContract The address of the new RenExTokens /// contract. function updateRenExTokens(RenExTokens _newRenExTokensContract) external onlyOwner { emit LogRenExTokensUpdated(renExTokensContract, _newRenExTokensContract); renExTokensContract = _newRenExTokensContract; } /// @notice The owner of the contract can update the RenExBalances address. /// @param _newRenExBalancesContract The address of the new RenExBalances /// contract. function updateRenExBalances(RenExBalances _newRenExBalancesContract) external onlyOwner { emit LogRenExBalancesUpdated(renExBalancesContract, _newRenExBalancesContract); renExBalancesContract = _newRenExBalancesContract; } /// @notice The owner of the contract can update the order submission gas /// price limit. /// @param _newSubmissionGasPriceLimit The new gas price limit. function updateSubmissionGasPriceLimit(uint256 _newSubmissionGasPriceLimit) external onlyOwner { emit LogSubmissionGasPriceLimitUpdated(submissionGasPriceLimit, _newSubmissionGasPriceLimit); submissionGasPriceLimit = _newSubmissionGasPriceLimit; } /// @notice The owner of the contract can update the slasher address. /// @param _newSlasherAddress The new slasher address. function updateSlasher(address _newSlasherAddress) external onlyOwner { emit LogSlasherUpdated(slasherAddress, _newSlasherAddress); slasherAddress = _newSlasherAddress; } /// @notice Stores the details of an order. /// /// @param _prefix The miscellaneous details of the order required for /// calculating the order id. /// @param _settlementID The settlement identifier. /// @param _tokens The encoding of the token pair (buy token is encoded as /// the first 32 bytes and sell token is encoded as the last 32 /// bytes). /// @param _price The price of the order. Interpreted as the cost for 1 /// standard unit of the non-priority token, in 1e12 (i.e. /// PRICE_OFFSET) units of the priority token). /// @param _volume The volume of the order. Interpreted as the maximum /// number of 1e-12 (i.e. VOLUME_OFFSET) units of the non-priority /// token that can be traded by this order. /// @param _minimumVolume The minimum volume the trader is willing to /// accept. Encoded the same as the volume. function submitOrder( bytes _prefix, uint64 _settlementID, uint64 _tokens, uint256 _price, uint256 _volume, uint256 _minimumVolume ) external withGasPriceLimit(submissionGasPriceLimit) { SettlementUtils.OrderDetails memory order = SettlementUtils.OrderDetails({ settlementID: _settlementID, tokens: _tokens, price: _price, volume: _volume, minimumVolume: _minimumVolume }); bytes32 orderID = SettlementUtils.hashOrder(_prefix, order); require(orderStatus[orderID] == OrderStatus.None, "order already submitted"); require(orderbookContract.orderState(orderID) == Orderbook.OrderState.Confirmed, "unconfirmed order"); orderSubmitter[orderID] = msg.sender; orderStatus[orderID] = OrderStatus.Submitted; orderDetails[orderID] = order; } /// @notice Settles two orders that are matched. `submitOrder` must have been /// called for each order before this function is called. /// /// @param _buyID The 32 byte ID of the buy order. /// @param _sellID The 32 byte ID of the sell order. function settle(bytes32 _buyID, bytes32 _sellID) external { require(orderStatus[_buyID] == OrderStatus.Submitted, "invalid buy status"); require(orderStatus[_sellID] == OrderStatus.Submitted, "invalid sell status"); // Check the settlement ID (only have to check for one, since // `verifyMatchDetails` checks that they are the same) require( orderDetails[_buyID].settlementID == RENEX_ATOMIC_SETTLEMENT_ID || orderDetails[_buyID].settlementID == RENEX_SETTLEMENT_ID, "invalid settlement id" ); // Verify that the two order details are compatible. require(SettlementUtils.verifyMatchDetails(orderDetails[_buyID], orderDetails[_sellID]), "incompatible orders"); // Verify that the two orders have been confirmed to one another. require(orderbookContract.orderMatch(_buyID) == _sellID, "unconfirmed orders"); // Retrieve token details. TokenPair memory tokens = getTokenDetails(orderDetails[_buyID].tokens); // Require that the tokens have been registered. require(tokens.priorityToken.registered, "unregistered priority token"); require(tokens.secondaryToken.registered, "unregistered secondary token"); address buyer = orderbookContract.orderTrader(_buyID); address seller = orderbookContract.orderTrader(_sellID); require(buyer != seller, "orders from same trader"); execute(_buyID, _sellID, buyer, seller, tokens); /* solium-disable-next-line security/no-block-members */ matchTimestamp[_buyID][_sellID] = now; // Store that the orders have been settled. orderStatus[_buyID] = OrderStatus.Settled; orderStatus[_sellID] = OrderStatus.Settled; } /// @notice Slashes the bond of a guilty trader. This is called when an /// atomic swap is not executed successfully. /// To open an atomic order, a trader must have a balance equivalent to /// 0.6% of the trade in the Ethereum-based token. 0.2% is always paid in /// darknode fees when the order is matched. If the remaining amount is /// is slashed, it is distributed as follows: /// 1) 0.2% goes to the other trader, covering their fee /// 2) 0.2% goes to the slasher address /// Only one order in a match can be slashed. /// /// @param _guiltyOrderID The 32 byte ID of the order of the guilty trader. function slash(bytes32 _guiltyOrderID) external onlySlasher { require(orderDetails[_guiltyOrderID].settlementID == RENEX_ATOMIC_SETTLEMENT_ID, "slashing non-atomic trade"); bytes32 innocentOrderID = orderbookContract.orderMatch(_guiltyOrderID); require(orderStatus[_guiltyOrderID] == OrderStatus.Settled, "invalid order status"); require(orderStatus[innocentOrderID] == OrderStatus.Settled, "invalid order status"); orderStatus[_guiltyOrderID] = OrderStatus.Slashed; (bytes32 buyID, bytes32 sellID) = isBuyOrder(_guiltyOrderID) ? (_guiltyOrderID, innocentOrderID) : (innocentOrderID, _guiltyOrderID); TokenPair memory tokens = getTokenDetails(orderDetails[buyID].tokens); SettlementDetails memory settlementDetails = calculateAtomicFees(buyID, sellID, tokens); // Transfer the fee amount to the other trader renExBalancesContract.transferBalanceWithFee( orderbookContract.orderTrader(_guiltyOrderID), orderbookContract.orderTrader(innocentOrderID), settlementDetails.leftTokenAddress, settlementDetails.leftTokenFee, 0, 0x0 ); // Transfer the fee amount to the slasher renExBalancesContract.transferBalanceWithFee( orderbookContract.orderTrader(_guiltyOrderID), slasherAddress, settlementDetails.leftTokenAddress, settlementDetails.leftTokenFee, 0, 0x0 ); } /// @notice Retrieves the settlement details of an order. /// For atomic swaps, it returns the full volumes, not the settled fees. /// /// @param _orderID The order to lookup the details of. Can be the ID of a /// buy or a sell order. /// @return [ /// a boolean representing whether or not the order has been settled, /// a boolean representing whether or not the order is a buy /// the 32-byte order ID of the matched order /// the volume of the priority token, /// the volume of the secondary token, /// the fee paid in the priority token, /// the fee paid in the secondary token, /// the token code of the priority token, /// the token code of the secondary token /// ] function getMatchDetails(bytes32 _orderID) external view returns ( bool settled, bool orderIsBuy, bytes32 matchedID, uint256 priorityVolume, uint256 secondaryVolume, uint256 priorityFee, uint256 secondaryFee, uint32 priorityToken, uint32 secondaryToken ) { matchedID = orderbookContract.orderMatch(_orderID); orderIsBuy = isBuyOrder(_orderID); (bytes32 buyID, bytes32 sellID) = orderIsBuy ? (_orderID, matchedID) : (matchedID, _orderID); SettlementDetails memory settlementDetails = calculateSettlementDetails( buyID, sellID, getTokenDetails(orderDetails[buyID].tokens) ); return ( orderStatus[_orderID] == OrderStatus.Settled || orderStatus[_orderID] == OrderStatus.Slashed, orderIsBuy, matchedID, settlementDetails.leftVolume, settlementDetails.rightVolume, settlementDetails.leftTokenFee, settlementDetails.rightTokenFee, uint32(orderDetails[buyID].tokens >> 32), uint32(orderDetails[buyID].tokens) ); } /// @notice Exposes the hashOrder function for computing a hash of an /// order's details. An order hash is used as its ID. See `submitOrder` /// for the parameter descriptions. /// /// @return The 32-byte hash of the order. function hashOrder( bytes _prefix, uint64 _settlementID, uint64 _tokens, uint256 _price, uint256 _volume, uint256 _minimumVolume ) external pure returns (bytes32) { return SettlementUtils.hashOrder(_prefix, SettlementUtils.OrderDetails({ settlementID: _settlementID, tokens: _tokens, price: _price, volume: _volume, minimumVolume: _minimumVolume })); } /// @notice Called by `settle`, executes the settlement for a RenEx order /// or distributes the fees for a RenExAtomic swap. /// /// @param _buyID The 32 byte ID of the buy order. /// @param _sellID The 32 byte ID of the sell order. /// @param _buyer The address of the buy trader. /// @param _seller The address of the sell trader. /// @param _tokens The details of the priority and secondary tokens. function execute( bytes32 _buyID, bytes32 _sellID, address _buyer, address _seller, TokenPair memory _tokens ) private { // Calculate the fees for atomic swaps, and the settlement details // otherwise. SettlementDetails memory settlementDetails = (orderDetails[_buyID].settlementID == RENEX_ATOMIC_SETTLEMENT_ID) ? settlementDetails = calculateAtomicFees(_buyID, _sellID, _tokens) : settlementDetails = calculateSettlementDetails(_buyID, _sellID, _tokens); // Transfer priority token value renExBalancesContract.transferBalanceWithFee( _buyer, _seller, settlementDetails.leftTokenAddress, settlementDetails.leftVolume, settlementDetails.leftTokenFee, orderSubmitter[_buyID] ); // Transfer secondary token value renExBalancesContract.transferBalanceWithFee( _seller, _buyer, settlementDetails.rightTokenAddress, settlementDetails.rightVolume, settlementDetails.rightTokenFee, orderSubmitter[_sellID] ); } /// @notice Calculates the details required to execute two matched orders. /// /// @param _buyID The 32 byte ID of the buy order. /// @param _sellID The 32 byte ID of the sell order. /// @param _tokens The details of the priority and secondary tokens. /// @return A struct containing the settlement details. function calculateSettlementDetails( bytes32 _buyID, bytes32 _sellID, TokenPair memory _tokens ) private view returns (SettlementDetails memory) { // Calculate the mid-price (using numerator and denominator to not loose // precision). Fraction memory midPrice = Fraction(orderDetails[_buyID].price + orderDetails[_sellID].price, 2); // Calculate the lower of the two max volumes of each trader uint256 commonVolume = Math.min256(orderDetails[_buyID].volume, orderDetails[_sellID].volume); uint256 priorityTokenVolume = joinFraction( commonVolume.mul(midPrice.numerator), midPrice.denominator, int16(_tokens.priorityToken.decimals) - PRICE_OFFSET - VOLUME_OFFSET ); uint256 secondaryTokenVolume = joinFraction( commonVolume, 1, int16(_tokens.secondaryToken.decimals) - VOLUME_OFFSET ); // Calculate darknode fees ValueWithFees memory priorityVwF = subtractDarknodeFee(priorityTokenVolume); ValueWithFees memory secondaryVwF = subtractDarknodeFee(secondaryTokenVolume); return SettlementDetails({ leftVolume: priorityVwF.value, rightVolume: secondaryVwF.value, leftTokenFee: priorityVwF.fees, rightTokenFee: secondaryVwF.fees, leftTokenAddress: _tokens.priorityToken.addr, rightTokenAddress: _tokens.secondaryToken.addr }); } /// @notice Calculates the fees to be transferred for an atomic swap. /// /// @param _buyID The 32 byte ID of the buy order. /// @param _sellID The 32 byte ID of the sell order. /// @param _tokens The details of the priority and secondary tokens. /// @return A struct containing the fee details. function calculateAtomicFees( bytes32 _buyID, bytes32 _sellID, TokenPair memory _tokens ) private view returns (SettlementDetails memory) { // Calculate the mid-price (using numerator and denominator to not loose // precision). Fraction memory midPrice = Fraction(orderDetails[_buyID].price + orderDetails[_sellID].price, 2); // Calculate the lower of the two max volumes of each trader uint256 commonVolume = Math.min256(orderDetails[_buyID].volume, orderDetails[_sellID].volume); if (isEthereumBased(_tokens.secondaryToken.addr)) { uint256 secondaryTokenVolume = joinFraction( commonVolume, 1, int16(_tokens.secondaryToken.decimals) - VOLUME_OFFSET ); // Calculate darknode fees ValueWithFees memory secondaryVwF = subtractDarknodeFee(secondaryTokenVolume); return SettlementDetails({ leftVolume: 0, rightVolume: 0, leftTokenFee: secondaryVwF.fees, rightTokenFee: secondaryVwF.fees, leftTokenAddress: _tokens.secondaryToken.addr, rightTokenAddress: _tokens.secondaryToken.addr }); } else if (isEthereumBased(_tokens.priorityToken.addr)) { uint256 priorityTokenVolume = joinFraction( commonVolume.mul(midPrice.numerator), midPrice.denominator, int16(_tokens.priorityToken.decimals) - PRICE_OFFSET - VOLUME_OFFSET ); // Calculate darknode fees ValueWithFees memory priorityVwF = subtractDarknodeFee(priorityTokenVolume); return SettlementDetails({ leftVolume: 0, rightVolume: 0, leftTokenFee: priorityVwF.fees, rightTokenFee: priorityVwF.fees, leftTokenAddress: _tokens.priorityToken.addr, rightTokenAddress: _tokens.priorityToken.addr }); } else { // Currently, at least one token must be Ethereum-based. // This will be implemented in the future. revert("non-eth atomic swaps are not supported"); } } /// @notice Order parity is set by the order tokens are listed. This returns /// whether an order is a buy or a sell. /// @return true if _orderID is a buy order. function isBuyOrder(bytes32 _orderID) private view returns (bool) { uint64 tokens = orderDetails[_orderID].tokens; uint32 firstToken = uint32(tokens >> 32); uint32 secondaryToken = uint32(tokens); return (firstToken < secondaryToken); } /// @return (value - fee, fee) where fee is 0.2% of value function subtractDarknodeFee(uint256 _value) private pure returns (ValueWithFees memory) { uint256 newValue = (_value * (DARKNODE_FEES_DENOMINATOR - DARKNODE_FEES_NUMERATOR)) / DARKNODE_FEES_DENOMINATOR; return ValueWithFees(newValue, _value - newValue); } /// @notice Gets the order details of the priority and secondary token from /// the RenExTokens contract and returns them as a single struct. /// /// @param _tokens The 64-bit combined token identifiers. /// @return A TokenPair struct containing two TokenDetails structs. function getTokenDetails(uint64 _tokens) private view returns (TokenPair memory) { ( address priorityAddress, uint8 priorityDecimals, bool priorityRegistered ) = renExTokensContract.tokens(uint32(_tokens >> 32)); ( address secondaryAddress, uint8 secondaryDecimals, bool secondaryRegistered ) = renExTokensContract.tokens(uint32(_tokens)); return TokenPair({ priorityToken: RenExTokens.TokenDetails(priorityAddress, priorityDecimals, priorityRegistered), secondaryToken: RenExTokens.TokenDetails(secondaryAddress, secondaryDecimals, secondaryRegistered) }); } /// @return true if _tokenAddress is 0x0, representing a token that is not /// on Ethereum function isEthereumBased(address _tokenAddress) private pure returns (bool) { return (_tokenAddress != address(0x0)); } /// @notice Computes (_numerator / _denominator) * 10 ** _scale function joinFraction(uint256 _numerator, uint256 _denominator, int16 _scale) private pure returns (uint256) { if (_scale >= 0) { // Check that (10**_scale) doesn't overflow assert(_scale <= 77); // log10(2**256) = 77.06 return _numerator.mul(10 ** uint256(_scale)) / _denominator; } else { /// @dev If _scale is less than -77, 10**-_scale would overflow. // For now, -_scale > -24 (when a token has 0 decimals and // VOLUME_OFFSET and PRICE_OFFSET are each 12). It is unlikely these // will be increased to add to more than 77. // assert((-_scale) <= 77); // log10(2**256) = 77.06 return (_numerator / _denominator) / 10 ** uint256(-_scale); } } } /// @notice RenExBrokerVerifier implements the BrokerVerifier contract, /// verifying broker signatures for order opening and fund withdrawal. contract RenExBrokerVerifier is Ownable { string public VERSION; // Passed in as a constructor parameter. // Events event LogBalancesContractUpdated(address previousBalancesContract, address nextBalancesContract); event LogBrokerRegistered(address broker); event LogBrokerDeregistered(address broker); // Storage mapping(address => bool) public brokers; mapping(address => uint256) public traderNonces; address public balancesContract; modifier onlyBalancesContract() { require(msg.sender == balancesContract, "not authorized"); _; } /// @notice The contract constructor. /// /// @param _VERSION A string defining the contract version. constructor(string _VERSION) public { VERSION = _VERSION; } /// @notice Allows the owner of the contract to update the address of the /// RenExBalances contract. /// /// @param _balancesContract The address of the new balances contract function updateBalancesContract(address _balancesContract) external onlyOwner { emit LogBalancesContractUpdated(balancesContract, _balancesContract); balancesContract = _balancesContract; } /// @notice Approved an address to sign order-opening and withdrawals. /// @param _broker The address of the broker. function registerBroker(address _broker) external onlyOwner { require(!brokers[_broker], "already registered"); brokers[_broker] = true; emit LogBrokerRegistered(_broker); } /// @notice Reverts the a broker's registration. /// @param _broker The address of the broker. function deregisterBroker(address _broker) external onlyOwner { require(brokers[_broker], "not registered"); brokers[_broker] = false; emit LogBrokerDeregistered(_broker); } /// @notice Verifies a broker's signature for an order opening. /// The data signed by the broker is a prefixed message and the order ID. /// /// @param _trader The trader requesting the withdrawal. /// @param _signature The 65-byte signature from the broker. /// @param _orderID The 32-byte order ID. /// @return True if the signature is valid, false otherwise. function verifyOpenSignature( address _trader, bytes _signature, bytes32 _orderID ) external view returns (bool) { bytes memory data = abi.encodePacked("Republic Protocol: open: ", _trader, _orderID); address signer = Utils.addr(data, _signature); return (brokers[signer] == true); } /// @notice Verifies a broker's signature for a trader withdrawal. /// The data signed by the broker is a prefixed message, the trader address /// and a 256-bit trader nonce, which is incremented every time a valid /// signature is checked. /// /// @param _trader The trader requesting the withdrawal. /// @param _signature 65-byte signature from the broker. /// @return True if the signature is valid, false otherwise. function verifyWithdrawSignature( address _trader, bytes _signature ) external onlyBalancesContract returns (bool) { bytes memory data = abi.encodePacked("Republic Protocol: withdraw: ", _trader, traderNonces[_trader]); address signer = Utils.addr(data, _signature); if (brokers[signer]) { traderNonces[_trader] += 1; return true; } return false; } } /// @notice RenExBalances is responsible for holding RenEx trader funds. contract RenExBalances is Ownable { using SafeMath for uint256; using CompatibleERC20Functions for CompatibleERC20; string public VERSION; // Passed in as a constructor parameter. RenExSettlement public settlementContract; RenExBrokerVerifier public brokerVerifierContract; DarknodeRewardVault public rewardVaultContract; /// @dev Should match the address in the DarknodeRewardVault address constant public ETHEREUM = address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE); // Delay between a trader calling `withdrawSignal` and being able to call // `withdraw` without a broker signature. uint256 constant public SIGNAL_DELAY = 48 hours; // Events event LogBalanceDecreased(address trader, ERC20 token, uint256 value); event LogBalanceIncreased(address trader, ERC20 token, uint256 value); event LogRenExSettlementContractUpdated(address previousRenExSettlementContract, address newRenExSettlementContract); event LogRewardVaultContractUpdated(address previousRewardVaultContract, address newRewardVaultContract); event LogBrokerVerifierContractUpdated(address previousBrokerVerifierContract, address newBrokerVerifierContract); // Storage mapping(address => mapping(address => uint256)) public traderBalances; mapping(address => mapping(address => uint256)) public traderWithdrawalSignals; /// @notice The contract constructor. /// /// @param _VERSION A string defining the contract version. /// @param _rewardVaultContract The address of the RewardVault contract. constructor( string _VERSION, DarknodeRewardVault _rewardVaultContract, RenExBrokerVerifier _brokerVerifierContract ) public { VERSION = _VERSION; rewardVaultContract = _rewardVaultContract; brokerVerifierContract = _brokerVerifierContract; } /// @notice Restricts a function to only being called by the RenExSettlement /// contract. modifier onlyRenExSettlementContract() { require(msg.sender == address(settlementContract), "not authorized"); _; } /// @notice Restricts trader withdrawing to be called if a signature from a /// RenEx broker is provided, or if a certain amount of time has passed /// since a trader has called `signalBackupWithdraw`. /// @dev If the trader is withdrawing after calling `signalBackupWithdraw`, /// this will reset the time to zero, writing to storage. modifier withBrokerSignatureOrSignal(address _token, bytes _signature) { address trader = msg.sender; // If a signature has been provided, verify it - otherwise, verify that // the user has signalled the withdraw if (_signature.length > 0) { require (brokerVerifierContract.verifyWithdrawSignature(trader, _signature), "invalid signature"); } else { require(traderWithdrawalSignals[trader][_token] != 0, "not signalled"); /* solium-disable-next-line security/no-block-members */ require((now - traderWithdrawalSignals[trader][_token]) > SIGNAL_DELAY, "signal time remaining"); traderWithdrawalSignals[trader][_token] = 0; } _; } /// @notice Allows the owner of the contract to update the address of the /// RenExSettlement contract. /// /// @param _newSettlementContract the address of the new settlement contract function updateRenExSettlementContract(RenExSettlement _newSettlementContract) external onlyOwner { emit LogRenExSettlementContractUpdated(settlementContract, _newSettlementContract); settlementContract = _newSettlementContract; } /// @notice Allows the owner of the contract to update the address of the /// DarknodeRewardVault contract. /// /// @param _newRewardVaultContract the address of the new reward vault contract function updateRewardVaultContract(DarknodeRewardVault _newRewardVaultContract) external onlyOwner { emit LogRewardVaultContractUpdated(rewardVaultContract, _newRewardVaultContract); rewardVaultContract = _newRewardVaultContract; } /// @notice Allows the owner of the contract to update the address of the /// RenExBrokerVerifier contract. /// /// @param _newBrokerVerifierContract the address of the new broker verifier contract function updateBrokerVerifierContract(RenExBrokerVerifier _newBrokerVerifierContract) external onlyOwner { emit LogBrokerVerifierContractUpdated(brokerVerifierContract, _newBrokerVerifierContract); brokerVerifierContract = _newBrokerVerifierContract; } /// @notice Transfer a token value from one trader to another, transferring /// a fee to the RewardVault. Can only be called by the RenExSettlement /// contract. /// /// @param _traderFrom The address of the trader to decrement the balance of. /// @param _traderTo The address of the trader to increment the balance of. /// @param _token The token's address. /// @param _value The number of tokens to decrement the balance by (in the /// token's smallest unit). /// @param _fee The fee amount to forward on to the RewardVault. /// @param _feePayee The recipient of the fee. function transferBalanceWithFee(address _traderFrom, address _traderTo, address _token, uint256 _value, uint256 _fee, address _feePayee) external onlyRenExSettlementContract { require(traderBalances[_traderFrom][_token] >= _fee, "insufficient funds for fee"); if (address(_token) == ETHEREUM) { rewardVaultContract.deposit.value(_fee)(_feePayee, ERC20(_token), _fee); } else { CompatibleERC20(_token).safeApprove(rewardVaultContract, _fee); rewardVaultContract.deposit(_feePayee, ERC20(_token), _fee); } privateDecrementBalance(_traderFrom, ERC20(_token), _value + _fee); if (_value > 0) { privateIncrementBalance(_traderTo, ERC20(_token), _value); } } /// @notice Deposits ETH or an ERC20 token into the contract. /// /// @param _token The token's address (must be a registered token). /// @param _value The amount to deposit in the token's smallest unit. function deposit(ERC20 _token, uint256 _value) external payable { address trader = msg.sender; uint256 receivedValue = _value; if (address(_token) == ETHEREUM) { require(msg.value == _value, "mismatched value parameter and tx value"); } else { require(msg.value == 0, "unexpected ether transfer"); receivedValue = CompatibleERC20(_token).safeTransferFromWithFees(trader, this, _value); } privateIncrementBalance(trader, _token, receivedValue); } /// @notice Withdraws ETH or an ERC20 token from the contract. A broker /// signature is required to guarantee that the trader has a sufficient /// balance after accounting for open orders. As a trustless backup, /// traders can withdraw 48 hours after calling `signalBackupWithdraw`. /// /// @param _token The token's address. /// @param _value The amount to withdraw in the token's smallest unit. /// @param _signature The broker signature function withdraw(ERC20 _token, uint256 _value, bytes _signature) external withBrokerSignatureOrSignal(_token, _signature) { address trader = msg.sender; privateDecrementBalance(trader, _token, _value); if (address(_token) == ETHEREUM) { trader.transfer(_value); } else { CompatibleERC20(_token).safeTransfer(trader, _value); } } /// @notice A trader can withdraw without needing a broker signature if they /// first call `signalBackupWithdraw` for the token they want to withdraw. /// The trader can only withdraw the particular token once for each call to /// this function. Traders can signal the intent to withdraw multiple /// tokens. /// Once this function is called, brokers will not sign order-opens for the /// trader until the trader has withdrawn, guaranteeing that they won't have /// orders open for the particular token. function signalBackupWithdraw(address _token) external { /* solium-disable-next-line security/no-block-members */ traderWithdrawalSignals[msg.sender][_token] = now; } function privateIncrementBalance(address _trader, ERC20 _token, uint256 _value) private { traderBalances[_trader][_token] = traderBalances[_trader][_token].add(_value); emit LogBalanceIncreased(_trader, _token, _value); } function privateDecrementBalance(address _trader, ERC20 _token, uint256 _value) private { require(traderBalances[_trader][_token] >= _value, "insufficient funds"); traderBalances[_trader][_token] = traderBalances[_trader][_token].sub(_value); emit LogBalanceDecreased(_trader, _token, _value); } }
Block number of the most recent state change
uint256 blockNumber;
1,044,475
[ 1, 1768, 1300, 434, 326, 4486, 8399, 919, 2549, 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, 1203, 1854, 31, 282, 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 ]
// SPDX-License-Identifier: AGPL-3.0-only /* Bounty.sol - SKALE Manager Copyright (C) 2020-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "./delegation/DelegationController.sol"; import "./delegation/PartialDifferences.sol"; import "./delegation/TimeHelpers.sol"; import "./delegation/ValidatorService.sol"; import "./ConstantsHolder.sol"; import "./Nodes.sol"; import "./Permissions.sol"; contract BountyV2 is Permissions { using PartialDifferences for PartialDifferences.Value; using PartialDifferences for PartialDifferences.Sequence; struct BountyHistory { uint month; uint bountyPaid; } uint public constant YEAR1_BOUNTY = 3850e5 * 1e18; uint public constant YEAR2_BOUNTY = 3465e5 * 1e18; uint public constant YEAR3_BOUNTY = 3080e5 * 1e18; uint public constant YEAR4_BOUNTY = 2695e5 * 1e18; uint public constant YEAR5_BOUNTY = 2310e5 * 1e18; uint public constant YEAR6_BOUNTY = 1925e5 * 1e18; uint public constant EPOCHS_PER_YEAR = 12; uint public constant SECONDS_PER_DAY = 24 * 60 * 60; uint public constant BOUNTY_WINDOW_SECONDS = 3 * SECONDS_PER_DAY; uint private _nextEpoch; uint private _epochPool; uint private _bountyWasPaidInCurrentEpoch; bool public bountyReduction; uint public nodeCreationWindowSeconds; PartialDifferences.Value private _effectiveDelegatedSum; // validatorId amount of nodes mapping (uint => uint) public nodesByValidator; // deprecated // validatorId => BountyHistory mapping (uint => BountyHistory) private _bountyHistory; bytes32 public constant BOUNTY_REDUCTION_MANAGER_ROLE = keccak256("BOUNTY_REDUCTION_MANAGER_ROLE"); modifier onlyBountyReductionManager() { require(hasRole(BOUNTY_REDUCTION_MANAGER_ROLE, msg.sender), "BOUNTY_REDUCTION_MANAGER_ROLE is required"); _; } function calculateBounty(uint nodeIndex) external allow("SkaleManager") returns (uint) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); Nodes nodes = Nodes(contractManager.getContract("Nodes")); TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers")); DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController") ); require( _getNextRewardTimestamp(nodeIndex, nodes, timeHelpers) <= now, "Transaction is sent too early" ); uint validatorId = nodes.getValidatorId(nodeIndex); if (nodesByValidator[validatorId] > 0) { delete nodesByValidator[validatorId]; } uint currentMonth = timeHelpers.getCurrentMonth(); _refillEpochPool(currentMonth, timeHelpers, constantsHolder); _prepareBountyHistory(validatorId, currentMonth); uint bounty = _calculateMaximumBountyAmount( _epochPool, _effectiveDelegatedSum.getAndUpdateValue(currentMonth), _bountyWasPaidInCurrentEpoch, nodeIndex, _bountyHistory[validatorId].bountyPaid, delegationController.getAndUpdateEffectiveDelegatedToValidator(validatorId, currentMonth), delegationController.getAndUpdateDelegatedToValidatorNow(validatorId), constantsHolder, nodes ); _bountyHistory[validatorId].bountyPaid = _bountyHistory[validatorId].bountyPaid.add(bounty); bounty = _reduceBounty( bounty, nodeIndex, nodes, constantsHolder ); _epochPool = _epochPool.sub(bounty); _bountyWasPaidInCurrentEpoch = _bountyWasPaidInCurrentEpoch.add(bounty); return bounty; } function enableBountyReduction() external onlyBountyReductionManager { bountyReduction = true; } function disableBountyReduction() external onlyBountyReductionManager { bountyReduction = false; } function setNodeCreationWindowSeconds(uint window) external allow("Nodes") { nodeCreationWindowSeconds = window; } function handleDelegationAdd( uint amount, uint month ) external allow("DelegationController") { _effectiveDelegatedSum.addToValue(amount, month); } function handleDelegationRemoving( uint amount, uint month ) external allow("DelegationController") { _effectiveDelegatedSum.subtractFromValue(amount, month); } function estimateBounty(uint nodeIndex) external view returns (uint) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); Nodes nodes = Nodes(contractManager.getContract("Nodes")); TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers")); DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController") ); uint currentMonth = timeHelpers.getCurrentMonth(); uint validatorId = nodes.getValidatorId(nodeIndex); uint stagePoolSize; (stagePoolSize, ) = _getEpochPool(currentMonth, timeHelpers, constantsHolder); return _calculateMaximumBountyAmount( stagePoolSize, _effectiveDelegatedSum.getValue(currentMonth), _nextEpoch == currentMonth.add(1) ? _bountyWasPaidInCurrentEpoch : 0, nodeIndex, _getBountyPaid(validatorId, currentMonth), delegationController.getEffectiveDelegatedToValidator(validatorId, currentMonth), delegationController.getDelegatedToValidator(validatorId, currentMonth), constantsHolder, nodes ); } function getNextRewardTimestamp(uint nodeIndex) external view returns (uint) { return _getNextRewardTimestamp( nodeIndex, Nodes(contractManager.getContract("Nodes")), TimeHelpers(contractManager.getContract("TimeHelpers")) ); } function getEffectiveDelegatedSum() external view returns (uint[] memory) { return _effectiveDelegatedSum.getValues(); } function initialize(address contractManagerAddress) public override initializer { Permissions.initialize(contractManagerAddress); _nextEpoch = 0; _epochPool = 0; _bountyWasPaidInCurrentEpoch = 0; bountyReduction = false; nodeCreationWindowSeconds = 3 * SECONDS_PER_DAY; } // private function _calculateMaximumBountyAmount( uint epochPoolSize, uint effectiveDelegatedSum, uint bountyWasPaidInCurrentEpoch, uint nodeIndex, uint bountyPaidToTheValidator, uint effectiveDelegated, uint delegated, ConstantsHolder constantsHolder, Nodes nodes ) private view returns (uint) { if (nodes.isNodeLeft(nodeIndex)) { return 0; } if (now < constantsHolder.launchTimestamp()) { // network is not launched // bounty is turned off return 0; } if (effectiveDelegatedSum == 0) { // no delegations in the system return 0; } if (constantsHolder.msr() == 0) { return 0; } uint bounty = _calculateBountyShare( epochPoolSize.add(bountyWasPaidInCurrentEpoch), effectiveDelegated, effectiveDelegatedSum, delegated.div(constantsHolder.msr()), bountyPaidToTheValidator ); return bounty; } function _calculateBountyShare( uint monthBounty, uint effectiveDelegated, uint effectiveDelegatedSum, uint maxNodesAmount, uint paidToValidator ) private pure returns (uint) { if (maxNodesAmount > 0) { uint totalBountyShare = monthBounty .mul(effectiveDelegated) .div(effectiveDelegatedSum); return _min( totalBountyShare.div(maxNodesAmount), totalBountyShare.sub(paidToValidator) ); } else { return 0; } } function _getFirstEpoch(TimeHelpers timeHelpers, ConstantsHolder constantsHolder) private view returns (uint) { return timeHelpers.timestampToMonth(constantsHolder.launchTimestamp()); } function _getEpochPool( uint currentMonth, TimeHelpers timeHelpers, ConstantsHolder constantsHolder ) private view returns (uint epochPool, uint nextEpoch) { epochPool = _epochPool; for (nextEpoch = _nextEpoch; nextEpoch <= currentMonth; ++nextEpoch) { epochPool = epochPool.add(_getEpochReward(nextEpoch, timeHelpers, constantsHolder)); } } function _refillEpochPool(uint currentMonth, TimeHelpers timeHelpers, ConstantsHolder constantsHolder) private { uint epochPool; uint nextEpoch; (epochPool, nextEpoch) = _getEpochPool(currentMonth, timeHelpers, constantsHolder); if (_nextEpoch < nextEpoch) { (_epochPool, _nextEpoch) = (epochPool, nextEpoch); _bountyWasPaidInCurrentEpoch = 0; } } function _getEpochReward( uint epoch, TimeHelpers timeHelpers, ConstantsHolder constantsHolder ) private view returns (uint) { uint firstEpoch = _getFirstEpoch(timeHelpers, constantsHolder); if (epoch < firstEpoch) { return 0; } uint epochIndex = epoch.sub(firstEpoch); uint year = epochIndex.div(EPOCHS_PER_YEAR); if (year >= 6) { uint power = year.sub(6).div(3).add(1); if (power < 256) { return YEAR6_BOUNTY.div(2 ** power).div(EPOCHS_PER_YEAR); } else { return 0; } } else { uint[6] memory customBounties = [ YEAR1_BOUNTY, YEAR2_BOUNTY, YEAR3_BOUNTY, YEAR4_BOUNTY, YEAR5_BOUNTY, YEAR6_BOUNTY ]; return customBounties[year].div(EPOCHS_PER_YEAR); } } function _reduceBounty( uint bounty, uint nodeIndex, Nodes nodes, ConstantsHolder constants ) private returns (uint reducedBounty) { if (!bountyReduction) { return bounty; } reducedBounty = bounty; if (!nodes.checkPossibilityToMaintainNode(nodes.getValidatorId(nodeIndex), nodeIndex)) { reducedBounty = reducedBounty.div(constants.MSR_REDUCING_COEFFICIENT()); } } function _prepareBountyHistory(uint validatorId, uint currentMonth) private { if (_bountyHistory[validatorId].month < currentMonth) { _bountyHistory[validatorId].month = currentMonth; delete _bountyHistory[validatorId].bountyPaid; } } function _getBountyPaid(uint validatorId, uint month) private view returns (uint) { require(_bountyHistory[validatorId].month <= month, "Can't get bounty paid"); if (_bountyHistory[validatorId].month == month) { return _bountyHistory[validatorId].bountyPaid; } else { return 0; } } function _getNextRewardTimestamp(uint nodeIndex, Nodes nodes, TimeHelpers timeHelpers) private view returns (uint) { uint lastRewardTimestamp = nodes.getNodeLastRewardDate(nodeIndex); uint lastRewardMonth = timeHelpers.timestampToMonth(lastRewardTimestamp); uint lastRewardMonthStart = timeHelpers.monthToTimestamp(lastRewardMonth); uint timePassedAfterMonthStart = lastRewardTimestamp.sub(lastRewardMonthStart); uint currentMonth = timeHelpers.getCurrentMonth(); assert(lastRewardMonth <= currentMonth); if (lastRewardMonth == currentMonth) { uint nextMonthStart = timeHelpers.monthToTimestamp(currentMonth.add(1)); uint nextMonthFinish = timeHelpers.monthToTimestamp(lastRewardMonth.add(2)); if (lastRewardTimestamp < lastRewardMonthStart.add(nodeCreationWindowSeconds)) { return nextMonthStart.sub(BOUNTY_WINDOW_SECONDS); } else { return _min(nextMonthStart.add(timePassedAfterMonthStart), nextMonthFinish.sub(BOUNTY_WINDOW_SECONDS)); } } else if (lastRewardMonth.add(1) == currentMonth) { uint currentMonthStart = timeHelpers.monthToTimestamp(currentMonth); uint currentMonthFinish = timeHelpers.monthToTimestamp(currentMonth.add(1)); return _min( currentMonthStart.add(_max(timePassedAfterMonthStart, nodeCreationWindowSeconds)), currentMonthFinish.sub(BOUNTY_WINDOW_SECONDS) ); } else { uint currentMonthStart = timeHelpers.monthToTimestamp(currentMonth); return currentMonthStart.add(nodeCreationWindowSeconds); } } function _min(uint a, uint b) private pure returns (uint) { if (a < b) { return a; } else { return b; } } function _max(uint a, uint b) private pure returns (uint) { if (a < b) { return b; } else { return a; } } } // SPDX-License-Identifier: AGPL-3.0-only /* DelegationController.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC777/IERC777.sol"; import "../BountyV2.sol"; import "../Nodes.sol"; import "../Permissions.sol"; import "../utils/FractionUtils.sol"; import "../utils/MathUtils.sol"; import "./DelegationPeriodManager.sol"; import "./PartialDifferences.sol"; import "./Punisher.sol"; import "./TokenState.sol"; import "./ValidatorService.sol"; /** * @title Delegation Controller * @dev This contract performs all delegation functions including delegation * requests, and undelegation, etc. * * Delegators and validators may both perform delegations. Validators who perform * delegations to themselves are effectively self-delegating or self-bonding. * * IMPORTANT: Undelegation may be requested at any time, but undelegation is only * performed at the completion of the current delegation period. * * Delegated tokens may be in one of several states: * * - PROPOSED: token holder proposes tokens to delegate to a validator. * - ACCEPTED: token delegations are accepted by a validator and are locked-by-delegation. * - CANCELED: token holder cancels delegation proposal. Only allowed before the proposal is accepted by the validator. * - REJECTED: token proposal expires at the UTC start of the next month. * - DELEGATED: accepted delegations are delegated at the UTC start of the month. * - UNDELEGATION_REQUESTED: token holder requests delegations to undelegate from the validator. * - COMPLETED: undelegation request is completed at the end of the delegation period. */ contract DelegationController is Permissions, ILocker { using MathUtils for uint; using PartialDifferences for PartialDifferences.Sequence; using PartialDifferences for PartialDifferences.Value; using FractionUtils for FractionUtils.Fraction; uint public constant UNDELEGATION_PROHIBITION_WINDOW_SECONDS = 3 * 24 * 60 * 60; enum State { PROPOSED, ACCEPTED, CANCELED, REJECTED, DELEGATED, UNDELEGATION_REQUESTED, COMPLETED } struct Delegation { address holder; // address of token owner uint validatorId; uint amount; uint delegationPeriod; uint created; // time of delegation creation uint started; // month when a delegation becomes active uint finished; // first month after a delegation ends string info; } struct SlashingLogEvent { FractionUtils.Fraction reducingCoefficient; uint nextMonth; } struct SlashingLog { // month => slashing event mapping (uint => SlashingLogEvent) slashes; uint firstMonth; uint lastMonth; } struct DelegationExtras { uint lastSlashingMonthBeforeDelegation; } struct SlashingEvent { FractionUtils.Fraction reducingCoefficient; uint validatorId; uint month; } struct SlashingSignal { address holder; uint penalty; } struct LockedInPending { uint amount; uint month; } struct FirstDelegationMonth { // month uint value; //validatorId => month mapping (uint => uint) byValidator; } struct ValidatorsStatistics { // number of validators uint number; //validatorId => bool - is Delegated or not mapping (uint => uint) delegated; } /** * @dev Emitted when a delegation is proposed to a validator. */ event DelegationProposed( uint delegationId ); /** * @dev Emitted when a delegation is accepted by a validator. */ event DelegationAccepted( uint delegationId ); /** * @dev Emitted when a delegation is cancelled by the delegator. */ event DelegationRequestCanceledByUser( uint delegationId ); /** * @dev Emitted when a delegation is requested to undelegate. */ event UndelegationRequested( uint delegationId ); /// @dev delegations will never be deleted to index in this array may be used like delegation id Delegation[] public delegations; // validatorId => delegationId[] mapping (uint => uint[]) public delegationsByValidator; // holder => delegationId[] mapping (address => uint[]) public delegationsByHolder; // delegationId => extras mapping(uint => DelegationExtras) private _delegationExtras; // validatorId => sequence mapping (uint => PartialDifferences.Value) private _delegatedToValidator; // validatorId => sequence mapping (uint => PartialDifferences.Sequence) private _effectiveDelegatedToValidator; // validatorId => slashing log mapping (uint => SlashingLog) private _slashesOfValidator; // holder => sequence mapping (address => PartialDifferences.Value) private _delegatedByHolder; // holder => validatorId => sequence mapping (address => mapping (uint => PartialDifferences.Value)) private _delegatedByHolderToValidator; // holder => validatorId => sequence mapping (address => mapping (uint => PartialDifferences.Sequence)) private _effectiveDelegatedByHolderToValidator; SlashingEvent[] private _slashes; // holder => index in _slashes; mapping (address => uint) private _firstUnprocessedSlashByHolder; // holder => validatorId => month mapping (address => FirstDelegationMonth) private _firstDelegationMonth; // holder => locked in pending mapping (address => LockedInPending) private _lockedInPendingDelegations; mapping (address => ValidatorsStatistics) private _numberOfValidatorsPerDelegator; /** * @dev Modifier to make a function callable only if delegation exists. */ modifier checkDelegationExists(uint delegationId) { require(delegationId < delegations.length, "Delegation does not exist"); _; } /** * @dev Update and return a validator's delegations. */ function getAndUpdateDelegatedToValidatorNow(uint validatorId) external returns (uint) { return _getAndUpdateDelegatedToValidator(validatorId, _getCurrentMonth()); } /** * @dev Update and return the amount delegated. */ function getAndUpdateDelegatedAmount(address holder) external returns (uint) { return _getAndUpdateDelegatedByHolder(holder); } /** * @dev Update and return the effective amount delegated (minus slash) for * the given month. */ function getAndUpdateEffectiveDelegatedByHolderToValidator(address holder, uint validatorId, uint month) external allow("Distributor") returns (uint effectiveDelegated) { SlashingSignal[] memory slashingSignals = _processAllSlashesWithoutSignals(holder); effectiveDelegated = _effectiveDelegatedByHolderToValidator[holder][validatorId] .getAndUpdateValueInSequence(month); _sendSlashingSignals(slashingSignals); } /** * @dev Allows a token holder to create a delegation proposal of an `amount` * and `delegationPeriod` to a `validatorId`. Delegation must be accepted * by the validator before the UTC start of the month, otherwise the * delegation will be rejected. * * The token holder may add additional information in each proposal. * * Emits a {DelegationProposed} event. * * Requirements: * * - Holder must have sufficient delegatable tokens. * - Delegation must be above the validator's minimum delegation amount. * - Delegation period must be allowed. * - Validator must be authorized if trusted list is enabled. * - Validator must be accepting new delegation requests. */ function delegate( uint validatorId, uint amount, uint delegationPeriod, string calldata info ) external { require( _getDelegationPeriodManager().isDelegationPeriodAllowed(delegationPeriod), "This delegation period is not allowed"); _getValidatorService().checkValidatorCanReceiveDelegation(validatorId, amount); _checkIfDelegationIsAllowed(msg.sender, validatorId); SlashingSignal[] memory slashingSignals = _processAllSlashesWithoutSignals(msg.sender); uint delegationId = _addDelegation( msg.sender, validatorId, amount, delegationPeriod, info); // check that there is enough money uint holderBalance = IERC777(contractManager.getSkaleToken()).balanceOf(msg.sender); uint forbiddenForDelegation = TokenState(contractManager.getTokenState()) .getAndUpdateForbiddenForDelegationAmount(msg.sender); require(holderBalance >= forbiddenForDelegation, "Token holder does not have enough tokens to delegate"); emit DelegationProposed(delegationId); _sendSlashingSignals(slashingSignals); } /** * @dev See {ILocker-getAndUpdateLockedAmount}. */ function getAndUpdateLockedAmount(address wallet) external override returns (uint) { return _getAndUpdateLockedAmount(wallet); } /** * @dev See {ILocker-getAndUpdateForbiddenForDelegationAmount}. */ function getAndUpdateForbiddenForDelegationAmount(address wallet) external override returns (uint) { return _getAndUpdateLockedAmount(wallet); } /** * @dev Allows token holder to cancel a delegation proposal. * * Emits a {DelegationRequestCanceledByUser} event. * * Requirements: * * - `msg.sender` must be the token holder of the delegation proposal. * - Delegation state must be PROPOSED. */ function cancelPendingDelegation(uint delegationId) external checkDelegationExists(delegationId) { require(msg.sender == delegations[delegationId].holder, "Only token holders can cancel delegation request"); require(getState(delegationId) == State.PROPOSED, "Token holders are only able to cancel PROPOSED delegations"); delegations[delegationId].finished = _getCurrentMonth(); _subtractFromLockedInPendingDelegations(delegations[delegationId].holder, delegations[delegationId].amount); emit DelegationRequestCanceledByUser(delegationId); } /** * @dev Allows a validator to accept a proposed delegation. * Successful acceptance of delegations transition the tokens from a * PROPOSED state to ACCEPTED, and tokens are locked for the remainder of the * delegation period. * * Emits a {DelegationAccepted} event. * * Requirements: * * - Validator must be recipient of proposal. * - Delegation state must be PROPOSED. */ function acceptPendingDelegation(uint delegationId) external checkDelegationExists(delegationId) { require( _getValidatorService().checkValidatorAddressToId(msg.sender, delegations[delegationId].validatorId), "No permissions to accept request"); _accept(delegationId); } /** * @dev Allows delegator to undelegate a specific delegation. * * Emits UndelegationRequested event. * * Requirements: * * - `msg.sender` must be the delegator. * - Delegation state must be DELEGATED. */ function requestUndelegation(uint delegationId) external checkDelegationExists(delegationId) { require(getState(delegationId) == State.DELEGATED, "Cannot request undelegation"); ValidatorService validatorService = _getValidatorService(); require( delegations[delegationId].holder == msg.sender || (validatorService.validatorAddressExists(msg.sender) && delegations[delegationId].validatorId == validatorService.getValidatorId(msg.sender)), "Permission denied to request undelegation"); _removeValidatorFromValidatorsPerDelegators( delegations[delegationId].holder, delegations[delegationId].validatorId); processAllSlashes(msg.sender); delegations[delegationId].finished = _calculateDelegationEndMonth(delegationId); require( now.add(UNDELEGATION_PROHIBITION_WINDOW_SECONDS) < _getTimeHelpers().monthToTimestamp(delegations[delegationId].finished), "Undelegation requests must be sent 3 days before the end of delegation period" ); _subtractFromAllStatistics(delegationId); emit UndelegationRequested(delegationId); } /** * @dev Allows Punisher contract to slash an `amount` of stake from * a validator. This slashes an amount of delegations of the validator, * which reduces the amount that the validator has staked. This consequence * may force the SKALE Manager to reduce the number of nodes a validator is * operating so the validator can meet the Minimum Staking Requirement. * * Emits a {SlashingEvent}. * * See {Punisher}. */ function confiscate(uint validatorId, uint amount) external allow("Punisher") { uint currentMonth = _getCurrentMonth(); FractionUtils.Fraction memory coefficient = _delegatedToValidator[validatorId].reduceValue(amount, currentMonth); uint initialEffectiveDelegated = _effectiveDelegatedToValidator[validatorId].getAndUpdateValueInSequence(currentMonth); uint[] memory initialSubtractions = new uint[](0); if (currentMonth < _effectiveDelegatedToValidator[validatorId].lastChangedMonth) { initialSubtractions = new uint[]( _effectiveDelegatedToValidator[validatorId].lastChangedMonth.sub(currentMonth) ); for (uint i = 0; i < initialSubtractions.length; ++i) { initialSubtractions[i] = _effectiveDelegatedToValidator[validatorId] .subtractDiff[currentMonth.add(i).add(1)]; } } _effectiveDelegatedToValidator[validatorId].reduceSequence(coefficient, currentMonth); _putToSlashingLog(_slashesOfValidator[validatorId], coefficient, currentMonth); _slashes.push(SlashingEvent({reducingCoefficient: coefficient, validatorId: validatorId, month: currentMonth})); BountyV2 bounty = _getBounty(); bounty.handleDelegationRemoving( initialEffectiveDelegated.sub( _effectiveDelegatedToValidator[validatorId].getAndUpdateValueInSequence(currentMonth) ), currentMonth ); for (uint i = 0; i < initialSubtractions.length; ++i) { bounty.handleDelegationAdd( initialSubtractions[i].sub( _effectiveDelegatedToValidator[validatorId].subtractDiff[currentMonth.add(i).add(1)] ), currentMonth.add(i).add(1) ); } } /** * @dev Allows Distributor contract to return and update the effective * amount delegated (minus slash) to a validator for a given month. */ function getAndUpdateEffectiveDelegatedToValidator(uint validatorId, uint month) external allowTwo("Bounty", "Distributor") returns (uint) { return _effectiveDelegatedToValidator[validatorId].getAndUpdateValueInSequence(month); } /** * @dev Return and update the amount delegated to a validator for the * current month. */ function getAndUpdateDelegatedByHolderToValidatorNow(address holder, uint validatorId) external returns (uint) { return _getAndUpdateDelegatedByHolderToValidator(holder, validatorId, _getCurrentMonth()); } function getEffectiveDelegatedValuesByValidator(uint validatorId) external view returns (uint[] memory) { return _effectiveDelegatedToValidator[validatorId].getValuesInSequence(); } function getEffectiveDelegatedToValidator(uint validatorId, uint month) external view returns (uint) { return _effectiveDelegatedToValidator[validatorId].getValueInSequence(month); } function getDelegatedToValidator(uint validatorId, uint month) external view returns (uint) { return _delegatedToValidator[validatorId].getValue(month); } /** * @dev Return Delegation struct. */ function getDelegation(uint delegationId) external view checkDelegationExists(delegationId) returns (Delegation memory) { return delegations[delegationId]; } /** * @dev Returns the first delegation month. */ function getFirstDelegationMonth(address holder, uint validatorId) external view returns(uint) { return _firstDelegationMonth[holder].byValidator[validatorId]; } /** * @dev Returns a validator's total number of delegations. */ function getDelegationsByValidatorLength(uint validatorId) external view returns (uint) { return delegationsByValidator[validatorId].length; } /** * @dev Returns a holder's total number of delegations. */ function getDelegationsByHolderLength(address holder) external view returns (uint) { return delegationsByHolder[holder].length; } function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); } /** * @dev Process slashes up to the given limit. */ function processSlashes(address holder, uint limit) public { _sendSlashingSignals(_processSlashesWithoutSignals(holder, limit)); } /** * @dev Process all slashes. */ function processAllSlashes(address holder) public { processSlashes(holder, 0); } /** * @dev Returns the token state of a given delegation. */ function getState(uint delegationId) public view checkDelegationExists(delegationId) returns (State state) { if (delegations[delegationId].started == 0) { if (delegations[delegationId].finished == 0) { if (_getCurrentMonth() == _getTimeHelpers().timestampToMonth(delegations[delegationId].created)) { return State.PROPOSED; } else { return State.REJECTED; } } else { return State.CANCELED; } } else { if (_getCurrentMonth() < delegations[delegationId].started) { return State.ACCEPTED; } else { if (delegations[delegationId].finished == 0) { return State.DELEGATED; } else { if (_getCurrentMonth() < delegations[delegationId].finished) { return State.UNDELEGATION_REQUESTED; } else { return State.COMPLETED; } } } } } /** * @dev Returns the amount of tokens in PENDING delegation state. */ function getLockedInPendingDelegations(address holder) public view returns (uint) { uint currentMonth = _getCurrentMonth(); if (_lockedInPendingDelegations[holder].month < currentMonth) { return 0; } else { return _lockedInPendingDelegations[holder].amount; } } /** * @dev Checks whether there are any unprocessed slashes. */ function hasUnprocessedSlashes(address holder) public view returns (bool) { return _everDelegated(holder) && _firstUnprocessedSlashByHolder[holder] < _slashes.length; } // private /** * @dev Allows Nodes contract to get and update the amount delegated * to validator for a given month. */ function _getAndUpdateDelegatedToValidator(uint validatorId, uint month) private returns (uint) { return _delegatedToValidator[validatorId].getAndUpdateValue(month); } /** * @dev Adds a new delegation proposal. */ function _addDelegation( address holder, uint validatorId, uint amount, uint delegationPeriod, string memory info ) private returns (uint delegationId) { delegationId = delegations.length; delegations.push(Delegation( holder, validatorId, amount, delegationPeriod, now, 0, 0, info )); delegationsByValidator[validatorId].push(delegationId); delegationsByHolder[holder].push(delegationId); _addToLockedInPendingDelegations(delegations[delegationId].holder, delegations[delegationId].amount); } /** * @dev Returns the month when a delegation ends. */ function _calculateDelegationEndMonth(uint delegationId) private view returns (uint) { uint currentMonth = _getCurrentMonth(); uint started = delegations[delegationId].started; if (currentMonth < started) { return started.add(delegations[delegationId].delegationPeriod); } else { uint completedPeriods = currentMonth.sub(started).div(delegations[delegationId].delegationPeriod); return started.add(completedPeriods.add(1).mul(delegations[delegationId].delegationPeriod)); } } function _addToDelegatedToValidator(uint validatorId, uint amount, uint month) private { _delegatedToValidator[validatorId].addToValue(amount, month); } function _addToEffectiveDelegatedToValidator(uint validatorId, uint effectiveAmount, uint month) private { _effectiveDelegatedToValidator[validatorId].addToSequence(effectiveAmount, month); } function _addToDelegatedByHolder(address holder, uint amount, uint month) private { _delegatedByHolder[holder].addToValue(amount, month); } function _addToDelegatedByHolderToValidator( address holder, uint validatorId, uint amount, uint month) private { _delegatedByHolderToValidator[holder][validatorId].addToValue(amount, month); } function _addValidatorToValidatorsPerDelegators(address holder, uint validatorId) private { if (_numberOfValidatorsPerDelegator[holder].delegated[validatorId] == 0) { _numberOfValidatorsPerDelegator[holder].number = _numberOfValidatorsPerDelegator[holder].number.add(1); } _numberOfValidatorsPerDelegator[holder]. delegated[validatorId] = _numberOfValidatorsPerDelegator[holder].delegated[validatorId].add(1); } function _removeFromDelegatedByHolder(address holder, uint amount, uint month) private { _delegatedByHolder[holder].subtractFromValue(amount, month); } function _removeFromDelegatedByHolderToValidator( address holder, uint validatorId, uint amount, uint month) private { _delegatedByHolderToValidator[holder][validatorId].subtractFromValue(amount, month); } function _removeValidatorFromValidatorsPerDelegators(address holder, uint validatorId) private { if (_numberOfValidatorsPerDelegator[holder].delegated[validatorId] == 1) { _numberOfValidatorsPerDelegator[holder].number = _numberOfValidatorsPerDelegator[holder].number.sub(1); } _numberOfValidatorsPerDelegator[holder]. delegated[validatorId] = _numberOfValidatorsPerDelegator[holder].delegated[validatorId].sub(1); } function _addToEffectiveDelegatedByHolderToValidator( address holder, uint validatorId, uint effectiveAmount, uint month) private { _effectiveDelegatedByHolderToValidator[holder][validatorId].addToSequence(effectiveAmount, month); } function _removeFromEffectiveDelegatedByHolderToValidator( address holder, uint validatorId, uint effectiveAmount, uint month) private { _effectiveDelegatedByHolderToValidator[holder][validatorId].subtractFromSequence(effectiveAmount, month); } function _getAndUpdateDelegatedByHolder(address holder) private returns (uint) { uint currentMonth = _getCurrentMonth(); processAllSlashes(holder); return _delegatedByHolder[holder].getAndUpdateValue(currentMonth); } function _getAndUpdateDelegatedByHolderToValidator( address holder, uint validatorId, uint month) private returns (uint) { return _delegatedByHolderToValidator[holder][validatorId].getAndUpdateValue(month); } function _addToLockedInPendingDelegations(address holder, uint amount) private returns (uint) { uint currentMonth = _getCurrentMonth(); if (_lockedInPendingDelegations[holder].month < currentMonth) { _lockedInPendingDelegations[holder].amount = amount; _lockedInPendingDelegations[holder].month = currentMonth; } else { assert(_lockedInPendingDelegations[holder].month == currentMonth); _lockedInPendingDelegations[holder].amount = _lockedInPendingDelegations[holder].amount.add(amount); } } function _subtractFromLockedInPendingDelegations(address holder, uint amount) private returns (uint) { uint currentMonth = _getCurrentMonth(); assert(_lockedInPendingDelegations[holder].month == currentMonth); _lockedInPendingDelegations[holder].amount = _lockedInPendingDelegations[holder].amount.sub(amount); } function _getCurrentMonth() private view returns (uint) { return _getTimeHelpers().getCurrentMonth(); } /** * @dev See {ILocker-getAndUpdateLockedAmount}. */ function _getAndUpdateLockedAmount(address wallet) private returns (uint) { return _getAndUpdateDelegatedByHolder(wallet).add(getLockedInPendingDelegations(wallet)); } function _updateFirstDelegationMonth(address holder, uint validatorId, uint month) private { if (_firstDelegationMonth[holder].value == 0) { _firstDelegationMonth[holder].value = month; _firstUnprocessedSlashByHolder[holder] = _slashes.length; } if (_firstDelegationMonth[holder].byValidator[validatorId] == 0) { _firstDelegationMonth[holder].byValidator[validatorId] = month; } } /** * @dev Checks whether the holder has performed a delegation. */ function _everDelegated(address holder) private view returns (bool) { return _firstDelegationMonth[holder].value > 0; } function _removeFromDelegatedToValidator(uint validatorId, uint amount, uint month) private { _delegatedToValidator[validatorId].subtractFromValue(amount, month); } function _removeFromEffectiveDelegatedToValidator(uint validatorId, uint effectiveAmount, uint month) private { _effectiveDelegatedToValidator[validatorId].subtractFromSequence(effectiveAmount, month); } /** * @dev Returns the delegated amount after a slashing event. */ function _calculateDelegationAmountAfterSlashing(uint delegationId) private view returns (uint) { uint startMonth = _delegationExtras[delegationId].lastSlashingMonthBeforeDelegation; uint validatorId = delegations[delegationId].validatorId; uint amount = delegations[delegationId].amount; if (startMonth == 0) { startMonth = _slashesOfValidator[validatorId].firstMonth; if (startMonth == 0) { return amount; } } for (uint i = startMonth; i > 0 && i < delegations[delegationId].finished; i = _slashesOfValidator[validatorId].slashes[i].nextMonth) { if (i >= delegations[delegationId].started) { amount = amount .mul(_slashesOfValidator[validatorId].slashes[i].reducingCoefficient.numerator) .div(_slashesOfValidator[validatorId].slashes[i].reducingCoefficient.denominator); } } return amount; } function _putToSlashingLog( SlashingLog storage log, FractionUtils.Fraction memory coefficient, uint month) private { if (log.firstMonth == 0) { log.firstMonth = month; log.lastMonth = month; log.slashes[month].reducingCoefficient = coefficient; log.slashes[month].nextMonth = 0; } else { require(log.lastMonth <= month, "Cannot put slashing event in the past"); if (log.lastMonth == month) { log.slashes[month].reducingCoefficient = log.slashes[month].reducingCoefficient.multiplyFraction(coefficient); } else { log.slashes[month].reducingCoefficient = coefficient; log.slashes[month].nextMonth = 0; log.slashes[log.lastMonth].nextMonth = month; log.lastMonth = month; } } } function _processSlashesWithoutSignals(address holder, uint limit) private returns (SlashingSignal[] memory slashingSignals) { if (hasUnprocessedSlashes(holder)) { uint index = _firstUnprocessedSlashByHolder[holder]; uint end = _slashes.length; if (limit > 0 && index.add(limit) < end) { end = index.add(limit); } slashingSignals = new SlashingSignal[](end.sub(index)); uint begin = index; for (; index < end; ++index) { uint validatorId = _slashes[index].validatorId; uint month = _slashes[index].month; uint oldValue = _getAndUpdateDelegatedByHolderToValidator(holder, validatorId, month); if (oldValue.muchGreater(0)) { _delegatedByHolderToValidator[holder][validatorId].reduceValueByCoefficientAndUpdateSum( _delegatedByHolder[holder], _slashes[index].reducingCoefficient, month); _effectiveDelegatedByHolderToValidator[holder][validatorId].reduceSequence( _slashes[index].reducingCoefficient, month); slashingSignals[index.sub(begin)].holder = holder; slashingSignals[index.sub(begin)].penalty = oldValue.boundedSub(_getAndUpdateDelegatedByHolderToValidator(holder, validatorId, month)); } } _firstUnprocessedSlashByHolder[holder] = end; } } function _processAllSlashesWithoutSignals(address holder) private returns (SlashingSignal[] memory slashingSignals) { return _processSlashesWithoutSignals(holder, 0); } function _sendSlashingSignals(SlashingSignal[] memory slashingSignals) private { Punisher punisher = Punisher(contractManager.getPunisher()); address previousHolder = address(0); uint accumulatedPenalty = 0; for (uint i = 0; i < slashingSignals.length; ++i) { if (slashingSignals[i].holder != previousHolder) { if (accumulatedPenalty > 0) { punisher.handleSlash(previousHolder, accumulatedPenalty); } previousHolder = slashingSignals[i].holder; accumulatedPenalty = slashingSignals[i].penalty; } else { accumulatedPenalty = accumulatedPenalty.add(slashingSignals[i].penalty); } } if (accumulatedPenalty > 0) { punisher.handleSlash(previousHolder, accumulatedPenalty); } } function _addToAllStatistics(uint delegationId) private { uint currentMonth = _getCurrentMonth(); delegations[delegationId].started = currentMonth.add(1); if (_slashesOfValidator[delegations[delegationId].validatorId].lastMonth > 0) { _delegationExtras[delegationId].lastSlashingMonthBeforeDelegation = _slashesOfValidator[delegations[delegationId].validatorId].lastMonth; } _addToDelegatedToValidator( delegations[delegationId].validatorId, delegations[delegationId].amount, currentMonth.add(1)); _addToDelegatedByHolder( delegations[delegationId].holder, delegations[delegationId].amount, currentMonth.add(1)); _addToDelegatedByHolderToValidator( delegations[delegationId].holder, delegations[delegationId].validatorId, delegations[delegationId].amount, currentMonth.add(1)); _updateFirstDelegationMonth( delegations[delegationId].holder, delegations[delegationId].validatorId, currentMonth.add(1)); uint effectiveAmount = delegations[delegationId].amount.mul( _getDelegationPeriodManager().stakeMultipliers(delegations[delegationId].delegationPeriod)); _addToEffectiveDelegatedToValidator( delegations[delegationId].validatorId, effectiveAmount, currentMonth.add(1)); _addToEffectiveDelegatedByHolderToValidator( delegations[delegationId].holder, delegations[delegationId].validatorId, effectiveAmount, currentMonth.add(1)); _addValidatorToValidatorsPerDelegators( delegations[delegationId].holder, delegations[delegationId].validatorId ); } function _subtractFromAllStatistics(uint delegationId) private { uint amountAfterSlashing = _calculateDelegationAmountAfterSlashing(delegationId); _removeFromDelegatedToValidator( delegations[delegationId].validatorId, amountAfterSlashing, delegations[delegationId].finished); _removeFromDelegatedByHolder( delegations[delegationId].holder, amountAfterSlashing, delegations[delegationId].finished); _removeFromDelegatedByHolderToValidator( delegations[delegationId].holder, delegations[delegationId].validatorId, amountAfterSlashing, delegations[delegationId].finished); uint effectiveAmount = amountAfterSlashing.mul( _getDelegationPeriodManager().stakeMultipliers(delegations[delegationId].delegationPeriod)); _removeFromEffectiveDelegatedToValidator( delegations[delegationId].validatorId, effectiveAmount, delegations[delegationId].finished); _removeFromEffectiveDelegatedByHolderToValidator( delegations[delegationId].holder, delegations[delegationId].validatorId, effectiveAmount, delegations[delegationId].finished); _getBounty().handleDelegationRemoving( effectiveAmount, delegations[delegationId].finished); } /** * @dev Checks whether delegation to a validator is allowed. * * Requirements: * * - Delegator must not have reached the validator limit. * - Delegation must be made in or after the first delegation month. */ function _checkIfDelegationIsAllowed(address holder, uint validatorId) private view returns (bool) { require( _numberOfValidatorsPerDelegator[holder].delegated[validatorId] > 0 || ( _numberOfValidatorsPerDelegator[holder].delegated[validatorId] == 0 && _numberOfValidatorsPerDelegator[holder].number < _getConstantsHolder().limitValidatorsPerDelegator() ), "Limit of validators is reached" ); } function _getDelegationPeriodManager() private view returns (DelegationPeriodManager) { return DelegationPeriodManager(contractManager.getDelegationPeriodManager()); } function _getBounty() private view returns (BountyV2) { return BountyV2(contractManager.getBounty()); } function _getValidatorService() private view returns (ValidatorService) { return ValidatorService(contractManager.getValidatorService()); } function _getTimeHelpers() private view returns (TimeHelpers) { return TimeHelpers(contractManager.getTimeHelpers()); } function _getConstantsHolder() private view returns (ConstantsHolder) { return ConstantsHolder(contractManager.getConstantsHolder()); } function _accept(uint delegationId) private { _checkIfDelegationIsAllowed(delegations[delegationId].holder, delegations[delegationId].validatorId); State currentState = getState(delegationId); if (currentState != State.PROPOSED) { if (currentState == State.ACCEPTED || currentState == State.DELEGATED || currentState == State.UNDELEGATION_REQUESTED || currentState == State.COMPLETED) { revert("The delegation has been already accepted"); } else if (currentState == State.CANCELED) { revert("The delegation has been cancelled by token holder"); } else if (currentState == State.REJECTED) { revert("The delegation request is outdated"); } } require(currentState == State.PROPOSED, "Cannot set delegation state to accepted"); SlashingSignal[] memory slashingSignals = _processAllSlashesWithoutSignals(delegations[delegationId].holder); _addToAllStatistics(delegationId); uint amount = delegations[delegationId].amount; uint effectiveAmount = amount.mul( _getDelegationPeriodManager().stakeMultipliers(delegations[delegationId].delegationPeriod) ); _getBounty().handleDelegationAdd( effectiveAmount, delegations[delegationId].started ); _sendSlashingSignals(slashingSignals); emit DelegationAccepted(delegationId); } } // SPDX-License-Identifier: AGPL-3.0-only /* PartialDifferences.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "../utils/MathUtils.sol"; import "../utils/FractionUtils.sol"; /** * @title Partial Differences Library * @dev This library contains functions to manage Partial Differences data * structure. Partial Differences is an array of value differences over time. * * For example: assuming an array [3, 6, 3, 1, 2], partial differences can * represent this array as [_, 3, -3, -2, 1]. * * This data structure allows adding values on an open interval with O(1) * complexity. * * For example: add +5 to [3, 6, 3, 1, 2] starting from the second element (3), * instead of performing [3, 6, 3+5, 1+5, 2+5] partial differences allows * performing [_, 3, -3+5, -2, 1]. The original array can be restored by * adding values from partial differences. */ library PartialDifferences { using SafeMath for uint; using MathUtils for uint; struct Sequence { // month => diff mapping (uint => uint) addDiff; // month => diff mapping (uint => uint) subtractDiff; // month => value mapping (uint => uint) value; uint firstUnprocessedMonth; uint lastChangedMonth; } struct Value { // month => diff mapping (uint => uint) addDiff; // month => diff mapping (uint => uint) subtractDiff; uint value; uint firstUnprocessedMonth; uint lastChangedMonth; } // functions for sequence function addToSequence(Sequence storage sequence, uint diff, uint month) internal { require(sequence.firstUnprocessedMonth <= month, "Cannot add to the past"); if (sequence.firstUnprocessedMonth == 0) { sequence.firstUnprocessedMonth = month; } sequence.addDiff[month] = sequence.addDiff[month].add(diff); if (sequence.lastChangedMonth != month) { sequence.lastChangedMonth = month; } } function subtractFromSequence(Sequence storage sequence, uint diff, uint month) internal { require(sequence.firstUnprocessedMonth <= month, "Cannot subtract from the past"); if (sequence.firstUnprocessedMonth == 0) { sequence.firstUnprocessedMonth = month; } sequence.subtractDiff[month] = sequence.subtractDiff[month].add(diff); if (sequence.lastChangedMonth != month) { sequence.lastChangedMonth = month; } } function getAndUpdateValueInSequence(Sequence storage sequence, uint month) internal returns (uint) { if (sequence.firstUnprocessedMonth == 0) { return 0; } if (sequence.firstUnprocessedMonth <= month) { for (uint i = sequence.firstUnprocessedMonth; i <= month; ++i) { uint nextValue = sequence.value[i.sub(1)].add(sequence.addDiff[i]).boundedSub(sequence.subtractDiff[i]); if (sequence.value[i] != nextValue) { sequence.value[i] = nextValue; } if (sequence.addDiff[i] > 0) { delete sequence.addDiff[i]; } if (sequence.subtractDiff[i] > 0) { delete sequence.subtractDiff[i]; } } sequence.firstUnprocessedMonth = month.add(1); } return sequence.value[month]; } function getValueInSequence(Sequence storage sequence, uint month) internal view returns (uint) { if (sequence.firstUnprocessedMonth == 0) { return 0; } if (sequence.firstUnprocessedMonth <= month) { uint value = sequence.value[sequence.firstUnprocessedMonth.sub(1)]; for (uint i = sequence.firstUnprocessedMonth; i <= month; ++i) { value = value.add(sequence.addDiff[i]).sub(sequence.subtractDiff[i]); } return value; } else { return sequence.value[month]; } } function getValuesInSequence(Sequence storage sequence) internal view returns (uint[] memory values) { if (sequence.firstUnprocessedMonth == 0) { return values; } uint begin = sequence.firstUnprocessedMonth.sub(1); uint end = sequence.lastChangedMonth.add(1); if (end <= begin) { end = begin.add(1); } values = new uint[](end.sub(begin)); values[0] = sequence.value[sequence.firstUnprocessedMonth.sub(1)]; for (uint i = 0; i.add(1) < values.length; ++i) { uint month = sequence.firstUnprocessedMonth.add(i); values[i.add(1)] = values[i].add(sequence.addDiff[month]).sub(sequence.subtractDiff[month]); } } function reduceSequence( Sequence storage sequence, FractionUtils.Fraction memory reducingCoefficient, uint month) internal { require(month.add(1) >= sequence.firstUnprocessedMonth, "Cannot reduce value in the past"); require( reducingCoefficient.numerator <= reducingCoefficient.denominator, "Increasing of values is not implemented"); if (sequence.firstUnprocessedMonth == 0) { return; } uint value = getAndUpdateValueInSequence(sequence, month); if (value.approximatelyEqual(0)) { return; } sequence.value[month] = sequence.value[month] .mul(reducingCoefficient.numerator) .div(reducingCoefficient.denominator); for (uint i = month.add(1); i <= sequence.lastChangedMonth; ++i) { sequence.subtractDiff[i] = sequence.subtractDiff[i] .mul(reducingCoefficient.numerator) .div(reducingCoefficient.denominator); } } // functions for value function addToValue(Value storage sequence, uint diff, uint month) internal { require(sequence.firstUnprocessedMonth <= month, "Cannot add to the past"); if (sequence.firstUnprocessedMonth == 0) { sequence.firstUnprocessedMonth = month; sequence.lastChangedMonth = month; } if (month > sequence.lastChangedMonth) { sequence.lastChangedMonth = month; } if (month >= sequence.firstUnprocessedMonth) { sequence.addDiff[month] = sequence.addDiff[month].add(diff); } else { sequence.value = sequence.value.add(diff); } } function subtractFromValue(Value storage sequence, uint diff, uint month) internal { require(sequence.firstUnprocessedMonth <= month.add(1), "Cannot subtract from the past"); if (sequence.firstUnprocessedMonth == 0) { sequence.firstUnprocessedMonth = month; sequence.lastChangedMonth = month; } if (month > sequence.lastChangedMonth) { sequence.lastChangedMonth = month; } if (month >= sequence.firstUnprocessedMonth) { sequence.subtractDiff[month] = sequence.subtractDiff[month].add(diff); } else { sequence.value = sequence.value.boundedSub(diff); } } function getAndUpdateValue(Value storage sequence, uint month) internal returns (uint) { require( month.add(1) >= sequence.firstUnprocessedMonth, "Cannot calculate value in the past"); if (sequence.firstUnprocessedMonth == 0) { return 0; } if (sequence.firstUnprocessedMonth <= month) { uint value = sequence.value; for (uint i = sequence.firstUnprocessedMonth; i <= month; ++i) { value = value.add(sequence.addDiff[i]).boundedSub(sequence.subtractDiff[i]); if (sequence.addDiff[i] > 0) { delete sequence.addDiff[i]; } if (sequence.subtractDiff[i] > 0) { delete sequence.subtractDiff[i]; } } if (sequence.value != value) { sequence.value = value; } sequence.firstUnprocessedMonth = month.add(1); } return sequence.value; } function getValue(Value storage sequence, uint month) internal view returns (uint) { require( month.add(1) >= sequence.firstUnprocessedMonth, "Cannot calculate value in the past"); if (sequence.firstUnprocessedMonth == 0) { return 0; } if (sequence.firstUnprocessedMonth <= month) { uint value = sequence.value; for (uint i = sequence.firstUnprocessedMonth; i <= month; ++i) { value = value.add(sequence.addDiff[i]).sub(sequence.subtractDiff[i]); } return value; } else { return sequence.value; } } function getValues(Value storage sequence) internal view returns (uint[] memory values) { if (sequence.firstUnprocessedMonth == 0) { return values; } uint begin = sequence.firstUnprocessedMonth.sub(1); uint end = sequence.lastChangedMonth.add(1); if (end <= begin) { end = begin.add(1); } values = new uint[](end.sub(begin)); values[0] = sequence.value; for (uint i = 0; i.add(1) < values.length; ++i) { uint month = sequence.firstUnprocessedMonth.add(i); values[i.add(1)] = values[i].add(sequence.addDiff[month]).sub(sequence.subtractDiff[month]); } } function reduceValue( Value storage sequence, uint amount, uint month) internal returns (FractionUtils.Fraction memory) { require(month.add(1) >= sequence.firstUnprocessedMonth, "Cannot reduce value in the past"); if (sequence.firstUnprocessedMonth == 0) { return FractionUtils.createFraction(0); } uint value = getAndUpdateValue(sequence, month); if (value.approximatelyEqual(0)) { return FractionUtils.createFraction(0); } uint _amount = amount; if (value < amount) { _amount = value; } FractionUtils.Fraction memory reducingCoefficient = FractionUtils.createFraction(value.boundedSub(_amount), value); reduceValueByCoefficient(sequence, reducingCoefficient, month); return reducingCoefficient; } function reduceValueByCoefficient( Value storage sequence, FractionUtils.Fraction memory reducingCoefficient, uint month) internal { reduceValueByCoefficientAndUpdateSumIfNeeded( sequence, sequence, reducingCoefficient, month, false); } function reduceValueByCoefficientAndUpdateSum( Value storage sequence, Value storage sumSequence, FractionUtils.Fraction memory reducingCoefficient, uint month) internal { reduceValueByCoefficientAndUpdateSumIfNeeded( sequence, sumSequence, reducingCoefficient, month, true); } function reduceValueByCoefficientAndUpdateSumIfNeeded( Value storage sequence, Value storage sumSequence, FractionUtils.Fraction memory reducingCoefficient, uint month, bool hasSumSequence) internal { require(month.add(1) >= sequence.firstUnprocessedMonth, "Cannot reduce value in the past"); if (hasSumSequence) { require(month.add(1) >= sumSequence.firstUnprocessedMonth, "Cannot reduce value in the past"); } require( reducingCoefficient.numerator <= reducingCoefficient.denominator, "Increasing of values is not implemented"); if (sequence.firstUnprocessedMonth == 0) { return; } uint value = getAndUpdateValue(sequence, month); if (value.approximatelyEqual(0)) { return; } uint newValue = sequence.value.mul(reducingCoefficient.numerator).div(reducingCoefficient.denominator); if (hasSumSequence) { subtractFromValue(sumSequence, sequence.value.boundedSub(newValue), month); } sequence.value = newValue; for (uint i = month.add(1); i <= sequence.lastChangedMonth; ++i) { uint newDiff = sequence.subtractDiff[i] .mul(reducingCoefficient.numerator) .div(reducingCoefficient.denominator); if (hasSumSequence) { sumSequence.subtractDiff[i] = sumSequence.subtractDiff[i] .boundedSub(sequence.subtractDiff[i].boundedSub(newDiff)); } sequence.subtractDiff[i] = newDiff; } } function clear(Value storage sequence) internal { for (uint i = sequence.firstUnprocessedMonth; i <= sequence.lastChangedMonth; ++i) { if (sequence.addDiff[i] > 0) { delete sequence.addDiff[i]; } if (sequence.subtractDiff[i] > 0) { delete sequence.subtractDiff[i]; } } if (sequence.value > 0) { delete sequence.value; } if (sequence.firstUnprocessedMonth > 0) { delete sequence.firstUnprocessedMonth; } if (sequence.lastChangedMonth > 0) { delete sequence.lastChangedMonth; } } } // SPDX-License-Identifier: AGPL-3.0-only /* TimeHelpers.sol - SKALE Manager Copyright (C) 2019-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "../thirdparty/BokkyPooBahsDateTimeLibrary.sol"; /** * @title TimeHelpers * @dev The contract performs time operations. * * These functions are used to calculate monthly and Proof of Use epochs. */ contract TimeHelpers { using SafeMath for uint; uint constant private _ZERO_YEAR = 2020; function calculateProofOfUseLockEndTime(uint month, uint lockUpPeriodDays) external view returns (uint timestamp) { timestamp = BokkyPooBahsDateTimeLibrary.addDays(monthToTimestamp(month), lockUpPeriodDays); } function addDays(uint fromTimestamp, uint n) external pure returns (uint) { return BokkyPooBahsDateTimeLibrary.addDays(fromTimestamp, n); } function addMonths(uint fromTimestamp, uint n) external pure returns (uint) { return BokkyPooBahsDateTimeLibrary.addMonths(fromTimestamp, n); } function addYears(uint fromTimestamp, uint n) external pure returns (uint) { return BokkyPooBahsDateTimeLibrary.addYears(fromTimestamp, n); } function getCurrentMonth() external view virtual returns (uint) { return timestampToMonth(now); } function timestampToDay(uint timestamp) external view returns (uint) { uint wholeDays = timestamp / BokkyPooBahsDateTimeLibrary.SECONDS_PER_DAY; uint zeroDay = BokkyPooBahsDateTimeLibrary.timestampFromDate(_ZERO_YEAR, 1, 1) / BokkyPooBahsDateTimeLibrary.SECONDS_PER_DAY; require(wholeDays >= zeroDay, "Timestamp is too far in the past"); return wholeDays - zeroDay; } function timestampToYear(uint timestamp) external view virtual returns (uint) { uint year; (year, , ) = BokkyPooBahsDateTimeLibrary.timestampToDate(timestamp); require(year >= _ZERO_YEAR, "Timestamp is too far in the past"); return year - _ZERO_YEAR; } function timestampToMonth(uint timestamp) public view virtual returns (uint) { uint year; uint month; (year, month, ) = BokkyPooBahsDateTimeLibrary.timestampToDate(timestamp); require(year >= _ZERO_YEAR, "Timestamp is too far in the past"); month = month.sub(1).add(year.sub(_ZERO_YEAR).mul(12)); require(month > 0, "Timestamp is too far in the past"); return month; } function monthToTimestamp(uint month) public view virtual returns (uint timestamp) { uint year = _ZERO_YEAR; uint _month = month; year = year.add(_month.div(12)); _month = _month.mod(12); _month = _month.add(1); return BokkyPooBahsDateTimeLibrary.timestampFromDate(year, _month, 1); } } // SPDX-License-Identifier: AGPL-3.0-only /* ValidatorService.sol - SKALE Manager Copyright (C) 2019-Present SKALE Labs @author Dmytro Stebaiev @author Artem Payvin @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/cryptography/ECDSA.sol"; import "../Permissions.sol"; import "../ConstantsHolder.sol"; import "./DelegationController.sol"; import "./TimeHelpers.sol"; /** * @title ValidatorService * @dev This contract handles all validator operations including registration, * node management, validator-specific delegation parameters, and more. * * TIP: For more information see our main instructions * https://forum.skale.network/t/skale-mainnet-launch-faq/182[SKALE MainNet Launch FAQ]. * * Validators register an address, and use this address to accept delegations and * register nodes. */ contract ValidatorService is Permissions { using ECDSA for bytes32; struct Validator { string name; address validatorAddress; address requestedAddress; string description; uint feeRate; uint registrationTime; uint minimumDelegationAmount; bool acceptNewRequests; } /** * @dev Emitted when a validator registers. */ event ValidatorRegistered( uint validatorId ); /** * @dev Emitted when a validator address changes. */ event ValidatorAddressChanged( uint validatorId, address newAddress ); /** * @dev Emitted when a validator is enabled. */ event ValidatorWasEnabled( uint validatorId ); /** * @dev Emitted when a validator is disabled. */ event ValidatorWasDisabled( uint validatorId ); /** * @dev Emitted when a node address is linked to a validator. */ event NodeAddressWasAdded( uint validatorId, address nodeAddress ); /** * @dev Emitted when a node address is unlinked from a validator. */ event NodeAddressWasRemoved( uint validatorId, address nodeAddress ); mapping (uint => Validator) public validators; mapping (uint => bool) private _trustedValidators; uint[] public trustedValidatorsList; // address => validatorId mapping (address => uint) private _validatorAddressToId; // address => validatorId mapping (address => uint) private _nodeAddressToValidatorId; // validatorId => nodeAddress[] mapping (uint => address[]) private _nodeAddresses; uint public numberOfValidators; bool public useWhitelist; bytes32 public constant VALIDATOR_MANAGER_ROLE = keccak256("VALIDATOR_MANAGER_ROLE"); modifier onlyValidatorManager() { require(hasRole(VALIDATOR_MANAGER_ROLE, msg.sender), "VALIDATOR_MANAGER_ROLE is required"); _; } modifier checkValidatorExists(uint validatorId) { require(validatorExists(validatorId), "Validator with such ID does not exist"); _; } /** * @dev Creates a new validator ID that includes a validator name, description, * commission or fee rate, and a minimum delegation amount accepted by the validator. * * Emits a {ValidatorRegistered} event. * * Requirements: * * - Sender must not already have registered a validator ID. * - Fee rate must be between 0 - 1000‰. Note: in per mille. */ function registerValidator( string calldata name, string calldata description, uint feeRate, uint minimumDelegationAmount ) external returns (uint validatorId) { require(!validatorAddressExists(msg.sender), "Validator with such address already exists"); require(feeRate <= 1000, "Fee rate of validator should be lower than 100%"); validatorId = ++numberOfValidators; validators[validatorId] = Validator( name, msg.sender, address(0), description, feeRate, now, minimumDelegationAmount, true ); _setValidatorAddress(validatorId, msg.sender); emit ValidatorRegistered(validatorId); } /** * @dev Allows Admin to enable a validator by adding their ID to the * trusted list. * * Emits a {ValidatorWasEnabled} event. * * Requirements: * * - Validator must not already be enabled. */ function enableValidator(uint validatorId) external checkValidatorExists(validatorId) onlyValidatorManager { require(!_trustedValidators[validatorId], "Validator is already enabled"); _trustedValidators[validatorId] = true; trustedValidatorsList.push(validatorId); emit ValidatorWasEnabled(validatorId); } /** * @dev Allows Admin to disable a validator by removing their ID from * the trusted list. * * Emits a {ValidatorWasDisabled} event. * * Requirements: * * - Validator must not already be disabled. */ function disableValidator(uint validatorId) external checkValidatorExists(validatorId) onlyValidatorManager { require(_trustedValidators[validatorId], "Validator is already disabled"); _trustedValidators[validatorId] = false; uint position = _find(trustedValidatorsList, validatorId); if (position < trustedValidatorsList.length) { trustedValidatorsList[position] = trustedValidatorsList[trustedValidatorsList.length.sub(1)]; } trustedValidatorsList.pop(); emit ValidatorWasDisabled(validatorId); } /** * @dev Owner can disable the trusted validator list. Once turned off, the * trusted list cannot be re-enabled. */ function disableWhitelist() external onlyValidatorManager { useWhitelist = false; } /** * @dev Allows `msg.sender` to request a new address. * * Requirements: * * - `msg.sender` must already be a validator. * - New address must not be null. * - New address must not be already registered as a validator. */ function requestForNewAddress(address newValidatorAddress) external { require(newValidatorAddress != address(0), "New address cannot be null"); require(_validatorAddressToId[newValidatorAddress] == 0, "Address already registered"); // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); validators[validatorId].requestedAddress = newValidatorAddress; } /** * @dev Allows msg.sender to confirm an address change. * * Emits a {ValidatorAddressChanged} event. * * Requirements: * * - Must be owner of new address. */ function confirmNewAddress(uint validatorId) external checkValidatorExists(validatorId) { require( getValidator(validatorId).requestedAddress == msg.sender, "The validator address cannot be changed because it is not the actual owner" ); delete validators[validatorId].requestedAddress; _setValidatorAddress(validatorId, msg.sender); emit ValidatorAddressChanged(validatorId, validators[validatorId].validatorAddress); } /** * @dev Links a node address to validator ID. Validator must present * the node signature of the validator ID. * * Requirements: * * - Signature must be valid. * - Address must not be assigned to a validator. */ function linkNodeAddress(address nodeAddress, bytes calldata sig) external { // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); require( keccak256(abi.encodePacked(validatorId)).toEthSignedMessageHash().recover(sig) == nodeAddress, "Signature is not pass" ); require(_validatorAddressToId[nodeAddress] == 0, "Node address is a validator"); _addNodeAddress(validatorId, nodeAddress); emit NodeAddressWasAdded(validatorId, nodeAddress); } /** * @dev Unlinks a node address from a validator. * * Emits a {NodeAddressWasRemoved} event. */ function unlinkNodeAddress(address nodeAddress) external { // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); this.removeNodeAddress(validatorId, nodeAddress); emit NodeAddressWasRemoved(validatorId, nodeAddress); } /** * @dev Allows a validator to set a minimum delegation amount. */ function setValidatorMDA(uint minimumDelegationAmount) external { // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); validators[validatorId].minimumDelegationAmount = minimumDelegationAmount; } /** * @dev Allows a validator to set a new validator name. */ function setValidatorName(string calldata newName) external { // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); validators[validatorId].name = newName; } /** * @dev Allows a validator to set a new validator description. */ function setValidatorDescription(string calldata newDescription) external { // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); validators[validatorId].description = newDescription; } /** * @dev Allows a validator to start accepting new delegation requests. * * Requirements: * * - Must not have already enabled accepting new requests. */ function startAcceptingNewRequests() external { // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); require(!isAcceptingNewRequests(validatorId), "Accepting request is already enabled"); validators[validatorId].acceptNewRequests = true; } /** * @dev Allows a validator to stop accepting new delegation requests. * * Requirements: * * - Must not have already stopped accepting new requests. */ function stopAcceptingNewRequests() external { // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); require(isAcceptingNewRequests(validatorId), "Accepting request is already disabled"); validators[validatorId].acceptNewRequests = false; } function removeNodeAddress(uint validatorId, address nodeAddress) external allowTwo("ValidatorService", "Nodes") { require(_nodeAddressToValidatorId[nodeAddress] == validatorId, "Validator does not have permissions to unlink node"); delete _nodeAddressToValidatorId[nodeAddress]; for (uint i = 0; i < _nodeAddresses[validatorId].length; ++i) { if (_nodeAddresses[validatorId][i] == nodeAddress) { if (i + 1 < _nodeAddresses[validatorId].length) { _nodeAddresses[validatorId][i] = _nodeAddresses[validatorId][_nodeAddresses[validatorId].length.sub(1)]; } delete _nodeAddresses[validatorId][_nodeAddresses[validatorId].length.sub(1)]; _nodeAddresses[validatorId].pop(); break; } } } /** * @dev Returns the amount of validator bond (self-delegation). */ function getAndUpdateBondAmount(uint validatorId) external returns (uint) { DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController") ); return delegationController.getAndUpdateDelegatedByHolderToValidatorNow( getValidator(validatorId).validatorAddress, validatorId ); } /** * @dev Returns node addresses linked to the msg.sender. */ function getMyNodesAddresses() external view returns (address[] memory) { return getNodeAddresses(getValidatorId(msg.sender)); } /** * @dev Returns the list of trusted validators. */ function getTrustedValidators() external view returns (uint[] memory) { return trustedValidatorsList; } /** * @dev Checks whether the validator ID is linked to the validator address. */ function checkValidatorAddressToId(address validatorAddress, uint validatorId) external view returns (bool) { return getValidatorId(validatorAddress) == validatorId ? true : false; } /** * @dev Returns the validator ID linked to a node address. * * Requirements: * * - Node address must be linked to a validator. */ function getValidatorIdByNodeAddress(address nodeAddress) external view returns (uint validatorId) { validatorId = _nodeAddressToValidatorId[nodeAddress]; require(validatorId != 0, "Node address is not assigned to a validator"); } function checkValidatorCanReceiveDelegation(uint validatorId, uint amount) external view { require(isAuthorizedValidator(validatorId), "Validator is not authorized to accept delegation request"); require(isAcceptingNewRequests(validatorId), "The validator is not currently accepting new requests"); require( validators[validatorId].minimumDelegationAmount <= amount, "Amount does not meet the validator's minimum delegation amount" ); } function initialize(address contractManagerAddress) public override initializer { Permissions.initialize(contractManagerAddress); useWhitelist = true; } /** * @dev Returns a validator's node addresses. */ function getNodeAddresses(uint validatorId) public view returns (address[] memory) { return _nodeAddresses[validatorId]; } /** * @dev Checks whether validator ID exists. */ function validatorExists(uint validatorId) public view returns (bool) { return validatorId <= numberOfValidators && validatorId != 0; } /** * @dev Checks whether validator address exists. */ function validatorAddressExists(address validatorAddress) public view returns (bool) { return _validatorAddressToId[validatorAddress] != 0; } /** * @dev Checks whether validator address exists. */ function checkIfValidatorAddressExists(address validatorAddress) public view { require(validatorAddressExists(validatorAddress), "Validator address does not exist"); } /** * @dev Returns the Validator struct. */ function getValidator(uint validatorId) public view checkValidatorExists(validatorId) returns (Validator memory) { return validators[validatorId]; } /** * @dev Returns the validator ID for the given validator address. */ function getValidatorId(address validatorAddress) public view returns (uint) { checkIfValidatorAddressExists(validatorAddress); return _validatorAddressToId[validatorAddress]; } /** * @dev Checks whether the validator is currently accepting new delegation requests. */ function isAcceptingNewRequests(uint validatorId) public view checkValidatorExists(validatorId) returns (bool) { return validators[validatorId].acceptNewRequests; } function isAuthorizedValidator(uint validatorId) public view checkValidatorExists(validatorId) returns (bool) { return _trustedValidators[validatorId] || !useWhitelist; } // private /** * @dev Links a validator address to a validator ID. * * Requirements: * * - Address is not already in use by another validator. */ function _setValidatorAddress(uint validatorId, address validatorAddress) private { if (_validatorAddressToId[validatorAddress] == validatorId) { return; } require(_validatorAddressToId[validatorAddress] == 0, "Address is in use by another validator"); address oldAddress = validators[validatorId].validatorAddress; delete _validatorAddressToId[oldAddress]; _nodeAddressToValidatorId[validatorAddress] = validatorId; validators[validatorId].validatorAddress = validatorAddress; _validatorAddressToId[validatorAddress] = validatorId; } /** * @dev Links a node address to a validator ID. * * Requirements: * * - Node address must not be already linked to a validator. */ function _addNodeAddress(uint validatorId, address nodeAddress) private { if (_nodeAddressToValidatorId[nodeAddress] == validatorId) { return; } require(_nodeAddressToValidatorId[nodeAddress] == 0, "Validator cannot override node address"); _nodeAddressToValidatorId[nodeAddress] = validatorId; _nodeAddresses[validatorId].push(nodeAddress); } function _find(uint[] memory array, uint index) private pure returns (uint) { uint i; for (i = 0; i < array.length; i++) { if (array[i] == index) { return i; } } return array.length; } } // SPDX-License-Identifier: AGPL-3.0-only /* ConstantsHolder.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "./Permissions.sol"; /** * @title ConstantsHolder * @dev Contract contains constants and common variables for the SKALE Network. */ contract ConstantsHolder is Permissions { // initial price for creating Node (100 SKL) uint public constant NODE_DEPOSIT = 100 * 1e18; uint8 public constant TOTAL_SPACE_ON_NODE = 128; // part of Node for Small Skale-chain (1/128 of Node) uint8 public constant SMALL_DIVISOR = 128; // part of Node for Medium Skale-chain (1/32 of Node) uint8 public constant MEDIUM_DIVISOR = 32; // part of Node for Large Skale-chain (full Node) uint8 public constant LARGE_DIVISOR = 1; // part of Node for Medium Test Skale-chain (1/4 of Node) uint8 public constant MEDIUM_TEST_DIVISOR = 4; // typically number of Nodes for Skale-chain (16 Nodes) uint public constant NUMBER_OF_NODES_FOR_SCHAIN = 16; // number of Nodes for Test Skale-chain (2 Nodes) uint public constant NUMBER_OF_NODES_FOR_TEST_SCHAIN = 2; // number of Nodes for Test Skale-chain (4 Nodes) uint public constant NUMBER_OF_NODES_FOR_MEDIUM_TEST_SCHAIN = 4; // number of seconds in one year uint32 public constant SECONDS_TO_YEAR = 31622400; // initial number of monitors uint public constant NUMBER_OF_MONITORS = 24; uint public constant OPTIMAL_LOAD_PERCENTAGE = 80; uint public constant ADJUSTMENT_SPEED = 1000; uint public constant COOLDOWN_TIME = 60; uint public constant MIN_PRICE = 10**6; uint public constant MSR_REDUCING_COEFFICIENT = 2; uint public constant DOWNTIME_THRESHOLD_PART = 30; uint public constant BOUNTY_LOCKUP_MONTHS = 2; uint public constant ALRIGHT_DELTA = 62893; uint public constant BROADCAST_DELTA = 131000; uint public constant COMPLAINT_BAD_DATA_DELTA = 49580; uint public constant PRE_RESPONSE_DELTA = 74500; uint public constant COMPLAINT_DELTA = 76221; uint public constant RESPONSE_DELTA = 183000; // MSR - Minimum staking requirement uint public msr; // Reward period - 30 days (each 30 days Node would be granted for bounty) uint32 public rewardPeriod; // Allowable latency - 150000 ms by default uint32 public allowableLatency; /** * Delta period - 1 hour (1 hour before Reward period became Monitors need * to send Verdicts and 1 hour after Reward period became Node need to come * and get Bounty) */ uint32 public deltaPeriod; /** * Check time - 2 minutes (every 2 minutes monitors should check metrics * from checked nodes) */ uint public checkTime; //Need to add minimal allowed parameters for verdicts uint public launchTimestamp; uint public rotationDelay; uint public proofOfUseLockUpPeriodDays; uint public proofOfUseDelegationPercentage; uint public limitValidatorsPerDelegator; uint256 public firstDelegationsMonth; // deprecated // date when schains will be allowed for creation uint public schainCreationTimeStamp; uint public minimalSchainLifetime; uint public complaintTimelimit; bytes32 public constant CONSTANTS_HOLDER_MANAGER_ROLE = keccak256("CONSTANTS_HOLDER_MANAGER_ROLE"); modifier onlyConstantsHolderManager() { require(hasRole(CONSTANTS_HOLDER_MANAGER_ROLE, msg.sender), "CONSTANTS_HOLDER_MANAGER_ROLE is required"); _; } /** * @dev Allows the Owner to set new reward and delta periods * This function is only for tests. */ function setPeriods(uint32 newRewardPeriod, uint32 newDeltaPeriod) external onlyConstantsHolderManager { require( newRewardPeriod >= newDeltaPeriod && newRewardPeriod - newDeltaPeriod >= checkTime, "Incorrect Periods" ); rewardPeriod = newRewardPeriod; deltaPeriod = newDeltaPeriod; } /** * @dev Allows the Owner to set the new check time. * This function is only for tests. */ function setCheckTime(uint newCheckTime) external onlyConstantsHolderManager { require(rewardPeriod - deltaPeriod >= checkTime, "Incorrect check time"); checkTime = newCheckTime; } /** * @dev Allows the Owner to set the allowable latency in milliseconds. * This function is only for testing purposes. */ function setLatency(uint32 newAllowableLatency) external onlyConstantsHolderManager { allowableLatency = newAllowableLatency; } /** * @dev Allows the Owner to set the minimum stake requirement. */ function setMSR(uint newMSR) external onlyConstantsHolderManager { msr = newMSR; } /** * @dev Allows the Owner to set the launch timestamp. */ function setLaunchTimestamp(uint timestamp) external onlyConstantsHolderManager { require(now < launchTimestamp, "Cannot set network launch timestamp because network is already launched"); launchTimestamp = timestamp; } /** * @dev Allows the Owner to set the node rotation delay. */ function setRotationDelay(uint newDelay) external onlyConstantsHolderManager { rotationDelay = newDelay; } /** * @dev Allows the Owner to set the proof-of-use lockup period. */ function setProofOfUseLockUpPeriod(uint periodDays) external onlyConstantsHolderManager { proofOfUseLockUpPeriodDays = periodDays; } /** * @dev Allows the Owner to set the proof-of-use delegation percentage * requirement. */ function setProofOfUseDelegationPercentage(uint percentage) external onlyConstantsHolderManager { require(percentage <= 100, "Percentage value is incorrect"); proofOfUseDelegationPercentage = percentage; } /** * @dev Allows the Owner to set the maximum number of validators that a * single delegator can delegate to. */ function setLimitValidatorsPerDelegator(uint newLimit) external onlyConstantsHolderManager { limitValidatorsPerDelegator = newLimit; } function setSchainCreationTimeStamp(uint timestamp) external onlyConstantsHolderManager { schainCreationTimeStamp = timestamp; } function setMinimalSchainLifetime(uint lifetime) external onlyConstantsHolderManager { minimalSchainLifetime = lifetime; } function setComplaintTimelimit(uint timelimit) external onlyConstantsHolderManager { complaintTimelimit = timelimit; } function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); msr = 0; rewardPeriod = 2592000; allowableLatency = 150000; deltaPeriod = 3600; checkTime = 300; launchTimestamp = uint(-1); rotationDelay = 12 hours; proofOfUseLockUpPeriodDays = 90; proofOfUseDelegationPercentage = 50; limitValidatorsPerDelegator = 20; firstDelegationsMonth = 0; complaintTimelimit = 1800; } } // SPDX-License-Identifier: AGPL-3.0-only /* Nodes.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin @author Dmytro Stebaiev @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/utils/SafeCast.sol"; import "./delegation/DelegationController.sol"; import "./delegation/ValidatorService.sol"; import "./utils/Random.sol"; import "./utils/SegmentTree.sol"; import "./BountyV2.sol"; import "./ConstantsHolder.sol"; import "./Permissions.sol"; /** * @title Nodes * @dev This contract contains all logic to manage SKALE Network nodes states, * space availability, stake requirement checks, and exit functions. * * Nodes may be in one of several states: * * - Active: Node is registered and is in network operation. * - Leaving: Node has begun exiting from the network. * - Left: Node has left the network. * - In_Maintenance: Node is temporarily offline or undergoing infrastructure * maintenance * * Note: Online nodes contain both Active and Leaving states. */ contract Nodes is Permissions { using Random for Random.RandomGenerator; using SafeCast for uint; using SegmentTree for SegmentTree.Tree; // All Nodes states enum NodeStatus {Active, Leaving, Left, In_Maintenance} struct Node { string name; bytes4 ip; bytes4 publicIP; uint16 port; bytes32[2] publicKey; uint startBlock; uint lastRewardDate; uint finishTime; NodeStatus status; uint validatorId; } // struct to note which Nodes and which number of Nodes owned by user struct CreatedNodes { mapping (uint => bool) isNodeExist; uint numberOfNodes; } struct SpaceManaging { uint8 freeSpace; uint indexInSpaceMap; } // TODO: move outside the contract struct NodeCreationParams { string name; bytes4 ip; bytes4 publicIp; uint16 port; bytes32[2] publicKey; uint16 nonce; string domainName; } bytes32 constant public COMPLIANCE_ROLE = keccak256("COMPLIANCE_ROLE"); bytes32 public constant NODE_MANAGER_ROLE = keccak256("NODE_MANAGER_ROLE"); // array which contain all Nodes Node[] public nodes; SpaceManaging[] public spaceOfNodes; // mapping for checking which Nodes and which number of Nodes owned by user mapping (address => CreatedNodes) public nodeIndexes; // mapping for checking is IP address busy mapping (bytes4 => bool) public nodesIPCheck; // mapping for checking is Name busy mapping (bytes32 => bool) public nodesNameCheck; // mapping for indication from Name to Index mapping (bytes32 => uint) public nodesNameToIndex; // mapping for indication from space to Nodes mapping (uint8 => uint[]) public spaceToNodes; mapping (uint => uint[]) public validatorToNodeIndexes; uint public numberOfActiveNodes; uint public numberOfLeavingNodes; uint public numberOfLeftNodes; mapping (uint => string) public domainNames; mapping (uint => bool) private _invisible; SegmentTree.Tree private _nodesAmountBySpace; mapping (uint => bool) public incompliant; /** * @dev Emitted when a node is created. */ event NodeCreated( uint nodeIndex, address owner, string name, bytes4 ip, bytes4 publicIP, uint16 port, uint16 nonce, string domainName, uint time, uint gasSpend ); /** * @dev Emitted when a node completes a network exit. */ event ExitCompleted( uint nodeIndex, uint time, uint gasSpend ); /** * @dev Emitted when a node begins to exit from the network. */ event ExitInitialized( uint nodeIndex, uint startLeavingPeriod, uint time, uint gasSpend ); modifier checkNodeExists(uint nodeIndex) { _checkNodeIndex(nodeIndex); _; } modifier onlyNodeOrNodeManager(uint nodeIndex) { _checkNodeOrNodeManager(nodeIndex, msg.sender); _; } modifier onlyCompliance() { require(hasRole(COMPLIANCE_ROLE, msg.sender), "COMPLIANCE_ROLE is required"); _; } modifier nonZeroIP(bytes4 ip) { require(ip != 0x0 && !nodesIPCheck[ip], "IP address is zero or is not available"); _; } /** * @dev Allows Schains and SchainsInternal contracts to occupy available * space on a node. * * Returns whether operation is successful. */ function removeSpaceFromNode(uint nodeIndex, uint8 space) external checkNodeExists(nodeIndex) allowTwo("NodeRotation", "SchainsInternal") returns (bool) { if (spaceOfNodes[nodeIndex].freeSpace < space) { return false; } if (space > 0) { _moveNodeToNewSpaceMap( nodeIndex, uint(spaceOfNodes[nodeIndex].freeSpace).sub(space).toUint8() ); } return true; } /** * @dev Allows Schains contract to occupy free space on a node. * * Returns whether operation is successful. */ function addSpaceToNode(uint nodeIndex, uint8 space) external checkNodeExists(nodeIndex) allowTwo("Schains", "NodeRotation") { if (space > 0) { _moveNodeToNewSpaceMap( nodeIndex, uint(spaceOfNodes[nodeIndex].freeSpace).add(space).toUint8() ); } } /** * @dev Allows SkaleManager to change a node's last reward date. */ function changeNodeLastRewardDate(uint nodeIndex) external checkNodeExists(nodeIndex) allow("SkaleManager") { nodes[nodeIndex].lastRewardDate = block.timestamp; } /** * @dev Allows SkaleManager to change a node's finish time. */ function changeNodeFinishTime(uint nodeIndex, uint time) external checkNodeExists(nodeIndex) allow("SkaleManager") { nodes[nodeIndex].finishTime = time; } /** * @dev Allows SkaleManager contract to create new node and add it to the * Nodes contract. * * Emits a {NodeCreated} event. * * Requirements: * * - Node IP must be non-zero. * - Node IP must be available. * - Node name must not already be registered. * - Node port must be greater than zero. */ function createNode(address from, NodeCreationParams calldata params) external allow("SkaleManager") nonZeroIP(params.ip) { // checks that Node has correct data require(!nodesNameCheck[keccak256(abi.encodePacked(params.name))], "Name is already registered"); require(params.port > 0, "Port is zero"); require(from == _publicKeyToAddress(params.publicKey), "Public Key is incorrect"); uint validatorId = ValidatorService( contractManager.getContract("ValidatorService")).getValidatorIdByNodeAddress(from); uint8 totalSpace = ConstantsHolder(contractManager.getContract("ConstantsHolder")).TOTAL_SPACE_ON_NODE(); nodes.push(Node({ name: params.name, ip: params.ip, publicIP: params.publicIp, port: params.port, publicKey: params.publicKey, startBlock: block.number, lastRewardDate: block.timestamp, finishTime: 0, status: NodeStatus.Active, validatorId: validatorId })); uint nodeIndex = nodes.length.sub(1); validatorToNodeIndexes[validatorId].push(nodeIndex); bytes32 nodeId = keccak256(abi.encodePacked(params.name)); nodesIPCheck[params.ip] = true; nodesNameCheck[nodeId] = true; nodesNameToIndex[nodeId] = nodeIndex; nodeIndexes[from].isNodeExist[nodeIndex] = true; nodeIndexes[from].numberOfNodes++; domainNames[nodeIndex] = params.domainName; spaceOfNodes.push(SpaceManaging({ freeSpace: totalSpace, indexInSpaceMap: spaceToNodes[totalSpace].length })); _setNodeActive(nodeIndex); emit NodeCreated( nodeIndex, from, params.name, params.ip, params.publicIp, params.port, params.nonce, params.domainName, block.timestamp, gasleft()); } /** * @dev Allows SkaleManager contract to initiate a node exit procedure. * * Returns whether the operation is successful. * * Emits an {ExitInitialized} event. */ function initExit(uint nodeIndex) external checkNodeExists(nodeIndex) allow("SkaleManager") returns (bool) { require(isNodeActive(nodeIndex), "Node should be Active"); _setNodeLeaving(nodeIndex); emit ExitInitialized( nodeIndex, block.timestamp, block.timestamp, gasleft()); return true; } /** * @dev Allows SkaleManager contract to complete a node exit procedure. * * Returns whether the operation is successful. * * Emits an {ExitCompleted} event. * * Requirements: * * - Node must have already initialized a node exit procedure. */ function completeExit(uint nodeIndex) external checkNodeExists(nodeIndex) allow("SkaleManager") returns (bool) { require(isNodeLeaving(nodeIndex), "Node is not Leaving"); _setNodeLeft(nodeIndex); emit ExitCompleted( nodeIndex, block.timestamp, gasleft()); return true; } /** * @dev Allows SkaleManager contract to delete a validator's node. * * Requirements: * * - Validator ID must exist. */ function deleteNodeForValidator(uint validatorId, uint nodeIndex) external checkNodeExists(nodeIndex) allow("SkaleManager") { ValidatorService validatorService = ValidatorService(contractManager.getValidatorService()); require(validatorService.validatorExists(validatorId), "Validator ID does not exist"); uint[] memory validatorNodes = validatorToNodeIndexes[validatorId]; uint position = _findNode(validatorNodes, nodeIndex); if (position < validatorNodes.length) { validatorToNodeIndexes[validatorId][position] = validatorToNodeIndexes[validatorId][validatorNodes.length.sub(1)]; } validatorToNodeIndexes[validatorId].pop(); address nodeOwner = _publicKeyToAddress(nodes[nodeIndex].publicKey); if (validatorService.getValidatorIdByNodeAddress(nodeOwner) == validatorId) { if (nodeIndexes[nodeOwner].numberOfNodes == 1 && !validatorService.validatorAddressExists(nodeOwner)) { validatorService.removeNodeAddress(validatorId, nodeOwner); } nodeIndexes[nodeOwner].isNodeExist[nodeIndex] = false; nodeIndexes[nodeOwner].numberOfNodes--; } } /** * @dev Allows SkaleManager contract to check whether a validator has * sufficient stake to create another node. * * Requirements: * * - Validator must be included on trusted list if trusted list is enabled. * - Validator must have sufficient stake to operate an additional node. */ function checkPossibilityCreatingNode(address nodeAddress) external allow("SkaleManager") { ValidatorService validatorService = ValidatorService(contractManager.getValidatorService()); uint validatorId = validatorService.getValidatorIdByNodeAddress(nodeAddress); require(validatorService.isAuthorizedValidator(validatorId), "Validator is not authorized to create a node"); require( _checkValidatorPositionToMaintainNode(validatorId, validatorToNodeIndexes[validatorId].length), "Validator must meet the Minimum Staking Requirement"); } /** * @dev Allows SkaleManager contract to check whether a validator has * sufficient stake to maintain a node. * * Returns whether validator can maintain node with current stake. * * Requirements: * * - Validator ID and nodeIndex must both exist. */ function checkPossibilityToMaintainNode( uint validatorId, uint nodeIndex ) external checkNodeExists(nodeIndex) allow("Bounty") returns (bool) { ValidatorService validatorService = ValidatorService(contractManager.getValidatorService()); require(validatorService.validatorExists(validatorId), "Validator ID does not exist"); uint[] memory validatorNodes = validatorToNodeIndexes[validatorId]; uint position = _findNode(validatorNodes, nodeIndex); require(position < validatorNodes.length, "Node does not exist for this Validator"); return _checkValidatorPositionToMaintainNode(validatorId, position); } /** * @dev Allows Node to set In_Maintenance status. * * Requirements: * * - Node must already be Active. * - `msg.sender` must be owner of Node, validator, or SkaleManager. */ function setNodeInMaintenance(uint nodeIndex) external onlyNodeOrNodeManager(nodeIndex) { require(nodes[nodeIndex].status == NodeStatus.Active, "Node is not Active"); _setNodeInMaintenance(nodeIndex); } /** * @dev Allows Node to remove In_Maintenance status. * * Requirements: * * - Node must already be In Maintenance. * - `msg.sender` must be owner of Node, validator, or SkaleManager. */ function removeNodeFromInMaintenance(uint nodeIndex) external onlyNodeOrNodeManager(nodeIndex) { require(nodes[nodeIndex].status == NodeStatus.In_Maintenance, "Node is not In Maintenance"); _setNodeActive(nodeIndex); } /** * @dev Marks the node as incompliant * */ function setNodeIncompliant(uint nodeIndex) external onlyCompliance checkNodeExists(nodeIndex) { if (!incompliant[nodeIndex]) { incompliant[nodeIndex] = true; _makeNodeInvisible(nodeIndex); } } /** * @dev Marks the node as compliant * */ function setNodeCompliant(uint nodeIndex) external onlyCompliance checkNodeExists(nodeIndex) { if (incompliant[nodeIndex]) { incompliant[nodeIndex] = false; _tryToMakeNodeVisible(nodeIndex); } } function setDomainName(uint nodeIndex, string memory domainName) external onlyNodeOrNodeManager(nodeIndex) { domainNames[nodeIndex] = domainName; } function makeNodeVisible(uint nodeIndex) external allow("SchainsInternal") { _tryToMakeNodeVisible(nodeIndex); } function makeNodeInvisible(uint nodeIndex) external allow("SchainsInternal") { _makeNodeInvisible(nodeIndex); } function changeIP( uint nodeIndex, bytes4 newIP, bytes4 newPublicIP ) external onlyAdmin checkNodeExists(nodeIndex) nonZeroIP(newIP) { if (newPublicIP != 0x0) { require(newIP == newPublicIP, "IP address is not the same"); nodes[nodeIndex].publicIP = newPublicIP; } nodesIPCheck[nodes[nodeIndex].ip] = false; nodesIPCheck[newIP] = true; nodes[nodeIndex].ip = newIP; } function getRandomNodeWithFreeSpace( uint8 freeSpace, Random.RandomGenerator memory randomGenerator ) external view returns (uint) { uint8 place = _nodesAmountBySpace.getRandomNonZeroElementFromPlaceToLast( freeSpace == 0 ? 1 : freeSpace, randomGenerator ).toUint8(); require(place > 0, "Node not found"); return spaceToNodes[place][randomGenerator.random(spaceToNodes[place].length)]; } /** * @dev Checks whether it is time for a node's reward. */ function isTimeForReward(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (bool) { return BountyV2(contractManager.getBounty()).getNextRewardTimestamp(nodeIndex) <= now; } /** * @dev Returns IP address of a given node. * * Requirements: * * - Node must exist. */ function getNodeIP(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (bytes4) { require(nodeIndex < nodes.length, "Node does not exist"); return nodes[nodeIndex].ip; } /** * @dev Returns domain name of a given node. * * Requirements: * * - Node must exist. */ function getNodeDomainName(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (string memory) { return domainNames[nodeIndex]; } /** * @dev Returns the port of a given node. * * Requirements: * * - Node must exist. */ function getNodePort(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (uint16) { return nodes[nodeIndex].port; } /** * @dev Returns the public key of a given node. */ function getNodePublicKey(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (bytes32[2] memory) { return nodes[nodeIndex].publicKey; } /** * @dev Returns an address of a given node. */ function getNodeAddress(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (address) { return _publicKeyToAddress(nodes[nodeIndex].publicKey); } /** * @dev Returns the finish exit time of a given node. */ function getNodeFinishTime(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (uint) { return nodes[nodeIndex].finishTime; } /** * @dev Checks whether a node has left the network. */ function isNodeLeft(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (bool) { return nodes[nodeIndex].status == NodeStatus.Left; } function isNodeInMaintenance(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (bool) { return nodes[nodeIndex].status == NodeStatus.In_Maintenance; } /** * @dev Returns a given node's last reward date. */ function getNodeLastRewardDate(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (uint) { return nodes[nodeIndex].lastRewardDate; } /** * @dev Returns a given node's next reward date. */ function getNodeNextRewardDate(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (uint) { return BountyV2(contractManager.getBounty()).getNextRewardTimestamp(nodeIndex); } /** * @dev Returns the total number of registered nodes. */ function getNumberOfNodes() external view returns (uint) { return nodes.length; } /** * @dev Returns the total number of online nodes. * * Note: Online nodes are equal to the number of active plus leaving nodes. */ function getNumberOnlineNodes() external view returns (uint) { return numberOfActiveNodes.add(numberOfLeavingNodes); } /** * @dev Return active node IDs. */ function getActiveNodeIds() external view returns (uint[] memory activeNodeIds) { activeNodeIds = new uint[](numberOfActiveNodes); uint indexOfActiveNodeIds = 0; for (uint indexOfNodes = 0; indexOfNodes < nodes.length; indexOfNodes++) { if (isNodeActive(indexOfNodes)) { activeNodeIds[indexOfActiveNodeIds] = indexOfNodes; indexOfActiveNodeIds++; } } } /** * @dev Return a given node's current status. */ function getNodeStatus(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (NodeStatus) { return nodes[nodeIndex].status; } /** * @dev Return a validator's linked nodes. * * Requirements: * * - Validator ID must exist. */ function getValidatorNodeIndexes(uint validatorId) external view returns (uint[] memory) { ValidatorService validatorService = ValidatorService(contractManager.getValidatorService()); require(validatorService.validatorExists(validatorId), "Validator ID does not exist"); return validatorToNodeIndexes[validatorId]; } /** * @dev Returns number of nodes with available space. */ function countNodesWithFreeSpace(uint8 freeSpace) external view returns (uint count) { if (freeSpace == 0) { return _nodesAmountBySpace.sumFromPlaceToLast(1); } return _nodesAmountBySpace.sumFromPlaceToLast(freeSpace); } /** * @dev constructor in Permissions approach. */ function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); numberOfActiveNodes = 0; numberOfLeavingNodes = 0; numberOfLeftNodes = 0; _nodesAmountBySpace.create(128); } /** * @dev Returns the Validator ID for a given node. */ function getValidatorId(uint nodeIndex) public view checkNodeExists(nodeIndex) returns (uint) { return nodes[nodeIndex].validatorId; } /** * @dev Checks whether a node exists for a given address. */ function isNodeExist(address from, uint nodeIndex) public view checkNodeExists(nodeIndex) returns (bool) { return nodeIndexes[from].isNodeExist[nodeIndex]; } /** * @dev Checks whether a node's status is Active. */ function isNodeActive(uint nodeIndex) public view checkNodeExists(nodeIndex) returns (bool) { return nodes[nodeIndex].status == NodeStatus.Active; } /** * @dev Checks whether a node's status is Leaving. */ function isNodeLeaving(uint nodeIndex) public view checkNodeExists(nodeIndex) returns (bool) { return nodes[nodeIndex].status == NodeStatus.Leaving; } function _removeNodeFromSpaceToNodes(uint nodeIndex, uint8 space) internal { uint indexInArray = spaceOfNodes[nodeIndex].indexInSpaceMap; uint len = spaceToNodes[space].length.sub(1); if (indexInArray < len) { uint shiftedIndex = spaceToNodes[space][len]; spaceToNodes[space][indexInArray] = shiftedIndex; spaceOfNodes[shiftedIndex].indexInSpaceMap = indexInArray; } spaceToNodes[space].pop(); delete spaceOfNodes[nodeIndex].indexInSpaceMap; } function _getNodesAmountBySpace() internal view returns (SegmentTree.Tree storage) { return _nodesAmountBySpace; } /** * @dev Returns the index of a given node within the validator's node index. */ function _findNode(uint[] memory validatorNodeIndexes, uint nodeIndex) private pure returns (uint) { uint i; for (i = 0; i < validatorNodeIndexes.length; i++) { if (validatorNodeIndexes[i] == nodeIndex) { return i; } } return validatorNodeIndexes.length; } /** * @dev Moves a node to a new space mapping. */ function _moveNodeToNewSpaceMap(uint nodeIndex, uint8 newSpace) private { if (!_invisible[nodeIndex]) { uint8 space = spaceOfNodes[nodeIndex].freeSpace; _removeNodeFromTree(space); _addNodeToTree(newSpace); _removeNodeFromSpaceToNodes(nodeIndex, space); _addNodeToSpaceToNodes(nodeIndex, newSpace); } spaceOfNodes[nodeIndex].freeSpace = newSpace; } /** * @dev Changes a node's status to Active. */ function _setNodeActive(uint nodeIndex) private { nodes[nodeIndex].status = NodeStatus.Active; numberOfActiveNodes = numberOfActiveNodes.add(1); if (_invisible[nodeIndex]) { _tryToMakeNodeVisible(nodeIndex); } else { uint8 space = spaceOfNodes[nodeIndex].freeSpace; _addNodeToSpaceToNodes(nodeIndex, space); _addNodeToTree(space); } } /** * @dev Changes a node's status to In_Maintenance. */ function _setNodeInMaintenance(uint nodeIndex) private { nodes[nodeIndex].status = NodeStatus.In_Maintenance; numberOfActiveNodes = numberOfActiveNodes.sub(1); _makeNodeInvisible(nodeIndex); } /** * @dev Changes a node's status to Left. */ function _setNodeLeft(uint nodeIndex) private { nodesIPCheck[nodes[nodeIndex].ip] = false; nodesNameCheck[keccak256(abi.encodePacked(nodes[nodeIndex].name))] = false; delete nodesNameToIndex[keccak256(abi.encodePacked(nodes[nodeIndex].name))]; if (nodes[nodeIndex].status == NodeStatus.Active) { numberOfActiveNodes--; } else { numberOfLeavingNodes--; } nodes[nodeIndex].status = NodeStatus.Left; numberOfLeftNodes++; delete spaceOfNodes[nodeIndex].freeSpace; } /** * @dev Changes a node's status to Leaving. */ function _setNodeLeaving(uint nodeIndex) private { nodes[nodeIndex].status = NodeStatus.Leaving; numberOfActiveNodes--; numberOfLeavingNodes++; _makeNodeInvisible(nodeIndex); } function _makeNodeInvisible(uint nodeIndex) private { if (!_invisible[nodeIndex]) { uint8 space = spaceOfNodes[nodeIndex].freeSpace; _removeNodeFromSpaceToNodes(nodeIndex, space); _removeNodeFromTree(space); _invisible[nodeIndex] = true; } } function _tryToMakeNodeVisible(uint nodeIndex) private { if (_invisible[nodeIndex] && _canBeVisible(nodeIndex)) { _makeNodeVisible(nodeIndex); } } function _makeNodeVisible(uint nodeIndex) private { if (_invisible[nodeIndex]) { uint8 space = spaceOfNodes[nodeIndex].freeSpace; _addNodeToSpaceToNodes(nodeIndex, space); _addNodeToTree(space); delete _invisible[nodeIndex]; } } function _addNodeToSpaceToNodes(uint nodeIndex, uint8 space) private { spaceToNodes[space].push(nodeIndex); spaceOfNodes[nodeIndex].indexInSpaceMap = spaceToNodes[space].length.sub(1); } function _addNodeToTree(uint8 space) private { if (space > 0) { _nodesAmountBySpace.addToPlace(space, 1); } } function _removeNodeFromTree(uint8 space) private { if (space > 0) { _nodesAmountBySpace.removeFromPlace(space, 1); } } function _checkValidatorPositionToMaintainNode(uint validatorId, uint position) private returns (bool) { DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController") ); uint delegationsTotal = delegationController.getAndUpdateDelegatedToValidatorNow(validatorId); uint msr = ConstantsHolder(contractManager.getConstantsHolder()).msr(); return position.add(1).mul(msr) <= delegationsTotal; } function _checkNodeIndex(uint nodeIndex) private view { require(nodeIndex < nodes.length, "Node with such index does not exist"); } function _checkNodeOrNodeManager(uint nodeIndex, address sender) private view { ValidatorService validatorService = ValidatorService(contractManager.getValidatorService()); require( isNodeExist(sender, nodeIndex) || hasRole(NODE_MANAGER_ROLE, msg.sender) || getValidatorId(nodeIndex) == validatorService.getValidatorId(sender), "Sender is not permitted to call this function" ); } function _publicKeyToAddress(bytes32[2] memory pubKey) private pure returns (address) { bytes32 hash = keccak256(abi.encodePacked(pubKey[0], pubKey[1])); bytes20 addr; for (uint8 i = 12; i < 32; i++) { addr |= bytes20(hash[i] & 0xFF) >> ((i - 12) * 8); } return address(addr); } function _canBeVisible(uint nodeIndex) private view returns (bool) { return !incompliant[nodeIndex] && nodes[nodeIndex].status == NodeStatus.Active; } } // SPDX-License-Identifier: AGPL-3.0-only /* Permissions.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/access/AccessControl.sol"; import "./ContractManager.sol"; /** * @title Permissions * @dev Contract is connected module for Upgradeable approach, knows ContractManager */ contract Permissions is AccessControlUpgradeSafe { using SafeMath for uint; using Address for address; ContractManager public contractManager; /** * @dev Modifier to make a function callable only when caller is the Owner. * * Requirements: * * - The caller must be the owner. */ modifier onlyOwner() { require(_isOwner(), "Caller is not the owner"); _; } /** * @dev Modifier to make a function callable only when caller is an Admin. * * Requirements: * * - The caller must be an admin. */ modifier onlyAdmin() { require(_isAdmin(msg.sender), "Caller is not an admin"); _; } /** * @dev Modifier to make a function callable only when caller is the Owner * or `contractName` contract. * * Requirements: * * - The caller must be the owner or `contractName`. */ modifier allow(string memory contractName) { require( contractManager.getContract(contractName) == msg.sender || _isOwner(), "Message sender is invalid"); _; } /** * @dev Modifier to make a function callable only when caller is the Owner * or `contractName1` or `contractName2` contract. * * Requirements: * * - The caller must be the owner, `contractName1`, or `contractName2`. */ modifier allowTwo(string memory contractName1, string memory contractName2) { require( contractManager.getContract(contractName1) == msg.sender || contractManager.getContract(contractName2) == msg.sender || _isOwner(), "Message sender is invalid"); _; } /** * @dev Modifier to make a function callable only when caller is the Owner * or `contractName1`, `contractName2`, or `contractName3` contract. * * Requirements: * * - The caller must be the owner, `contractName1`, `contractName2`, or * `contractName3`. */ modifier allowThree(string memory contractName1, string memory contractName2, string memory contractName3) { require( contractManager.getContract(contractName1) == msg.sender || contractManager.getContract(contractName2) == msg.sender || contractManager.getContract(contractName3) == msg.sender || _isOwner(), "Message sender is invalid"); _; } function initialize(address contractManagerAddress) public virtual initializer { AccessControlUpgradeSafe.__AccessControl_init(); _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setContractManager(contractManagerAddress); } function _isOwner() internal view returns (bool) { return hasRole(DEFAULT_ADMIN_ROLE, msg.sender); } function _isAdmin(address account) internal view returns (bool) { address skaleManagerAddress = contractManager.contracts(keccak256(abi.encodePacked("SkaleManager"))); if (skaleManagerAddress != address(0)) { AccessControlUpgradeSafe skaleManager = AccessControlUpgradeSafe(skaleManagerAddress); return skaleManager.hasRole(keccak256("ADMIN_ROLE"), account) || _isOwner(); } else { return _isOwner(); } } function _setContractManager(address contractManagerAddress) private { require(contractManagerAddress != address(0), "ContractManager address is not set"); require(contractManagerAddress.isContract(), "Address is not contract"); contractManager = ContractManager(contractManagerAddress); } } pragma solidity ^0.6.0; /** * @dev Interface of the ERC777Token standard as defined in the EIP. * * This contract uses the * https://eips.ethereum.org/EIPS/eip-1820[ERC1820 registry standard] to let * token holders and recipients react to token movements by using setting implementers * for the associated interfaces in said registry. See {IERC1820Registry} and * {ERC1820Implementer}. */ interface IERC777 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() external view returns (string memory); /** * @dev Returns the smallest part of the token that is not divisible. This * means all token operations (creation, movement and destruction) must have * amounts that are a multiple of this number. * * For most token contracts, this value will equal 1. */ function granularity() external view returns (uint256); /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by an account (`owner`). */ function balanceOf(address owner) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * If send or receive hooks are registered for the caller and `recipient`, * the corresponding functions will be called with `data` and empty * `operatorData`. See {IERC777Sender} and {IERC777Recipient}. * * Emits a {Sent} event. * * Requirements * * - the caller must have at least `amount` tokens. * - `recipient` cannot be the zero address. * - if `recipient` is a contract, it must implement the {IERC777Recipient} * interface. */ function send(address recipient, uint256 amount, bytes calldata data) external; /** * @dev Destroys `amount` tokens from the caller's account, reducing the * total supply. * * If a send hook is registered for the caller, the corresponding function * will be called with `data` and empty `operatorData`. See {IERC777Sender}. * * Emits a {Burned} event. * * Requirements * * - the caller must have at least `amount` tokens. */ function burn(uint256 amount, bytes calldata data) external; /** * @dev Returns true if an account is an operator of `tokenHolder`. * Operators can send and burn tokens on behalf of their owners. All * accounts are their own operator. * * See {operatorSend} and {operatorBurn}. */ function isOperatorFor(address operator, address tokenHolder) external view returns (bool); /** * @dev Make an account an operator of the caller. * * See {isOperatorFor}. * * Emits an {AuthorizedOperator} event. * * Requirements * * - `operator` cannot be calling address. */ function authorizeOperator(address operator) external; /** * @dev Revoke an account's operator status for the caller. * * See {isOperatorFor} and {defaultOperators}. * * Emits a {RevokedOperator} event. * * Requirements * * - `operator` cannot be calling address. */ function revokeOperator(address operator) external; /** * @dev Returns the list of default operators. These accounts are operators * for all token holders, even if {authorizeOperator} was never called on * them. * * This list is immutable, but individual holders may revoke these via * {revokeOperator}, in which case {isOperatorFor} will return false. */ function defaultOperators() external view returns (address[] memory); /** * @dev Moves `amount` tokens from `sender` to `recipient`. The caller must * be an operator of `sender`. * * If send or receive hooks are registered for `sender` and `recipient`, * the corresponding functions will be called with `data` and * `operatorData`. See {IERC777Sender} and {IERC777Recipient}. * * Emits a {Sent} event. * * Requirements * * - `sender` cannot be the zero address. * - `sender` must have at least `amount` tokens. * - the caller must be an operator for `sender`. * - `recipient` cannot be the zero address. * - if `recipient` is a contract, it must implement the {IERC777Recipient} * interface. */ function operatorSend( address sender, address recipient, uint256 amount, bytes calldata data, bytes calldata operatorData ) external; /** * @dev Destroys `amount` tokens from `account`, reducing the total supply. * The caller must be an operator of `account`. * * If a send hook is registered for `account`, the corresponding function * will be called with `data` and `operatorData`. See {IERC777Sender}. * * Emits a {Burned} event. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. * - the caller must be an operator for `account`. */ function operatorBurn( address account, uint256 amount, bytes calldata data, bytes calldata operatorData ) external; event Sent( address indexed operator, address indexed from, address indexed to, uint256 amount, bytes data, bytes operatorData ); event Minted(address indexed operator, address indexed to, uint256 amount, bytes data, bytes operatorData); event Burned(address indexed operator, address indexed from, uint256 amount, bytes data, bytes operatorData); event AuthorizedOperator(address indexed operator, address indexed tokenHolder); event RevokedOperator(address indexed operator, address indexed tokenHolder); } // SPDX-License-Identifier: AGPL-3.0-only /* FractionUtils.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; library FractionUtils { using SafeMath for uint; struct Fraction { uint numerator; uint denominator; } function createFraction(uint numerator, uint denominator) internal pure returns (Fraction memory) { require(denominator > 0, "Division by zero"); Fraction memory fraction = Fraction({numerator: numerator, denominator: denominator}); reduceFraction(fraction); return fraction; } function createFraction(uint value) internal pure returns (Fraction memory) { return createFraction(value, 1); } function reduceFraction(Fraction memory fraction) internal pure { uint _gcd = gcd(fraction.numerator, fraction.denominator); fraction.numerator = fraction.numerator.div(_gcd); fraction.denominator = fraction.denominator.div(_gcd); } // numerator - is limited by 7*10^27, we could multiply it numerator * numerator - it would less than 2^256-1 function multiplyFraction(Fraction memory a, Fraction memory b) internal pure returns (Fraction memory) { return createFraction(a.numerator.mul(b.numerator), a.denominator.mul(b.denominator)); } function gcd(uint a, uint b) internal pure returns (uint) { uint _a = a; uint _b = b; if (_b > _a) { (_a, _b) = swap(_a, _b); } while (_b > 0) { _a = _a.mod(_b); (_a, _b) = swap (_a, _b); } return _a; } function swap(uint a, uint b) internal pure returns (uint, uint) { return (b, a); } } // SPDX-License-Identifier: AGPL-3.0-only /* MathUtils.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; library MathUtils { uint constant private _EPS = 1e6; event UnderflowError( uint a, uint b ); function boundedSub(uint256 a, uint256 b) internal returns (uint256) { if (a >= b) { return a - b; } else { emit UnderflowError(a, b); return 0; } } function boundedSubWithoutEvent(uint256 a, uint256 b) internal pure returns (uint256) { if (a >= b) { return a - b; } else { return 0; } } function muchGreater(uint256 a, uint256 b) internal pure returns (bool) { assert(uint(-1) - _EPS > b); return a > b + _EPS; } function approximatelyEqual(uint256 a, uint256 b) internal pure returns (bool) { if (a > b) { return a - b < _EPS; } else { return b - a < _EPS; } } } // SPDX-License-Identifier: AGPL-3.0-only /* DelegationPeriodManager.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "../Permissions.sol"; import "../ConstantsHolder.sol"; /** * @title Delegation Period Manager * @dev This contract handles all delegation offerings. Delegations are held for * a specified period (months), and different durations can have different * returns or `stakeMultiplier`. Currently, only delegation periods can be added. */ contract DelegationPeriodManager is Permissions { mapping (uint => uint) public stakeMultipliers; bytes32 public constant DELEGATION_PERIOD_SETTER_ROLE = keccak256("DELEGATION_PERIOD_SETTER_ROLE"); /** * @dev Emitted when a new delegation period is specified. */ event DelegationPeriodWasSet( uint length, uint stakeMultiplier ); /** * @dev Allows the Owner to create a new available delegation period and * stake multiplier in the network. * * Emits a {DelegationPeriodWasSet} event. */ function setDelegationPeriod(uint monthsCount, uint stakeMultiplier) external { require(hasRole(DELEGATION_PERIOD_SETTER_ROLE, msg.sender), "DELEGATION_PERIOD_SETTER_ROLE is required"); require(stakeMultipliers[monthsCount] == 0, "Delegation period is already set"); stakeMultipliers[monthsCount] = stakeMultiplier; emit DelegationPeriodWasSet(monthsCount, stakeMultiplier); } /** * @dev Checks whether given delegation period is allowed. */ function isDelegationPeriodAllowed(uint monthsCount) external view returns (bool) { return stakeMultipliers[monthsCount] != 0; } /** * @dev Initial delegation period and multiplier settings. */ function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); stakeMultipliers[2] = 100; // 2 months at 100 // stakeMultipliers[6] = 150; // 6 months at 150 // stakeMultipliers[12] = 200; // 12 months at 200 } } // SPDX-License-Identifier: AGPL-3.0-only /* Punisher.sol - SKALE Manager Copyright (C) 2019-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "../Permissions.sol"; import "../interfaces/delegation/ILocker.sol"; import "./ValidatorService.sol"; import "./DelegationController.sol"; /** * @title Punisher * @dev This contract handles all slashing and forgiving operations. */ contract Punisher is Permissions, ILocker { // holder => tokens mapping (address => uint) private _locked; bytes32 public constant FORGIVER_ROLE = keccak256("FORGIVER_ROLE"); /** * @dev Emitted upon slashing condition. */ event Slash( uint validatorId, uint amount ); /** * @dev Emitted upon forgive condition. */ event Forgive( address wallet, uint amount ); /** * @dev Allows SkaleDKG contract to execute slashing on a validator and * validator's delegations by an `amount` of tokens. * * Emits a {Slash} event. * * Requirements: * * - Validator must exist. */ function slash(uint validatorId, uint amount) external allow("SkaleDKG") { ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController")); require(validatorService.validatorExists(validatorId), "Validator does not exist"); delegationController.confiscate(validatorId, amount); emit Slash(validatorId, amount); } /** * @dev Allows the Admin to forgive a slashing condition. * * Emits a {Forgive} event. * * Requirements: * * - All slashes must have been processed. */ function forgive(address holder, uint amount) external { require(hasRole(FORGIVER_ROLE, msg.sender), "FORGIVER_ROLE is required"); DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController")); require(!delegationController.hasUnprocessedSlashes(holder), "Not all slashes were calculated"); if (amount > _locked[holder]) { delete _locked[holder]; } else { _locked[holder] = _locked[holder].sub(amount); } emit Forgive(holder, amount); } /** * @dev See {ILocker-getAndUpdateLockedAmount}. */ function getAndUpdateLockedAmount(address wallet) external override returns (uint) { return _getAndUpdateLockedAmount(wallet); } /** * @dev See {ILocker-getAndUpdateForbiddenForDelegationAmount}. */ function getAndUpdateForbiddenForDelegationAmount(address wallet) external override returns (uint) { return _getAndUpdateLockedAmount(wallet); } /** * @dev Allows DelegationController contract to execute slashing of * delegations. */ function handleSlash(address holder, uint amount) external allow("DelegationController") { _locked[holder] = _locked[holder].add(amount); } function initialize(address contractManagerAddress) public override initializer { Permissions.initialize(contractManagerAddress); } // private /** * @dev See {ILocker-getAndUpdateLockedAmount}. */ function _getAndUpdateLockedAmount(address wallet) private returns (uint) { DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController")); delegationController.processAllSlashes(wallet); return _locked[wallet]; } } // SPDX-License-Identifier: AGPL-3.0-only /* TokenState.sol - SKALE Manager Copyright (C) 2019-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "../interfaces/delegation/ILocker.sol"; import "../Permissions.sol"; import "./DelegationController.sol"; import "./TimeHelpers.sol"; /** * @title Token State * @dev This contract manages lockers to control token transferability. * * The SKALE Network has three types of locked tokens: * * - Tokens that are transferrable but are currently locked into delegation with * a validator. * * - Tokens that are not transferable from one address to another, but may be * delegated to a validator `getAndUpdateLockedAmount`. This lock enforces * Proof-of-Use requirements. * * - Tokens that are neither transferable nor delegatable * `getAndUpdateForbiddenForDelegationAmount`. This lock enforces slashing. */ contract TokenState is Permissions, ILocker { string[] private _lockers; DelegationController private _delegationController; bytes32 public constant LOCKER_MANAGER_ROLE = keccak256("LOCKER_MANAGER_ROLE"); modifier onlyLockerManager() { require(hasRole(LOCKER_MANAGER_ROLE, msg.sender), "LOCKER_MANAGER_ROLE is required"); _; } /** * @dev Emitted when a contract is added to the locker. */ event LockerWasAdded( string locker ); /** * @dev Emitted when a contract is removed from the locker. */ event LockerWasRemoved( string locker ); /** * @dev See {ILocker-getAndUpdateLockedAmount}. */ function getAndUpdateLockedAmount(address holder) external override returns (uint) { if (address(_delegationController) == address(0)) { _delegationController = DelegationController(contractManager.getContract("DelegationController")); } uint locked = 0; if (_delegationController.getDelegationsByHolderLength(holder) > 0) { // the holder ever delegated for (uint i = 0; i < _lockers.length; ++i) { ILocker locker = ILocker(contractManager.getContract(_lockers[i])); locked = locked.add(locker.getAndUpdateLockedAmount(holder)); } } return locked; } /** * @dev See {ILocker-getAndUpdateForbiddenForDelegationAmount}. */ function getAndUpdateForbiddenForDelegationAmount(address holder) external override returns (uint amount) { uint forbidden = 0; for (uint i = 0; i < _lockers.length; ++i) { ILocker locker = ILocker(contractManager.getContract(_lockers[i])); forbidden = forbidden.add(locker.getAndUpdateForbiddenForDelegationAmount(holder)); } return forbidden; } /** * @dev Allows the Owner to remove a contract from the locker. * * Emits a {LockerWasRemoved} event. */ function removeLocker(string calldata locker) external onlyLockerManager { uint index; bytes32 hash = keccak256(abi.encodePacked(locker)); for (index = 0; index < _lockers.length; ++index) { if (keccak256(abi.encodePacked(_lockers[index])) == hash) { break; } } if (index < _lockers.length) { if (index < _lockers.length.sub(1)) { _lockers[index] = _lockers[_lockers.length.sub(1)]; } delete _lockers[_lockers.length.sub(1)]; _lockers.pop(); emit LockerWasRemoved(locker); } } function initialize(address contractManagerAddress) public override initializer { Permissions.initialize(contractManagerAddress); _setupRole(LOCKER_MANAGER_ROLE, msg.sender); addLocker("DelegationController"); addLocker("Punisher"); } /** * @dev Allows the Owner to add a contract to the Locker. * * Emits a {LockerWasAdded} event. */ function addLocker(string memory locker) public onlyLockerManager { _lockers.push(locker); emit LockerWasAdded(locker); } } 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) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } pragma solidity ^0.6.0; // ---------------------------------------------------------------------------- // BokkyPooBah's DateTime Library v1.01 // // A gas-efficient Solidity date and time library // // https://github.com/bokkypoobah/BokkyPooBahsDateTimeLibrary // // Tested date range 1970/01/01 to 2345/12/31 // // Conventions: // Unit | Range | Notes // :-------- |:-------------:|:----- // timestamp | >= 0 | Unix timestamp, number of seconds since 1970/01/01 00:00:00 UTC // year | 1970 ... 2345 | // month | 1 ... 12 | // day | 1 ... 31 | // hour | 0 ... 23 | // minute | 0 ... 59 | // second | 0 ... 59 | // dayOfWeek | 1 ... 7 | 1 = Monday, ..., 7 = Sunday // // // Enjoy. (c) BokkyPooBah / Bok Consulting Pty Ltd 2018-2019. The MIT Licence. // ---------------------------------------------------------------------------- library BokkyPooBahsDateTimeLibrary { uint constant SECONDS_PER_DAY = 24 * 60 * 60; uint constant SECONDS_PER_HOUR = 60 * 60; uint constant SECONDS_PER_MINUTE = 60; int constant OFFSET19700101 = 2440588; uint constant DOW_MON = 1; uint constant DOW_TUE = 2; uint constant DOW_WED = 3; uint constant DOW_THU = 4; uint constant DOW_FRI = 5; uint constant DOW_SAT = 6; uint constant DOW_SUN = 7; // ------------------------------------------------------------------------ // Calculate the number of days from 1970/01/01 to year/month/day using // the date conversion algorithm from // http://aa.usno.navy.mil/faq/docs/JD_Formula.php // and subtracting the offset 2440588 so that 1970/01/01 is day 0 // // days = day // - 32075 // + 1461 * (year + 4800 + (month - 14) / 12) / 4 // + 367 * (month - 2 - (month - 14) / 12 * 12) / 12 // - 3 * ((year + 4900 + (month - 14) / 12) / 100) / 4 // - offset // ------------------------------------------------------------------------ function _daysFromDate(uint year, uint month, uint day) internal pure returns (uint _days) { require(year >= 1970); int _year = int(year); int _month = int(month); int _day = int(day); int __days = _day - 32075 + 1461 * (_year + 4800 + (_month - 14) / 12) / 4 + 367 * (_month - 2 - (_month - 14) / 12 * 12) / 12 - 3 * ((_year + 4900 + (_month - 14) / 12) / 100) / 4 - OFFSET19700101; _days = uint(__days); } // ------------------------------------------------------------------------ // Calculate year/month/day from the number of days since 1970/01/01 using // the date conversion algorithm from // http://aa.usno.navy.mil/faq/docs/JD_Formula.php // and adding the offset 2440588 so that 1970/01/01 is day 0 // // int L = days + 68569 + offset // int N = 4 * L / 146097 // L = L - (146097 * N + 3) / 4 // year = 4000 * (L + 1) / 1461001 // L = L - 1461 * year / 4 + 31 // month = 80 * L / 2447 // dd = L - 2447 * month / 80 // L = month / 11 // month = month + 2 - 12 * L // year = 100 * (N - 49) + year + L // ------------------------------------------------------------------------ function _daysToDate(uint _days) internal pure returns (uint year, uint month, uint day) { int __days = int(_days); int L = __days + 68569 + OFFSET19700101; int N = 4 * L / 146097; L = L - (146097 * N + 3) / 4; int _year = 4000 * (L + 1) / 1461001; L = L - 1461 * _year / 4 + 31; int _month = 80 * L / 2447; int _day = L - 2447 * _month / 80; L = _month / 11; _month = _month + 2 - 12 * L; _year = 100 * (N - 49) + _year + L; year = uint(_year); month = uint(_month); day = uint(_day); } function timestampFromDate(uint year, uint month, uint day) internal pure returns (uint timestamp) { timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY; } function timestampFromDateTime(uint year, uint month, uint day, uint hour, uint minute, uint second) internal pure returns (uint timestamp) { timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + hour * SECONDS_PER_HOUR + minute * SECONDS_PER_MINUTE + second; } function timestampToDate(uint timestamp) internal pure returns (uint year, uint month, uint day) { (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function timestampToDateTime(uint timestamp) internal pure returns (uint year, uint month, uint day, uint hour, uint minute, uint second) { (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); uint secs = timestamp % SECONDS_PER_DAY; hour = secs / SECONDS_PER_HOUR; secs = secs % SECONDS_PER_HOUR; minute = secs / SECONDS_PER_MINUTE; second = secs % SECONDS_PER_MINUTE; } function isValidDate(uint year, uint month, uint day) internal pure returns (bool valid) { if (year >= 1970 && month > 0 && month <= 12) { uint daysInMonth = _getDaysInMonth(year, month); if (day > 0 && day <= daysInMonth) { valid = true; } } } function isValidDateTime(uint year, uint month, uint day, uint hour, uint minute, uint second) internal pure returns (bool valid) { if (isValidDate(year, month, day)) { if (hour < 24 && minute < 60 && second < 60) { valid = true; } } } function isLeapYear(uint timestamp) internal pure returns (bool leapYear) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); leapYear = _isLeapYear(year); } function _isLeapYear(uint year) internal pure returns (bool leapYear) { leapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0); } function isWeekDay(uint timestamp) internal pure returns (bool weekDay) { weekDay = getDayOfWeek(timestamp) <= DOW_FRI; } function isWeekEnd(uint timestamp) internal pure returns (bool weekEnd) { weekEnd = getDayOfWeek(timestamp) >= DOW_SAT; } function getDaysInMonth(uint timestamp) internal pure returns (uint daysInMonth) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); daysInMonth = _getDaysInMonth(year, month); } function _getDaysInMonth(uint year, uint month) internal pure returns (uint daysInMonth) { if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) { daysInMonth = 31; } else if (month != 2) { daysInMonth = 30; } else { daysInMonth = _isLeapYear(year) ? 29 : 28; } } // 1 = Monday, 7 = Sunday function getDayOfWeek(uint timestamp) internal pure returns (uint dayOfWeek) { uint _days = timestamp / SECONDS_PER_DAY; dayOfWeek = (_days + 3) % 7 + 1; } function getYear(uint timestamp) internal pure returns (uint year) { uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getMonth(uint timestamp) internal pure returns (uint month) { uint year; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getDay(uint timestamp) internal pure returns (uint day) { uint year; uint month; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getHour(uint timestamp) internal pure returns (uint hour) { uint secs = timestamp % SECONDS_PER_DAY; hour = secs / SECONDS_PER_HOUR; } function getMinute(uint timestamp) internal pure returns (uint minute) { uint secs = timestamp % SECONDS_PER_HOUR; minute = secs / SECONDS_PER_MINUTE; } function getSecond(uint timestamp) internal pure returns (uint second) { second = timestamp % SECONDS_PER_MINUTE; } function addYears(uint timestamp, uint _years) internal pure returns (uint newTimestamp) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); year += _years; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp >= timestamp); } function addMonths(uint timestamp, uint _months) internal pure returns (uint newTimestamp) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); month += _months; year += (month - 1) / 12; month = (month - 1) % 12 + 1; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp >= timestamp); } function addDays(uint timestamp, uint _days) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _days * SECONDS_PER_DAY; require(newTimestamp >= timestamp); } function addHours(uint timestamp, uint _hours) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _hours * SECONDS_PER_HOUR; require(newTimestamp >= timestamp); } function addMinutes(uint timestamp, uint _minutes) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _minutes * SECONDS_PER_MINUTE; require(newTimestamp >= timestamp); } function addSeconds(uint timestamp, uint _seconds) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _seconds; require(newTimestamp >= timestamp); } function subYears(uint timestamp, uint _years) internal pure returns (uint newTimestamp) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); year -= _years; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp <= timestamp); } function subMonths(uint timestamp, uint _months) internal pure returns (uint newTimestamp) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); uint yearMonth = year * 12 + (month - 1) - _months; year = yearMonth / 12; month = yearMonth % 12 + 1; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp <= timestamp); } function subDays(uint timestamp, uint _days) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _days * SECONDS_PER_DAY; require(newTimestamp <= timestamp); } function subHours(uint timestamp, uint _hours) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _hours * SECONDS_PER_HOUR; require(newTimestamp <= timestamp); } function subMinutes(uint timestamp, uint _minutes) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _minutes * SECONDS_PER_MINUTE; require(newTimestamp <= timestamp); } function subSeconds(uint timestamp, uint _seconds) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _seconds; require(newTimestamp <= timestamp); } function diffYears(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _years) { require(fromTimestamp <= toTimestamp); uint fromYear; uint fromMonth; uint fromDay; uint toYear; uint toMonth; uint toDay; (fromYear, fromMonth, fromDay) = _daysToDate(fromTimestamp / SECONDS_PER_DAY); (toYear, toMonth, toDay) = _daysToDate(toTimestamp / SECONDS_PER_DAY); _years = toYear - fromYear; } function diffMonths(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _months) { require(fromTimestamp <= toTimestamp); uint fromYear; uint fromMonth; uint fromDay; uint toYear; uint toMonth; uint toDay; (fromYear, fromMonth, fromDay) = _daysToDate(fromTimestamp / SECONDS_PER_DAY); (toYear, toMonth, toDay) = _daysToDate(toTimestamp / SECONDS_PER_DAY); _months = toYear * 12 + toMonth - fromYear * 12 - fromMonth; } function diffDays(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _days) { require(fromTimestamp <= toTimestamp); _days = (toTimestamp - fromTimestamp) / SECONDS_PER_DAY; } function diffHours(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _hours) { require(fromTimestamp <= toTimestamp); _hours = (toTimestamp - fromTimestamp) / SECONDS_PER_HOUR; } function diffMinutes(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _minutes) { require(fromTimestamp <= toTimestamp); _minutes = (toTimestamp - fromTimestamp) / SECONDS_PER_MINUTE; } function diffSeconds(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _seconds) { require(fromTimestamp <= toTimestamp); _seconds = toTimestamp - fromTimestamp; } } pragma solidity ^0.6.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))) } // 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. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { revert("ECDSA: invalid signature 's' value"); } if (v != 27 && v != 28) { revert("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)); } } pragma solidity ^0.6.0; import "../utils/EnumerableSet.sol"; import "../utils/Address.sol"; import "../GSN/Context.sol"; import "../Initializable.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, _msgSender())); * ... * } * ``` * * 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}. */ abstract contract AccessControlUpgradeSafe is Initializable, ContextUpgradeSafe { function __AccessControl_init() internal initializer { __Context_init_unchained(); __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal initializer { } 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 `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. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { _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()); } } uint256[49] private __gap; } // SPDX-License-Identifier: AGPL-3.0-only /* ContractManager.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/access/Ownable.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/utils/Address.sol"; import "@skalenetwork/skale-manager-interfaces/IContractManager.sol"; import "./utils/StringUtils.sol"; /** * @title ContractManager * @dev Contract contains the actual current mapping from contract IDs * (in the form of human-readable strings) to addresses. */ contract ContractManager is OwnableUpgradeSafe, IContractManager { using StringUtils for string; using Address for address; string public constant BOUNTY = "Bounty"; string public constant CONSTANTS_HOLDER = "ConstantsHolder"; string public constant DELEGATION_PERIOD_MANAGER = "DelegationPeriodManager"; string public constant PUNISHER = "Punisher"; string public constant SKALE_TOKEN = "SkaleToken"; string public constant TIME_HELPERS = "TimeHelpers"; string public constant TOKEN_STATE = "TokenState"; string public constant VALIDATOR_SERVICE = "ValidatorService"; // mapping of actual smart contracts addresses mapping (bytes32 => address) public contracts; /** * @dev Emitted when contract is upgraded. */ event ContractUpgraded(string contractsName, address contractsAddress); function initialize() external initializer { OwnableUpgradeSafe.__Ownable_init(); } /** * @dev Allows the Owner to add contract to mapping of contract addresses. * * Emits a {ContractUpgraded} event. * * Requirements: * * - New address is non-zero. * - Contract is not already added. * - Contract address contains code. */ function setContractsAddress( string calldata contractsName, address newContractsAddress ) external override onlyOwner { // check newContractsAddress is not equal to zero require(newContractsAddress != address(0), "New address is equal zero"); // create hash of contractsName bytes32 contractId = keccak256(abi.encodePacked(contractsName)); // check newContractsAddress is not equal the previous contract's address require(contracts[contractId] != newContractsAddress, "Contract is already added"); require(newContractsAddress.isContract(), "Given contract address does not contain code"); // add newContractsAddress to mapping of actual contract addresses contracts[contractId] = newContractsAddress; emit ContractUpgraded(contractsName, newContractsAddress); } /** * @dev Returns contract address. * * Requirements: * * - Contract must exist. */ function getDelegationPeriodManager() external view returns (address) { return getContract(DELEGATION_PERIOD_MANAGER); } function getBounty() external view returns (address) { return getContract(BOUNTY); } function getValidatorService() external view returns (address) { return getContract(VALIDATOR_SERVICE); } function getTimeHelpers() external view returns (address) { return getContract(TIME_HELPERS); } function getConstantsHolder() external view returns (address) { return getContract(CONSTANTS_HOLDER); } function getSkaleToken() external view returns (address) { return getContract(SKALE_TOKEN); } function getTokenState() external view returns (address) { return getContract(TOKEN_STATE); } function getPunisher() external view returns (address) { return getContract(PUNISHER); } function getContract(string memory name) public view override returns (address contractAddress) { contractAddress = contracts[keccak256(abi.encodePacked(name))]; if (contractAddress == address(0)) { revert(name.strConcat(" contract has not been found")); } } } 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.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"); } } pragma solidity ^0.6.0; import "../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 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. */ contract ContextUpgradeSafe is Initializable { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } 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; } uint256[50] private __gap; } pragma solidity >=0.4.24 <0.7.0; /** * @title Initializable * * @dev Helper contract to support initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. */ 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; } pragma solidity ^0.6.0; import "../GSN/Context.sol"; import "../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. */ contract OwnableUpgradeSafe is Initializable, ContextUpgradeSafe { 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 initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { 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; } uint256[49] private __gap; } // SPDX-License-Identifier: AGPL-3.0-only /* IContractManager.sol - SKALE Manager Interfaces Copyright (C) 2021-Present SKALE Labs @author Dmytro Stebaeiv SKALE Manager Interfaces is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager Interfaces is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager Interfaces. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity >=0.6.10 <0.9.0; interface IContractManager { function setContractsAddress(string calldata contractsName, address newContractsAddress) external; function getContract(string calldata name) external view returns (address); } // SPDX-License-Identifier: AGPL-3.0-only /* StringUtils.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; library StringUtils { using SafeMath for uint; function strConcat(string memory a, string memory b) internal pure returns (string memory) { bytes memory _ba = bytes(a); bytes memory _bb = bytes(b); string memory ab = new string(_ba.length.add(_bb.length)); bytes memory strBytes = bytes(ab); uint k = 0; uint i = 0; for (i = 0; i < _ba.length; i++) { strBytes[k++] = _ba[i]; } for (i = 0; i < _bb.length; i++) { strBytes[k++] = _bb[i]; } return string(strBytes); } } pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's uintXX casting operators with added overflow * checks. * * Downcasting from uint256 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} to extend it to smaller types, by performing * all math on `uint256` and then downcasting. */ 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 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); } } // SPDX-License-Identifier: AGPL-3.0-only /* SegmentTree.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; /** * @title Random * @dev The library for generating of pseudo random numbers */ library Random { using SafeMath for uint; struct RandomGenerator { uint seed; } /** * @dev Create an instance of RandomGenerator */ function create(uint seed) internal pure returns (RandomGenerator memory) { return RandomGenerator({seed: seed}); } function createFromEntropy(bytes memory entropy) internal pure returns (RandomGenerator memory) { return create(uint(keccak256(entropy))); } /** * @dev Generates random value */ function random(RandomGenerator memory self) internal pure returns (uint) { self.seed = uint(sha256(abi.encodePacked(self.seed))); return self.seed; } /** * @dev Generates random value in range [0, max) */ function random(RandomGenerator memory self, uint max) internal pure returns (uint) { assert(max > 0); uint maxRand = uint(-1).sub(uint(-1).mod(max)); if (uint(-1).sub(maxRand) == max.sub(1)) { return random(self).mod(max); } else { uint rand = random(self); while (rand >= maxRand) { rand = random(self); } return rand.mod(max); } } /** * @dev Generates random value in range [min, max) */ function random(RandomGenerator memory self, uint min, uint max) internal pure returns (uint) { assert(min < max); return min.add(random(self, max.sub(min))); } } // SPDX-License-Identifier: AGPL-3.0-only /* SegmentTree.sol - SKALE Manager Copyright (C) 2021-Present SKALE Labs @author Artem Payvin @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "./Random.sol"; /** * @title SegmentTree * @dev This library implements segment tree data structure * * Segment tree allows effectively calculate sum of elements in sub arrays * by storing some amount of additional data. * * IMPORTANT: Provided implementation assumes that arrays is indexed from 1 to n. * Size of initial array always must be power of 2 * * Example: * * Array: * +---+---+---+---+---+---+---+---+ * | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | * +---+---+---+---+---+---+---+---+ * * Segment tree structure: * +-------------------------------+ * | 36 | * +---------------+---------------+ * | 10 | 26 | * +-------+-------+-------+-------+ * | 3 | 7 | 11 | 15 | * +---+---+---+---+---+---+---+---+ * | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | * +---+---+---+---+---+---+---+---+ * * How the segment tree is stored in an array: * +----+----+----+---+---+----+----+---+---+---+---+---+---+---+---+ * | 36 | 10 | 26 | 3 | 7 | 11 | 15 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | * +----+----+----+---+---+----+----+---+---+---+---+---+---+---+---+ */ library SegmentTree { using Random for Random.RandomGenerator; using SafeMath for uint; struct Tree { uint[] tree; } /** * @dev Allocates storage for segment tree of `size` elements * * Requirements: * * - `size` must be greater than 0 * - `size` must be power of 2 */ function create(Tree storage segmentTree, uint size) external { require(size > 0, "Size can't be 0"); require(size & size.sub(1) == 0, "Size is not power of 2"); segmentTree.tree = new uint[](size.mul(2).sub(1)); } /** * @dev Adds `delta` to element of segment tree at `place` * * Requirements: * * - `place` must be in range [1, size] */ function addToPlace(Tree storage self, uint place, uint delta) external { require(_correctPlace(self, place), "Incorrect place"); uint leftBound = 1; uint rightBound = getSize(self); uint step = 1; self.tree[0] = self.tree[0].add(delta); while(leftBound < rightBound) { uint middle = leftBound.add(rightBound).div(2); if (place > middle) { leftBound = middle.add(1); step = step.add(step).add(1); } else { rightBound = middle; step = step.add(step); } self.tree[step.sub(1)] = self.tree[step.sub(1)].add(delta); } } /** * @dev Subtracts `delta` from element of segment tree at `place` * * Requirements: * * - `place` must be in range [1, size] * - initial value of target element must be not less than `delta` */ function removeFromPlace(Tree storage self, uint place, uint delta) external { require(_correctPlace(self, place), "Incorrect place"); uint leftBound = 1; uint rightBound = getSize(self); uint step = 1; self.tree[0] = self.tree[0].sub(delta); while(leftBound < rightBound) { uint middle = leftBound.add(rightBound).div(2); if (place > middle) { leftBound = middle.add(1); step = step.add(step).add(1); } else { rightBound = middle; step = step.add(step); } self.tree[step.sub(1)] = self.tree[step.sub(1)].sub(delta); } } /** * @dev Adds `delta` to element of segment tree at `toPlace` * and subtracts `delta` from element at `fromPlace` * * Requirements: * * - `fromPlace` must be in range [1, size] * - `toPlace` must be in range [1, size] * - initial value of element at `fromPlace` must be not less than `delta` */ function moveFromPlaceToPlace( Tree storage self, uint fromPlace, uint toPlace, uint delta ) external { require(_correctPlace(self, fromPlace) && _correctPlace(self, toPlace), "Incorrect place"); uint leftBound = 1; uint rightBound = getSize(self); uint step = 1; uint middle = leftBound.add(rightBound).div(2); uint fromPlaceMove = fromPlace > toPlace ? toPlace : fromPlace; uint toPlaceMove = fromPlace > toPlace ? fromPlace : toPlace; while (toPlaceMove <= middle || middle < fromPlaceMove) { if (middle < fromPlaceMove) { leftBound = middle.add(1); step = step.add(step).add(1); } else { rightBound = middle; step = step.add(step); } middle = leftBound.add(rightBound).div(2); } uint leftBoundMove = leftBound; uint rightBoundMove = rightBound; uint stepMove = step; while(leftBoundMove < rightBoundMove && leftBound < rightBound) { uint middleMove = leftBoundMove.add(rightBoundMove).div(2); if (fromPlace > middleMove) { leftBoundMove = middleMove.add(1); stepMove = stepMove.add(stepMove).add(1); } else { rightBoundMove = middleMove; stepMove = stepMove.add(stepMove); } self.tree[stepMove.sub(1)] = self.tree[stepMove.sub(1)].sub(delta); middle = leftBound.add(rightBound).div(2); if (toPlace > middle) { leftBound = middle.add(1); step = step.add(step).add(1); } else { rightBound = middle; step = step.add(step); } self.tree[step.sub(1)] = self.tree[step.sub(1)].add(delta); } } /** * @dev Returns random position in range [`place`, size] * with probability proportional to value stored at this position. * If all element in range are 0 returns 0 * * Requirements: * * - `place` must be in range [1, size] */ function getRandomNonZeroElementFromPlaceToLast( Tree storage self, uint place, Random.RandomGenerator memory randomGenerator ) external view returns (uint) { require(_correctPlace(self, place), "Incorrect place"); uint vertex = 1; uint leftBound = 0; uint rightBound = getSize(self); uint currentFrom = place.sub(1); uint currentSum = sumFromPlaceToLast(self, place); if (currentSum == 0) { return 0; } while(leftBound.add(1) < rightBound) { if (_middle(leftBound, rightBound) <= currentFrom) { vertex = _right(vertex); leftBound = _middle(leftBound, rightBound); } else { uint rightSum = self.tree[_right(vertex).sub(1)]; uint leftSum = currentSum.sub(rightSum); if (Random.random(randomGenerator, currentSum) < leftSum) { // go left vertex = _left(vertex); rightBound = _middle(leftBound, rightBound); currentSum = leftSum; } else { // go right vertex = _right(vertex); leftBound = _middle(leftBound, rightBound); currentFrom = leftBound; currentSum = rightSum; } } } return leftBound.add(1); } /** * @dev Returns sum of elements in range [`place`, size] * * Requirements: * * - `place` must be in range [1, size] */ function sumFromPlaceToLast(Tree storage self, uint place) public view returns (uint sum) { require(_correctPlace(self, place), "Incorrect place"); if (place == 1) { return self.tree[0]; } uint leftBound = 1; uint rightBound = getSize(self); uint step = 1; while(leftBound < rightBound) { uint middle = leftBound.add(rightBound).div(2); if (place > middle) { leftBound = middle.add(1); step = step.add(step).add(1); } else { rightBound = middle; step = step.add(step); sum = sum.add(self.tree[step]); } } sum = sum.add(self.tree[step.sub(1)]); } /** * @dev Returns amount of elements in segment tree */ function getSize(Tree storage segmentTree) internal view returns (uint) { if (segmentTree.tree.length > 0) { return segmentTree.tree.length.div(2).add(1); } else { return 0; } } /** * @dev Checks if `place` is valid position in segment tree */ function _correctPlace(Tree storage self, uint place) private view returns (bool) { return place >= 1 && place <= getSize(self); } /** * @dev Calculates index of left child of the vertex */ function _left(uint vertex) private pure returns (uint) { return vertex.mul(2); } /** * @dev Calculates index of right child of the vertex */ function _right(uint vertex) private pure returns (uint) { return vertex.mul(2).add(1); } /** * @dev Calculates arithmetical mean of 2 numbers */ function _middle(uint left, uint right) private pure returns (uint) { return left.add(right).div(2); } } // SPDX-License-Identifier: AGPL-3.0-only /* ILocker.sol - SKALE Manager Copyright (C) 2019-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; /** * @dev Interface of the Locker functions. */ interface ILocker { /** * @dev Returns and updates the total amount of locked tokens of a given * `holder`. */ function getAndUpdateLockedAmount(address wallet) external returns (uint); /** * @dev Returns and updates the total non-transferrable and un-delegatable * amount of a given `holder`. */ function getAndUpdateForbiddenForDelegationAmount(address wallet) external returns (uint); } // SPDX-License-Identifier: AGPL-3.0-only /* NodesMock.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "../BountyV2.sol"; import "../Permissions.sol"; contract NodesMock is Permissions { uint public nodesCount = 0; uint public nodesLeft = 0; // nodeId => timestamp mapping (uint => uint) public lastRewardDate; // nodeId => left mapping (uint => bool) public nodeLeft; // nodeId => validatorId mapping (uint => uint) public owner; function registerNodes(uint amount, uint validatorId) external { for (uint nodeId = nodesCount; nodeId < nodesCount + amount; ++nodeId) { lastRewardDate[nodeId] = now; owner[nodeId] = validatorId; } nodesCount += amount; } function removeNode(uint nodeId) external { ++nodesLeft; nodeLeft[nodeId] = true; } function changeNodeLastRewardDate(uint nodeId) external { lastRewardDate[nodeId] = now; } function getNodeLastRewardDate(uint nodeIndex) external view returns (uint) { require(nodeIndex < nodesCount, "Node does not exist"); return lastRewardDate[nodeIndex]; } function isNodeLeft(uint nodeId) external view returns (bool) { return nodeLeft[nodeId]; } function getNumberOnlineNodes() external view returns (uint) { return nodesCount.sub(nodesLeft); } function checkPossibilityToMaintainNode(uint /* validatorId */, uint /* nodeIndex */) external pure returns (bool) { return true; } function getValidatorId(uint nodeId) external view returns (uint) { return owner[nodeId]; } } // SPDX-License-Identifier: AGPL-3.0-only /* SkaleManagerMock.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/introspection/IERC1820Registry.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC777/IERC777Recipient.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC777/IERC777.sol"; import "../interfaces/IMintableToken.sol"; import "../Permissions.sol"; contract SkaleManagerMock is Permissions, IERC777Recipient { IERC1820Registry private _erc1820 = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); bytes32 constant public ADMIN_ROLE = keccak256("ADMIN_ROLE"); constructor (address contractManagerAddress) public { Permissions.initialize(contractManagerAddress); _erc1820.setInterfaceImplementer(address(this), keccak256("ERC777TokensRecipient"), address(this)); } function payBounty(uint validatorId, uint amount) external { IERC777 skaleToken = IERC777(contractManager.getContract("SkaleToken")); require(IMintableToken(address(skaleToken)).mint(address(this), amount, "", ""), "Token was not minted"); require( IMintableToken(address(skaleToken)) .mint(contractManager.getContract("Distributor"), amount, abi.encode(validatorId), ""), "Token was not minted" ); } function tokensReceived( address operator, address from, address to, uint256 amount, bytes calldata userData, bytes calldata operatorData ) external override allow("SkaleToken") // solhint-disable-next-line no-empty-blocks { } } pragma solidity ^0.6.0; /** * @dev Interface of the global ERC1820 Registry, as defined in the * https://eips.ethereum.org/EIPS/eip-1820[EIP]. Accounts may register * implementers for interfaces in this registry, as well as query support. * * Implementers may be shared by multiple accounts, and can also implement more * than a single interface for each account. Contracts can implement interfaces * for themselves, but externally-owned accounts (EOA) must delegate this to a * contract. * * {IERC165} interfaces can also be queried via the registry. * * For an in-depth explanation and source code analysis, see the EIP text. */ interface IERC1820Registry { /** * @dev Sets `newManager` as the manager for `account`. A manager of an * account is able to set interface implementers for it. * * By default, each account is its own manager. Passing a value of `0x0` in * `newManager` will reset the manager to this initial state. * * Emits a {ManagerChanged} event. * * Requirements: * * - the caller must be the current manager for `account`. */ function setManager(address account, address newManager) external; /** * @dev Returns the manager for `account`. * * See {setManager}. */ function getManager(address account) external view returns (address); /** * @dev Sets the `implementer` contract as ``account``'s implementer for * `interfaceHash`. * * `account` being the zero address is an alias for the caller's address. * The zero address can also be used in `implementer` to remove an old one. * * See {interfaceHash} to learn how these are created. * * Emits an {InterfaceImplementerSet} event. * * Requirements: * * - the caller must be the current manager for `account`. * - `interfaceHash` must not be an {IERC165} interface id (i.e. it must not * end in 28 zeroes). * - `implementer` must implement {IERC1820Implementer} and return true when * queried for support, unless `implementer` is the caller. See * {IERC1820Implementer-canImplementInterfaceForAddress}. */ function setInterfaceImplementer(address account, bytes32 interfaceHash, address implementer) external; /** * @dev Returns the implementer of `interfaceHash` for `account`. If no such * implementer is registered, returns the zero address. * * If `interfaceHash` is an {IERC165} interface id (i.e. it ends with 28 * zeroes), `account` will be queried for support of it. * * `account` being the zero address is an alias for the caller's address. */ function getInterfaceImplementer(address account, bytes32 interfaceHash) external view returns (address); /** * @dev Returns the interface hash for an `interfaceName`, as defined in the * corresponding * https://eips.ethereum.org/EIPS/eip-1820#interface-name[section of the EIP]. */ function interfaceHash(string calldata interfaceName) external pure returns (bytes32); /** * @notice Updates the cache with whether the contract implements an ERC165 interface or not. * @param account Address of the contract for which to update the cache. * @param interfaceId ERC165 interface for which to update the cache. */ function updateERC165Cache(address account, bytes4 interfaceId) external; /** * @notice Checks whether a contract implements an ERC165 interface or not. * If the result is not cached a direct lookup on the contract address is performed. * If the result is not cached or the cached value is out-of-date, the cache MUST be updated manually by calling * {updateERC165Cache} with the contract address. * @param account Address of the contract to check. * @param interfaceId ERC165 interface to check. * @return True if `account` implements `interfaceId`, false otherwise. */ function implementsERC165Interface(address account, bytes4 interfaceId) external view returns (bool); /** * @notice Checks whether a contract implements an ERC165 interface or not without using nor updating the cache. * @param account Address of the contract to check. * @param interfaceId ERC165 interface to check. * @return True if `account` implements `interfaceId`, false otherwise. */ function implementsERC165InterfaceNoCache(address account, bytes4 interfaceId) external view returns (bool); event InterfaceImplementerSet(address indexed account, bytes32 indexed interfaceHash, address indexed implementer); event ManagerChanged(address indexed account, address indexed newManager); } pragma solidity ^0.6.0; /** * @dev Interface of the ERC777TokensRecipient standard as defined in the EIP. * * Accounts can be notified of {IERC777} tokens being sent to them by having a * contract implement this interface (contract holders can be their own * implementer) and registering it on the * https://eips.ethereum.org/EIPS/eip-1820[ERC1820 global registry]. * * See {IERC1820Registry} and {ERC1820Implementer}. */ interface IERC777Recipient { /** * @dev Called by an {IERC777} token contract whenever tokens are being * moved or created into a registered account (`to`). The type of operation * is conveyed by `from` being the zero address or not. * * This call occurs _after_ the token contract's state is updated, so * {IERC777-balanceOf}, etc., can be used to query the post-operation state. * * This function may revert to prevent the operation from being executed. */ function tokensReceived( address operator, address from, address to, uint256 amount, bytes calldata userData, bytes calldata operatorData ) external; } // SPDX-License-Identifier: AGPL-3.0-only /* IMintableToken.sol - SKALE Manager Copyright (C) 2019-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; interface IMintableToken { function mint( address account, uint256 amount, bytes calldata userData, bytes calldata operatorData ) external returns (bool); } // SPDX-License-Identifier: AGPL-3.0-only /* SkaleToken.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "./thirdparty/openzeppelin/ERC777.sol"; import "./Permissions.sol"; import "./interfaces/delegation/IDelegatableToken.sol"; import "./interfaces/IMintableToken.sol"; import "./delegation/Punisher.sol"; import "./delegation/TokenState.sol"; /** * @title SkaleToken * @dev Contract defines the SKALE token and is based on ERC777 token * implementation. */ contract SkaleToken is ERC777, Permissions, ReentrancyGuard, IDelegatableToken, IMintableToken { using SafeMath for uint; string public constant NAME = "SKALE"; string public constant SYMBOL = "SKL"; uint public constant DECIMALS = 18; uint public constant CAP = 7 * 1e9 * (10 ** DECIMALS); // the maximum amount of tokens that can ever be created constructor(address contractsAddress, address[] memory defOps) public ERC777("SKALE", "SKL", defOps) { Permissions.initialize(contractsAddress); } /** * @dev Allows Owner or SkaleManager to mint an amount of tokens and * transfer minted tokens to a specified address. * * Returns whether the operation is successful. * * Requirements: * * - Mint must not exceed the total supply. */ function mint( address account, uint256 amount, bytes calldata userData, bytes calldata operatorData ) external override allow("SkaleManager") //onlyAuthorized returns (bool) { require(amount <= CAP.sub(totalSupply()), "Amount is too big"); _mint( account, amount, userData, operatorData ); return true; } /** * @dev See {IDelegatableToken-getAndUpdateDelegatedAmount}. */ function getAndUpdateDelegatedAmount(address wallet) external override returns (uint) { return DelegationController(contractManager.getContract("DelegationController")) .getAndUpdateDelegatedAmount(wallet); } /** * @dev See {IDelegatableToken-getAndUpdateSlashedAmount}. */ function getAndUpdateSlashedAmount(address wallet) external override returns (uint) { return Punisher(contractManager.getContract("Punisher")).getAndUpdateLockedAmount(wallet); } /** * @dev See {IDelegatableToken-getAndUpdateLockedAmount}. */ function getAndUpdateLockedAmount(address wallet) public override returns (uint) { return TokenState(contractManager.getContract("TokenState")).getAndUpdateLockedAmount(wallet); } // internal function _beforeTokenTransfer( address, // operator address from, address, // to uint256 tokenId) internal override { uint locked = getAndUpdateLockedAmount(from); if (locked > 0) { require(balanceOf(from) >= locked.add(tokenId), "Token should be unlocked for transferring"); } } function _callTokensToSend( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData ) internal override nonReentrant { super._callTokensToSend(operator, from, to, amount, userData, operatorData); } function _callTokensReceived( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData, bool requireReceptionAck ) internal override nonReentrant { super._callTokensReceived(operator, from, to, amount, userData, operatorData, requireReceptionAck); } // we have to override _msgData() and _msgSender() functions because of collision in Context and ContextUpgradeSafe function _msgData() internal view override(Context, ContextUpgradeSafe) returns (bytes memory) { return Context._msgData(); } function _msgSender() internal view override(Context, ContextUpgradeSafe) returns (address payable) { return Context._msgSender(); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <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 () internal { _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; } } pragma solidity ^0.6.0; import "@openzeppelin/contracts/GSN/Context.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC777/IERC777.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC777/IERC777Recipient.sol"; import "@openzeppelin/contracts/token/ERC777/IERC777Sender.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol"; // import "@openzeppelin/contracts/math/SafeMath.sol"; Removed by SKALE // import "@openzeppelin/contracts/utils/Address.sol"; Removed by SKALE import "@openzeppelin/contracts-ethereum-package/contracts/introspection/IERC1820Registry.sol"; /* Added by SKALE */ import "../../Permissions.sol"; /* End of added by SKALE */ /** * @dev Implementation of the {IERC777} 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}. * * Support for ERC20 is included in this contract, as specified by the EIP: both * the ERC777 and ERC20 interfaces can be safely used when interacting with it. * Both {IERC777-Sent} and {IERC20-Transfer} events are emitted on token * movements. * * Additionally, the {IERC777-granularity} value is hard-coded to `1`, meaning that there * are no special restrictions in the amount of tokens that created, moved, or * destroyed. This makes integration with ERC20 applications seamless. */ contract ERC777 is Context, IERC777, IERC20 { using SafeMath for uint256; using Address for address; IERC1820Registry constant internal _ERC1820_REGISTRY = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); mapping(address => uint256) private _balances; uint256 private _totalSupply; string private _name; string private _symbol; // We inline the result of the following hashes because Solidity doesn't resolve them at compile time. // See https://github.com/ethereum/solidity/issues/4024. // keccak256("ERC777TokensSender") bytes32 constant private _TOKENS_SENDER_INTERFACE_HASH = 0x29ddb589b1fb5fc7cf394961c1adf5f8c6454761adf795e67fe149f658abe895; // keccak256("ERC777TokensRecipient") bytes32 constant private _TOKENS_RECIPIENT_INTERFACE_HASH = 0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b; // This isn't ever read from - it's only used to respond to the defaultOperators query. address[] private _defaultOperatorsArray; // Immutable, but accounts may revoke them (tracked in __revokedDefaultOperators). mapping(address => bool) private _defaultOperators; // For each account, a mapping of its operators and revoked default operators. mapping(address => mapping(address => bool)) private _operators; mapping(address => mapping(address => bool)) private _revokedDefaultOperators; // ERC20-allowances mapping (address => mapping (address => uint256)) private _allowances; /** * @dev `defaultOperators` may be an empty array. */ constructor( string memory name, string memory symbol, address[] memory defaultOperators ) public { _name = name; _symbol = symbol; _defaultOperatorsArray = defaultOperators; for (uint256 i = 0; i < _defaultOperatorsArray.length; i++) { _defaultOperators[_defaultOperatorsArray[i]] = true; } // register interfaces _ERC1820_REGISTRY.setInterfaceImplementer(address(this), keccak256("ERC777Token"), address(this)); _ERC1820_REGISTRY.setInterfaceImplementer(address(this), keccak256("ERC20Token"), address(this)); } /** * @dev See {IERC777-name}. */ function name() public view override returns (string memory) { return _name; } /** * @dev See {IERC777-symbol}. */ function symbol() public view override returns (string memory) { return _symbol; } /** * @dev See {ERC20-decimals}. * * Always returns 18, as per the * [ERC777 EIP](https://eips.ethereum.org/EIPS/eip-777#backward-compatibility). */ function decimals() public pure returns (uint8) { return 18; } /** * @dev See {IERC777-granularity}. * * This implementation always returns `1`. */ function granularity() public view override returns (uint256) { return 1; } /** * @dev See {IERC777-totalSupply}. */ function totalSupply() public view override(IERC20, IERC777) returns (uint256) { return _totalSupply; } /** * @dev Returns the amount of tokens owned by an account (`tokenHolder`). */ function balanceOf(address tokenHolder) public view override(IERC20, IERC777) returns (uint256) { return _balances[tokenHolder]; } /** * @dev See {IERC777-send}. * * Also emits a {IERC20-Transfer} event for ERC20 compatibility. */ function send(address recipient, uint256 amount, bytes memory data) public override { _send(_msgSender(), recipient, amount, data, "", true); } /** * @dev See {IERC20-transfer}. * * Unlike `send`, `recipient` is _not_ required to implement the {IERC777Recipient} * interface if it is a contract. * * Also emits a {Sent} event. */ function transfer(address recipient, uint256 amount) public override returns (bool) { require(recipient != address(0), "ERC777: transfer to the zero address"); address from = _msgSender(); _callTokensToSend(from, from, recipient, amount, "", ""); _move(from, from, recipient, amount, "", ""); _callTokensReceived(from, from, recipient, amount, "", "", false); return true; } /** * @dev See {IERC777-burn}. * * Also emits a {IERC20-Transfer} event for ERC20 compatibility. */ function burn(uint256 amount, bytes memory data) public override { _burn(_msgSender(), amount, data, ""); } /** * @dev See {IERC777-isOperatorFor}. */ function isOperatorFor( address operator, address tokenHolder ) public view override returns (bool) { return operator == tokenHolder || (_defaultOperators[operator] && !_revokedDefaultOperators[tokenHolder][operator]) || _operators[tokenHolder][operator]; } /** * @dev See {IERC777-authorizeOperator}. */ function authorizeOperator(address operator) public override { require(_msgSender() != operator, "ERC777: authorizing self as operator"); if (_defaultOperators[operator]) { delete _revokedDefaultOperators[_msgSender()][operator]; } else { _operators[_msgSender()][operator] = true; } emit AuthorizedOperator(operator, _msgSender()); } /** * @dev See {IERC777-revokeOperator}. */ function revokeOperator(address operator) public override { require(operator != _msgSender(), "ERC777: revoking self as operator"); if (_defaultOperators[operator]) { _revokedDefaultOperators[_msgSender()][operator] = true; } else { delete _operators[_msgSender()][operator]; } emit RevokedOperator(operator, _msgSender()); } /** * @dev See {IERC777-defaultOperators}. */ function defaultOperators() public view override returns (address[] memory) { return _defaultOperatorsArray; } /** * @dev See {IERC777-operatorSend}. * * Emits {Sent} and {IERC20-Transfer} events. */ function operatorSend( address sender, address recipient, uint256 amount, bytes memory data, bytes memory operatorData ) public override { require(isOperatorFor(_msgSender(), sender), "ERC777: caller is not an operator for holder"); _send(sender, recipient, amount, data, operatorData, true); } /** * @dev See {IERC777-operatorBurn}. * * Emits {Burned} and {IERC20-Transfer} events. */ function operatorBurn(address account, uint256 amount, bytes memory data, bytes memory operatorData) public override { require(isOperatorFor(_msgSender(), account), "ERC777: caller is not an operator for holder"); _burn(account, amount, data, operatorData); } /** * @dev See {IERC20-allowance}. * * Note that operator and allowance concepts are orthogonal: operators may * not have allowance, and accounts with allowance may not be operators * themselves. */ function allowance(address holder, address spender) public view override returns (uint256) { return _allowances[holder][spender]; } /** * @dev See {IERC20-approve}. * * Note that accounts cannot have allowance issued by their operators. */ function approve(address spender, uint256 value) public override returns (bool) { address holder = _msgSender(); _approve(holder, spender, value); return true; } /** * @dev See {IERC20-transferFrom}. * * Note that operator and allowance concepts are orthogonal: operators cannot * call `transferFrom` (unless they have allowance), and accounts with * allowance cannot call `operatorSend` (unless they are operators). * * Emits {Sent}, {IERC20-Transfer} and {IERC20-Approval} events. */ function transferFrom(address holder, address recipient, uint256 amount) public override returns (bool) { require(recipient != address(0), "ERC777: transfer to the zero address"); require(holder != address(0), "ERC777: transfer from the zero address"); address spender = _msgSender(); _callTokensToSend(spender, holder, recipient, amount, "", ""); _move(spender, holder, recipient, amount, "", ""); _approve(holder, spender, _allowances[holder][spender].sub(amount, "ERC777: transfer amount exceeds allowance")); _callTokensReceived(spender, holder, recipient, amount, "", "", false); return true; } /** * @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * If a send hook is registered for `account`, the corresponding function * will be called with `operator`, `data` and `operatorData`. * * See {IERC777Sender} and {IERC777Recipient}. * * Emits {Minted} and {IERC20-Transfer} events. * * Requirements * * - `account` cannot be the zero address. * - if `account` is a contract, it must implement the {IERC777Recipient} * interface. */ function _mint( address account, uint256 amount, bytes memory userData, bytes memory operatorData ) internal virtual { require(account != address(0), "ERC777: mint to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), account, amount); // Update state variables _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); _callTokensReceived(operator, address(0), account, amount, userData, operatorData, true); emit Minted(operator, account, amount, userData, operatorData); emit Transfer(address(0), account, amount); } /** * @dev Send tokens * @param from address token holder address * @param to address recipient address * @param amount uint256 amount of tokens to transfer * @param userData bytes extra information provided by the token holder (if any) * @param operatorData bytes extra information provided by the operator (if any) * @param requireReceptionAck if true, contract recipients are required to implement ERC777TokensRecipient */ function _send( address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData, bool requireReceptionAck ) internal { require(from != address(0), "ERC777: send from the zero address"); require(to != address(0), "ERC777: send to the zero address"); address operator = _msgSender(); _callTokensToSend(operator, from, to, amount, userData, operatorData); _move(operator, from, to, amount, userData, operatorData); _callTokensReceived(operator, from, to, amount, userData, operatorData, requireReceptionAck); } /** * @dev Burn tokens * @param from address token holder address * @param amount uint256 amount of tokens to burn * @param data bytes extra information provided by the token holder * @param operatorData bytes extra information provided by the operator (if any) */ function _burn( address from, uint256 amount, bytes memory data, bytes memory operatorData ) internal virtual { require(from != address(0), "ERC777: burn from the zero address"); address operator = _msgSender(); /* Chaged by SKALE: we swapped these lines to prevent delegation of burning tokens */ _callTokensToSend(operator, from, address(0), amount, data, operatorData); _beforeTokenTransfer(operator, from, address(0), amount); /* End of changed by SKALE */ // Update state variables _balances[from] = _balances[from].sub(amount, "ERC777: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Burned(operator, from, amount, data, operatorData); emit Transfer(from, address(0), amount); } function _move( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData ) private { _beforeTokenTransfer(operator, from, to, amount); _balances[from] = _balances[from].sub(amount, "ERC777: transfer amount exceeds balance"); _balances[to] = _balances[to].add(amount); emit Sent(operator, from, to, amount, userData, operatorData); emit Transfer(from, to, amount); } /** * @dev See {ERC20-_approve}. * * Note that accounts cannot have allowance issued by their operators. */ function _approve(address holder, address spender, uint256 value) internal { require(holder != address(0), "ERC777: approve from the zero address"); require(spender != address(0), "ERC777: approve to the zero address"); _allowances[holder][spender] = value; emit Approval(holder, spender, value); } /** * @dev Call from.tokensToSend() if the interface is registered * @param operator address operator requesting the transfer * @param from address token holder address * @param to address recipient address * @param amount uint256 amount of tokens to transfer * @param userData bytes extra information provided by the token holder (if any) * @param operatorData bytes extra information provided by the operator (if any) */ function _callTokensToSend( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData ) /* Chaged by SKALE from private */ internal /* End of changed by SKALE */ /* Added by SKALE */ virtual /* End of added by SKALE */ { address implementer = _ERC1820_REGISTRY.getInterfaceImplementer(from, _TOKENS_SENDER_INTERFACE_HASH); if (implementer != address(0)) { IERC777Sender(implementer).tokensToSend(operator, from, to, amount, userData, operatorData); } } /** * @dev Call to.tokensReceived() if the interface is registered. Reverts if the recipient is a contract but * tokensReceived() was not registered for the recipient * @param operator address operator requesting the transfer * @param from address token holder address * @param to address recipient address * @param amount uint256 amount of tokens to transfer * @param userData bytes extra information provided by the token holder (if any) * @param operatorData bytes extra information provided by the operator (if any) * @param requireReceptionAck if true, contract recipients are required to implement ERC777TokensRecipient */ function _callTokensReceived( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData, bool requireReceptionAck ) /* Chaged by SKALE from private */ internal /* End of changed by SKALE */ /* Added by SKALE */ virtual /* End of added by SKALE */ { address implementer = _ERC1820_REGISTRY.getInterfaceImplementer(to, _TOKENS_RECIPIENT_INTERFACE_HASH); if (implementer != address(0)) { IERC777Recipient(implementer).tokensReceived(operator, from, to, amount, userData, operatorData); } else if (requireReceptionAck) { require(!to.isContract(), "ERC777: token recipient contract has no implementer for ERC777TokensRecipient"); } } /** * @dev Hook that is called before any token transfer. This includes * calls to {send}, {transfer}, {operatorSend}, 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 operator, address from, address to, uint256 tokenId) internal virtual { } } // SPDX-License-Identifier: AGPL-3.0-only /* IDelegatableToken.sol - SKALE Manager Copyright (C) 2019-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; /** * @dev Interface of the SkaleToken contract. */ interface IDelegatableToken { /** * @dev Returns and updates the amount of locked tokens of a given account `wallet`. */ function getAndUpdateLockedAmount(address wallet) external returns (uint); /** * @dev Returns and updates the amount of delegated tokens of a given account `wallet`. */ function getAndUpdateDelegatedAmount(address wallet) external returns (uint); /** * @dev Returns and updates the amount of slashed tokens of a given account `wallet`. */ function getAndUpdateSlashedAmount(address wallet) external returns (uint); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/Context.sol"; // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC777TokensSender standard as defined in the EIP. * * {IERC777} Token holders can be notified of operations performed on their * tokens by having a contract implement this interface (contract holders can be * their own implementer) and registering it on the * https://eips.ethereum.org/EIPS/eip-1820[ERC1820 global registry]. * * See {IERC1820Registry} and {ERC1820Implementer}. */ interface IERC777Sender { /** * @dev Called by an {IERC777} token contract whenever a registered holder's * (`from`) tokens are about to be moved or destroyed. The type of operation * is conveyed by `to` being the zero address or not. * * This call occurs _before_ the token contract's state is updated, so * {IERC777-balanceOf}, etc., can be used to query the pre-operation state. * * This function may revert to prevent the operation from being executed. */ function tokensToSend( address operator, address from, address to, uint256 amount, bytes calldata userData, bytes calldata operatorData ) external; } pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <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: AGPL-3.0-only /* SkaleTokenInternalTester.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "../SkaleToken.sol"; contract SkaleTokenInternalTester is SkaleToken { constructor(address contractManagerAddress, address[] memory defOps) public SkaleToken(contractManagerAddress, defOps) // solhint-disable-next-line no-empty-blocks { } function getMsgData() external view returns (bytes memory) { return _msgData(); } } // SPDX-License-Identifier: AGPL-3.0-only /* TimeHelpersWithDebug.sol - SKALE Manager Copyright (C) 2019-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/access/Ownable.sol"; import "../delegation/TimeHelpers.sol"; contract TimeHelpersWithDebug is TimeHelpers, OwnableUpgradeSafe { struct TimeShift { uint pointInTime; uint shift; } TimeShift[] private _timeShift; function skipTime(uint sec) external onlyOwner { if (_timeShift.length > 0) { _timeShift.push(TimeShift({pointInTime: now, shift: _timeShift[_timeShift.length.sub(1)].shift.add(sec)})); } else { _timeShift.push(TimeShift({pointInTime: now, shift: sec})); } } function initialize() external initializer { OwnableUpgradeSafe.__Ownable_init(); } function timestampToMonth(uint timestamp) public view override returns (uint) { return super.timestampToMonth(timestamp.add(_getTimeShift(timestamp))); } function monthToTimestamp(uint month) public view override returns (uint) { uint shiftedTimestamp = super.monthToTimestamp(month); if (_timeShift.length > 0) { return _findTimeBeforeTimeShift(shiftedTimestamp); } else { return shiftedTimestamp; } } // private function _getTimeShift(uint timestamp) private view returns (uint) { if (_timeShift.length > 0) { if (timestamp < _timeShift[0].pointInTime) { return 0; } else if (timestamp >= _timeShift[_timeShift.length.sub(1)].pointInTime) { return _timeShift[_timeShift.length.sub(1)].shift; } else { uint left = 0; uint right = _timeShift.length.sub(1); while (left + 1 < right) { uint middle = left.add(right).div(2); if (timestamp < _timeShift[middle].pointInTime) { right = middle; } else { left = middle; } } return _timeShift[left].shift; } } else { return 0; } } function _findTimeBeforeTimeShift(uint shiftedTimestamp) private view returns (uint) { uint lastTimeShiftIndex = _timeShift.length.sub(1); if (_timeShift[lastTimeShiftIndex].pointInTime.add(_timeShift[lastTimeShiftIndex].shift) < shiftedTimestamp) { return shiftedTimestamp.sub(_timeShift[lastTimeShiftIndex].shift); } else { if (shiftedTimestamp <= _timeShift[0].pointInTime.add(_timeShift[0].shift)) { if (shiftedTimestamp < _timeShift[0].pointInTime) { return shiftedTimestamp; } else { return _timeShift[0].pointInTime; } } else { uint left = 0; uint right = lastTimeShiftIndex; while (left + 1 < right) { uint middle = left.add(right).div(2); if (_timeShift[middle].pointInTime.add(_timeShift[middle].shift) < shiftedTimestamp) { left = middle; } else { right = middle; } } if (shiftedTimestamp < _timeShift[right].pointInTime.add(_timeShift[left].shift)) { return shiftedTimestamp.sub(_timeShift[left].shift); } else { return _timeShift[right].pointInTime; } } } } } // SPDX-License-Identifier: AGPL-3.0-only /* SafeMock.sol - SKALE Manager Copyright (C) 2021-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/access/Ownable.sol"; contract SafeMock is OwnableUpgradeSafe { constructor() public { OwnableUpgradeSafe.__Ownable_init(); multiSend(""); // this is needed to remove slither warning } function transferProxyAdminOwnership(OwnableUpgradeSafe proxyAdmin, address newOwner) external onlyOwner { proxyAdmin.transferOwnership(newOwner); } function destroy() external onlyOwner { selfdestruct(msg.sender); } /// @dev Sends multiple transactions and reverts all if one fails. /// @param transactions Encoded transactions. Each transaction is encoded as a packed bytes of /// operation as a uint8 with 0 for a call or 1 for a delegatecall (=> 1 byte), /// to as a address (=> 20 bytes), /// value as a uint256 (=> 32 bytes), /// data length as a uint256 (=> 32 bytes), /// data as bytes. /// see abi.encodePacked for more information on packed encoding function multiSend(bytes memory transactions) public { // solhint-disable-next-line no-inline-assembly assembly { let length := mload(transactions) let i := 0x20 // solhint-disable-next-line no-empty-blocks for { } lt(i, length) { } { // First byte of the data is the operation. // We shift by 248 bits (256 - 8 [operation byte]) it right // since mload will always load 32 bytes (a word). // This will also zero out unused data. let operation := shr(0xf8, mload(add(transactions, i))) // We offset the load address by 1 byte (operation byte) // We shift it right by 96 bits (256 - 160 [20 address bytes]) // to right-align the data and zero out unused data. let to := shr(0x60, mload(add(transactions, add(i, 0x01)))) // We offset the load address by 21 byte (operation byte + 20 address bytes) let value := mload(add(transactions, add(i, 0x15))) // We offset the load address by 53 byte (operation byte + 20 address bytes + 32 value bytes) let dataLength := mload(add(transactions, add(i, 0x35))) // We offset the load address by 85 byte // (operation byte + 20 address bytes + 32 value bytes + 32 data length bytes) let data := add(transactions, add(i, 0x55)) let success := 0 switch operation case 0 { success := call(gas(), to, value, data, dataLength, 0, 0) } case 1 { success := delegatecall(gas(), to, data, dataLength, 0, 0) } if eq(success, 0) { revert(0, 0) } // Next entry starts at 85 byte + data length i := add(i, add(0x55, dataLength)) } } } } // SPDX-License-Identifier: AGPL-3.0-only /* SkaleDkgAlright.sol - SKALE Manager Copyright (C) 2021-Present SKALE Labs @author Dmytro Stebaiev @author Artem Payvin @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "../SkaleDKG.sol"; import "../ContractManager.sol"; import "../Wallets.sol"; import "../KeyStorage.sol"; /** * @title SkaleDkgAlright * @dev Contains functions to manage distributed key generation per * Joint-Feldman protocol. */ library SkaleDkgAlright { event AllDataReceived(bytes32 indexed schainHash, uint nodeIndex); event SuccessfulDKG(bytes32 indexed schainHash); function alright( bytes32 schainHash, uint fromNodeIndex, ContractManager contractManager, mapping(bytes32 => SkaleDKG.Channel) storage channels, mapping(bytes32 => SkaleDKG.ProcessDKG) storage dkgProcess, mapping(bytes32 => SkaleDKG.ComplaintData) storage complaints, mapping(bytes32 => uint) storage lastSuccessfulDKG ) external { SkaleDKG skaleDKG = SkaleDKG(contractManager.getContract("SkaleDKG")); (uint index, ) = skaleDKG.checkAndReturnIndexInGroup(schainHash, fromNodeIndex, true); uint numberOfParticipant = channels[schainHash].n; require(numberOfParticipant == dkgProcess[schainHash].numberOfBroadcasted, "Still Broadcasting phase"); require( complaints[schainHash].fromNodeToComplaint != fromNodeIndex || (fromNodeIndex == 0 && complaints[schainHash].startComplaintBlockTimestamp == 0), "Node has already sent complaint" ); require(!dkgProcess[schainHash].completed[index], "Node is already alright"); dkgProcess[schainHash].completed[index] = true; dkgProcess[schainHash].numberOfCompleted++; emit AllDataReceived(schainHash, fromNodeIndex); if (dkgProcess[schainHash].numberOfCompleted == numberOfParticipant) { lastSuccessfulDKG[schainHash] = now; channels[schainHash].active = false; KeyStorage(contractManager.getContract("KeyStorage")).finalizePublicKey(schainHash); emit SuccessfulDKG(schainHash); } } } // SPDX-License-Identifier: AGPL-3.0-only /* SkaleDKG.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "./Permissions.sol"; import "./delegation/Punisher.sol"; import "./SlashingTable.sol"; import "./Schains.sol"; import "./SchainsInternal.sol"; import "./utils/FieldOperations.sol"; import "./NodeRotation.sol"; import "./KeyStorage.sol"; import "./interfaces/ISkaleDKG.sol"; import "./thirdparty/ECDH.sol"; import "./utils/Precompiled.sol"; import "./Wallets.sol"; import "./dkg/SkaleDkgAlright.sol"; import "./dkg/SkaleDkgBroadcast.sol"; import "./dkg/SkaleDkgComplaint.sol"; import "./dkg/SkaleDkgPreResponse.sol"; import "./dkg/SkaleDkgResponse.sol"; /** * @title SkaleDKG * @dev Contains functions to manage distributed key generation per * Joint-Feldman protocol. */ contract SkaleDKG is Permissions, ISkaleDKG { using Fp2Operations for Fp2Operations.Fp2Point; using G2Operations for G2Operations.G2Point; enum DkgFunction {Broadcast, Alright, ComplaintBadData, PreResponse, Complaint, Response} struct Channel { bool active; uint n; uint startedBlockTimestamp; uint startedBlock; } struct ProcessDKG { uint numberOfBroadcasted; uint numberOfCompleted; bool[] broadcasted; bool[] completed; } struct ComplaintData { uint nodeToComplaint; uint fromNodeToComplaint; uint startComplaintBlockTimestamp; bool isResponse; bytes32 keyShare; G2Operations.G2Point sumOfVerVec; } struct KeyShare { bytes32[2] publicKey; bytes32 share; } struct Context { bool isDebt; uint delta; DkgFunction dkgFunction; } uint public constant COMPLAINT_TIMELIMIT = 1800; mapping(bytes32 => Channel) public channels; mapping(bytes32 => uint) public lastSuccessfulDKG; mapping(bytes32 => ProcessDKG) public dkgProcess; mapping(bytes32 => ComplaintData) public complaints; mapping(bytes32 => uint) public startAlrightTimestamp; mapping(bytes32 => mapping(uint => bytes32)) public hashedData; mapping(bytes32 => uint) private _badNodes; /** * @dev Emitted when a channel is opened. */ event ChannelOpened(bytes32 schainHash); /** * @dev Emitted when a channel is closed. */ event ChannelClosed(bytes32 schainHash); /** * @dev Emitted when a node broadcasts keyshare. */ event BroadcastAndKeyShare( bytes32 indexed schainHash, uint indexed fromNode, G2Operations.G2Point[] verificationVector, KeyShare[] secretKeyContribution ); /** * @dev Emitted when all group data is received by node. */ event AllDataReceived(bytes32 indexed schainHash, uint nodeIndex); /** * @dev Emitted when DKG is successful. */ event SuccessfulDKG(bytes32 indexed schainHash); /** * @dev Emitted when a complaint against a node is verified. */ event BadGuy(uint nodeIndex); /** * @dev Emitted when DKG failed. */ event FailedDKG(bytes32 indexed schainHash); /** * @dev Emitted when a new node is rotated in. */ event NewGuy(uint nodeIndex); /** * @dev Emitted when an incorrect complaint is sent. */ event ComplaintError(string error); /** * @dev Emitted when a complaint is sent. */ event ComplaintSent( bytes32 indexed schainHash, uint indexed fromNodeIndex, uint indexed toNodeIndex); modifier correctGroup(bytes32 schainHash) { require(channels[schainHash].active, "Group is not created"); _; } modifier correctGroupWithoutRevert(bytes32 schainHash) { if (!channels[schainHash].active) { emit ComplaintError("Group is not created"); } else { _; } } modifier correctNode(bytes32 schainHash, uint nodeIndex) { (uint index, ) = checkAndReturnIndexInGroup(schainHash, nodeIndex, true); _; } modifier correctNodeWithoutRevert(bytes32 schainHash, uint nodeIndex) { (, bool check) = checkAndReturnIndexInGroup(schainHash, nodeIndex, false); if (!check) { emit ComplaintError("Node is not in this group"); } else { _; } } modifier onlyNodeOwner(uint nodeIndex) { _checkMsgSenderIsNodeOwner(nodeIndex); _; } modifier refundGasBySchain(bytes32 schainHash, Context memory context) { uint gasTotal = gasleft(); _; _refundGasBySchain(schainHash, gasTotal, context); } modifier refundGasByValidatorToSchain(bytes32 schainHash, Context memory context) { uint gasTotal = gasleft(); _; _refundGasBySchain(schainHash, gasTotal, context); _refundGasByValidatorToSchain(schainHash); } function alright(bytes32 schainHash, uint fromNodeIndex) external refundGasBySchain(schainHash, Context({ isDebt: false, delta: ConstantsHolder(contractManager.getConstantsHolder()).ALRIGHT_DELTA(), dkgFunction: DkgFunction.Alright })) correctGroup(schainHash) onlyNodeOwner(fromNodeIndex) { SkaleDkgAlright.alright( schainHash, fromNodeIndex, contractManager, channels, dkgProcess, complaints, lastSuccessfulDKG ); } function broadcast( bytes32 schainHash, uint nodeIndex, G2Operations.G2Point[] memory verificationVector, KeyShare[] memory secretKeyContribution ) external refundGasBySchain(schainHash, Context({ isDebt: false, delta: ConstantsHolder(contractManager.getConstantsHolder()).BROADCAST_DELTA(), dkgFunction: DkgFunction.Broadcast })) correctGroup(schainHash) onlyNodeOwner(nodeIndex) { SkaleDkgBroadcast.broadcast( schainHash, nodeIndex, verificationVector, secretKeyContribution, contractManager, channels, dkgProcess, hashedData ); } function complaintBadData(bytes32 schainHash, uint fromNodeIndex, uint toNodeIndex) external refundGasBySchain( schainHash, Context({ isDebt: true, delta: ConstantsHolder(contractManager.getConstantsHolder()).COMPLAINT_BAD_DATA_DELTA(), dkgFunction: DkgFunction.ComplaintBadData })) correctGroupWithoutRevert(schainHash) correctNode(schainHash, fromNodeIndex) correctNodeWithoutRevert(schainHash, toNodeIndex) onlyNodeOwner(fromNodeIndex) { SkaleDkgComplaint.complaintBadData( schainHash, fromNodeIndex, toNodeIndex, contractManager, complaints ); } function preResponse( bytes32 schainId, uint fromNodeIndex, G2Operations.G2Point[] memory verificationVector, G2Operations.G2Point[] memory verificationVectorMult, KeyShare[] memory secretKeyContribution ) external refundGasBySchain( schainId, Context({ isDebt: true, delta: ConstantsHolder(contractManager.getConstantsHolder()).PRE_RESPONSE_DELTA(), dkgFunction: DkgFunction.PreResponse })) correctGroup(schainId) onlyNodeOwner(fromNodeIndex) { SkaleDkgPreResponse.preResponse( schainId, fromNodeIndex, verificationVector, verificationVectorMult, secretKeyContribution, contractManager, complaints, hashedData ); } function complaint(bytes32 schainHash, uint fromNodeIndex, uint toNodeIndex) external refundGasByValidatorToSchain( schainHash, Context({ isDebt: true, delta: ConstantsHolder(contractManager.getConstantsHolder()).COMPLAINT_DELTA(), dkgFunction: DkgFunction.Complaint })) correctGroupWithoutRevert(schainHash) correctNode(schainHash, fromNodeIndex) correctNodeWithoutRevert(schainHash, toNodeIndex) onlyNodeOwner(fromNodeIndex) { SkaleDkgComplaint.complaint( schainHash, fromNodeIndex, toNodeIndex, contractManager, channels, complaints, startAlrightTimestamp ); } function response( bytes32 schainHash, uint fromNodeIndex, uint secretNumber, G2Operations.G2Point memory multipliedShare ) external refundGasByValidatorToSchain( schainHash, Context({isDebt: true, delta: ConstantsHolder(contractManager.getConstantsHolder()).RESPONSE_DELTA(), dkgFunction: DkgFunction.Response })) correctGroup(schainHash) onlyNodeOwner(fromNodeIndex) { SkaleDkgResponse.response( schainHash, fromNodeIndex, secretNumber, multipliedShare, contractManager, channels, complaints ); } /** * @dev Allows Schains and NodeRotation contracts to open a channel. * * Emits a {ChannelOpened} event. * * Requirements: * * - Channel is not already created. */ function openChannel(bytes32 schainHash) external override allowTwo("Schains","NodeRotation") { _openChannel(schainHash); } /** * @dev Allows SchainsInternal contract to delete a channel. * * Requirements: * * - Channel must exist. */ function deleteChannel(bytes32 schainHash) external override allow("SchainsInternal") { delete channels[schainHash]; delete dkgProcess[schainHash]; delete complaints[schainHash]; KeyStorage(contractManager.getContract("KeyStorage")).deleteKey(schainHash); } function setStartAlrightTimestamp(bytes32 schainHash) external allow("SkaleDKG") { startAlrightTimestamp[schainHash] = now; } function setBadNode(bytes32 schainHash, uint nodeIndex) external allow("SkaleDKG") { _badNodes[schainHash] = nodeIndex; } function finalizeSlashing(bytes32 schainHash, uint badNode) external allow("SkaleDKG") { NodeRotation nodeRotation = NodeRotation(contractManager.getContract("NodeRotation")); SchainsInternal schainsInternal = SchainsInternal( contractManager.getContract("SchainsInternal") ); emit BadGuy(badNode); emit FailedDKG(schainHash); schainsInternal.makeSchainNodesInvisible(schainHash); if (schainsInternal.isAnyFreeNode(schainHash)) { uint newNode = nodeRotation.rotateNode( badNode, schainHash, false, true ); emit NewGuy(newNode); } else { _openChannel(schainHash); schainsInternal.removeNodeFromSchain( badNode, schainHash ); channels[schainHash].active = false; } schainsInternal.makeSchainNodesVisible(schainHash); Punisher(contractManager.getPunisher()).slash( Nodes(contractManager.getContract("Nodes")).getValidatorId(badNode), SlashingTable(contractManager.getContract("SlashingTable")).getPenalty("FailedDKG") ); } function getChannelStartedTime(bytes32 schainHash) external view returns (uint) { return channels[schainHash].startedBlockTimestamp; } function getChannelStartedBlock(bytes32 schainHash) external view returns (uint) { return channels[schainHash].startedBlock; } function getNumberOfBroadcasted(bytes32 schainHash) external view returns (uint) { return dkgProcess[schainHash].numberOfBroadcasted; } function getNumberOfCompleted(bytes32 schainHash) external view returns (uint) { return dkgProcess[schainHash].numberOfCompleted; } function getTimeOfLastSuccessfulDKG(bytes32 schainHash) external view returns (uint) { return lastSuccessfulDKG[schainHash]; } function getComplaintData(bytes32 schainHash) external view returns (uint, uint) { return (complaints[schainHash].fromNodeToComplaint, complaints[schainHash].nodeToComplaint); } function getComplaintStartedTime(bytes32 schainHash) external view returns (uint) { return complaints[schainHash].startComplaintBlockTimestamp; } function getAlrightStartedTime(bytes32 schainHash) external view returns (uint) { return startAlrightTimestamp[schainHash]; } /** * @dev Checks whether channel is opened. */ function isChannelOpened(bytes32 schainHash) external override view returns (bool) { return channels[schainHash].active; } function isLastDKGSuccessful(bytes32 schainHash) external override view returns (bool) { return channels[schainHash].startedBlockTimestamp <= lastSuccessfulDKG[schainHash]; } /** * @dev Checks whether broadcast is possible. */ function isBroadcastPossible(bytes32 schainHash, uint nodeIndex) external view returns (bool) { (uint index, bool check) = checkAndReturnIndexInGroup(schainHash, nodeIndex, false); return channels[schainHash].active && check && _isNodeOwnedByMessageSender(nodeIndex, msg.sender) && !dkgProcess[schainHash].broadcasted[index]; } /** * @dev Checks whether complaint is possible. */ function isComplaintPossible( bytes32 schainHash, uint fromNodeIndex, uint toNodeIndex ) external view returns (bool) { (uint indexFrom, bool checkFrom) = checkAndReturnIndexInGroup(schainHash, fromNodeIndex, false); (uint indexTo, bool checkTo) = checkAndReturnIndexInGroup(schainHash, toNodeIndex, false); if (!checkFrom || !checkTo) return false; bool complaintSending = ( complaints[schainHash].nodeToComplaint == uint(-1) && dkgProcess[schainHash].broadcasted[indexTo] && !dkgProcess[schainHash].completed[indexFrom] ) || ( dkgProcess[schainHash].broadcasted[indexTo] && complaints[schainHash].startComplaintBlockTimestamp.add(_getComplaintTimelimit()) <= block.timestamp && complaints[schainHash].nodeToComplaint == toNodeIndex ) || ( !dkgProcess[schainHash].broadcasted[indexTo] && complaints[schainHash].nodeToComplaint == uint(-1) && channels[schainHash].startedBlockTimestamp.add(_getComplaintTimelimit()) <= block.timestamp ) || ( complaints[schainHash].nodeToComplaint == uint(-1) && isEveryoneBroadcasted(schainHash) && dkgProcess[schainHash].completed[indexFrom] && !dkgProcess[schainHash].completed[indexTo] && startAlrightTimestamp[schainHash].add(_getComplaintTimelimit()) <= block.timestamp ); return channels[schainHash].active && dkgProcess[schainHash].broadcasted[indexFrom] && _isNodeOwnedByMessageSender(fromNodeIndex, msg.sender) && complaintSending; } /** * @dev Checks whether sending Alright response is possible. */ function isAlrightPossible(bytes32 schainHash, uint nodeIndex) external view returns (bool) { (uint index, bool check) = checkAndReturnIndexInGroup(schainHash, nodeIndex, false); return channels[schainHash].active && check && _isNodeOwnedByMessageSender(nodeIndex, msg.sender) && channels[schainHash].n == dkgProcess[schainHash].numberOfBroadcasted && (complaints[schainHash].fromNodeToComplaint != nodeIndex || (nodeIndex == 0 && complaints[schainHash].startComplaintBlockTimestamp == 0)) && !dkgProcess[schainHash].completed[index]; } /** * @dev Checks whether sending a pre-response is possible. */ function isPreResponsePossible(bytes32 schainHash, uint nodeIndex) external view returns (bool) { (, bool check) = checkAndReturnIndexInGroup(schainHash, nodeIndex, false); return channels[schainHash].active && check && _isNodeOwnedByMessageSender(nodeIndex, msg.sender) && complaints[schainHash].nodeToComplaint == nodeIndex && !complaints[schainHash].isResponse; } /** * @dev Checks whether sending a response is possible. */ function isResponsePossible(bytes32 schainHash, uint nodeIndex) external view returns (bool) { (, bool check) = checkAndReturnIndexInGroup(schainHash, nodeIndex, false); return channels[schainHash].active && check && _isNodeOwnedByMessageSender(nodeIndex, msg.sender) && complaints[schainHash].nodeToComplaint == nodeIndex && complaints[schainHash].isResponse; } function isNodeBroadcasted(bytes32 schainHash, uint nodeIndex) external view returns (bool) { (uint index, bool check) = checkAndReturnIndexInGroup(schainHash, nodeIndex, false); return check && dkgProcess[schainHash].broadcasted[index]; } /** * @dev Checks whether all data has been received by node. */ function isAllDataReceived(bytes32 schainHash, uint nodeIndex) external view returns (bool) { (uint index, bool check) = checkAndReturnIndexInGroup(schainHash, nodeIndex, false); return check && dkgProcess[schainHash].completed[index]; } function hashData( KeyShare[] memory secretKeyContribution, G2Operations.G2Point[] memory verificationVector ) external pure returns (bytes32) { bytes memory data; for (uint i = 0; i < secretKeyContribution.length; i++) { data = abi.encodePacked(data, secretKeyContribution[i].publicKey, secretKeyContribution[i].share); } for (uint i = 0; i < verificationVector.length; i++) { data = abi.encodePacked( data, verificationVector[i].x.a, verificationVector[i].x.b, verificationVector[i].y.a, verificationVector[i].y.b ); } return keccak256(data); } function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); } function checkAndReturnIndexInGroup( bytes32 schainHash, uint nodeIndex, bool revertCheck ) public view returns (uint, bool) { uint index = SchainsInternal(contractManager.getContract("SchainsInternal")) .getNodeIndexInGroup(schainHash, nodeIndex); if (index >= channels[schainHash].n && revertCheck) { revert("Node is not in this group"); } return (index, index < channels[schainHash].n); } function _refundGasBySchain(bytes32 schainHash, uint gasTotal, Context memory context) private { Wallets wallets = Wallets(payable(contractManager.getContract("Wallets"))); bool isLastNode = channels[schainHash].n == dkgProcess[schainHash].numberOfCompleted; if (context.dkgFunction == DkgFunction.Alright && isLastNode) { wallets.refundGasBySchain( schainHash, msg.sender, gasTotal.sub(gasleft()).add(context.delta).sub(74800), context.isDebt ); } else if (context.dkgFunction == DkgFunction.Complaint && gasTotal.sub(gasleft()) > 14e5) { wallets.refundGasBySchain( schainHash, msg.sender, gasTotal.sub(gasleft()).add(context.delta).sub(590000), context.isDebt ); } else if (context.dkgFunction == DkgFunction.Complaint && gasTotal.sub(gasleft()) > 7e5) { wallets.refundGasBySchain( schainHash, msg.sender, gasTotal.sub(gasleft()).add(context.delta).sub(250000), context.isDebt ); } else if (context.dkgFunction == DkgFunction.Response){ wallets.refundGasBySchain( schainHash, msg.sender, gasTotal.sub(gasleft()).sub(context.delta), context.isDebt ); } else { wallets.refundGasBySchain( schainHash, msg.sender, gasTotal.sub(gasleft()).add(context.delta), context.isDebt ); } } function _refundGasByValidatorToSchain(bytes32 schainHash) private { uint validatorId = Nodes(contractManager.getContract("Nodes")) .getValidatorId(_badNodes[schainHash]); Wallets(payable(contractManager.getContract("Wallets"))) .refundGasByValidatorToSchain(validatorId, schainHash); delete _badNodes[schainHash]; } function _openChannel(bytes32 schainHash) private { SchainsInternal schainsInternal = SchainsInternal( contractManager.getContract("SchainsInternal") ); uint len = schainsInternal.getNumberOfNodesInGroup(schainHash); channels[schainHash].active = true; channels[schainHash].n = len; delete dkgProcess[schainHash].completed; delete dkgProcess[schainHash].broadcasted; dkgProcess[schainHash].broadcasted = new bool[](len); dkgProcess[schainHash].completed = new bool[](len); complaints[schainHash].fromNodeToComplaint = uint(-1); complaints[schainHash].nodeToComplaint = uint(-1); delete complaints[schainHash].startComplaintBlockTimestamp; delete dkgProcess[schainHash].numberOfBroadcasted; delete dkgProcess[schainHash].numberOfCompleted; channels[schainHash].startedBlockTimestamp = now; channels[schainHash].startedBlock = block.number; KeyStorage(contractManager.getContract("KeyStorage")).initPublicKeyInProgress(schainHash); emit ChannelOpened(schainHash); } function isEveryoneBroadcasted(bytes32 schainHash) public view returns (bool) { return channels[schainHash].n == dkgProcess[schainHash].numberOfBroadcasted; } function _isNodeOwnedByMessageSender(uint nodeIndex, address from) private view returns (bool) { return Nodes(contractManager.getContract("Nodes")).isNodeExist(from, nodeIndex); } function _checkMsgSenderIsNodeOwner(uint nodeIndex) private view { require(_isNodeOwnedByMessageSender(nodeIndex, msg.sender), "Node does not exist for message sender"); } function _getComplaintTimelimit() private view returns (uint) { return ConstantsHolder(contractManager.getConstantsHolder()).complaintTimelimit(); } } // SPDX-License-Identifier: AGPL-3.0-only /* Wallets.sol - SKALE Manager Copyright (C) 2021-Present SKALE Labs @author Dmytro Stebaiev @author Artem Payvin @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "@skalenetwork/skale-manager-interfaces/IWallets.sol"; import "./Permissions.sol"; import "./delegation/ValidatorService.sol"; import "./SchainsInternal.sol"; import "./Nodes.sol"; /** * @title Wallets * @dev Contract contains logic to perform automatic self-recharging ether for nodes */ contract Wallets is Permissions, IWallets { mapping (uint => uint) private _validatorWallets; mapping (bytes32 => uint) private _schainWallets; mapping (bytes32 => uint) private _schainDebts; /** * @dev Emitted when the validator wallet was funded */ event ValidatorWalletRecharged(address sponsor, uint amount, uint validatorId); /** * @dev Emitted when the schain wallet was funded */ event SchainWalletRecharged(address sponsor, uint amount, bytes32 schainHash); /** * @dev Emitted when the node received a refund from validator to its wallet */ event NodeRefundedByValidator(address node, uint validatorId, uint amount); /** * @dev Emitted when the node received a refund from schain to its wallet */ event NodeRefundedBySchain(address node, bytes32 schainHash, uint amount); /** * @dev Is executed on a call to the contract with empty calldata. * This is the function that is executed on plain Ether transfers, * so validator or schain owner can use usual transfer ether to recharge wallet. */ receive() external payable { ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); bytes32[] memory schainHashs = schainsInternal.getSchainHashsByAddress(msg.sender); if (schainHashs.length == 1) { rechargeSchainWallet(schainHashs[0]); } else { uint validatorId = validatorService.getValidatorId(msg.sender); rechargeValidatorWallet(validatorId); } } /** * @dev Reimburse gas for node by validator wallet. If validator wallet has not enough funds * the node will receive the entire remaining amount in the validator's wallet. * `validatorId` - validator that will reimburse desired transaction * `spender` - address to send reimbursed funds * `spentGas` - amount of spent gas that should be reimbursed to desired node * * Emits a {NodeRefundedByValidator} event. * * Requirements: * - Given validator should exist */ function refundGasByValidator( uint validatorId, address payable spender, uint spentGas ) external allowTwo("SkaleManager", "SkaleDKG") { require(validatorId != 0, "ValidatorId could not be zero"); uint amount = tx.gasprice * spentGas; if (amount <= _validatorWallets[validatorId]) { _validatorWallets[validatorId] = _validatorWallets[validatorId].sub(amount); emit NodeRefundedByValidator(spender, validatorId, amount); spender.transfer(amount); } else { uint wholeAmount = _validatorWallets[validatorId]; // solhint-disable-next-line reentrancy delete _validatorWallets[validatorId]; emit NodeRefundedByValidator(spender, validatorId, wholeAmount); spender.transfer(wholeAmount); } } /** * @dev Returns the amount owed to the owner of the chain by the validator, * if the validator does not have enough funds, then everything * that the validator has will be returned to the owner of the chain. */ function refundGasByValidatorToSchain(uint validatorId, bytes32 schainHash) external allow("SkaleDKG") { uint debtAmount = _schainDebts[schainHash]; uint validatorWallet = _validatorWallets[validatorId]; if (debtAmount <= validatorWallet) { _validatorWallets[validatorId] = validatorWallet.sub(debtAmount); } else { debtAmount = validatorWallet; delete _validatorWallets[validatorId]; } _schainWallets[schainHash] = _schainWallets[schainHash].add(debtAmount); delete _schainDebts[schainHash]; } /** * @dev Reimburse gas for node by schain wallet. If schain wallet has not enough funds * than transaction will be reverted. * `schainHash` - schain that will reimburse desired transaction * `spender` - address to send reimbursed funds * `spentGas` - amount of spent gas that should be reimbursed to desired node * `isDebt` - parameter that indicates whether this amount should be recorded as debt for the validator * * Emits a {NodeRefundedBySchain} event. * * Requirements: * - Given schain should exist * - Schain wallet should have enough funds */ function refundGasBySchain( bytes32 schainHash, address payable spender, uint spentGas, bool isDebt ) external override allowTwo("SkaleDKG", "MessageProxyForMainnet") { uint amount = tx.gasprice * spentGas; if (isDebt) { amount += (_schainDebts[schainHash] == 0 ? 21000 : 6000) * tx.gasprice; _schainDebts[schainHash] = _schainDebts[schainHash].add(amount); } require(schainHash != bytes32(0), "SchainHash cannot be null"); require(amount <= _schainWallets[schainHash], "Schain wallet has not enough funds"); _schainWallets[schainHash] = _schainWallets[schainHash].sub(amount); emit NodeRefundedBySchain(spender, schainHash, amount); spender.transfer(amount); } /** * @dev Withdraws money from schain wallet. Possible to execute only after deleting schain. * `schainOwner` - address of schain owner that will receive rest of the schain balance * `schainHash` - schain wallet from which money is withdrawn * * Requirements: * - Executable only after initing delete schain */ function withdrawFundsFromSchainWallet(address payable schainOwner, bytes32 schainHash) external allow("Schains") { uint amount = _schainWallets[schainHash]; delete _schainWallets[schainHash]; schainOwner.transfer(amount); } /** * @dev Withdraws money from vaildator wallet. * `amount` - the amount of money in wei * * Requirements: * - Validator must have sufficient withdrawal amount */ function withdrawFundsFromValidatorWallet(uint amount) external { ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); uint validatorId = validatorService.getValidatorId(msg.sender); require(amount <= _validatorWallets[validatorId], "Balance is too low"); _validatorWallets[validatorId] = _validatorWallets[validatorId].sub(amount); msg.sender.transfer(amount); } function getSchainBalance(bytes32 schainHash) external view returns (uint) { return _schainWallets[schainHash]; } function getValidatorBalance(uint validatorId) external view returns (uint) { return _validatorWallets[validatorId]; } /** * @dev Recharge the validator wallet by id. * `validatorId` - id of existing validator. * * Emits a {ValidatorWalletRecharged} event. * * Requirements: * - Given validator must exist */ function rechargeValidatorWallet(uint validatorId) public payable { ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); require(validatorService.validatorExists(validatorId), "Validator does not exists"); _validatorWallets[validatorId] = _validatorWallets[validatorId].add(msg.value); emit ValidatorWalletRecharged(msg.sender, msg.value, validatorId); } /** * @dev Recharge the schain wallet by schainHash (hash of schain name). * `schainHash` - id of existing schain. * * Emits a {SchainWalletRecharged} event. * * Requirements: * - Given schain must be created */ function rechargeSchainWallet(bytes32 schainHash) public payable override { SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); require(schainsInternal.isSchainActive(schainHash), "Schain should be active for recharging"); _schainWallets[schainHash] = _schainWallets[schainHash].add(msg.value); emit SchainWalletRecharged(msg.sender, msg.value, schainHash); } function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); } } // SPDX-License-Identifier: AGPL-3.0-only /* KeyStorage.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "./Decryption.sol"; import "./Permissions.sol"; import "./SchainsInternal.sol"; import "./thirdparty/ECDH.sol"; import "./utils/Precompiled.sol"; import "./utils/FieldOperations.sol"; contract KeyStorage is Permissions { using Fp2Operations for Fp2Operations.Fp2Point; using G2Operations for G2Operations.G2Point; struct BroadcastedData { KeyShare[] secretKeyContribution; G2Operations.G2Point[] verificationVector; } struct KeyShare { bytes32[2] publicKey; bytes32 share; } // Unused variable!! mapping(bytes32 => mapping(uint => BroadcastedData)) private _data; // mapping(bytes32 => G2Operations.G2Point) private _publicKeysInProgress; mapping(bytes32 => G2Operations.G2Point) private _schainsPublicKeys; // Unused variable mapping(bytes32 => G2Operations.G2Point[]) private _schainsNodesPublicKeys; // mapping(bytes32 => G2Operations.G2Point[]) private _previousSchainsPublicKeys; function deleteKey(bytes32 schainHash) external allow("SkaleDKG") { _previousSchainsPublicKeys[schainHash].push(_schainsPublicKeys[schainHash]); delete _schainsPublicKeys[schainHash]; delete _data[schainHash][0]; delete _schainsNodesPublicKeys[schainHash]; } function initPublicKeyInProgress(bytes32 schainHash) external allow("SkaleDKG") { _publicKeysInProgress[schainHash] = G2Operations.getG2Zero(); } function adding(bytes32 schainHash, G2Operations.G2Point memory value) external allow("SkaleDKG") { require(value.isG2(), "Incorrect g2 point"); _publicKeysInProgress[schainHash] = value.addG2(_publicKeysInProgress[schainHash]); } function finalizePublicKey(bytes32 schainHash) external allow("SkaleDKG") { if (!_isSchainsPublicKeyZero(schainHash)) { _previousSchainsPublicKeys[schainHash].push(_schainsPublicKeys[schainHash]); } _schainsPublicKeys[schainHash] = _publicKeysInProgress[schainHash]; delete _publicKeysInProgress[schainHash]; } function getCommonPublicKey(bytes32 schainHash) external view returns (G2Operations.G2Point memory) { return _schainsPublicKeys[schainHash]; } function getPreviousPublicKey(bytes32 schainHash) external view returns (G2Operations.G2Point memory) { uint length = _previousSchainsPublicKeys[schainHash].length; if (length == 0) { return G2Operations.getG2Zero(); } return _previousSchainsPublicKeys[schainHash][length - 1]; } function getAllPreviousPublicKeys(bytes32 schainHash) external view returns (G2Operations.G2Point[] memory) { return _previousSchainsPublicKeys[schainHash]; } function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); } function _isSchainsPublicKeyZero(bytes32 schainHash) private view returns (bool) { return _schainsPublicKeys[schainHash].x.a == 0 && _schainsPublicKeys[schainHash].x.b == 0 && _schainsPublicKeys[schainHash].y.a == 0 && _schainsPublicKeys[schainHash].y.b == 0; } } // SPDX-License-Identifier: AGPL-3.0-only /* SlashingTable.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "./Permissions.sol"; import "./ConstantsHolder.sol"; /** * @title Slashing Table * @dev This contract manages slashing conditions and penalties. */ contract SlashingTable is Permissions { mapping (uint => uint) private _penalties; bytes32 public constant PENALTY_SETTER_ROLE = keccak256("PENALTY_SETTER_ROLE"); /** * @dev Allows the Owner to set a slashing penalty in SKL tokens for a * given offense. */ function setPenalty(string calldata offense, uint penalty) external { require(hasRole(PENALTY_SETTER_ROLE, msg.sender), "PENALTY_SETTER_ROLE is required"); _penalties[uint(keccak256(abi.encodePacked(offense)))] = penalty; } /** * @dev Returns the penalty in SKL tokens for a given offense. */ function getPenalty(string calldata offense) external view returns (uint) { uint penalty = _penalties[uint(keccak256(abi.encodePacked(offense)))]; return penalty; } function initialize(address contractManagerAddress) public override initializer { Permissions.initialize(contractManagerAddress); } } // SPDX-License-Identifier: AGPL-3.0-only /* Schains.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "@skalenetwork/skale-manager-interfaces/ISchains.sol"; import "./Permissions.sol"; import "./SchainsInternal.sol"; import "./ConstantsHolder.sol"; import "./KeyStorage.sol"; import "./SkaleVerifier.sol"; import "./utils/FieldOperations.sol"; import "./NodeRotation.sol"; import "./interfaces/ISkaleDKG.sol"; import "./Wallets.sol"; /** * @title Schains * @dev Contains functions to manage Schains such as Schain creation, * deletion, and rotation. */ contract Schains is Permissions, ISchains { struct SchainParameters { uint lifetime; uint8 typeOfSchain; uint16 nonce; string name; } bytes32 public constant SCHAIN_CREATOR_ROLE = keccak256("SCHAIN_CREATOR_ROLE"); /** * @dev Emitted when an schain is created. */ event SchainCreated( string name, address owner, uint partOfNode, uint lifetime, uint numberOfNodes, uint deposit, uint16 nonce, bytes32 schainHash, uint time, uint gasSpend ); /** * @dev Emitted when an schain is deleted. */ event SchainDeleted( address owner, string name, bytes32 indexed schainHash ); /** * @dev Emitted when a node in an schain is rotated. */ event NodeRotated( bytes32 schainHash, uint oldNode, uint newNode ); /** * @dev Emitted when a node is added to an schain. */ event NodeAdded( bytes32 schainHash, uint newNode ); /** * @dev Emitted when a group of nodes is created for an schain. */ event SchainNodes( string name, bytes32 schainHash, uint[] nodesInGroup, uint time, uint gasSpend ); /** * @dev Allows SkaleManager contract to create an Schain. * * Emits an {SchainCreated} event. * * Requirements: * * - Schain type is valid. * - There is sufficient deposit to create type of schain. */ function addSchain(address from, uint deposit, bytes calldata data) external allow("SkaleManager") { SchainParameters memory schainParameters = _fallbackSchainParametersDataConverter(data); ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getConstantsHolder()); uint schainCreationTimeStamp = constantsHolder.schainCreationTimeStamp(); uint minSchainLifetime = constantsHolder.minimalSchainLifetime(); require(now >= schainCreationTimeStamp, "It is not a time for creating Schain"); require( schainParameters.lifetime >= minSchainLifetime, "Minimal schain lifetime should be satisfied" ); require( getSchainPrice(schainParameters.typeOfSchain, schainParameters.lifetime) <= deposit, "Not enough money to create Schain"); _addSchain(from, deposit, schainParameters); } /** * @dev Allows the foundation to create an Schain without tokens. * * Emits an {SchainCreated} event. * * Requirements: * * - sender is granted with SCHAIN_CREATOR_ROLE * - Schain type is valid. */ function addSchainByFoundation( uint lifetime, uint8 typeOfSchain, uint16 nonce, string calldata name, address schainOwner ) external payable { require(hasRole(SCHAIN_CREATOR_ROLE, msg.sender), "Sender is not authorized to create schain"); SchainParameters memory schainParameters = SchainParameters({ lifetime: lifetime, typeOfSchain: typeOfSchain, nonce: nonce, name: name }); address _schainOwner; if (schainOwner != address(0)) { _schainOwner = schainOwner; } else { _schainOwner = msg.sender; } _addSchain(_schainOwner, 0, schainParameters); bytes32 schainHash = keccak256(abi.encodePacked(name)); Wallets(payable(contractManager.getContract("Wallets"))).rechargeSchainWallet{value: msg.value}(schainHash); } /** * @dev Allows SkaleManager to remove an schain from the network. * Upon removal, the space availability of each node is updated. * * Emits an {SchainDeleted} event. * * Requirements: * * - Executed by schain owner. */ function deleteSchain(address from, string calldata name) external allow("SkaleManager") { SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); bytes32 schainHash = keccak256(abi.encodePacked(name)); require( schainsInternal.isOwnerAddress(from, schainHash), "Message sender is not the owner of the Schain" ); _deleteSchain(name, schainsInternal); } /** * @dev Allows SkaleManager to delete any Schain. * Upon removal, the space availability of each node is updated. * * Emits an {SchainDeleted} event. * * Requirements: * * - Schain exists. */ function deleteSchainByRoot(string calldata name) external allow("SkaleManager") { _deleteSchain(name, SchainsInternal(contractManager.getContract("SchainsInternal"))); } /** * @dev Allows SkaleManager contract to restart schain creation by forming a * new schain group. Executed when DKG procedure fails and becomes stuck. * * Emits a {NodeAdded} event. * * Requirements: * * - Previous DKG procedure must have failed. * - DKG failure got stuck because there were no free nodes to rotate in. * - A free node must be released in the network. */ function restartSchainCreation(string calldata name) external allow("SkaleManager") { NodeRotation nodeRotation = NodeRotation(contractManager.getContract("NodeRotation")); bytes32 schainHash = keccak256(abi.encodePacked(name)); ISkaleDKG skaleDKG = ISkaleDKG(contractManager.getContract("SkaleDKG")); require(!skaleDKG.isLastDKGSuccessful(schainHash), "DKG success"); SchainsInternal schainsInternal = SchainsInternal( contractManager.getContract("SchainsInternal")); require(schainsInternal.isAnyFreeNode(schainHash), "No free Nodes for new group formation"); uint newNodeIndex = nodeRotation.selectNodeToGroup(schainHash); skaleDKG.openChannel(schainHash); emit NodeAdded(schainHash, newNodeIndex); } /** * @dev addSpace - return occupied space to Node * nodeIndex - index of Node at common array of Nodes * partOfNode - divisor of given type of Schain */ function addSpace(uint nodeIndex, uint8 partOfNode) external allowTwo("Schains", "NodeRotation") { Nodes nodes = Nodes(contractManager.getContract("Nodes")); nodes.addSpaceToNode(nodeIndex, partOfNode); } /** * @dev Checks whether schain group signature is valid. */ function verifySchainSignature( uint signatureA, uint signatureB, bytes32 hash, uint counter, uint hashA, uint hashB, string calldata schainName ) external view override returns (bool) { SkaleVerifier skaleVerifier = SkaleVerifier(contractManager.getContract("SkaleVerifier")); G2Operations.G2Point memory publicKey = KeyStorage( contractManager.getContract("KeyStorage") ).getCommonPublicKey( keccak256(abi.encodePacked(schainName)) ); return skaleVerifier.verify( Fp2Operations.Fp2Point({ a: signatureA, b: signatureB }), hash, counter, hashA, hashB, publicKey ); } function initialize(address newContractsAddress) public override initializer { Permissions.initialize(newContractsAddress); } /** * @dev Returns the current price in SKL tokens for given Schain type and lifetime. */ function getSchainPrice(uint typeOfSchain, uint lifetime) public view returns (uint) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getConstantsHolder()); SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); uint nodeDeposit = constantsHolder.NODE_DEPOSIT(); uint numberOfNodes; uint8 divisor; (divisor, numberOfNodes) = schainsInternal.getSchainType(typeOfSchain); if (divisor == 0) { return 1e18; } else { uint up = nodeDeposit.mul(numberOfNodes.mul(lifetime.mul(2))); uint down = uint( uint(constantsHolder.SMALL_DIVISOR()) .mul(uint(constantsHolder.SECONDS_TO_YEAR())) .div(divisor) ); return up.div(down); } } /** * @dev Initializes an schain in the SchainsInternal contract. * * Requirements: * * - Schain name is not already in use. */ function _initializeSchainInSchainsInternal( string memory name, address from, uint deposit, uint lifetime, SchainsInternal schainsInternal ) private { require(schainsInternal.isSchainNameAvailable(name), "Schain name is not available"); // initialize Schain schainsInternal.initializeSchain(name, from, lifetime, deposit); schainsInternal.setSchainIndex(keccak256(abi.encodePacked(name)), from); } /** * @dev Converts data from bytes to normal schain parameters of lifetime, * type, nonce, and name. */ function _fallbackSchainParametersDataConverter(bytes memory data) private pure returns (SchainParameters memory schainParameters) { (schainParameters.lifetime, schainParameters.typeOfSchain, schainParameters.nonce, schainParameters.name) = abi.decode(data, (uint, uint8, uint16, string)); } /** * @dev Allows creation of node group for Schain. * * Emits an {SchainNodes} event. */ function _createGroupForSchain( string memory schainName, bytes32 schainHash, uint numberOfNodes, uint8 partOfNode, SchainsInternal schainsInternal ) private { uint[] memory nodesInGroup = schainsInternal.createGroupForSchain(schainHash, numberOfNodes, partOfNode); ISkaleDKG(contractManager.getContract("SkaleDKG")).openChannel(schainHash); emit SchainNodes( schainName, schainHash, nodesInGroup, block.timestamp, gasleft()); } /** * @dev Creates an schain. * * Emits an {SchainCreated} event. * * Requirements: * * - Schain type must be valid. */ function _addSchain(address from, uint deposit, SchainParameters memory schainParameters) private { SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); //initialize Schain _initializeSchainInSchainsInternal( schainParameters.name, from, deposit, schainParameters.lifetime, schainsInternal ); // create a group for Schain uint numberOfNodes; uint8 partOfNode; (partOfNode, numberOfNodes) = schainsInternal.getSchainType(schainParameters.typeOfSchain); _createGroupForSchain( schainParameters.name, keccak256(abi.encodePacked(schainParameters.name)), numberOfNodes, partOfNode, schainsInternal ); emit SchainCreated( schainParameters.name, from, partOfNode, schainParameters.lifetime, numberOfNodes, deposit, schainParameters.nonce, keccak256(abi.encodePacked(schainParameters.name)), block.timestamp, gasleft()); } function _deleteSchain(string calldata name, SchainsInternal schainsInternal) private { NodeRotation nodeRotation = NodeRotation(contractManager.getContract("NodeRotation")); bytes32 schainHash = keccak256(abi.encodePacked(name)); require(schainsInternal.isSchainExist(schainHash), "Schain does not exist"); uint[] memory nodesInGroup = schainsInternal.getNodesInGroup(schainHash); uint8 partOfNode = schainsInternal.getSchainsPartOfNode(schainHash); for (uint i = 0; i < nodesInGroup.length; i++) { uint schainIndex = schainsInternal.findSchainAtSchainsForNode( nodesInGroup[i], schainHash ); if (schainsInternal.checkHoleForSchain(schainHash, i)) { continue; } require( schainIndex < schainsInternal.getLengthOfSchainsForNode(nodesInGroup[i]), "Some Node does not contain given Schain"); schainsInternal.removeNodeFromSchain(nodesInGroup[i], schainHash); schainsInternal.removeNodeFromExceptions(schainHash, nodesInGroup[i]); this.addSpace(nodesInGroup[i], partOfNode); } schainsInternal.deleteGroup(schainHash); address from = schainsInternal.getSchainOwner(schainHash); schainsInternal.removeSchain(schainHash, from); schainsInternal.removeHolesForSchain(schainHash); nodeRotation.removeRotation(schainHash); Wallets( payable(contractManager.getContract("Wallets")) ).withdrawFundsFromSchainWallet(payable(from), schainHash); emit SchainDeleted(from, name, schainHash); } } // SPDX-License-Identifier: AGPL-3.0-only /* SchainsInternal.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/utils/EnumerableSet.sol"; import "@skalenetwork/skale-manager-interfaces/ISchainsInternal.sol"; import "./interfaces/ISkaleDKG.sol"; import "./utils/Random.sol"; import "./ConstantsHolder.sol"; import "./Nodes.sol"; /** * @title SchainsInternal * @dev Contract contains all functionality logic to internally manage Schains. */ contract SchainsInternal is Permissions, ISchainsInternal { using Random for Random.RandomGenerator; using EnumerableSet for EnumerableSet.UintSet; struct Schain { string name; address owner; uint indexInOwnerList; uint8 partOfNode; uint lifetime; uint startDate; uint startBlock; uint deposit; uint64 index; } struct SchainType { uint8 partOfNode; uint numberOfNodes; } // mapping which contain all schains mapping (bytes32 => Schain) public schains; mapping (bytes32 => bool) public isSchainActive; mapping (bytes32 => uint[]) public schainsGroups; mapping (bytes32 => mapping (uint => bool)) private _exceptionsForGroups; // mapping shows schains by owner's address mapping (address => bytes32[]) public schainIndexes; // mapping shows schains which Node composed in mapping (uint => bytes32[]) public schainsForNodes; mapping (uint => uint[]) public holesForNodes; mapping (bytes32 => uint[]) public holesForSchains; // array which contain all schains bytes32[] public schainsAtSystem; uint64 public numberOfSchains; // total resources that schains occupied uint public sumOfSchainsResources; mapping (bytes32 => bool) public usedSchainNames; mapping (uint => SchainType) public schainTypes; uint public numberOfSchainTypes; // schain hash => node index => index of place // index of place is a number from 1 to max number of slots on node(128) mapping (bytes32 => mapping (uint => uint)) public placeOfSchainOnNode; mapping (uint => bytes32[]) private _nodeToLockedSchains; mapping (bytes32 => uint[]) private _schainToExceptionNodes; EnumerableSet.UintSet private _keysOfSchainTypes; bytes32 public constant SCHAIN_TYPE_MANAGER_ROLE = keccak256("SCHAIN_TYPE_MANAGER_ROLE"); bytes32 public constant DEBUGGER_ROLE = keccak256("DEBUGGER_ROLE"); modifier onlySchainTypeManager() { require(hasRole(SCHAIN_TYPE_MANAGER_ROLE, msg.sender), "SCHAIN_TYPE_MANAGER_ROLE is required"); _; } modifier onlyDebugger() { require(hasRole(DEBUGGER_ROLE, msg.sender), "DEBUGGER_ROLE is required"); _; } /** * @dev Allows Schain contract to initialize an schain. */ function initializeSchain( string calldata name, address from, uint lifetime, uint deposit) external allow("Schains") { bytes32 schainHash = keccak256(abi.encodePacked(name)); schains[schainHash].name = name; schains[schainHash].owner = from; schains[schainHash].startDate = block.timestamp; schains[schainHash].startBlock = block.number; schains[schainHash].lifetime = lifetime; schains[schainHash].deposit = deposit; schains[schainHash].index = numberOfSchains; isSchainActive[schainHash] = true; numberOfSchains++; schainsAtSystem.push(schainHash); usedSchainNames[schainHash] = true; } /** * @dev Allows Schain contract to create a node group for an schain. */ function createGroupForSchain( bytes32 schainHash, uint numberOfNodes, uint8 partOfNode ) external allow("Schains") returns (uint[] memory) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); schains[schainHash].partOfNode = partOfNode; if (partOfNode > 0) { sumOfSchainsResources = sumOfSchainsResources.add( numberOfNodes.mul(constantsHolder.TOTAL_SPACE_ON_NODE()).div(partOfNode) ); } return _generateGroup(schainHash, numberOfNodes); } /** * @dev Allows Schains contract to set index in owner list. */ function setSchainIndex(bytes32 schainHash, address from) external allow("Schains") { schains[schainHash].indexInOwnerList = schainIndexes[from].length; schainIndexes[from].push(schainHash); } /** * @dev Allows Schains contract to change the Schain lifetime through * an additional SKL token deposit. */ function changeLifetime(bytes32 schainHash, uint lifetime, uint deposit) external allow("Schains") { schains[schainHash].deposit = schains[schainHash].deposit.add(deposit); schains[schainHash].lifetime = schains[schainHash].lifetime.add(lifetime); } /** * @dev Allows Schains contract to remove an schain from the network. * Generally schains are not removed from the system; instead they are * simply allowed to expire. */ function removeSchain(bytes32 schainHash, address from) external allow("Schains") { isSchainActive[schainHash] = false; uint length = schainIndexes[from].length; uint index = schains[schainHash].indexInOwnerList; if (index != length.sub(1)) { bytes32 lastSchainHash = schainIndexes[from][length.sub(1)]; schains[lastSchainHash].indexInOwnerList = index; schainIndexes[from][index] = lastSchainHash; } schainIndexes[from].pop(); // TODO: // optimize for (uint i = 0; i + 1 < schainsAtSystem.length; i++) { if (schainsAtSystem[i] == schainHash) { schainsAtSystem[i] = schainsAtSystem[schainsAtSystem.length.sub(1)]; break; } } schainsAtSystem.pop(); delete schains[schainHash]; numberOfSchains--; } /** * @dev Allows Schains and SkaleDKG contracts to remove a node from an * schain for node rotation or DKG failure. */ function removeNodeFromSchain( uint nodeIndex, bytes32 schainHash ) external allowThree("NodeRotation", "SkaleDKG", "Schains") { uint indexOfNode = _findNode(schainHash, nodeIndex); uint indexOfLastNode = schainsGroups[schainHash].length.sub(1); if (indexOfNode == indexOfLastNode) { schainsGroups[schainHash].pop(); } else { delete schainsGroups[schainHash][indexOfNode]; if (holesForSchains[schainHash].length > 0 && holesForSchains[schainHash][0] > indexOfNode) { uint hole = holesForSchains[schainHash][0]; holesForSchains[schainHash][0] = indexOfNode; holesForSchains[schainHash].push(hole); } else { holesForSchains[schainHash].push(indexOfNode); } } uint schainIndexOnNode = findSchainAtSchainsForNode(nodeIndex, schainHash); removeSchainForNode(nodeIndex, schainIndexOnNode); delete placeOfSchainOnNode[schainHash][nodeIndex]; } /** * @dev Allows Schains contract to delete a group of schains */ function deleteGroup(bytes32 schainHash) external allow("Schains") { // delete channel ISkaleDKG skaleDKG = ISkaleDKG(contractManager.getContract("SkaleDKG")); delete schainsGroups[schainHash]; skaleDKG.deleteChannel(schainHash); } /** * @dev Allows Schain and NodeRotation contracts to set a Node like * exception for a given schain and nodeIndex. */ function setException(bytes32 schainHash, uint nodeIndex) external allowTwo("Schains", "NodeRotation") { _setException(schainHash, nodeIndex); } /** * @dev Allows Schains and NodeRotation contracts to add node to an schain * group. */ function setNodeInGroup(bytes32 schainHash, uint nodeIndex) external allowTwo("Schains", "NodeRotation") { if (holesForSchains[schainHash].length == 0) { schainsGroups[schainHash].push(nodeIndex); } else { schainsGroups[schainHash][holesForSchains[schainHash][0]] = nodeIndex; uint min = uint(-1); uint index = 0; for (uint i = 1; i < holesForSchains[schainHash].length; i++) { if (min > holesForSchains[schainHash][i]) { min = holesForSchains[schainHash][i]; index = i; } } if (min == uint(-1)) { delete holesForSchains[schainHash]; } else { holesForSchains[schainHash][0] = min; holesForSchains[schainHash][index] = holesForSchains[schainHash][holesForSchains[schainHash].length - 1]; holesForSchains[schainHash].pop(); } } } /** * @dev Allows Schains contract to remove holes for schains */ function removeHolesForSchain(bytes32 schainHash) external allow("Schains") { delete holesForSchains[schainHash]; } /** * @dev Allows Admin to add schain type */ function addSchainType(uint8 partOfNode, uint numberOfNodes) external onlySchainTypeManager { require(_keysOfSchainTypes.add(numberOfSchainTypes + 1), "Schain type is already added"); schainTypes[numberOfSchainTypes + 1].partOfNode = partOfNode; schainTypes[numberOfSchainTypes + 1].numberOfNodes = numberOfNodes; numberOfSchainTypes++; } /** * @dev Allows Admin to remove schain type */ function removeSchainType(uint typeOfSchain) external onlySchainTypeManager { require(_keysOfSchainTypes.remove(typeOfSchain), "Schain type is already removed"); delete schainTypes[typeOfSchain].partOfNode; delete schainTypes[typeOfSchain].numberOfNodes; } /** * @dev Allows Admin to set number of schain types */ function setNumberOfSchainTypes(uint newNumberOfSchainTypes) external onlySchainTypeManager { numberOfSchainTypes = newNumberOfSchainTypes; } /** * @dev Allows Admin to move schain to placeOfSchainOnNode map */ function moveToPlaceOfSchainOnNode(bytes32 schainHash) external onlyDebugger { for (uint i = 0; i < schainsGroups[schainHash].length; i++) { uint nodeIndex = schainsGroups[schainHash][i]; for (uint j = 0; j < schainsForNodes[nodeIndex].length; j++) { if (schainsForNodes[nodeIndex][j] == schainHash) { placeOfSchainOnNode[schainHash][nodeIndex] = j + 1; } } } } function removeNodeFromAllExceptionSchains(uint nodeIndex) external allow("SkaleManager") { uint len = _nodeToLockedSchains[nodeIndex].length; if (len > 0) { for (uint i = len; i > 0; i--) { removeNodeFromExceptions(_nodeToLockedSchains[nodeIndex][i - 1], nodeIndex); } } } function makeSchainNodesInvisible(bytes32 schainHash) external allowTwo("NodeRotation", "SkaleDKG") { Nodes nodes = Nodes(contractManager.getContract("Nodes")); for (uint i = 0; i < _schainToExceptionNodes[schainHash].length; i++) { nodes.makeNodeInvisible(_schainToExceptionNodes[schainHash][i]); } } function makeSchainNodesVisible(bytes32 schainHash) external allowTwo("NodeRotation", "SkaleDKG") { _makeSchainNodesVisible(schainHash); } /** * @dev Returns all Schains in the network. */ function getSchains() external view returns (bytes32[] memory) { return schainsAtSystem; } /** * @dev Returns all occupied resources on one node for an Schain. */ function getSchainsPartOfNode(bytes32 schainHash) external view returns (uint8) { return schains[schainHash].partOfNode; } /** * @dev Returns number of schains by schain owner. */ function getSchainListSize(address from) external view returns (uint) { return schainIndexes[from].length; } /** * @dev Returns hashes of schain names by schain owner. */ function getSchainHashsByAddress(address from) external view returns (bytes32[] memory) { return schainIndexes[from]; } /** * @dev Returns hashes of schain names by schain owner. */ function getSchainIdsByAddress(address from) external view returns (bytes32[] memory) { return schainIndexes[from]; } /** * @dev Returns hashes of schain names running on a node. */ function getSchainHashsForNode(uint nodeIndex) external view returns (bytes32[] memory) { return schainsForNodes[nodeIndex]; } /** * @dev Returns hashes of schain names running on a node. */ function getSchainIdsForNode(uint nodeIndex) external view returns (bytes32[] memory) { return schainsForNodes[nodeIndex]; } /** * @dev Returns the owner of an schain. */ function getSchainOwner(bytes32 schainHash) external view returns (address) { return schains[schainHash].owner; } /** * @dev Checks whether schain name is available. * TODO Need to delete - copy of web3.utils.soliditySha3 */ function isSchainNameAvailable(string calldata name) external view returns (bool) { bytes32 schainHash = keccak256(abi.encodePacked(name)); return schains[schainHash].owner == address(0) && !usedSchainNames[schainHash] && keccak256(abi.encodePacked(name)) != keccak256(abi.encodePacked("Mainnet")); } /** * @dev Checks whether schain lifetime has expired. */ function isTimeExpired(bytes32 schainHash) external view returns (bool) { return uint(schains[schainHash].startDate).add(schains[schainHash].lifetime) < block.timestamp; } /** * @dev Checks whether address is owner of schain. */ function isOwnerAddress(address from, bytes32 schainHash) external view override returns (bool) { return schains[schainHash].owner == from; } /** * @dev Checks whether schain exists. */ function isSchainExist(bytes32 schainHash) external view returns (bool) { return keccak256(abi.encodePacked(schains[schainHash].name)) != keccak256(abi.encodePacked("")); } /** * @dev Returns schain name. */ function getSchainName(bytes32 schainHash) external view returns (string memory) { return schains[schainHash].name; } /** * @dev Returns last active schain of a node. */ function getActiveSchain(uint nodeIndex) external view returns (bytes32) { for (uint i = schainsForNodes[nodeIndex].length; i > 0; i--) { if (schainsForNodes[nodeIndex][i - 1] != bytes32(0)) { return schainsForNodes[nodeIndex][i - 1]; } } return bytes32(0); } /** * @dev Returns active schains of a node. */ function getActiveSchains(uint nodeIndex) external view returns (bytes32[] memory activeSchains) { uint activeAmount = 0; for (uint i = 0; i < schainsForNodes[nodeIndex].length; i++) { if (schainsForNodes[nodeIndex][i] != bytes32(0)) { activeAmount++; } } uint cursor = 0; activeSchains = new bytes32[](activeAmount); for (uint i = schainsForNodes[nodeIndex].length; i > 0; i--) { if (schainsForNodes[nodeIndex][i - 1] != bytes32(0)) { activeSchains[cursor++] = schainsForNodes[nodeIndex][i - 1]; } } } /** * @dev Returns number of nodes in an schain group. */ function getNumberOfNodesInGroup(bytes32 schainHash) external view returns (uint) { return schainsGroups[schainHash].length; } /** * @dev Returns nodes in an schain group. */ function getNodesInGroup(bytes32 schainHash) external view returns (uint[] memory) { return schainsGroups[schainHash]; } /** * @dev Checks whether sender is a node address from a given schain group. */ function isNodeAddressesInGroup(bytes32 schainHash, address sender) external view override returns (bool) { Nodes nodes = Nodes(contractManager.getContract("Nodes")); for (uint i = 0; i < schainsGroups[schainHash].length; i++) { if (nodes.getNodeAddress(schainsGroups[schainHash][i]) == sender) { return true; } } return false; } /** * @dev Returns node index in schain group. */ function getNodeIndexInGroup(bytes32 schainHash, uint nodeId) external view returns (uint) { for (uint index = 0; index < schainsGroups[schainHash].length; index++) { if (schainsGroups[schainHash][index] == nodeId) { return index; } } return schainsGroups[schainHash].length; } /** * @dev Checks whether there are any nodes with free resources for given * schain. */ function isAnyFreeNode(bytes32 schainHash) external view returns (bool) { Nodes nodes = Nodes(contractManager.getContract("Nodes")); uint8 space = schains[schainHash].partOfNode; return nodes.countNodesWithFreeSpace(space) > 0; } /** * @dev Returns whether any exceptions exist for node in a schain group. */ function checkException(bytes32 schainHash, uint nodeIndex) external view returns (bool) { return _exceptionsForGroups[schainHash][nodeIndex]; } function checkHoleForSchain(bytes32 schainHash, uint indexOfNode) external view returns (bool) { for (uint i = 0; i < holesForSchains[schainHash].length; i++) { if (holesForSchains[schainHash][i] == indexOfNode) { return true; } } return false; } /** * @dev Returns number of Schains on a node. */ function getLengthOfSchainsForNode(uint nodeIndex) external view returns (uint) { return schainsForNodes[nodeIndex].length; } function getSchainType(uint typeOfSchain) external view returns(uint8, uint) { require(_keysOfSchainTypes.contains(typeOfSchain), "Invalid type of schain"); return (schainTypes[typeOfSchain].partOfNode, schainTypes[typeOfSchain].numberOfNodes); } function initialize(address newContractsAddress) public override initializer { Permissions.initialize(newContractsAddress); numberOfSchains = 0; sumOfSchainsResources = 0; numberOfSchainTypes = 0; } /** * @dev Allows Schains and NodeRotation contracts to add schain to node. */ function addSchainForNode(uint nodeIndex, bytes32 schainHash) public allowTwo("Schains", "NodeRotation") { if (holesForNodes[nodeIndex].length == 0) { schainsForNodes[nodeIndex].push(schainHash); placeOfSchainOnNode[schainHash][nodeIndex] = schainsForNodes[nodeIndex].length; } else { uint lastHoleOfNode = holesForNodes[nodeIndex][holesForNodes[nodeIndex].length - 1]; schainsForNodes[nodeIndex][lastHoleOfNode] = schainHash; placeOfSchainOnNode[schainHash][nodeIndex] = lastHoleOfNode + 1; holesForNodes[nodeIndex].pop(); } } /** * @dev Allows Schains, NodeRotation, and SkaleDKG contracts to remove an * schain from a node. */ function removeSchainForNode(uint nodeIndex, uint schainIndex) public allowThree("NodeRotation", "SkaleDKG", "Schains") { uint length = schainsForNodes[nodeIndex].length; if (schainIndex == length.sub(1)) { schainsForNodes[nodeIndex].pop(); } else { delete schainsForNodes[nodeIndex][schainIndex]; if (holesForNodes[nodeIndex].length > 0 && holesForNodes[nodeIndex][0] > schainIndex) { uint hole = holesForNodes[nodeIndex][0]; holesForNodes[nodeIndex][0] = schainIndex; holesForNodes[nodeIndex].push(hole); } else { holesForNodes[nodeIndex].push(schainIndex); } } } /** * @dev Allows Schains contract to remove node from exceptions */ function removeNodeFromExceptions(bytes32 schainHash, uint nodeIndex) public allowThree("Schains", "NodeRotation", "SkaleManager") { _exceptionsForGroups[schainHash][nodeIndex] = false; uint len = _nodeToLockedSchains[nodeIndex].length; bool removed = false; if (len > 0 && _nodeToLockedSchains[nodeIndex][len - 1] == schainHash) { _nodeToLockedSchains[nodeIndex].pop(); removed = true; } else { for (uint i = len; i > 0 && !removed; i--) { if (_nodeToLockedSchains[nodeIndex][i - 1] == schainHash) { _nodeToLockedSchains[nodeIndex][i - 1] = _nodeToLockedSchains[nodeIndex][len - 1]; _nodeToLockedSchains[nodeIndex].pop(); removed = true; } } } len = _schainToExceptionNodes[schainHash].length; removed = false; if (len > 0 && _schainToExceptionNodes[schainHash][len - 1] == nodeIndex) { _schainToExceptionNodes[schainHash].pop(); removed = true; } else { for (uint i = len; i > 0 && !removed; i--) { if (_schainToExceptionNodes[schainHash][i - 1] == nodeIndex) { _schainToExceptionNodes[schainHash][i - 1] = _schainToExceptionNodes[schainHash][len - 1]; _schainToExceptionNodes[schainHash].pop(); removed = true; } } } } /** * @dev Returns index of Schain in list of schains for a given node. */ function findSchainAtSchainsForNode(uint nodeIndex, bytes32 schainHash) public view returns (uint) { if (placeOfSchainOnNode[schainHash][nodeIndex] == 0) return schainsForNodes[nodeIndex].length; return placeOfSchainOnNode[schainHash][nodeIndex] - 1; } function _getNodeToLockedSchains() internal view returns (mapping(uint => bytes32[]) storage) { return _nodeToLockedSchains; } function _getSchainToExceptionNodes() internal view returns (mapping(bytes32 => uint[]) storage) { return _schainToExceptionNodes; } /** * @dev Generates schain group using a pseudo-random generator. */ function _generateGroup(bytes32 schainHash, uint numberOfNodes) private returns (uint[] memory nodesInGroup) { Nodes nodes = Nodes(contractManager.getContract("Nodes")); uint8 space = schains[schainHash].partOfNode; nodesInGroup = new uint[](numberOfNodes); require(nodes.countNodesWithFreeSpace(space) >= nodesInGroup.length, "Not enough nodes to create Schain"); Random.RandomGenerator memory randomGenerator = Random.createFromEntropy( abi.encodePacked(uint(blockhash(block.number.sub(1))), schainHash) ); for (uint i = 0; i < numberOfNodes; i++) { uint node = nodes.getRandomNodeWithFreeSpace(space, randomGenerator); nodesInGroup[i] = node; _setException(schainHash, node); addSchainForNode(node, schainHash); nodes.makeNodeInvisible(node); require(nodes.removeSpaceFromNode(node, space), "Could not remove space from Node"); } // set generated group schainsGroups[schainHash] = nodesInGroup; _makeSchainNodesVisible(schainHash); } function _setException(bytes32 schainHash, uint nodeIndex) private { _exceptionsForGroups[schainHash][nodeIndex] = true; _nodeToLockedSchains[nodeIndex].push(schainHash); _schainToExceptionNodes[schainHash].push(nodeIndex); } function _makeSchainNodesVisible(bytes32 schainHash) private { Nodes nodes = Nodes(contractManager.getContract("Nodes")); for (uint i = 0; i < _schainToExceptionNodes[schainHash].length; i++) { nodes.makeNodeVisible(_schainToExceptionNodes[schainHash][i]); } } /** * @dev Returns local index of node in schain group. */ function _findNode(bytes32 schainHash, uint nodeIndex) private view returns (uint) { uint[] memory nodesInGroup = schainsGroups[schainHash]; uint index; for (index = 0; index < nodesInGroup.length; index++) { if (nodesInGroup[index] == nodeIndex) { return index; } } return index; } } // SPDX-License-Identifier: AGPL-3.0-only /* FieldOperations.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "./Precompiled.sol"; library Fp2Operations { using SafeMath for uint; struct Fp2Point { uint a; uint b; } uint constant public P = 21888242871839275222246405745257275088696311157297823662689037894645226208583; function addFp2(Fp2Point memory value1, Fp2Point memory value2) internal pure returns (Fp2Point memory) { return Fp2Point({ a: addmod(value1.a, value2.a, P), b: addmod(value1.b, value2.b, P) }); } function scalarMulFp2(Fp2Point memory value, uint scalar) internal pure returns (Fp2Point memory) { return Fp2Point({ a: mulmod(scalar, value.a, P), b: mulmod(scalar, value.b, P) }); } function minusFp2(Fp2Point memory diminished, Fp2Point memory subtracted) internal pure returns (Fp2Point memory difference) { uint p = P; if (diminished.a >= subtracted.a) { difference.a = addmod(diminished.a, p - subtracted.a, p); } else { difference.a = (p - addmod(subtracted.a, p - diminished.a, p)).mod(p); } if (diminished.b >= subtracted.b) { difference.b = addmod(diminished.b, p - subtracted.b, p); } else { difference.b = (p - addmod(subtracted.b, p - diminished.b, p)).mod(p); } } function mulFp2( Fp2Point memory value1, Fp2Point memory value2 ) internal pure returns (Fp2Point memory result) { uint p = P; Fp2Point memory point = Fp2Point({ a: mulmod(value1.a, value2.a, p), b: mulmod(value1.b, value2.b, p)}); result.a = addmod( point.a, mulmod(p - 1, point.b, p), p); result.b = addmod( mulmod( addmod(value1.a, value1.b, p), addmod(value2.a, value2.b, p), p), p - addmod(point.a, point.b, p), p); } function squaredFp2(Fp2Point memory value) internal pure returns (Fp2Point memory) { uint p = P; uint ab = mulmod(value.a, value.b, p); uint mult = mulmod(addmod(value.a, value.b, p), addmod(value.a, mulmod(p - 1, value.b, p), p), p); return Fp2Point({ a: mult, b: addmod(ab, ab, p) }); } function inverseFp2(Fp2Point memory value) internal view returns (Fp2Point memory result) { uint p = P; uint t0 = mulmod(value.a, value.a, p); uint t1 = mulmod(value.b, value.b, p); uint t2 = mulmod(p - 1, t1, p); if (t0 >= t2) { t2 = addmod(t0, p - t2, p); } else { t2 = (p - addmod(t2, p - t0, p)).mod(p); } uint t3 = Precompiled.bigModExp(t2, p - 2, p); result.a = mulmod(value.a, t3, p); result.b = (p - mulmod(value.b, t3, p)).mod(p); } function isEqual( Fp2Point memory value1, Fp2Point memory value2 ) internal pure returns (bool) { return value1.a == value2.a && value1.b == value2.b; } } library G1Operations { using SafeMath for uint; using Fp2Operations for Fp2Operations.Fp2Point; function getG1Generator() internal pure returns (Fp2Operations.Fp2Point memory) { // Current solidity version does not support Constants of non-value type // so we implemented this function return Fp2Operations.Fp2Point({ a: 1, b: 2 }); } function isG1Point(uint x, uint y) internal pure returns (bool) { uint p = Fp2Operations.P; return mulmod(y, y, p) == addmod(mulmod(mulmod(x, x, p), x, p), 3, p); } function isG1(Fp2Operations.Fp2Point memory point) internal pure returns (bool) { return isG1Point(point.a, point.b); } function checkRange(Fp2Operations.Fp2Point memory point) internal pure returns (bool) { return point.a < Fp2Operations.P && point.b < Fp2Operations.P; } function negate(uint y) internal pure returns (uint) { return Fp2Operations.P.sub(y).mod(Fp2Operations.P); } } library G2Operations { using SafeMath for uint; using Fp2Operations for Fp2Operations.Fp2Point; struct G2Point { Fp2Operations.Fp2Point x; Fp2Operations.Fp2Point y; } function getTWISTB() internal pure returns (Fp2Operations.Fp2Point memory) { // Current solidity version does not support Constants of non-value type // so we implemented this function return Fp2Operations.Fp2Point({ a: 19485874751759354771024239261021720505790618469301721065564631296452457478373, b: 266929791119991161246907387137283842545076965332900288569378510910307636690 }); } function getG2Generator() internal pure returns (G2Point memory) { // Current solidity version does not support Constants of non-value type // so we implemented this function return G2Point({ x: Fp2Operations.Fp2Point({ a: 10857046999023057135944570762232829481370756359578518086990519993285655852781, b: 11559732032986387107991004021392285783925812861821192530917403151452391805634 }), y: Fp2Operations.Fp2Point({ a: 8495653923123431417604973247489272438418190587263600148770280649306958101930, b: 4082367875863433681332203403145435568316851327593401208105741076214120093531 }) }); } function getG2Zero() internal pure returns (G2Point memory) { // Current solidity version does not support Constants of non-value type // so we implemented this function return G2Point({ x: Fp2Operations.Fp2Point({ a: 0, b: 0 }), y: Fp2Operations.Fp2Point({ a: 1, b: 0 }) }); } function isG2Point(Fp2Operations.Fp2Point memory x, Fp2Operations.Fp2Point memory y) internal pure returns (bool) { if (isG2ZeroPoint(x, y)) { return true; } Fp2Operations.Fp2Point memory squaredY = y.squaredFp2(); Fp2Operations.Fp2Point memory res = squaredY.minusFp2( x.squaredFp2().mulFp2(x) ).minusFp2(getTWISTB()); return res.a == 0 && res.b == 0; } function isG2(G2Point memory value) internal pure returns (bool) { return isG2Point(value.x, value.y); } function isG2ZeroPoint( Fp2Operations.Fp2Point memory x, Fp2Operations.Fp2Point memory y ) internal pure returns (bool) { return x.a == 0 && x.b == 0 && y.a == 1 && y.b == 0; } function isG2Zero(G2Point memory value) internal pure returns (bool) { return value.x.a == 0 && value.x.b == 0 && value.y.a == 1 && value.y.b == 0; // return isG2ZeroPoint(value.x, value.y); } function addG2( G2Point memory value1, G2Point memory value2 ) internal view returns (G2Point memory sum) { if (isG2Zero(value1)) { return value2; } if (isG2Zero(value2)) { return value1; } if (isEqual(value1, value2)) { return doubleG2(value1); } Fp2Operations.Fp2Point memory s = value2.y.minusFp2(value1.y).mulFp2(value2.x.minusFp2(value1.x).inverseFp2()); sum.x = s.squaredFp2().minusFp2(value1.x.addFp2(value2.x)); sum.y = value1.y.addFp2(s.mulFp2(sum.x.minusFp2(value1.x))); uint p = Fp2Operations.P; sum.y.a = (p - sum.y.a).mod(p); sum.y.b = (p - sum.y.b).mod(p); } function isEqual( G2Point memory value1, G2Point memory value2 ) internal pure returns (bool) { return value1.x.isEqual(value2.x) && value1.y.isEqual(value2.y); } function doubleG2(G2Point memory value) internal view returns (G2Point memory result) { if (isG2Zero(value)) { return value; } else { Fp2Operations.Fp2Point memory s = value.x.squaredFp2().scalarMulFp2(3).mulFp2(value.y.scalarMulFp2(2).inverseFp2()); result.x = s.squaredFp2().minusFp2(value.x.addFp2(value.x)); result.y = value.y.addFp2(s.mulFp2(result.x.minusFp2(value.x))); uint p = Fp2Operations.P; result.y.a = (p - result.y.a).mod(p); result.y.b = (p - result.y.b).mod(p); } } } // SPDX-License-Identifier: AGPL-3.0-only /* NodeRotation.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "./interfaces/ISkaleDKG.sol"; import "./utils/Random.sol"; import "./ConstantsHolder.sol"; import "./Nodes.sol"; import "./Permissions.sol"; import "./SchainsInternal.sol"; import "./Schains.sol"; /** * @title NodeRotation * @dev This contract handles all node rotation functionality. */ contract NodeRotation is Permissions { using Random for Random.RandomGenerator; /** * nodeIndex - index of Node which is in process of rotation (left from schain) * newNodeIndex - index of Node which is rotated(added to schain) * freezeUntil - time till which Node should be turned on * rotationCounter - how many rotations were on this schain */ struct Rotation { uint nodeIndex; uint newNodeIndex; uint freezeUntil; uint rotationCounter; } struct LeavingHistory { bytes32 schainIndex; uint finishedRotation; } mapping (bytes32 => Rotation) public rotations; mapping (uint => LeavingHistory[]) public leavingHistory; mapping (bytes32 => bool) public waitForNewNode; bytes32 public constant DEBUGGER_ROLE = keccak256("DEBUGGER_ROLE"); modifier onlyDebugger() { require(hasRole(DEBUGGER_ROLE, msg.sender), "DEBUGGER_ROLE is required"); _; } /** * @dev Allows SkaleManager to remove, find new node, and rotate node from * schain. * * Requirements: * * - A free node must exist. */ function exitFromSchain(uint nodeIndex) external allow("SkaleManager") returns (bool, bool) { SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); bytes32 schainHash = schainsInternal.getActiveSchain(nodeIndex); if (schainHash == bytes32(0)) { return (true, false); } _startRotation(schainHash, nodeIndex); rotateNode(nodeIndex, schainHash, true, false); return (schainsInternal.getActiveSchain(nodeIndex) == bytes32(0) ? true : false, true); } /** * @dev Allows SkaleManager contract to freeze all schains on a given node. */ function freezeSchains(uint nodeIndex) external allow("SkaleManager") { bytes32[] memory schains = SchainsInternal( contractManager.getContract("SchainsInternal") ).getSchainHashsForNode(nodeIndex); for (uint i = 0; i < schains.length; i++) { if (schains[i] != bytes32(0)) { require( ISkaleDKG(contractManager.getContract("SkaleDKG")).isLastDKGSuccessful(schains[i]), "DKG did not finish on Schain" ); if (rotations[schains[i]].freezeUntil < now) { _startWaiting(schains[i], nodeIndex); } else { if (rotations[schains[i]].nodeIndex != nodeIndex) { revert("Occupied by rotation on Schain"); } } } } } /** * @dev Allows Schains contract to remove a rotation from an schain. */ function removeRotation(bytes32 schainIndex) external allow("Schains") { delete rotations[schainIndex]; } /** * @dev Allows Owner to immediately rotate an schain. */ function skipRotationDelay(bytes32 schainIndex) external onlyDebugger { rotations[schainIndex].freezeUntil = now; } /** * @dev Returns rotation details for a given schain. */ function getRotation(bytes32 schainIndex) external view returns (Rotation memory) { return rotations[schainIndex]; } /** * @dev Returns leaving history for a given node. */ function getLeavingHistory(uint nodeIndex) external view returns (LeavingHistory[] memory) { return leavingHistory[nodeIndex]; } function isRotationInProgress(bytes32 schainIndex) external view returns (bool) { return rotations[schainIndex].freezeUntil >= now && !waitForNewNode[schainIndex]; } function initialize(address newContractsAddress) public override initializer { Permissions.initialize(newContractsAddress); } /** * @dev Allows SkaleDKG and SkaleManager contracts to rotate a node from an * schain. */ function rotateNode( uint nodeIndex, bytes32 schainHash, bool shouldDelay, bool isBadNode ) public allowTwo("SkaleDKG", "SkaleManager") returns (uint newNode) { SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); schainsInternal.removeNodeFromSchain(nodeIndex, schainHash); if (!isBadNode) { schainsInternal.removeNodeFromExceptions(schainHash, nodeIndex); } newNode = selectNodeToGroup(schainHash); Nodes(contractManager.getContract("Nodes")).addSpaceToNode( nodeIndex, schainsInternal.getSchainsPartOfNode(schainHash) ); _finishRotation(schainHash, nodeIndex, newNode, shouldDelay); } /** * @dev Allows SkaleManager, Schains, and SkaleDKG contracts to * pseudo-randomly select a new Node for an Schain. * * Requirements: * * - Schain is active. * - A free node already exists. * - Free space can be allocated from the node. */ function selectNodeToGroup(bytes32 schainHash) public allowThree("SkaleManager", "Schains", "SkaleDKG") returns (uint nodeIndex) { SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); Nodes nodes = Nodes(contractManager.getContract("Nodes")); require(schainsInternal.isSchainActive(schainHash), "Group is not active"); uint8 space = schainsInternal.getSchainsPartOfNode(schainHash); schainsInternal.makeSchainNodesInvisible(schainHash); require(schainsInternal.isAnyFreeNode(schainHash), "No free Nodes available for rotation"); Random.RandomGenerator memory randomGenerator = Random.createFromEntropy( abi.encodePacked(uint(blockhash(block.number - 1)), schainHash) ); nodeIndex = nodes.getRandomNodeWithFreeSpace(space, randomGenerator); require(nodes.removeSpaceFromNode(nodeIndex, space), "Could not remove space from nodeIndex"); schainsInternal.makeSchainNodesVisible(schainHash); schainsInternal.addSchainForNode(nodeIndex, schainHash); schainsInternal.setException(schainHash, nodeIndex); schainsInternal.setNodeInGroup(schainHash, nodeIndex); } /** * @dev Initiates rotation of a node from an schain. */ function _startRotation(bytes32 schainIndex, uint nodeIndex) private { rotations[schainIndex].newNodeIndex = nodeIndex; waitForNewNode[schainIndex] = true; } function _startWaiting(bytes32 schainIndex, uint nodeIndex) private { ConstantsHolder constants = ConstantsHolder(contractManager.getContract("ConstantsHolder")); rotations[schainIndex].nodeIndex = nodeIndex; rotations[schainIndex].freezeUntil = now.add(constants.rotationDelay()); } /** * @dev Completes rotation of a node from an schain. */ function _finishRotation( bytes32 schainIndex, uint nodeIndex, uint newNodeIndex, bool shouldDelay) private { leavingHistory[nodeIndex].push( LeavingHistory( schainIndex, shouldDelay ? now.add( ConstantsHolder(contractManager.getContract("ConstantsHolder")).rotationDelay() ) : now ) ); rotations[schainIndex].newNodeIndex = newNodeIndex; rotations[schainIndex].rotationCounter++; delete waitForNewNode[schainIndex]; ISkaleDKG(contractManager.getContract("SkaleDKG")).openChannel(schainIndex); } /** * @dev Checks whether a rotation can be performed. * * Requirements: * * - Schain must exist. */ function _checkRotation(bytes32 schainHash ) private view returns (bool) { SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); require(schainsInternal.isSchainExist(schainHash), "Schain does not exist for rotation"); return schainsInternal.isAnyFreeNode(schainHash); } } // SPDX-License-Identifier: AGPL-3.0-only /* ISkaleDKG.sol - SKALE Manager Copyright (C) 2019-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; /** * @dev Interface to {SkaleDKG}. */ interface ISkaleDKG { /** * @dev See {SkaleDKG-openChannel}. */ function openChannel(bytes32 schainHash) external; /** * @dev See {SkaleDKG-deleteChannel}. */ function deleteChannel(bytes32 schainHash) external; /** * @dev See {SkaleDKG-isLastDKGSuccessful}. */ function isLastDKGSuccessful(bytes32 groupIndex) external view returns (bool); /** * @dev See {SkaleDKG-isChannelOpened}. */ function isChannelOpened(bytes32 schainHash) external view returns (bool); } // SPDX-License-Identifier: GPL-3.0-or-later /* Modifications Copyright (C) 2018 SKALE Labs ec.sol by @jbaylina under GPL-3.0 License */ /** @file ECDH.sol * @author Jordi Baylina (@jbaylina) * @date 2016 */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; /** * @title ECDH * @dev This contract performs Elliptic-curve Diffie-Hellman key exchange to * support the DKG process. */ contract ECDH { using SafeMath for uint256; uint256 constant private _GX = 0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798; uint256 constant private _GY = 0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8; uint256 constant private _N = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F; uint256 constant private _A = 0; function publicKey(uint256 privKey) external pure returns (uint256 qx, uint256 qy) { uint256 x; uint256 y; uint256 z; (x, y, z) = ecMul( privKey, _GX, _GY, 1 ); z = inverse(z); qx = mulmod(x, z, _N); qy = mulmod(y, z, _N); } function deriveKey( uint256 privKey, uint256 pubX, uint256 pubY ) external pure returns (uint256 qx, uint256 qy) { uint256 x; uint256 y; uint256 z; (x, y, z) = ecMul( privKey, pubX, pubY, 1 ); z = inverse(z); qx = mulmod(x, z, _N); qy = mulmod(y, z, _N); } function jAdd( uint256 x1, uint256 z1, uint256 x2, uint256 z2 ) public pure returns (uint256 x3, uint256 z3) { (x3, z3) = (addmod(mulmod(z2, x1, _N), mulmod(x2, z1, _N), _N), mulmod(z1, z2, _N)); } function jSub( uint256 x1, uint256 z1, uint256 x2, uint256 z2 ) public pure returns (uint256 x3, uint256 z3) { (x3, z3) = (addmod(mulmod(z2, x1, _N), mulmod(_N.sub(x2), z1, _N), _N), mulmod(z1, z2, _N)); } function jMul( uint256 x1, uint256 z1, uint256 x2, uint256 z2 ) public pure returns (uint256 x3, uint256 z3) { (x3, z3) = (mulmod(x1, x2, _N), mulmod(z1, z2, _N)); } function jDiv( uint256 x1, uint256 z1, uint256 x2, uint256 z2 ) public pure returns (uint256 x3, uint256 z3) { (x3, z3) = (mulmod(x1, z2, _N), mulmod(z1, x2, _N)); } function inverse(uint256 a) public pure returns (uint256 invA) { require(a > 0 && a < _N, "Input is incorrect"); uint256 t = 0; uint256 newT = 1; uint256 r = _N; uint256 newR = a; uint256 q; while (newR != 0) { q = r.div(newR); (t, newT) = (newT, addmod(t, (_N.sub(mulmod(q, newT, _N))), _N)); (r, newR) = (newR, r % newR); } return t; } function ecAdd( uint256 x1, uint256 y1, uint256 z1, uint256 x2, uint256 y2, uint256 z2 ) public pure returns (uint256 x3, uint256 y3, uint256 z3) { uint256 ln; uint256 lz; uint256 da; uint256 db; // we use (0 0 1) as zero point, z always equal 1 if ((x1 == 0) && (y1 == 0)) { return (x2, y2, z2); } // we use (0 0 1) as zero point, z always equal 1 if ((x2 == 0) && (y2 == 0)) { return (x1, y1, z1); } if ((x1 == x2) && (y1 == y2)) { (ln, lz) = jMul(x1, z1, x1, z1); (ln, lz) = jMul(ln,lz,3,1); (ln, lz) = jAdd(ln,lz,_A,1); (da, db) = jMul(y1,z1,2,1); } else { (ln, lz) = jSub(y2,z2,y1,z1); (da, db) = jSub(x2,z2,x1,z1); } (ln, lz) = jDiv(ln,lz,da,db); (x3, da) = jMul(ln,lz,ln,lz); (x3, da) = jSub(x3,da,x1,z1); (x3, da) = jSub(x3,da,x2,z2); (y3, db) = jSub(x1,z1,x3,da); (y3, db) = jMul(y3,db,ln,lz); (y3, db) = jSub(y3,db,y1,z1); if (da != db) { x3 = mulmod(x3, db, _N); y3 = mulmod(y3, da, _N); z3 = mulmod(da, db, _N); } else { z3 = da; } } function ecDouble( uint256 x1, uint256 y1, uint256 z1 ) public pure returns (uint256 x3, uint256 y3, uint256 z3) { (x3, y3, z3) = ecAdd( x1, y1, z1, x1, y1, z1 ); } function ecMul( uint256 d, uint256 x1, uint256 y1, uint256 z1 ) public pure returns (uint256 x3, uint256 y3, uint256 z3) { uint256 remaining = d; uint256 px = x1; uint256 py = y1; uint256 pz = z1; uint256 acx = 0; uint256 acy = 0; uint256 acz = 1; if (d == 0) { return (0, 0, 1); } while (remaining != 0) { if ((remaining & 1) != 0) { (acx, acy, acz) = ecAdd( acx, acy, acz, px, py, pz ); } remaining = remaining.div(2); (px, py, pz) = ecDouble(px, py, pz); } (x3, y3, z3) = (acx, acy, acz); } } // SPDX-License-Identifier: AGPL-3.0-only /* Precompiled.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; library Precompiled { function bigModExp(uint base, uint power, uint modulus) internal view returns (uint) { uint[6] memory inputToBigModExp; inputToBigModExp[0] = 32; inputToBigModExp[1] = 32; inputToBigModExp[2] = 32; inputToBigModExp[3] = base; inputToBigModExp[4] = power; inputToBigModExp[5] = modulus; uint[1] memory out; bool success; // solhint-disable-next-line no-inline-assembly assembly { success := staticcall(not(0), 5, inputToBigModExp, mul(6, 0x20), out, 0x20) } require(success, "BigModExp failed"); return out[0]; } function bn256ScalarMul(uint x, uint y, uint k) internal view returns (uint , uint ) { uint[3] memory inputToMul; uint[2] memory output; inputToMul[0] = x; inputToMul[1] = y; inputToMul[2] = k; bool success; // solhint-disable-next-line no-inline-assembly assembly { success := staticcall(not(0), 7, inputToMul, 0x60, output, 0x40) } require(success, "Multiplication failed"); return (output[0], output[1]); } function bn256Pairing( uint x1, uint y1, uint a1, uint b1, uint c1, uint d1, uint x2, uint y2, uint a2, uint b2, uint c2, uint d2) internal view returns (bool) { bool success; uint[12] memory inputToPairing; inputToPairing[0] = x1; inputToPairing[1] = y1; inputToPairing[2] = a1; inputToPairing[3] = b1; inputToPairing[4] = c1; inputToPairing[5] = d1; inputToPairing[6] = x2; inputToPairing[7] = y2; inputToPairing[8] = a2; inputToPairing[9] = b2; inputToPairing[10] = c2; inputToPairing[11] = d2; uint[1] memory out; // solhint-disable-next-line no-inline-assembly assembly { success := staticcall(not(0), 8, inputToPairing, mul(12, 0x20), out, 0x20) } require(success, "Pairing check failed"); return out[0] != 0; } } // SPDX-License-Identifier: AGPL-3.0-only /* SkaleDkgBroadcast.sol - SKALE Manager Copyright (C) 2021-Present SKALE Labs @author Dmytro Stebaiev @author Artem Payvin @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "../SkaleDKG.sol"; import "../KeyStorage.sol"; import "../utils/FieldOperations.sol"; /** * @title SkaleDkgBroadcast * @dev Contains functions to manage distributed key generation per * Joint-Feldman protocol. */ library SkaleDkgBroadcast { using SafeMath for uint; /** * @dev Emitted when a node broadcasts keyshare. */ event BroadcastAndKeyShare( bytes32 indexed schainHash, uint indexed fromNode, G2Operations.G2Point[] verificationVector, SkaleDKG.KeyShare[] secretKeyContribution ); /** * @dev Broadcasts verification vector and secret key contribution to all * other nodes in the group. * * Emits BroadcastAndKeyShare event. * * Requirements: * * - `msg.sender` must have an associated node. * - `verificationVector` must be a certain length. * - `secretKeyContribution` length must be equal to number of nodes in group. */ function broadcast( bytes32 schainHash, uint nodeIndex, G2Operations.G2Point[] memory verificationVector, SkaleDKG.KeyShare[] memory secretKeyContribution, ContractManager contractManager, mapping(bytes32 => SkaleDKG.Channel) storage channels, mapping(bytes32 => SkaleDKG.ProcessDKG) storage dkgProcess, mapping(bytes32 => mapping(uint => bytes32)) storage hashedData ) external { uint n = channels[schainHash].n; require(verificationVector.length == getT(n), "Incorrect number of verification vectors"); require( secretKeyContribution.length == n, "Incorrect number of secret key shares" ); (uint index, ) = SkaleDKG(contractManager.getContract("SkaleDKG")).checkAndReturnIndexInGroup( schainHash, nodeIndex, true ); require(!dkgProcess[schainHash].broadcasted[index], "This node has already broadcasted"); dkgProcess[schainHash].broadcasted[index] = true; dkgProcess[schainHash].numberOfBroadcasted++; if (dkgProcess[schainHash].numberOfBroadcasted == channels[schainHash].n) { SkaleDKG(contractManager.getContract("SkaleDKG")).setStartAlrightTimestamp(schainHash); } hashedData[schainHash][index] = SkaleDKG(contractManager.getContract("SkaleDKG")).hashData( secretKeyContribution, verificationVector ); KeyStorage(contractManager.getContract("KeyStorage")).adding(schainHash, verificationVector[0]); emit BroadcastAndKeyShare( schainHash, nodeIndex, verificationVector, secretKeyContribution ); } function getT(uint n) public pure returns (uint) { return n.mul(2).add(1).div(3); } } // SPDX-License-Identifier: AGPL-3.0-only /* SkaleDkgComplaint.sol - SKALE Manager Copyright (C) 2021-Present SKALE Labs @author Dmytro Stebaiev @author Artem Payvin @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "../SkaleDKG.sol"; import "../ConstantsHolder.sol"; import "../Wallets.sol"; import "../Nodes.sol"; /** * @title SkaleDkgComplaint * @dev Contains functions to manage distributed key generation per * Joint-Feldman protocol. */ library SkaleDkgComplaint { using SafeMath for uint; /** * @dev Emitted when an incorrect complaint is sent. */ event ComplaintError(string error); /** * @dev Emitted when a complaint is sent. */ event ComplaintSent( bytes32 indexed schainHash, uint indexed fromNodeIndex, uint indexed toNodeIndex); /** * @dev Creates a complaint from a node (accuser) to a given node. * The accusing node must broadcast additional parameters within 1800 blocks. * * Emits {ComplaintSent} or {ComplaintError} event. * * Requirements: * * - `msg.sender` must have an associated node. */ function complaint( bytes32 schainHash, uint fromNodeIndex, uint toNodeIndex, ContractManager contractManager, mapping(bytes32 => SkaleDKG.Channel) storage channels, mapping(bytes32 => SkaleDKG.ComplaintData) storage complaints, mapping(bytes32 => uint) storage startAlrightTimestamp ) external { SkaleDKG skaleDKG = SkaleDKG(contractManager.getContract("SkaleDKG")); require(skaleDKG.isNodeBroadcasted(schainHash, fromNodeIndex), "Node has not broadcasted"); if (skaleDKG.isNodeBroadcasted(schainHash, toNodeIndex)) { _handleComplaintWhenBroadcasted( schainHash, fromNodeIndex, toNodeIndex, contractManager, complaints, startAlrightTimestamp ); } else { // not broadcasted in 30 min _handleComplaintWhenNotBroadcasted(schainHash, toNodeIndex, contractManager, channels); } skaleDKG.setBadNode(schainHash, toNodeIndex); } function complaintBadData( bytes32 schainHash, uint fromNodeIndex, uint toNodeIndex, ContractManager contractManager, mapping(bytes32 => SkaleDKG.ComplaintData) storage complaints ) external { SkaleDKG skaleDKG = SkaleDKG(contractManager.getContract("SkaleDKG")); require(skaleDKG.isNodeBroadcasted(schainHash, fromNodeIndex), "Node has not broadcasted"); require(skaleDKG.isNodeBroadcasted(schainHash, toNodeIndex), "Accused node has not broadcasted"); require(!skaleDKG.isAllDataReceived(schainHash, fromNodeIndex), "Node has already sent alright"); if (complaints[schainHash].nodeToComplaint == uint(-1)) { complaints[schainHash].nodeToComplaint = toNodeIndex; complaints[schainHash].fromNodeToComplaint = fromNodeIndex; complaints[schainHash].startComplaintBlockTimestamp = block.timestamp; emit ComplaintSent(schainHash, fromNodeIndex, toNodeIndex); } else { emit ComplaintError("First complaint has already been processed"); } } function _handleComplaintWhenBroadcasted( bytes32 schainHash, uint fromNodeIndex, uint toNodeIndex, ContractManager contractManager, mapping(bytes32 => SkaleDKG.ComplaintData) storage complaints, mapping(bytes32 => uint) storage startAlrightTimestamp ) private { SkaleDKG skaleDKG = SkaleDKG(contractManager.getContract("SkaleDKG")); // missing alright if (complaints[schainHash].nodeToComplaint == uint(-1)) { if ( skaleDKG.isEveryoneBroadcasted(schainHash) && !skaleDKG.isAllDataReceived(schainHash, toNodeIndex) && startAlrightTimestamp[schainHash].add(_getComplaintTimelimit(contractManager)) <= block.timestamp ) { // missing alright skaleDKG.finalizeSlashing(schainHash, toNodeIndex); return; } else if (!skaleDKG.isAllDataReceived(schainHash, fromNodeIndex)) { // incorrect data skaleDKG.finalizeSlashing(schainHash, fromNodeIndex); return; } emit ComplaintError("Has already sent alright"); return; } else if (complaints[schainHash].nodeToComplaint == toNodeIndex) { // 30 min after incorrect data complaint if (complaints[schainHash].startComplaintBlockTimestamp.add( _getComplaintTimelimit(contractManager) ) <= block.timestamp) { skaleDKG.finalizeSlashing(schainHash, complaints[schainHash].nodeToComplaint); return; } emit ComplaintError("The same complaint rejected"); return; } emit ComplaintError("One complaint is already sent"); } function _handleComplaintWhenNotBroadcasted( bytes32 schainHash, uint toNodeIndex, ContractManager contractManager, mapping(bytes32 => SkaleDKG.Channel) storage channels ) private { if (channels[schainHash].startedBlockTimestamp.add( _getComplaintTimelimit(contractManager) ) <= block.timestamp) { SkaleDKG(contractManager.getContract("SkaleDKG")).finalizeSlashing(schainHash, toNodeIndex); return; } emit ComplaintError("Complaint sent too early"); } function _getComplaintTimelimit(ContractManager contractManager) private view returns (uint) { return ConstantsHolder(contractManager.getConstantsHolder()).complaintTimelimit(); } } // SPDX-License-Identifier: AGPL-3.0-only /* SkaleDkgPreResponse.sol - SKALE Manager Copyright (C) 2021-Present SKALE Labs @author Dmytro Stebaiev @author Artem Payvin @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "../SkaleDKG.sol"; import "../Wallets.sol"; import "../utils/FieldOperations.sol"; /** * @title SkaleDkgPreResponse * @dev Contains functions to manage distributed key generation per * Joint-Feldman protocol. */ library SkaleDkgPreResponse { using SafeMath for uint; using G2Operations for G2Operations.G2Point; function preResponse( bytes32 schainHash, uint fromNodeIndex, G2Operations.G2Point[] memory verificationVector, G2Operations.G2Point[] memory verificationVectorMult, SkaleDKG.KeyShare[] memory secretKeyContribution, ContractManager contractManager, mapping(bytes32 => SkaleDKG.ComplaintData) storage complaints, mapping(bytes32 => mapping(uint => bytes32)) storage hashedData ) external { SkaleDKG skaleDKG = SkaleDKG(contractManager.getContract("SkaleDKG")); uint index = _preResponseCheck( schainHash, fromNodeIndex, verificationVector, verificationVectorMult, secretKeyContribution, skaleDKG, complaints, hashedData ); _processPreResponse(secretKeyContribution[index].share, schainHash, verificationVectorMult, complaints); } function _preResponseCheck( bytes32 schainHash, uint fromNodeIndex, G2Operations.G2Point[] memory verificationVector, G2Operations.G2Point[] memory verificationVectorMult, SkaleDKG.KeyShare[] memory secretKeyContribution, SkaleDKG skaleDKG, mapping(bytes32 => SkaleDKG.ComplaintData) storage complaints, mapping(bytes32 => mapping(uint => bytes32)) storage hashedData ) private view returns (uint index) { (uint indexOnSchain, ) = skaleDKG.checkAndReturnIndexInGroup(schainHash, fromNodeIndex, true); require(complaints[schainHash].nodeToComplaint == fromNodeIndex, "Not this Node"); require(!complaints[schainHash].isResponse, "Already submitted pre response data"); require( hashedData[schainHash][indexOnSchain] == skaleDKG.hashData(secretKeyContribution, verificationVector), "Broadcasted Data is not correct" ); require( verificationVector.length == verificationVectorMult.length, "Incorrect length of multiplied verification vector" ); (index, ) = skaleDKG.checkAndReturnIndexInGroup(schainHash, complaints[schainHash].fromNodeToComplaint, true); require( _checkCorrectVectorMultiplication(index, verificationVector, verificationVectorMult), "Multiplied verification vector is incorrect" ); } function _processPreResponse( bytes32 share, bytes32 schainHash, G2Operations.G2Point[] memory verificationVectorMult, mapping(bytes32 => SkaleDKG.ComplaintData) storage complaints ) private { complaints[schainHash].keyShare = share; complaints[schainHash].sumOfVerVec = _calculateSum(verificationVectorMult); complaints[schainHash].isResponse = true; } function _calculateSum(G2Operations.G2Point[] memory verificationVectorMult) private view returns (G2Operations.G2Point memory) { G2Operations.G2Point memory value = G2Operations.getG2Zero(); for (uint i = 0; i < verificationVectorMult.length; i++) { value = value.addG2(verificationVectorMult[i]); } return value; } function _checkCorrectVectorMultiplication( uint indexOnSchain, G2Operations.G2Point[] memory verificationVector, G2Operations.G2Point[] memory verificationVectorMult ) private view returns (bool) { Fp2Operations.Fp2Point memory value = G1Operations.getG1Generator(); Fp2Operations.Fp2Point memory tmp = G1Operations.getG1Generator(); for (uint i = 0; i < verificationVector.length; i++) { (tmp.a, tmp.b) = Precompiled.bn256ScalarMul(value.a, value.b, indexOnSchain.add(1) ** i); if (!_checkPairing(tmp, verificationVector[i], verificationVectorMult[i])) { return false; } } return true; } function _checkPairing( Fp2Operations.Fp2Point memory g1Mul, G2Operations.G2Point memory verificationVector, G2Operations.G2Point memory verificationVectorMult ) private view returns (bool) { require(G1Operations.checkRange(g1Mul), "g1Mul is not valid"); g1Mul.b = G1Operations.negate(g1Mul.b); Fp2Operations.Fp2Point memory one = G1Operations.getG1Generator(); return Precompiled.bn256Pairing( one.a, one.b, verificationVectorMult.x.b, verificationVectorMult.x.a, verificationVectorMult.y.b, verificationVectorMult.y.a, g1Mul.a, g1Mul.b, verificationVector.x.b, verificationVector.x.a, verificationVector.y.b, verificationVector.y.a ); } } // SPDX-License-Identifier: AGPL-3.0-only /* SkaleDkgResponse.sol - SKALE Manager Copyright (C) 2021-Present SKALE Labs @author Dmytro Stebaiev @author Artem Payvin @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "../SkaleDKG.sol"; import "../Wallets.sol"; import "../Decryption.sol"; import "../Nodes.sol"; import "../thirdparty/ECDH.sol"; import "../utils/FieldOperations.sol"; /** * @title SkaleDkgResponse * @dev Contains functions to manage distributed key generation per * Joint-Feldman protocol. */ library SkaleDkgResponse { using G2Operations for G2Operations.G2Point; function response( bytes32 schainHash, uint fromNodeIndex, uint secretNumber, G2Operations.G2Point memory multipliedShare, ContractManager contractManager, mapping(bytes32 => SkaleDKG.Channel) storage channels, mapping(bytes32 => SkaleDKG.ComplaintData) storage complaints ) external { uint index = SchainsInternal(contractManager.getContract("SchainsInternal")) .getNodeIndexInGroup(schainHash, fromNodeIndex); require(index < channels[schainHash].n, "Node is not in this group"); require(complaints[schainHash].nodeToComplaint == fromNodeIndex, "Not this Node"); require(complaints[schainHash].isResponse, "Have not submitted pre-response data"); uint badNode = _verifyDataAndSlash( schainHash, secretNumber, multipliedShare, contractManager, complaints ); SkaleDKG(contractManager.getContract("SkaleDKG")).setBadNode(schainHash, badNode); } function _verifyDataAndSlash( bytes32 schainHash, uint secretNumber, G2Operations.G2Point memory multipliedShare, ContractManager contractManager, mapping(bytes32 => SkaleDKG.ComplaintData) storage complaints ) private returns (uint badNode) { bytes32[2] memory publicKey = Nodes(contractManager.getContract("Nodes")).getNodePublicKey( complaints[schainHash].fromNodeToComplaint ); uint256 pkX = uint(publicKey[0]); (pkX, ) = ECDH(contractManager.getContract("ECDH")).deriveKey(secretNumber, pkX, uint(publicKey[1])); bytes32 key = bytes32(pkX); // Decrypt secret key contribution uint secret = Decryption(contractManager.getContract("Decryption")).decrypt( complaints[schainHash].keyShare, sha256(abi.encodePacked(key)) ); badNode = ( _checkCorrectMultipliedShare(multipliedShare, secret) && multipliedShare.isEqual(complaints[schainHash].sumOfVerVec) ? complaints[schainHash].fromNodeToComplaint : complaints[schainHash].nodeToComplaint ); SkaleDKG(contractManager.getContract("SkaleDKG")).finalizeSlashing(schainHash, badNode); } function _checkCorrectMultipliedShare( G2Operations.G2Point memory multipliedShare, uint secret ) private view returns (bool) { if (!multipliedShare.isG2()) { return false; } G2Operations.G2Point memory tmp = multipliedShare; Fp2Operations.Fp2Point memory g1 = G1Operations.getG1Generator(); Fp2Operations.Fp2Point memory share = Fp2Operations.Fp2Point({ a: 0, b: 0 }); (share.a, share.b) = Precompiled.bn256ScalarMul(g1.a, g1.b, secret); require(G1Operations.checkRange(share), "share is not valid"); share.b = G1Operations.negate(share.b); require(G1Operations.isG1(share), "mulShare not in G1"); G2Operations.G2Point memory g2 = G2Operations.getG2Generator(); return Precompiled.bn256Pairing( share.a, share.b, g2.x.b, g2.x.a, g2.y.b, g2.y.a, g1.a, g1.b, tmp.x.b, tmp.x.a, tmp.y.b, tmp.y.a); } } // SPDX-License-Identifier: AGPL-3.0-only /* ISchains.sol - SKALE Manager Interfaces Copyright (C) 2021-Present SKALE Labs @author Dmytro Stebaeiv SKALE Manager Interfaces is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager Interfaces is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager Interfaces. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity >=0.6.10 <0.9.0; interface ISchains { function verifySchainSignature( uint256 signA, uint256 signB, bytes32 hash, uint256 counter, uint256 hashA, uint256 hashB, string calldata schainName ) external view returns (bool); } // SPDX-License-Identifier: AGPL-3.0-only /* SkaleVerifier.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "./Permissions.sol"; import "./SchainsInternal.sol"; import "./utils/Precompiled.sol"; import "./utils/FieldOperations.sol"; /** * @title SkaleVerifier * @dev Contains verify function to perform BLS signature verification. */ contract SkaleVerifier is Permissions { using Fp2Operations for Fp2Operations.Fp2Point; /** * @dev Verifies a BLS signature. * * Requirements: * * - Signature is in G1. * - Hash is in G1. * - G2.one in G2. * - Public Key in G2. */ function verify( Fp2Operations.Fp2Point calldata signature, bytes32 hash, uint counter, uint hashA, uint hashB, G2Operations.G2Point calldata publicKey ) external view returns (bool) { require(G1Operations.checkRange(signature), "Signature is not valid"); if (!_checkHashToGroupWithHelper( hash, counter, hashA, hashB ) ) { return false; } uint newSignB = G1Operations.negate(signature.b); require(G1Operations.isG1Point(signature.a, newSignB), "Sign not in G1"); require(G1Operations.isG1Point(hashA, hashB), "Hash not in G1"); G2Operations.G2Point memory g2 = G2Operations.getG2Generator(); require( G2Operations.isG2(publicKey), "Public Key not in G2" ); return Precompiled.bn256Pairing( signature.a, newSignB, g2.x.b, g2.x.a, g2.y.b, g2.y.a, hashA, hashB, publicKey.x.b, publicKey.x.a, publicKey.y.b, publicKey.y.a ); } function initialize(address newContractsAddress) public override initializer { Permissions.initialize(newContractsAddress); } function _checkHashToGroupWithHelper( bytes32 hash, uint counter, uint hashA, uint hashB ) private pure returns (bool) { if (counter > 100) { return false; } uint xCoord = uint(hash) % Fp2Operations.P; xCoord = (xCoord.add(counter)) % Fp2Operations.P; uint ySquared = addmod( mulmod(mulmod(xCoord, xCoord, Fp2Operations.P), xCoord, Fp2Operations.P), 3, Fp2Operations.P ); if (hashB < Fp2Operations.P.div(2) || mulmod(hashB, hashB, Fp2Operations.P) != ySquared || xCoord != hashA) { return false; } return true; } } // SPDX-License-Identifier: AGPL-3.0-only /* ISchainsInternal - SKALE Manager Interfaces Copyright (C) 2021-Present SKALE Labs @author Dmytro Stebaeiv SKALE Manager Interfaces is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager Interfaces is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager Interfaces. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity >=0.6.10 <0.9.0; interface ISchainsInternal { function isNodeAddressesInGroup(bytes32 schainId, address sender) external view returns (bool); function isOwnerAddress(address from, bytes32 schainId) external view returns (bool); } // SPDX-License-Identifier: AGPL-3.0-only /* Decryption.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; /** * @title Decryption * @dev This contract performs encryption and decryption functions. * Decrypt is used by SkaleDKG contract to decrypt secret key contribution to * validate complaints during the DKG procedure. */ contract Decryption { /** * @dev Returns an encrypted text given a secret and a key. */ function encrypt(uint256 secretNumber, bytes32 key) external pure returns (bytes32 ciphertext) { return bytes32(secretNumber) ^ key; } /** * @dev Returns a secret given an encrypted text and a key. */ function decrypt(bytes32 ciphertext, bytes32 key) external pure returns (uint256 secretNumber) { return uint256(ciphertext ^ key); } } // SPDX-License-Identifier: AGPL-3.0-only /* IWallets - SKALE Manager Interfaces Copyright (C) 2021-Present SKALE Labs @author Dmytro Stebaeiv SKALE Manager Interfaces is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager Interfaces is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager Interfaces. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity >=0.6.10 <0.9.0; interface IWallets { function refundGasBySchain(bytes32 schainId, address payable spender, uint spentGas, bool isDebt) external; function rechargeSchainWallet(bytes32 schainId) external payable; } // SPDX-License-Identifier: AGPL-3.0-only /* PartialDifferencesTester.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "../delegation/PartialDifferences.sol"; contract PartialDifferencesTester { using PartialDifferences for PartialDifferences.Sequence; using PartialDifferences for PartialDifferences.Value; using SafeMath for uint; PartialDifferences.Sequence[] private _sequences; // PartialDifferences.Value[] private _values; function createSequence() external { _sequences.push(PartialDifferences.Sequence({firstUnprocessedMonth: 0, lastChangedMonth: 0})); } function addToSequence(uint sequence, uint diff, uint month) external { require(sequence < _sequences.length, "Sequence does not exist"); _sequences[sequence].addToSequence(diff, month); } function subtractFromSequence(uint sequence, uint diff, uint month) external { require(sequence < _sequences.length, "Sequence does not exist"); _sequences[sequence].subtractFromSequence(diff, month); } function getAndUpdateSequenceItem(uint sequence, uint month) external returns (uint) { require(sequence < _sequences.length, "Sequence does not exist"); return _sequences[sequence].getAndUpdateValueInSequence(month); } function reduceSequence( uint sequence, uint a, uint b, uint month) external { require(sequence < _sequences.length, "Sequence does not exist"); FractionUtils.Fraction memory reducingCoefficient = FractionUtils.createFraction(a, b); return _sequences[sequence].reduceSequence(reducingCoefficient, month); } function latestSequence() external view returns (uint id) { require(_sequences.length > 0, "There are no _sequences"); return _sequences.length.sub(1); } } // SPDX-License-Identifier: AGPL-3.0-only /* ReentrancyTester.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/introspection/IERC1820Registry.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC777/IERC777Recipient.sol"; import "@openzeppelin/contracts/token/ERC777/IERC777Sender.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC777/IERC777.sol"; import "../Permissions.sol"; import "../delegation/DelegationController.sol"; contract ReentrancyTester is Permissions, IERC777Recipient, IERC777Sender { IERC1820Registry private _erc1820 = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); bool private _reentrancyCheck = false; bool private _burningAttack = false; uint private _amount = 0; constructor (address contractManagerAddress) public { Permissions.initialize(contractManagerAddress); _erc1820.setInterfaceImplementer(address(this), keccak256("ERC777TokensRecipient"), address(this)); _erc1820.setInterfaceImplementer(address(this), keccak256("ERC777TokensSender"), address(this)); } function tokensReceived( address /* operator */, address /* from */, address /* to */, uint256 amount, bytes calldata /* userData */, bytes calldata /* operatorData */ ) external override { if (_reentrancyCheck) { IERC20 skaleToken = IERC20(contractManager.getContract("SkaleToken")); require( skaleToken.transfer(contractManager.getContract("SkaleToken"), amount), "Transfer is not successful"); } } function tokensToSend( address, // operator address, // from address, // to uint256, // amount bytes calldata, // userData bytes calldata // operatorData ) external override { if (_burningAttack) { DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController")); delegationController.delegate( 1, _amount, 2, "D2 is even"); } } function prepareToReentracyCheck() external { _reentrancyCheck = true; } function prepareToBurningAttack() external { _burningAttack = true; } function burningAttack() external { IERC777 skaleToken = IERC777(contractManager.getContract("SkaleToken")); _amount = skaleToken.balanceOf(address(this)); skaleToken.burn(_amount, ""); } } // SPDX-License-Identifier: AGPL-3.0-only /* SkaleManager.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/introspection/IERC1820Registry.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC777/IERC777.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC777/IERC777Recipient.sol"; import "./delegation/Distributor.sol"; import "./delegation/ValidatorService.sol"; import "./interfaces/IMintableToken.sol"; import "./BountyV2.sol"; import "./ConstantsHolder.sol"; import "./NodeRotation.sol"; import "./Permissions.sol"; import "./Schains.sol"; import "./Wallets.sol"; /** * @title SkaleManager * @dev Contract contains functions for node registration and exit, bounty * management, and monitoring verdicts. */ contract SkaleManager is IERC777Recipient, Permissions { IERC1820Registry private _erc1820; bytes32 constant private _TOKENS_RECIPIENT_INTERFACE_HASH = 0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b; bytes32 constant public ADMIN_ROLE = keccak256("ADMIN_ROLE"); string public version; bytes32 public constant SCHAIN_DELETER_ROLE = keccak256("SCHAIN_DELETER_ROLE"); /** * @dev Emitted when bounty is received. */ event BountyReceived( uint indexed nodeIndex, address owner, uint averageDowntime, uint averageLatency, uint bounty, uint previousBlockEvent, uint time, uint gasSpend ); function tokensReceived( address, // operator address from, address to, uint256 value, bytes calldata userData, bytes calldata // operator data ) external override allow("SkaleToken") { require(to == address(this), "Receiver is incorrect"); if (userData.length > 0) { Schains schains = Schains( contractManager.getContract("Schains")); schains.addSchain(from, value, userData); } } function createNode( uint16 port, uint16 nonce, bytes4 ip, bytes4 publicIp, bytes32[2] calldata publicKey, string calldata name, string calldata domainName ) external { Nodes nodes = Nodes(contractManager.getContract("Nodes")); // validators checks inside checkPossibilityCreatingNode nodes.checkPossibilityCreatingNode(msg.sender); Nodes.NodeCreationParams memory params = Nodes.NodeCreationParams({ name: name, ip: ip, publicIp: publicIp, port: port, publicKey: publicKey, nonce: nonce, domainName: domainName }); nodes.createNode(msg.sender, params); } function nodeExit(uint nodeIndex) external { uint gasTotal = gasleft(); ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); NodeRotation nodeRotation = NodeRotation(contractManager.getContract("NodeRotation")); Nodes nodes = Nodes(contractManager.getContract("Nodes")); uint validatorId = nodes.getValidatorId(nodeIndex); bool permitted = (_isOwner() || nodes.isNodeExist(msg.sender, nodeIndex)); if (!permitted && validatorService.validatorAddressExists(msg.sender)) { permitted = validatorService.getValidatorId(msg.sender) == validatorId; } require(permitted, "Sender is not permitted to call this function"); nodeRotation.freezeSchains(nodeIndex); if (nodes.isNodeActive(nodeIndex)) { require(nodes.initExit(nodeIndex), "Initialization of node exit is failed"); } require(nodes.isNodeLeaving(nodeIndex), "Node should be Leaving"); (bool completed, bool isSchains) = nodeRotation.exitFromSchain(nodeIndex); if (completed) { SchainsInternal( contractManager.getContract("SchainsInternal") ).removeNodeFromAllExceptionSchains(nodeIndex); require(nodes.completeExit(nodeIndex), "Finishing of node exit is failed"); nodes.changeNodeFinishTime( nodeIndex, now.add( isSchains ? ConstantsHolder(contractManager.getContract("ConstantsHolder")).rotationDelay() : 0 ) ); nodes.deleteNodeForValidator(validatorId, nodeIndex); } _refundGasByValidator(validatorId, msg.sender, gasTotal - gasleft()); } function deleteSchain(string calldata name) external { Schains schains = Schains(contractManager.getContract("Schains")); // schain owner checks inside deleteSchain schains.deleteSchain(msg.sender, name); } function deleteSchainByRoot(string calldata name) external { require(hasRole(SCHAIN_DELETER_ROLE, msg.sender), "SCHAIN_DELETER_ROLE is required"); Schains schains = Schains(contractManager.getContract("Schains")); schains.deleteSchainByRoot(name); } function getBounty(uint nodeIndex) external { uint gasTotal = gasleft(); Nodes nodes = Nodes(contractManager.getContract("Nodes")); require(nodes.isNodeExist(msg.sender, nodeIndex), "Node does not exist for Message sender"); require(nodes.isTimeForReward(nodeIndex), "Not time for bounty"); require(!nodes.isNodeLeft(nodeIndex), "The node must not be in Left state"); require(!nodes.incompliant(nodeIndex), "The node is incompliant"); BountyV2 bountyContract = BountyV2(contractManager.getContract("Bounty")); uint bounty = bountyContract.calculateBounty(nodeIndex); nodes.changeNodeLastRewardDate(nodeIndex); uint validatorId = nodes.getValidatorId(nodeIndex); if (bounty > 0) { _payBounty(bounty, validatorId); } emit BountyReceived( nodeIndex, msg.sender, 0, 0, bounty, uint(-1), block.timestamp, gasleft()); _refundGasByValidator(validatorId, msg.sender, gasTotal - gasleft()); } function setVersion(string calldata newVersion) external onlyOwner { version = newVersion; } function initialize(address newContractsAddress) public override initializer { Permissions.initialize(newContractsAddress); _erc1820 = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); _erc1820.setInterfaceImplementer(address(this), _TOKENS_RECIPIENT_INTERFACE_HASH, address(this)); } function _payBounty(uint bounty, uint validatorId) private returns (bool) { IERC777 skaleToken = IERC777(contractManager.getContract("SkaleToken")); Distributor distributor = Distributor(contractManager.getContract("Distributor")); require( IMintableToken(address(skaleToken)).mint(address(distributor), bounty, abi.encode(validatorId), ""), "Token was not minted" ); } function _refundGasByValidator(uint validatorId, address payable spender, uint spentGas) private { uint gasCostOfRefundGasByValidator = 29000; Wallets(payable(contractManager.getContract("Wallets"))) .refundGasByValidator(validatorId, spender, spentGas + gasCostOfRefundGasByValidator); } } // SPDX-License-Identifier: AGPL-3.0-only /* Distributor.sol - SKALE Manager Copyright (C) 2019-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/introspection/IERC1820Registry.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC777/IERC777Recipient.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol"; import "../Permissions.sol"; import "../ConstantsHolder.sol"; import "../utils/MathUtils.sol"; import "./ValidatorService.sol"; import "./DelegationController.sol"; import "./DelegationPeriodManager.sol"; import "./TimeHelpers.sol"; /** * @title Distributor * @dev This contract handles all distribution functions of bounty and fee * payments. */ contract Distributor is Permissions, IERC777Recipient { using MathUtils for uint; /** * @dev Emitted when bounty is withdrawn. */ event WithdrawBounty( address holder, uint validatorId, address destination, uint amount ); /** * @dev Emitted when a validator fee is withdrawn. */ event WithdrawFee( uint validatorId, address destination, uint amount ); /** * @dev Emitted when bounty is distributed. */ event BountyWasPaid( uint validatorId, uint amount ); IERC1820Registry private _erc1820; // validatorId => month => token mapping (uint => mapping (uint => uint)) private _bountyPaid; // validatorId => month => token mapping (uint => mapping (uint => uint)) private _feePaid; // holder => validatorId => month mapping (address => mapping (uint => uint)) private _firstUnwithdrawnMonth; // validatorId => month mapping (uint => uint) private _firstUnwithdrawnMonthForValidator; /** * @dev Return and update the amount of earned bounty from a validator. */ function getAndUpdateEarnedBountyAmount(uint validatorId) external returns (uint earned, uint endMonth) { return getAndUpdateEarnedBountyAmountOf(msg.sender, validatorId); } /** * @dev Allows msg.sender to withdraw earned bounty. Bounties are locked * until launchTimestamp and BOUNTY_LOCKUP_MONTHS have both passed. * * Emits a {WithdrawBounty} event. * * Requirements: * * - Bounty must be unlocked. */ function withdrawBounty(uint validatorId, address to) external { TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers")); ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); require(now >= timeHelpers.addMonths( constantsHolder.launchTimestamp(), constantsHolder.BOUNTY_LOCKUP_MONTHS() ), "Bounty is locked"); uint bounty; uint endMonth; (bounty, endMonth) = getAndUpdateEarnedBountyAmountOf(msg.sender, validatorId); _firstUnwithdrawnMonth[msg.sender][validatorId] = endMonth; IERC20 skaleToken = IERC20(contractManager.getContract("SkaleToken")); require(skaleToken.transfer(to, bounty), "Failed to transfer tokens"); emit WithdrawBounty( msg.sender, validatorId, to, bounty ); } /** * @dev Allows `msg.sender` to withdraw earned validator fees. Fees are * locked until launchTimestamp and BOUNTY_LOCKUP_MONTHS both have passed. * * Emits a {WithdrawFee} event. * * Requirements: * * - Fee must be unlocked. */ function withdrawFee(address to) external { ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); IERC20 skaleToken = IERC20(contractManager.getContract("SkaleToken")); TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers")); ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); require(now >= timeHelpers.addMonths( constantsHolder.launchTimestamp(), constantsHolder.BOUNTY_LOCKUP_MONTHS() ), "Fee is locked"); // check Validator Exist inside getValidatorId uint validatorId = validatorService.getValidatorId(msg.sender); uint fee; uint endMonth; (fee, endMonth) = getEarnedFeeAmountOf(validatorId); _firstUnwithdrawnMonthForValidator[validatorId] = endMonth; require(skaleToken.transfer(to, fee), "Failed to transfer tokens"); emit WithdrawFee( validatorId, to, fee ); } function tokensReceived( address, address, address to, uint256 amount, bytes calldata userData, bytes calldata ) external override allow("SkaleToken") { require(to == address(this), "Receiver is incorrect"); require(userData.length == 32, "Data length is incorrect"); uint validatorId = abi.decode(userData, (uint)); _distributeBounty(amount, validatorId); } /** * @dev Return the amount of earned validator fees of `msg.sender`. */ function getEarnedFeeAmount() external view returns (uint earned, uint endMonth) { ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); return getEarnedFeeAmountOf(validatorService.getValidatorId(msg.sender)); } function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); _erc1820 = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); _erc1820.setInterfaceImplementer(address(this), keccak256("ERC777TokensRecipient"), address(this)); } /** * @dev Return and update the amount of earned bounties. */ function getAndUpdateEarnedBountyAmountOf(address wallet, uint validatorId) public returns (uint earned, uint endMonth) { DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController")); TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers")); uint currentMonth = timeHelpers.getCurrentMonth(); uint startMonth = _firstUnwithdrawnMonth[wallet][validatorId]; if (startMonth == 0) { startMonth = delegationController.getFirstDelegationMonth(wallet, validatorId); if (startMonth == 0) { return (0, 0); } } earned = 0; endMonth = currentMonth; if (endMonth > startMonth.add(12)) { endMonth = startMonth.add(12); } for (uint i = startMonth; i < endMonth; ++i) { uint effectiveDelegatedToValidator = delegationController.getAndUpdateEffectiveDelegatedToValidator(validatorId, i); if (effectiveDelegatedToValidator.muchGreater(0)) { earned = earned.add( _bountyPaid[validatorId][i].mul( delegationController.getAndUpdateEffectiveDelegatedByHolderToValidator(wallet, validatorId, i)) .div(effectiveDelegatedToValidator) ); } } } /** * @dev Return the amount of earned fees by validator ID. */ function getEarnedFeeAmountOf(uint validatorId) public view returns (uint earned, uint endMonth) { TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers")); uint currentMonth = timeHelpers.getCurrentMonth(); uint startMonth = _firstUnwithdrawnMonthForValidator[validatorId]; if (startMonth == 0) { return (0, 0); } earned = 0; endMonth = currentMonth; if (endMonth > startMonth.add(12)) { endMonth = startMonth.add(12); } for (uint i = startMonth; i < endMonth; ++i) { earned = earned.add(_feePaid[validatorId][i]); } } // private /** * @dev Distributes bounties to delegators. * * Emits a {BountyWasPaid} event. */ function _distributeBounty(uint amount, uint validatorId) private { TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers")); ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); uint currentMonth = timeHelpers.getCurrentMonth(); uint feeRate = validatorService.getValidator(validatorId).feeRate; uint fee = amount.mul(feeRate).div(1000); uint bounty = amount.sub(fee); _bountyPaid[validatorId][currentMonth] = _bountyPaid[validatorId][currentMonth].add(bounty); _feePaid[validatorId][currentMonth] = _feePaid[validatorId][currentMonth].add(fee); if (_firstUnwithdrawnMonthForValidator[validatorId] == 0) { _firstUnwithdrawnMonthForValidator[validatorId] = currentMonth; } emit BountyWasPaid(validatorId, amount); } } // SPDX-License-Identifier: AGPL-3.0-only /* SkaleDKGTester.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "../SkaleDKG.sol"; contract SkaleDKGTester is SkaleDKG { function setSuccessfulDKGPublic(bytes32 schainHash) external { lastSuccessfulDKG[schainHash] = now; channels[schainHash].active = false; KeyStorage(contractManager.getContract("KeyStorage")).finalizePublicKey(schainHash); emit SuccessfulDKG(schainHash); } } // SPDX-License-Identifier: AGPL-3.0-only /* Pricing.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "./Permissions.sol"; import "./SchainsInternal.sol"; import "./Nodes.sol"; /** * @title Pricing * @dev Contains pricing operations for SKALE network. */ contract Pricing is Permissions { uint public constant INITIAL_PRICE = 5 * 10**6; uint public price; uint public totalNodes; uint public lastUpdated; function initNodes() external { Nodes nodes = Nodes(contractManager.getContract("Nodes")); totalNodes = nodes.getNumberOnlineNodes(); } /** * @dev Adjust the schain price based on network capacity and demand. * * Requirements: * * - Cooldown time has exceeded. */ function adjustPrice() external { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); require(now > lastUpdated.add(constantsHolder.COOLDOWN_TIME()), "It's not a time to update a price"); checkAllNodes(); uint load = _getTotalLoad(); uint capacity = _getTotalCapacity(); bool networkIsOverloaded = load.mul(100) > constantsHolder.OPTIMAL_LOAD_PERCENTAGE().mul(capacity); uint loadDiff; if (networkIsOverloaded) { loadDiff = load.mul(100).sub(constantsHolder.OPTIMAL_LOAD_PERCENTAGE().mul(capacity)); } else { loadDiff = constantsHolder.OPTIMAL_LOAD_PERCENTAGE().mul(capacity).sub(load.mul(100)); } uint priceChangeSpeedMultipliedByCapacityAndMinPrice = constantsHolder.ADJUSTMENT_SPEED().mul(loadDiff).mul(price); uint timeSkipped = now.sub(lastUpdated); uint priceChange = priceChangeSpeedMultipliedByCapacityAndMinPrice .mul(timeSkipped) .div(constantsHolder.COOLDOWN_TIME()) .div(capacity) .div(constantsHolder.MIN_PRICE()); if (networkIsOverloaded) { assert(priceChange > 0); price = price.add(priceChange); } else { if (priceChange > price) { price = constantsHolder.MIN_PRICE(); } else { price = price.sub(priceChange); if (price < constantsHolder.MIN_PRICE()) { price = constantsHolder.MIN_PRICE(); } } } lastUpdated = now; } /** * @dev Returns the total load percentage. */ function getTotalLoadPercentage() external view returns (uint) { return _getTotalLoad().mul(100).div(_getTotalCapacity()); } function initialize(address newContractsAddress) public override initializer { Permissions.initialize(newContractsAddress); lastUpdated = now; price = INITIAL_PRICE; } function checkAllNodes() public { Nodes nodes = Nodes(contractManager.getContract("Nodes")); uint numberOfActiveNodes = nodes.getNumberOnlineNodes(); require(totalNodes != numberOfActiveNodes, "No changes to node supply"); totalNodes = numberOfActiveNodes; } function _getTotalLoad() private view returns (uint) { SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); uint load = 0; uint numberOfSchains = schainsInternal.numberOfSchains(); for (uint i = 0; i < numberOfSchains; i++) { bytes32 schain = schainsInternal.schainsAtSystem(i); uint numberOfNodesInSchain = schainsInternal.getNumberOfNodesInGroup(schain); uint part = schainsInternal.getSchainsPartOfNode(schain); load = load.add( numberOfNodesInSchain.mul(part) ); } return load; } function _getTotalCapacity() private view returns (uint) { Nodes nodes = Nodes(contractManager.getContract("Nodes")); ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); return nodes.getNumberOnlineNodes().mul(constantsHolder.TOTAL_SPACE_ON_NODE()); } } // SPDX-License-Identifier: AGPL-3.0-only /* SchainsInternalMock.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "../SchainsInternal.sol"; contract SchainsInternalMock is SchainsInternal { function removePlaceOfSchainOnNode(bytes32 schainHash, uint nodeIndex) external { delete placeOfSchainOnNode[schainHash][nodeIndex]; } function removeNodeToLocked(uint nodeIndex) external { mapping(uint => bytes32[]) storage nodeToLocked = _getNodeToLockedSchains(); delete nodeToLocked[nodeIndex]; } function removeSchainToExceptionNode(bytes32 schainHash) external { mapping(bytes32 => uint[]) storage schainToException = _getSchainToExceptionNodes(); delete schainToException[schainHash]; } } // SPDX-License-Identifier: AGPL-3.0-only /* LockerMock.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "../interfaces/delegation/ILocker.sol"; contract LockerMock is ILocker { function getAndUpdateLockedAmount(address) external override returns (uint) { return 13; } function getAndUpdateForbiddenForDelegationAmount(address) external override returns (uint) { return 13; } } // SPDX-License-Identifier: AGPL-3.0-only /* MathUtilsTester.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "../utils/MathUtils.sol"; contract MathUtilsTester { using MathUtils for uint; function boundedSub(uint256 a, uint256 b) external returns (uint256) { return a.boundedSub(b); } function boundedSubWithoutEvent(uint256 a, uint256 b) external pure returns (uint256) { return a.boundedSubWithoutEvent(b); } function muchGreater(uint256 a, uint256 b) external pure returns (bool) { return a.muchGreater(b); } function approximatelyEqual(uint256 a, uint256 b) external pure returns (bool) { return a.approximatelyEqual(b); } } // SPDX-License-Identifier: AGPL-3.0-only /* SegmentTreeTester.sol - SKALE Manager Copyright (C) 2021-Present SKALE Labs @author Artem Payvin @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "../utils/SegmentTree.sol"; contract SegmentTreeTester { using SegmentTree for SegmentTree.Tree; SegmentTree.Tree private _tree; uint[129] private _places; function initTree() external { _tree.create(128); for (uint8 i = 1; i <= 128; i++) { if (_places[i] > 0) _tree.addToPlace(i, _places[i]); } } function addElemInPlaces(uint place, uint elem) external { _places[place] = elem; } function addToLast(uint elem) external { _tree.addToPlace(_tree.getSize(), elem); } function addToPlace(uint place, uint elem) external { _tree.addToPlace(place, elem); } function removeFromPlace(uint place, uint elem) external { _tree.removeFromPlace(place, elem); } function moveFromPlaceToPlace(uint fromPlace, uint toPlace, uint elem) external { _tree.moveFromPlaceToPlace(fromPlace, toPlace, elem); } function sumFromPlaceToLast(uint place) external view returns (uint) { return _tree.sumFromPlaceToLast(place); } function getRandomElem(uint place) external view returns (uint) { Random.RandomGenerator memory randomGenerator = Random.createFromEntropy( abi.encodePacked(uint(blockhash(block.number - 1)), place) ); return _tree.getRandomNonZeroElementFromPlaceToLast(place, randomGenerator); } function getElem(uint index) external view returns (uint) { require(index < _tree.tree.length, "Incorrect index"); return _tree.tree[index]; } function getSize() external view returns (uint) { return _tree.getSize(); } }
* @dev Checks whether complaint is possible./
function isComplaintPossible( bytes32 schainHash, uint fromNodeIndex, uint toNodeIndex ) external view returns (bool) { (uint indexFrom, bool checkFrom) = checkAndReturnIndexInGroup(schainHash, fromNodeIndex, false); (uint indexTo, bool checkTo) = checkAndReturnIndexInGroup(schainHash, toNodeIndex, false); if (!checkFrom || !checkTo) return false; bool complaintSending = ( complaints[schainHash].nodeToComplaint == uint(-1) && dkgProcess[schainHash].broadcasted[indexTo] && !dkgProcess[schainHash].completed[indexFrom] ) || ( dkgProcess[schainHash].broadcasted[indexTo] && complaints[schainHash].startComplaintBlockTimestamp.add(_getComplaintTimelimit()) <= block.timestamp && complaints[schainHash].nodeToComplaint == toNodeIndex ) || ( !dkgProcess[schainHash].broadcasted[indexTo] && complaints[schainHash].nodeToComplaint == uint(-1) && channels[schainHash].startedBlockTimestamp.add(_getComplaintTimelimit()) <= block.timestamp ) || ( complaints[schainHash].nodeToComplaint == uint(-1) && isEveryoneBroadcasted(schainHash) && dkgProcess[schainHash].completed[indexFrom] && !dkgProcess[schainHash].completed[indexTo] && startAlrightTimestamp[schainHash].add(_getComplaintTimelimit()) <= block.timestamp ); return channels[schainHash].active && dkgProcess[schainHash].broadcasted[indexFrom] && _isNodeOwnedByMessageSender(fromNodeIndex, msg.sender) && complaintSending; }
10,036,675
[ 1, 4081, 2856, 27534, 1598, 353, 3323, 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, 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, 445, 353, 799, 412, 1598, 13576, 12, 203, 3639, 1731, 1578, 272, 5639, 2310, 16, 203, 3639, 2254, 628, 907, 1016, 16, 203, 3639, 2254, 358, 907, 1016, 203, 565, 262, 203, 3639, 3903, 203, 3639, 1476, 203, 3639, 1135, 261, 6430, 13, 203, 565, 288, 203, 3639, 261, 11890, 770, 1265, 16, 1426, 866, 1265, 13, 273, 30970, 990, 1016, 31138, 12, 87, 5639, 2310, 16, 628, 907, 1016, 16, 629, 1769, 203, 3639, 261, 11890, 770, 774, 16, 1426, 866, 774, 13, 273, 30970, 990, 1016, 31138, 12, 87, 5639, 2310, 16, 358, 907, 1016, 16, 629, 1769, 203, 3639, 309, 16051, 1893, 1265, 747, 401, 1893, 774, 13, 203, 5411, 327, 629, 31, 203, 3639, 1426, 27534, 1598, 16322, 273, 261, 203, 7734, 27534, 1598, 87, 63, 87, 5639, 2310, 8009, 2159, 774, 799, 412, 1598, 422, 2254, 19236, 21, 13, 597, 203, 7734, 302, 14931, 2227, 63, 87, 5639, 2310, 8009, 19805, 329, 63, 1615, 774, 65, 597, 203, 7734, 401, 2883, 75, 2227, 63, 87, 5639, 2310, 8009, 13615, 63, 1615, 1265, 65, 203, 5411, 262, 747, 203, 5411, 261, 203, 7734, 302, 14931, 2227, 63, 87, 5639, 2310, 8009, 19805, 329, 63, 1615, 774, 65, 597, 203, 7734, 27534, 1598, 87, 63, 87, 5639, 2310, 8009, 1937, 799, 412, 1598, 1768, 4921, 18, 1289, 24899, 588, 799, 412, 1598, 10178, 19741, 10756, 1648, 1203, 18, 5508, 597, 203, 7734, 27534, 1598, 87, 63, 87, 5639, 2310, 8009, 2159, 774, 799, 412, 1598, 422, 358, 907, 1016, 203, 2 ]
// SPDX-License-Identifier: agpl-3.0 pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Burnable.sol"; import "@openzeppelin/contracts/access/AccessControl.sol"; interface IS16Presale { function getPresaleRegisterUserList() external view returns (address[] memory); function getPresaleTime() external view returns (uint); } contract S16Token is Ownable, ERC20, ERC20Burnable, AccessControl { uint256 maxTokenSupply = 10000000000e18; //10 billion max token supply bytes32 public constant S16DIST_ROLE = keccak256("S16DIST_ROLE"); bool public _airdropMintingPaused = false; address private s16PresaleAddress; address private s16DistAddress; constructor() ERC20("S16", "S16") {} function configureS16Presale(address _s16PresaleAddress) external onlyOwner { require(_s16PresaleAddress != address(0), "S16TOKEN: null address"); s16PresaleAddress = _s16PresaleAddress; } function configureS16Dist(address _s16DistAddress) external onlyOwner { require(_s16DistAddress != address(0), "S16TOKEN: null address"); s16DistAddress = _s16DistAddress; } function setRoleS16Dist() external onlyOwner { require(s16DistAddress != address(0), "S16TOKEN: null address"); _setupRole(S16DIST_ROLE, s16DistAddress); } function mint(address account, uint256 amount) external onlyOwner { require( totalSupply() + amount <= maxTokenSupply, "S16TOKEN: cap exceeded" ); super._mint(account, amount); } function airdropTokenbyAdmin() external onlyOwner { require(s16PresaleAddress != address(0), "S16TOKEN: s16 presale not configured"); require(block.timestamp > IS16Presale(s16PresaleAddress).getPresaleTime()); address[] memory preSaleUsers = IS16Presale(s16PresaleAddress).getPresaleRegisterUserList(); for (uint256 i = 0; i < preSaleUsers.length; i++) { require( totalSupply() + 1600e18 <= maxTokenSupply, "S16TOKEN: cap exceeded" ); super._mint(preSaleUsers[i], 1600e18); } } function airdropTokenUser(address account, uint256 amount) external { require(!_airdropMintingPaused, "S16TOKEN"); require(s16DistAddress != address(0), "S16Token: s16 dist not configured yet"); require( hasRole(S16DIST_ROLE, s16DistAddress), "S16Token: callet is not S16Dist" ); require( totalSupply() + amount <= maxTokenSupply, "S16TOKEN: cap exceeded" ); super._mint(account, amount); } function pauseAirdrop(bool _pause) external onlyOwner{ require(_airdropMintingPaused != _pause, "Already in desired pause state"); _airdropMintingPaused = _pause; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/AccessControl.sol) pragma solidity ^0.8.0; import "./IAccessControl.sol"; import "../utils/Context.sol"; import "../utils/Strings.sol"; import "../utils/introspection/ERC165.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context, IAccessControl, ERC165 { struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", Strings.toHexString(uint160(account), 20), " is missing role ", Strings.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been revoked `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== * * NOTE: This function is deprecated in favor of {_grantRole}. */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } /** * @dev Grants `role` to `account`. * * Internal function without access restriction. */ function _grantRole(bytes32 role, address account) internal virtual { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } /** * @dev Revokes `role` from `account`. * * Internal function without access restriction. */ function _revokeRole(bytes32 role, address account) internal virtual { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/ERC20Burnable.sol) pragma solidity ^0.8.0; import "../ERC20.sol"; import "../../../utils/Context.sol"; /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ abstract contract ERC20Burnable is Context, ERC20 { /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 currentAllowance = allowance(account, _msgSender()); require(currentAllowance >= amount, "ERC20: burn amount exceeds allowance"); unchecked { _approve(account, _msgSender(), currentAllowance - amount); } _burn(account, amount); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/ERC20.sol) pragma solidity ^0.8.0; import "./IERC20.sol"; import "./extensions/IERC20Metadata.sol"; import "../../utils/Context.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead 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, IERC20Metadata { 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 default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two 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 override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override 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 * overridden; * * 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 override 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"); unchecked { _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"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This 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"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(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: * * - `account` 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); _afterTokenTransfer(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"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(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 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 {} /** * @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, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been 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 _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // 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 (token/ERC20/extensions/IERC20Metadata.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // 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/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 (access/IAccessControl.sol) pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/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); }
10 billion max token supply
uint256 maxTokenSupply = 10000000000e18;
12,235,671
[ 1, 2163, 20714, 285, 943, 1147, 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, 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, 2254, 5034, 943, 1345, 3088, 1283, 273, 2130, 12648, 73, 2643, 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 ]
// SPDX-License-Identifier: GPL-3.0 // File: @openzeppelin/contracts/utils/Strings.sol pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts/utils/Context.sol pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol 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() { _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); } } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts/utils/introspection/IERC165.sol pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: Matt W - NFT.sol // André Luque pragma solidity >=0.8.2; // to enable certain compiler features //import '@openzeppelin/contracts/token/ERC721/ERC721.sol'; contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString(), '.json')) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { 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 _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } contract nft is ERC721, Ownable { //baseURI that is established string private _currentBaseURI; //accumulate the number of tokens that have been minted uint256 public numberOfTokens; //limit the tokens that can be minted uint256 public maxTokens; //stores the amount of mints each address has had mapping(address => uint) private mintsPerAddress; //price to pay for each nft uint256 private mintCost_ = 0.03 ether; //stores value of current reserved NFTs minted by creator uint private reservedMints; //stores the maimum amount of reserved mints allowed uint private maxReservedMints; constructor() ERC721('Reaper Boys', 'REAP') { //this uri will only be used once revealed is on _currentBaseURI = 'ipfs://Qme9M4eaLxRzMXp5k3rHuTSAxBCUTBBStyft7PLExayGAr/'; //start off with zero tokens and max in total collection will be 10k numberOfTokens = 0; maxTokens = 9999; //reserved mints values reservedMints = 0; maxReservedMints = 100; //minting the team´s NFTs _safeMint(msg.sender, 990); _safeMint(msg.sender, 3595); _safeMint(msg.sender, 8549); mintsPerAddress[msg.sender] += 3; numberOfTokens += 3; reservedMints += 3; } //this uri will only be used once revealed is on function setBaseURI(string memory baseURI) public onlyOwner { _currentBaseURI = baseURI; } //function to see the current baseURI function _baseURI() internal view override returns (string memory) { return _currentBaseURI; } //tokens are numbered from 1 to 10 function tokenId() internal view returns(uint256) { uint currentId = numberOfTokens - reservedMints; bool exists = true; while (exists || currentId == 6138) { currentId += 1; exists = _exists(currentId); } return currentId; } //minting a new NFT function mint(uint number) payable public { require(numberOfTokens + number <= maxTokens - (maxReservedMints - reservedMints), 'Max Number of Tokens reached!'); require(msg.value >= mintCost_ * number, 'insufficient Funds, Price of each NFT is 0.03'); for (uint256 i = 0; i < number; i++) { uint256 tid = tokenId(); _safeMint(msg.sender, tid); mintsPerAddress[msg.sender] += 1; numberOfTokens += 1; } //get amount of eth sent to pay for minting and automatically send to owner sendToOwner(); } //reserved NFTs for creator function reservedMintCreator(uint256 number) public onlyOwner { require(reservedMints + number <= maxReservedMints, "Not enough Reserved NFTs left to mint.."); for (uint256 i = 0; i < number; i++) { uint tid = tokenId(); _safeMint(msg.sender, tid); mintsPerAddress[msg.sender] += 1; numberOfTokens += 1; reservedMints += 1; } } //sending mint fees to owner function sendToOwner() internal { address payable owner_ = payable(owner()); (bool success, ) = owner_.call{value: msg.value}(""); require(success, "Address: unable to send value, recipient may have reverted"); } //function for the owner to see how many reserved mints he has left function reservedMintsLeft() public onlyOwner view returns(uint) { return maxReservedMints - reservedMints; } //total amount of NFTs that have been minted function totalSupply() public view returns(uint) { return numberOfTokens; } }
function for the owner to see how many reserved mints he has left
function reservedMintsLeft() public onlyOwner view returns(uint) { return maxReservedMints - reservedMints; }
270,860
[ 1, 915, 364, 326, 3410, 358, 2621, 3661, 4906, 8735, 312, 28142, 3904, 711, 2002, 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, 8735, 49, 28142, 3910, 1435, 1071, 1338, 5541, 1476, 1135, 12, 11890, 13, 288, 203, 3639, 327, 943, 10435, 49, 28142, 300, 8735, 49, 28142, 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 ]
./partial_match/3/0x69D242646BE3BA965059441feC2197d6bcDfbEFD/sources/WrappedADS.sol
* @dev Atomically decreases the minterAllowance granted to `minter`/
function decreaseMinterAllowance(address minter, uint256 subtractedValue) public onlyOwner returns (bool) { _minterApprove(minter, _minterAllowances[minter].sub(subtractedValue, "WrappedADS: decreased minterAllowance below zero")); return true; }
5,212,486
[ 1, 3641, 6478, 23850, 3304, 326, 1131, 387, 7009, 1359, 17578, 358, 1375, 1154, 387, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 20467, 49, 2761, 7009, 1359, 12, 2867, 1131, 387, 16, 2254, 5034, 10418, 329, 620, 13, 1071, 1338, 5541, 1135, 261, 6430, 13, 288, 203, 3639, 389, 1154, 387, 12053, 537, 12, 1154, 387, 16, 389, 1154, 387, 7009, 6872, 63, 1154, 387, 8009, 1717, 12, 1717, 1575, 329, 620, 16, 315, 17665, 1880, 55, 30, 23850, 8905, 1131, 387, 7009, 1359, 5712, 3634, 7923, 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 ]
./full_match/42161/0xD5a4C8cf4aE6249523112C621b0c95326b58C9B8/sources/Users/rostyslav/Desktop/projects/cup/encanto-contracts/contracts/Lock.sol
@dev Withdraw tokens after the end of the locking period or during the deposit period @param amount The amount of tokens to withdraw
function withdraw(uint256 amount) public { if ( block.timestamp < lockDuration ) { revert('lock perioud ongoing - failed'); } if (balanceOf[msg.sender] < amount) { revert('exceeds bbalance'); } balanceOf[msg.sender] -= amount; totalSupply -= amount; if (!token.transfer(msg.sender, amount)) { revert('transfer failed'); } cuplp.burn(address(msg.sender), amount); emit Transfer(address(this), msg.sender, amount); }
16,298,777
[ 1, 1190, 9446, 2430, 1839, 326, 679, 434, 326, 18887, 3879, 578, 4982, 326, 443, 1724, 3879, 225, 3844, 1021, 3844, 434, 2430, 358, 598, 9446, 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, 598, 9446, 12, 11890, 5034, 3844, 13, 1071, 288, 203, 3639, 309, 261, 203, 5411, 1203, 18, 5508, 411, 2176, 5326, 203, 3639, 262, 288, 203, 2398, 15226, 2668, 739, 1534, 1594, 1100, 30542, 300, 2535, 8284, 203, 3639, 289, 203, 3639, 309, 261, 12296, 951, 63, 3576, 18, 15330, 65, 411, 3844, 13, 288, 203, 5411, 15226, 2668, 338, 5288, 87, 7129, 6112, 8284, 203, 3639, 289, 203, 203, 3639, 11013, 951, 63, 3576, 18, 15330, 65, 3947, 3844, 31, 203, 3639, 2078, 3088, 1283, 3947, 3844, 31, 203, 203, 3639, 309, 16051, 2316, 18, 13866, 12, 3576, 18, 15330, 16, 3844, 3719, 288, 203, 5411, 15226, 2668, 13866, 2535, 8284, 203, 3639, 289, 203, 3639, 15985, 412, 84, 18, 70, 321, 12, 2867, 12, 3576, 18, 15330, 3631, 3844, 1769, 203, 3639, 3626, 12279, 12, 2867, 12, 2211, 3631, 1234, 18, 15330, 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, -100 ]
pragma solidity ^0.4.16; contract XCareTokenLocked { // no any function to tranfer token }
no any function to tranfer token
contract XCareTokenLocked { }
2,565,339
[ 1, 2135, 1281, 445, 358, 13637, 586, 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, 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, 16351, 1139, 39, 834, 1345, 8966, 288, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0xeB40E25AF8F5F22Bb201f53971480beA0094Cd65/sources/src/v0.8/functions/tests/1_0_0/testhelpers/FunctionsClientUpgradeHelper.sol
* @notice Callback that is invoked once the DON has resolved the request or hit an error @param requestId The request ID, returned by sendRequest() @param response Aggregated response from the user code @param err Aggregated error from the user code or from the execution pipeline Either response or error parameter will be set, but never both/
function fulfillRequest(bytes32 requestId, bytes memory response, bytes memory err) internal override { emit ResponseReceived(requestId, response, err); }
4,322,740
[ 1, 2428, 716, 353, 8187, 3647, 326, 463, 673, 711, 4640, 326, 590, 578, 6800, 392, 555, 225, 14459, 1021, 590, 1599, 16, 2106, 635, 12413, 1435, 225, 766, 10594, 690, 766, 628, 326, 729, 981, 225, 393, 10594, 690, 555, 628, 326, 729, 981, 578, 628, 326, 4588, 5873, 14635, 766, 578, 555, 1569, 903, 506, 444, 16, 1496, 5903, 3937, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 225, 445, 22290, 691, 12, 3890, 1578, 14459, 16, 1731, 3778, 766, 16, 1731, 3778, 393, 13, 2713, 3849, 288, 203, 565, 3626, 2306, 8872, 12, 2293, 548, 16, 766, 16, 393, 1769, 203, 225, 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 ]
pragma solidity ^0.4.24; import './lib/ECVerify.sol'; contract GeoEthChannels { /// STORAGE uint256 closingTimeout = 5760; //approx 24 hours uint256 channelsCount; mapping(bytes32 => Channel) public channels; // map of all channels, bytes32 -> Channel mapping(bytes32 => ClosingRequest) public closingRequests; // map of all closing requests, channel_id -> CloseRequest mapping(bytes32 => ReceiptsBalances) public receiptsBalances; enum ChannelStates { Uninitialized, Unidirectional, Bidirectional, Settled, Closed } struct Channel { address alice; address bob; ChannelStates state; uint256 balanceAlice; uint256 balanceBob; } struct ClosingRequest { uint256 closingRequested; //number of block at which request created uint256 channelEpoch; uint128 aliceNonce; uint128 bobNonce; } struct ReceiptsBalances { uint256 aliceReceived; uint256 bobReceived; } /// EXTERNAL function getChannelDetails( bytes32 channelID) external returns( address alice, address bob, uint8 state, uint256 balanceAlice, uint256 balanceBob) { alice = channels[channelID].alice; bob = channels[channelID].bob; state = uint8(channels[channelID].state); balanceAlice = channels[channelID].balanceAlice; balanceBob = channels[channelID].balanceBob; } function getClosingRequestDetails( bytes32 channelID) external returns( uint256 closingRequested, uint256 channelEpoch, uint128 aliceNonce, uint128 bobNonce) { closingRequested = closingRequests[channelID].closingRequested; channelEpoch = closingRequests[channelID].channelEpoch; aliceNonce = closingRequests[channelID].aliceNonce; bobNonce = closingRequests[channelID].bobNonce; } /// @dev creates unidirectional channel function openChannel( address bob) external payable { // getting channel id bytes32 channelID = calcChannelID(msg.sender, bob); // make sure, that channel is inactive require(channels[channelID].state == ChannelStates.Uninitialized || channels[channelID].state == ChannelStates.Closed); // Clear data if channel was closed if (channels[channelID].state == ChannelStates.Closed) { delete closingRequests[channelID]; } // initialize channel channels[channelID] = Channel({ alice: msg.sender, bob: bob, state: ChannelStates.Unidirectional, balanceAlice: msg.value, balanceBob: 0 }); emit ChannelCreated(channelID); } /// @dev makes channel bidirectional function respondChannel( address alice) external payable { bytes32 channelID = calcChannelID(alice, msg.sender); // make sure, that channel still opened require(channels[channelID].state == ChannelStates.Unidirectional); // make sure, that bob tries to respond channel with non zero value require(msg.value != 0); // make sure, that bob didn't responded yet require(channels[channelID].balanceBob == 0); // make sure, that it is not alice responded require(msg.sender != channels[channelID].alice); // update channel channels[channelID].balanceBob = msg.value; channels[channelID].state = ChannelStates.Bidirectional; emit ChannelResponded(channelID); } function auditProofSettlement( bytes32 channelID, uint256 auditEpoch, uint256 balanceAlice, uint256 balanceBob, bytes signatureAlice, bytes signatureBob) external { // make sure channel still not closed or uninitialized require(channels[channelID].state != ChannelStates.Closed); require(channels[channelID].state != ChannelStates.Uninitialized); // make sure that audit epoch is match or bigger than stored now require(auditEpoch >= closingRequests[channelID].channelEpoch); // make sure that channel not ready to close require(closingRequests[channelID].closingRequested + closingTimeout > block.number); // verify alice's signature of message require(channels[channelID].alice == extractAuditProofSettlementSignature( channelID, auditEpoch, balanceAlice, balanceBob, signatureAlice )); // verify bob's signature of message require(channels[channelID].bob == extractAuditProofSettlementSignature( channelID, auditEpoch, balanceAlice, balanceBob, signatureBob )); // set settlement data if closing not requested yet if (closingRequests[channelID].closingRequested == 0) { closingRequests[channelID].closingRequested = block.number; channels[channelID].state = ChannelStates.Settled; emit ChannelSettled(channelID); } // update channel and request data channels[channelID].balanceAlice = balanceAlice; channels[channelID].balanceBob = balanceBob; closingRequests[channelID].channelEpoch = auditEpoch + 1; emit NewAuditProofs(channelID); } function receiptsProofSettlement( bytes32 channelID, uint256 channelEpoch, address receiver, uint256[] receiptID, uint256[] amount, bytes32[] rs, uint8[] v ) external { // make sure that channel still not closed or uninitialized require(channels[channelID].state != ChannelStates.Closed); require(channels[channelID].state != ChannelStates.Uninitialized); // set settlement if closing not requested yet if (closingRequests[channelID].closingRequested == 0 && closingRequests[channelID].channelEpoch == 0) { closingRequests[channelID].closingRequested = block.number; } bool isAliceReceiver = channels[channelID].alice == receiver ? true : false; // to be implemented // for (uint256 i = 0; i < receiptID.length; i++) { // make sure that signer is from correct channel // make sure that receiptID is bigger than sender's nonce // make sure that channelEpoch in receipt is fit to current epoch // } emit NewReceiptsProofs(channelID); } function cooperativeClose( bytes32 channelID, uint256 balanceAlice, uint256 balanceBob, bytes signatureAlice, bytes signatureBob ) external { // make sure that channel opened require(channels[channelID].state != ChannelStates.Uninitialized); require(channels[channelID].state != ChannelStates.Closed); //make sure that requested balances not exceeds channel balance require(channels[channelID].balanceAlice + channels[channelID].balanceBob >= balanceAlice + balanceBob); // verify alice's signature of message require(channels[channelID].alice == extractCooperativeCloseSignature( channelID, balanceAlice, balanceBob, signatureAlice )); // verify bob's signature of message require(channels[channelID].bob == extractCooperativeCloseSignature( channelID, balanceAlice, balanceBob, signatureBob )); // update channel data channels[channelID].balanceAlice = balanceAlice; channels[channelID].balanceBob = balanceBob; channels[channelID].state = ChannelStates.Closed; // send ether to parties channels[channelID].alice.transfer(balanceAlice); channels[channelID].bob.transfer(balanceBob); emit ChannelClosed(channelID); } function closeChannel( bytes32 channelID) external { // make sure that channel ready to close require(closingRequests[channelID].closingRequested + closingTimeout <= block.number); // make sure that channel still settled require(channels[channelID].state == ChannelStates.Settled); // update channel data channels[channelID].state = ChannelStates.Closed; //send ether to parties channels[channelID].alice.transfer(channels[channelID].balanceAlice); channels[channelID].bob.transfer(channels[channelID].balanceBob); emit ChannelClosed(channelID); } function calcChannelID( address alice, address bob) public pure returns(bytes32 id) { //returns id derived from both addresses return keccak256(abi.encodePacked(alice, bob)); } /// INTERNAL function extractAuditProofSettlementSignature( bytes32 channelID, uint256 auditEpoch, uint256 aliceBalance, uint256 bobBalance, bytes signature) internal returns(address signer) { bytes32 message_hash = keccak256( channelID, auditEpoch, aliceBalance, bobBalance); signer = ECVerify.ecverify(message_hash, signature); } function extractCooperativeCloseSignature( bytes32 channelID, uint256 aliceBalance, uint256 bobBalance, bytes signature) internal returns(address signer) { bytes32 message_hash = keccak256( bobBalance, aliceBalance, channelID); signer = ECVerify.ecverify(message_hash, signature); } ///EVENTS event ChannelCreated(bytes32 indexed _channelID); event ChannelResponded(bytes32 indexed _channelID); event ChannelSettled(bytes32 indexed _channelID); event ChannelClosed(bytes32 indexed _channelID); event NewReceiptsProofs(bytes32 indexed _channelID); event NewAuditProofs(bytes32 indexed _channelID); }
@dev makes channel bidirectional make sure, that channel still opened make sure, that bob tries to respond channel with non zero value make sure, that bob didn't responded yet make sure, that it is not alice responded update channel
function respondChannel( address alice) external payable { bytes32 channelID = calcChannelID(alice, msg.sender); require(channels[channelID].state == ChannelStates.Unidirectional); require(msg.value != 0); require(channels[channelID].balanceBob == 0); require(msg.sender != channels[channelID].alice); channels[channelID].balanceBob = msg.value; channels[channelID].state = ChannelStates.Bidirectional; emit ChannelResponded(channelID); }
1,028,113
[ 1, 81, 3223, 1904, 9949, 24699, 1221, 3071, 16, 716, 1904, 4859, 10191, 1221, 3071, 16, 716, 800, 70, 9327, 358, 6846, 1904, 598, 1661, 3634, 460, 1221, 3071, 16, 716, 800, 70, 10242, 1404, 7899, 785, 4671, 1221, 3071, 16, 716, 518, 353, 486, 524, 1812, 7899, 785, 1089, 1904, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 6846, 2909, 12, 203, 3639, 1758, 524, 1812, 13, 203, 565, 3903, 203, 565, 8843, 429, 203, 565, 288, 203, 3639, 1731, 1578, 24324, 273, 7029, 2909, 734, 12, 287, 1812, 16, 1234, 18, 15330, 1769, 203, 203, 3639, 2583, 12, 9114, 63, 4327, 734, 8009, 2019, 422, 5307, 7629, 18, 984, 350, 24699, 1769, 203, 3639, 2583, 12, 3576, 18, 1132, 480, 374, 1769, 203, 3639, 2583, 12, 9114, 63, 4327, 734, 8009, 12296, 38, 947, 422, 374, 1769, 203, 3639, 2583, 12, 3576, 18, 15330, 480, 5750, 63, 4327, 734, 8009, 287, 1812, 1769, 203, 203, 3639, 5750, 63, 4327, 734, 8009, 12296, 38, 947, 273, 1234, 18, 1132, 31, 203, 3639, 5750, 63, 4327, 734, 8009, 2019, 273, 5307, 7629, 18, 17763, 24699, 31, 203, 203, 3639, 3626, 5307, 607, 500, 785, 12, 4327, 734, 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 ]
pragma solidity ^0.4.20; 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; } } contract Ownable { address public owner; address public controller; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } modifier onlyController() { require(msg.sender == controller); _; } function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } function setControler(address _controller) public onlyOwner { controller = _controller; } } contract OwnableToken { address public owner; address public minter; address public burner; address public controller; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); function OwnableToken() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } modifier onlyMinter() { require(msg.sender == minter); _; } modifier onlyBurner() { require(msg.sender == burner); _; } modifier onlyController() { require(msg.sender == controller); _; } modifier onlyPayloadSize(uint256 numwords) { assert(msg.data.length == numwords * 32 + 4); _; } function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } function setMinter(address _minterAddress) public onlyOwner { minter = _minterAddress; } function setBurner(address _burnerAddress) public onlyOwner { burner = _burnerAddress; } function setControler(address _controller) public onlyOwner { controller = _controller; } } contract KYCControl is OwnableToken { event KYCApproved(address _user, bool isApproved); mapping(address => bool) public KYCParticipants; function isKYCApproved(address _who) view public returns (bool _isAprroved){ return KYCParticipants[_who]; } function approveKYC(address _userAddress) onlyController public { KYCParticipants[_userAddress] = true; emit KYCApproved(_userAddress, true); } } contract VernamCrowdSaleToken is OwnableToken, KYCControl { using SafeMath for uint256; event Transfer(address indexed from, address indexed to, uint256 value); /* Public variables of the token */ string public name; string public symbol; uint8 public decimals; uint256 public _totalSupply; /*Private Variables*/ uint256 constant POW = 10 ** 18; uint256 _circulatingSupply; /* This creates an array with all balances */ mapping (address => uint256) public balances; // This notifies clients about the amount burnt event Burn(address indexed from, uint256 value); event Mint(address indexed _participant, uint256 value); /* Initializes contract with initial supply tokens to the creator of the contract */ function VernamCrowdSaleToken() public { name = "Vernam Crowdsale Token"; // Set the name for display purposes symbol = "VCT"; // Set the symbol for display purposes decimals = 18; // Amount of decimals for display purposes _totalSupply = SafeMath.mul(1000000000, POW); //1 Billion Tokens with 18 Decimals _circulatingSupply = 0; } function mintToken(address _participant, uint256 _mintedAmount) public onlyMinter returns (bool _success) { require(_mintedAmount > 0); require(_circulatingSupply.add(_mintedAmount) <= _totalSupply); KYCParticipants[_participant] = false; balances[_participant] = balances[_participant].add(_mintedAmount); _circulatingSupply = _circulatingSupply.add(_mintedAmount); emit Transfer(0, this, _mintedAmount); emit Transfer(this, _participant, _mintedAmount); emit Mint(_participant, _mintedAmount); return true; } function burn(address _participant, uint256 _value) public onlyBurner returns (bool _success) { require(_value > 0); require(balances[_participant] >= _value); // Check if the sender has enough require(isKYCApproved(_participant) == true); balances[_participant] = balances[_participant].sub(_value); // Subtract from the sender _circulatingSupply = _circulatingSupply.sub(_value); _totalSupply = _totalSupply.sub(_value); // Updates totalSupply emit Transfer(_participant, 0, _value); emit Burn(_participant, _value); return true; } function totalSupply() public view returns (uint256) { return _totalSupply; } function circulatingSupply() public view returns (uint256) { return _circulatingSupply; } function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } contract VernamCrowdSale is Ownable { using SafeMath for uint256; // After day 7 you can contribute only more than 10 ethers uint constant TEN_ETHERS = 10 ether; // Minimum and maximum contribution amount uint constant minimumContribution = 100 finney; uint constant maximumContribution = 500 ether; // uint constant FIRST_MONTH = 0; uint constant SECOND_MONTH = 1; uint constant THIRD_MONTH = 2; uint constant FORTH_MONTH = 3; uint constant FIFTH_MONTH = 4; uint constant SIXTH_MONTH = 5; address public benecifiary; // Check if the crowdsale is active bool public isInCrowdsale; // The start time of the crowdsale uint public startTime; // The total sold tokens uint public totalSoldTokens; // The total contributed wei uint public totalContributedWei; // Public parameters for all the stages uint constant public threeHotHoursDuration = 3 hours; uint constant public threeHotHoursPriceOfTokenInWei = 63751115644524 wei; //0.00006375111564452380 ETH per Token // 15686 VRN per ETH uint public threeHotHoursTokensCap; uint public threeHotHoursCapInWei; uint public threeHotHoursEnd; uint public firstStageDuration = 8 days; uint public firstStagePriceOfTokenInWei = 85005100306018 wei; //0.00008500510030601840 ETH per Token // 11764 VRN per ETH uint public firstStageEnd; uint constant public secondStageDuration = 12 days; uint constant public secondStagePriceOfTokenInWei = 90000900009000 wei; //0.00009000090000900010 ETH per Token // 11111 VRN per ETH uint public secondStageEnd; uint constant public thirdStageDuration = 41 days; uint constant public thirdStagePriceOfTokenInWei = 106258633513973 wei; //0.00010625863351397300 ETH per Token // 9411 VRN per ETH uint constant public thirdStageDiscountPriceOfTokenInWei = 95002850085503 wei; //0.00009500285008550260 ETH per Token // 10526 VRN per ETH uint public thirdStageEnd; uint constant public TOKENS_HARD_CAP = 500000000000000000000000000; // 500 000 000 with 18 decimals // 18 decimals uint constant POW = 10 ** 18; // Constants for Realase Three Hot Hours uint constant public LOCK_TOKENS_DURATION = 30 days; uint public firstMonthEnd; uint public secondMonthEnd; uint public thirdMonthEnd; uint public fourthMonthEnd; uint public fifthMonthEnd; // Mappings mapping(address => uint) public contributedInWei; mapping(address => uint) public threeHotHoursTokens; mapping(address => mapping(uint => uint)) public getTokensBalance; mapping(address => mapping(uint => bool)) public isTokensTaken; mapping(address => bool) public isCalculated; VernamCrowdSaleToken public vernamCrowdsaleToken; // Modifiers modifier afterCrowdsale() { require(block.timestamp > thirdStageEnd); _; } modifier isAfterThreeHotHours { require(block.timestamp > threeHotHoursEnd); _; } // Events event CrowdsaleActivated(uint startTime, uint endTime); event TokensBought(address participant, uint weiAmount, uint tokensAmount); event ReleasedTokens(uint _amount); event TokensClaimed(address _participant, uint tokensToGetFromWhiteList); /** @dev Constructor * @param _benecifiary * @param _vernamCrowdSaleTokenAddress The address of the crowdsale token. * */ constructor(address _benecifiary, address _vernamCrowdSaleTokenAddress) public { benecifiary = _benecifiary; vernamCrowdsaleToken = VernamCrowdSaleToken(_vernamCrowdSaleTokenAddress); isInCrowdsale = false; } /** @dev Function which activates the crowdsale * Only the owner can call the function * Activates the threeHotHours and the whole crowdsale * Set the duration of crowdsale stages * Set the tokens and wei cap of crowdsale stages * Set the duration in which the tokens bought in threeHotHours will be locked */ function activateCrowdSale() public onlyOwner { setTimeForCrowdsalePeriods(); threeHotHoursTokensCap = 100000000000000000000000000; threeHotHoursCapInWei = threeHotHoursPriceOfTokenInWei.mul((threeHotHoursTokensCap).div(POW)); timeLock(); isInCrowdsale = true; emit CrowdsaleActivated(startTime, thirdStageEnd); } /** @dev Fallback function. * Provides functionality for person to buy tokens. */ function() public payable { buyTokens(msg.sender,msg.value); } /** @dev Buy tokens function * Provides functionality for person to buy tokens. * @param _participant The investor which want to buy tokens. * @param _weiAmount The wei amount which the investor want to contribute. * @return success Is the buy tokens function called successfully. */ function buyTokens(address _participant, uint _weiAmount) public payable returns(bool success) { // Check if the crowdsale is active require(isInCrowdsale == true); // Check if the wei amount is between minimum and maximum contribution amount require(_weiAmount >= minimumContribution); require(_weiAmount <= maximumContribution); // Vaidates the purchase // Check if the _participant address is not null and the weiAmount is not zero validatePurchase(_participant, _weiAmount); uint currentLevelTokens; uint nextLevelTokens; // Returns the current and next level tokens amount (currentLevelTokens, nextLevelTokens) = calculateAndCreateTokens(_weiAmount); uint tokensAmount = currentLevelTokens.add(nextLevelTokens); // If the hard cap is reached the crowdsale is not active anymore if(totalSoldTokens.add(tokensAmount) > TOKENS_HARD_CAP) { isInCrowdsale = false; return; } // Transfer Ethers benecifiary.transfer(_weiAmount); // Stores the participant's contributed wei contributedInWei[_participant] = contributedInWei[_participant].add(_weiAmount); // If it is in threeHotHours tokens will not be minted they will be stored in mapping threeHotHoursTokens if(threeHotHoursEnd > block.timestamp) { threeHotHoursTokens[_participant] = threeHotHoursTokens[_participant].add(currentLevelTokens); isCalculated[_participant] = false; // If we overflow threeHotHours tokens cap the tokens for the next level will not be zero // So we should deactivate the threeHotHours and mint tokens if(nextLevelTokens > 0) { vernamCrowdsaleToken.mintToken(_participant, nextLevelTokens); } } else { vernamCrowdsaleToken.mintToken(_participant, tokensAmount); } // Store total sold tokens amount totalSoldTokens = totalSoldTokens.add(tokensAmount); // Store total contributed wei amount totalContributedWei = totalContributedWei.add(_weiAmount); emit TokensBought(_participant, _weiAmount, tokensAmount); return true; } /** @dev Function which gets the tokens amount for current and next level. * If we did not overflow the current level cap, the next level tokens will be zero. * @return _currentLevelTokensAmount and _nextLevelTokensAmount Returns the calculated tokens for the current and next level * It is called by calculateAndCreateTokens function */ function calculateAndCreateTokens(uint weiAmount) internal view returns (uint _currentLevelTokensAmount, uint _nextLevelTokensAmount) { if(block.timestamp < threeHotHoursEnd && totalSoldTokens < threeHotHoursTokensCap) { (_currentLevelTokensAmount, _nextLevelTokensAmount) = tokensCalculator(weiAmount, threeHotHoursPriceOfTokenInWei, firstStagePriceOfTokenInWei, threeHotHoursCapInWei); return (_currentLevelTokensAmount, _nextLevelTokensAmount); } if(block.timestamp < firstStageEnd) { _currentLevelTokensAmount = weiAmount.div(firstStagePriceOfTokenInWei); _currentLevelTokensAmount = _currentLevelTokensAmount.mul(POW); return (_currentLevelTokensAmount, 0); } if(block.timestamp < secondStageEnd) { _currentLevelTokensAmount = weiAmount.div(secondStagePriceOfTokenInWei); _currentLevelTokensAmount = _currentLevelTokensAmount.mul(POW); return (_currentLevelTokensAmount, 0); } if(block.timestamp < thirdStageEnd && weiAmount >= TEN_ETHERS) { _currentLevelTokensAmount = weiAmount.div(thirdStageDiscountPriceOfTokenInWei); _currentLevelTokensAmount = _currentLevelTokensAmount.mul(POW); return (_currentLevelTokensAmount, 0); } if(block.timestamp < thirdStageEnd){ _currentLevelTokensAmount = weiAmount.div(thirdStagePriceOfTokenInWei); _currentLevelTokensAmount = _currentLevelTokensAmount.mul(POW); return (_currentLevelTokensAmount, 0); } revert(); } /** @dev Realase the tokens from the three hot hours. */ function release() public { releaseThreeHotHourTokens(msg.sender); } /** @dev Realase the tokens from the three hot hours. * It can be called after the end of three hot hours * @param _participant The investor who want to release his tokens * @return success Is the release tokens function called successfully. */ function releaseThreeHotHourTokens(address _participant) public isAfterThreeHotHours returns(bool success) { // Check if the _participants tokens are realased // If not calculate his tokens for every month and set the isCalculated to true if(isCalculated[_participant] == false) { calculateTokensForMonth(_participant); isCalculated[_participant] = true; } // Unlock the tokens amount for the _participant uint _amount = unlockTokensAmount(_participant); // Substract the _amount from the threeHotHoursTokens mapping threeHotHoursTokens[_participant] = threeHotHoursTokens[_participant].sub(_amount); // Mint to the _participant vernamCrowdsaleTokens vernamCrowdsaleToken.mintToken(_participant, _amount); emit ReleasedTokens(_amount); return true; } /** @dev Get contributed amount in wei. * @return contributedInWei[_participant]. */ function getContributedAmountInWei(address _participant) public view returns (uint) { return contributedInWei[_participant]; } /** @dev Function which calculate tokens for every month (6 months). * @param weiAmount Participant's contribution in wei. * @param currentLevelPrice Price of the tokens for the current level. * @param nextLevelPrice Price of the tokens for the next level. * @param currentLevelCap Current level cap in wei. * @return _currentLevelTokensAmount and _nextLevelTokensAmount Returns the calculated tokens for the current and next level * It is called by three hot hours */ function tokensCalculator(uint weiAmount, uint currentLevelPrice, uint nextLevelPrice, uint currentLevelCap) internal view returns (uint _currentLevelTokensAmount, uint _nextLevelTokensAmount){ uint currentAmountInWei = 0; uint remainingAmountInWei = 0; uint currentLevelTokensAmount = 0; uint nextLevelTokensAmount = 0; // Check if the contribution overflows and you should buy tokens on next level price if(weiAmount.add(totalContributedWei) > currentLevelCap) { remainingAmountInWei = (weiAmount.add(totalContributedWei)).sub(currentLevelCap); currentAmountInWei = weiAmount.sub(remainingAmountInWei); currentLevelTokensAmount = currentAmountInWei.div(currentLevelPrice); nextLevelTokensAmount = remainingAmountInWei.div(nextLevelPrice); } else { currentLevelTokensAmount = weiAmount.div(currentLevelPrice); nextLevelTokensAmount = 0; } currentLevelTokensAmount = currentLevelTokensAmount.mul(POW); nextLevelTokensAmount = nextLevelTokensAmount.mul(POW); return (currentLevelTokensAmount, nextLevelTokensAmount); } /** @dev Function which calculate tokens for every month (6 months). * @param _participant The investor whose tokens are calculated. * It is called once from the releaseThreeHotHourTokens function */ function calculateTokensForMonth(address _participant) internal { // Get the max balance of the participant uint maxBalance = threeHotHoursTokens[_participant]; // Start from 10% for the first three months uint percentage = 10; for(uint month = 0; month < 6; month++) { // The fourth month the unlock tokens percentage is increased by 10% and for the fourth and fifth month will be 20% // It will increase one more by 10% in the last month and will become 30% if(month == 3 || month == 5) { percentage += 10; } // Set the participant at which month how much he will get getTokensBalance[_participant][month] = maxBalance.div(percentage); // Set for every month false to see the tokens for the month is not get it isTokensTaken[_participant][month] = false; } } /** @dev Function which validates if the participan is not null address and the wei amount is not zero * @param _participant The investor who want to unlock his tokens * @return _tokensAmount Tokens which are unlocked */ function unlockTokensAmount(address _participant) internal returns (uint _tokensAmount) { // Check if the _participant have tokens in threeHotHours stage require(threeHotHoursTokens[_participant] > 0); // Check if the _participant got his tokens in first month and if the time for the first month end has come if(block.timestamp < firstMonthEnd && isTokensTaken[_participant][FIRST_MONTH] == false) { // Go and get the tokens for the current month return getTokens(_participant, FIRST_MONTH.add(1)); // First month } // Check if the _participant got his tokens in second month and if the time is in the period between first and second month end if(((block.timestamp >= firstMonthEnd) && (block.timestamp < secondMonthEnd)) && isTokensTaken[_participant][SECOND_MONTH] == false) { // Go and get the tokens for the current month return getTokens(_participant, SECOND_MONTH.add(1)); // Second month } // Check if the _participant got his tokens in second month and if the time is in the period between second and third month end if(((block.timestamp >= secondMonthEnd) && (block.timestamp < thirdMonthEnd)) && isTokensTaken[_participant][THIRD_MONTH] == false) { // Go and get the tokens for the current month return getTokens(_participant, THIRD_MONTH.add(1)); // Third month } // Check if the _participant got his tokens in second month and if the time is in the period between third and fourth month end if(((block.timestamp >= thirdMonthEnd) && (block.timestamp < fourthMonthEnd)) && isTokensTaken[_participant][FORTH_MONTH] == false) { // Go and get the tokens for the current month return getTokens(_participant, FORTH_MONTH.add(1)); // Forth month } // Check if the _participant got his tokens in second month and if the time is in the period between forth and fifth month end if(((block.timestamp >= fourthMonthEnd) && (block.timestamp < fifthMonthEnd)) && isTokensTaken[_participant][FIFTH_MONTH] == false) { // Go and get the tokens for the current month return getTokens(_participant, FIFTH_MONTH.add(1)); // Fifth month } // Check if the _participant got his tokens in second month and if the time is after the end of the fifth month if((block.timestamp >= fifthMonthEnd) && isTokensTaken[_participant][SIXTH_MONTH] == false) { return getTokens(_participant, SIXTH_MONTH.add(1)); // Last month } } /** @dev Function for getting the tokens for unlock * @param _participant The investor who want to unlock his tokens * @param _period The period for which will be unlocked the tokens * @return tokensAmount Returns the amount of tokens for unlocing */ function getTokens(address _participant, uint _period) internal returns(uint tokensAmount) { uint tokens = 0; for(uint month = 0; month < _period; month++) { // Check if the tokens fot the current month unlocked if(isTokensTaken[_participant][month] == false) { // Set the isTokensTaken to true isTokensTaken[_participant][month] = true; // Calculates the tokens tokens += getTokensBalance[_participant][month]; // Set the balance for the curren month to zero getTokensBalance[_participant][month] = 0; } } return tokens; } /** @dev Function which validates if the participan is not null address and the wei amount is not zero * @param _participant The investor who want to buy tokens * @param _weiAmount The amount of wei which the investor want to contribute */ function validatePurchase(address _participant, uint _weiAmount) pure internal { require(_participant != address(0)); require(_weiAmount != 0); } /** @dev Function which set the duration of crowdsale stages * Called by the activateCrowdSale function */ function setTimeForCrowdsalePeriods() internal { startTime = block.timestamp; threeHotHoursEnd = startTime.add(threeHotHoursDuration); firstStageEnd = threeHotHoursEnd.add(firstStageDuration); secondStageEnd = firstStageEnd.add(secondStageDuration); thirdStageEnd = secondStageEnd.add(thirdStageDuration); } /** @dev Function which set the duration in which the tokens bought in threeHotHours will be locked * Called by the activateCrowdSale function */ function timeLock() internal { firstMonthEnd = (startTime.add(LOCK_TOKENS_DURATION)).add(threeHotHoursDuration); secondMonthEnd = firstMonthEnd.add(LOCK_TOKENS_DURATION); thirdMonthEnd = secondMonthEnd.add(LOCK_TOKENS_DURATION); fourthMonthEnd = thirdMonthEnd.add(LOCK_TOKENS_DURATION); fifthMonthEnd = fourthMonthEnd.add(LOCK_TOKENS_DURATION); } function getPrice(uint256 time, uint256 weiAmount) public view returns (uint levelPrice) { if(time < threeHotHoursEnd && totalSoldTokens < threeHotHoursTokensCap) { return threeHotHoursPriceOfTokenInWei; } if(time < firstStageEnd) { return firstStagePriceOfTokenInWei; } if(time < secondStageEnd) { return secondStagePriceOfTokenInWei; } if(time < thirdStageEnd && weiAmount > TEN_ETHERS) { return thirdStageDiscountPriceOfTokenInWei; } if(time < thirdStageEnd){ return thirdStagePriceOfTokenInWei; } } function setBenecifiary(address _newBenecifiary) public onlyOwner { benecifiary = _newBenecifiary; } } contract OwnableController { address public owner; address public KYCTeam; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } modifier onlyKYCTeam() { require(msg.sender == KYCTeam); _; } function setKYCTeam(address _KYCTeam) public onlyOwner { KYCTeam = _KYCTeam; } function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract Controller is OwnableController { VernamCrowdSale public vernamCrowdSale; VernamCrowdSaleToken public vernamCrowdsaleToken; VernamToken public vernamToken; mapping(address => bool) public isParticipantApproved; event Refunded(address _to, uint amountInWei); event Convert(address indexed participant, uint tokens); function Controller(address _crowdsaleAddress, address _vernamCrowdSaleToken) public { vernamCrowdSale = VernamCrowdSale(_crowdsaleAddress); vernamCrowdsaleToken = VernamCrowdSaleToken(_vernamCrowdSaleToken); } function releaseThreeHotHourTokens() public { vernamCrowdSale.releaseThreeHotHourTokens(msg.sender); } function convertYourTokens() public { convertTokens(msg.sender); } function convertTokens(address _participant) public { bool isApproved = vernamCrowdsaleToken.isKYCApproved(_participant); if(isApproved == false && isParticipantApproved[_participant] == true){ vernamCrowdsaleToken.approveKYC(_participant); isApproved = vernamCrowdsaleToken.isKYCApproved(_participant); } require(isApproved == true); uint256 tokens = vernamCrowdsaleToken.balanceOf(_participant); require(tokens > 0); vernamCrowdsaleToken.burn(_participant, tokens); vernamToken.transfer(_participant, tokens); emit Convert(_participant, tokens); } function approveKYC(address _participant) public onlyKYCTeam returns(bool _success) { vernamCrowdsaleToken.approveKYC(_participant); isParticipantApproved[_participant] = vernamCrowdsaleToken.isKYCApproved(_participant); return isParticipantApproved[_participant]; } function setVernamOriginalToken(address _vernamToken) public onlyOwner { vernamToken = VernamToken(_vernamToken); } } contract ERC20 { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); 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); } contract VernamToken is ERC20 { using SafeMath for uint256; /* Public variables of the token */ string public name; string public symbol; uint8 public decimals; uint256 public _totalSupply; modifier onlyPayloadSize(uint256 numwords) { //https://blog.golemproject.net/how-to-find-10m-by-just-reading-blockchain-6ae9d39fcd95 assert(msg.data.length == numwords * 32 + 4); _; } /* This creates an array with all balances */ mapping (address => uint256) public balances; mapping (address => mapping (address => uint256)) internal allowed; /* Initializes contract with initial supply tokens to the creator of the contract */ function VernamToken(uint256 _totalSupply_) public { name = "Vernam Token"; // Set the name for display purposes symbol = "VRN"; // Set the symbol for display purposes decimals = 18; // Amount of decimals for display purposes _totalSupply = _totalSupply_; //1 Billion Tokens with 18 Decimals balances[msg.sender] = _totalSupply_; } function transfer(address _to, uint256 _value) onlyPayloadSize(2) public returns (bool _success) { return _transfer(msg.sender, _to, _value); } function transferFrom(address _from, address _to, uint256 _value) public returns (bool _success) { require(_value <= allowed[_from][msg.sender]); // Check allowance _transfer(_from, _to, _value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); return true; } /* Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint256 _value) internal returns (bool _success) { require (_to != address(0x0)); // Prevent transfer to 0x0 address. require(_value >= 0); require (balances[_from] >= _value); // Check if the sender has enough require (balances[_to].add(_value) > balances[_to]); // Check for overflows uint256 previousBalances = balances[_from].add(balances[_to]); // Save this for an assertion in the future balances[_from] = balances[_from].sub(_value); // Subtract from the sender balances[_to] = balances[_to].add(_value); // Add the same to the recipient emit Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balances[_from] + balances[_to] == previousBalances); //add safeMath return true; } function increaseApproval(address _spender, uint256 _addedValue) onlyPayloadSize(2) public returns (bool _success) { require(allowed[msg.sender][_spender].add(_addedValue) <= balances[msg.sender]); allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval(address _spender, uint256 _subtractedValue) onlyPayloadSize(2) public returns (bool _success) { uint256 oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function approve(address _spender, uint256 _value) onlyPayloadSize(2) public returns (bool _success) { require(_value <= balances[msg.sender]); allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function totalSupply() public view returns (uint256) { return _totalSupply; } function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } function allowance(address _owner, address _spender) public view returns (uint256 _remaining) { return allowed[_owner][_spender]; } }
500 000 000 with 18 decimals
uint constant public TOKENS_HARD_CAP = 500000000000000000000000000;
5,729,796
[ 1, 12483, 20546, 20546, 598, 6549, 15105, 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, 202, 11890, 5381, 1071, 14275, 55, 67, 44, 8085, 67, 17296, 273, 1381, 12648, 12648, 2787, 9449, 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 ]
./full_match/11155111/0xaFE9d35157E0B54cB8A56e970635959Ee88d882D/sources/contracts/Ticketing.sol
Get ticket information
function getTicket(uint256 _ticketId) external view returns ( string memory, uint256, uint256, address, string memory, uint256, bool, bool ) { Ticket storage ticket = tickets[_ticketId]; return ( ticket.ticketType, ticket.validUntil, ticket.amount, ticket.owner, ticket.ipfsAddress, _ticketId, ticket.used, ticket.confirmTicketUse ); }
3,809,660
[ 1, 967, 9322, 1779, 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, 0 ]
[ 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, 0 ]
[ 1, 565, 445, 3181, 29378, 12, 11890, 5034, 389, 16282, 548, 13, 203, 3639, 3903, 203, 3639, 1476, 203, 3639, 1135, 261, 203, 5411, 533, 3778, 16, 203, 5411, 2254, 5034, 16, 203, 5411, 2254, 5034, 16, 203, 5411, 1758, 16, 203, 5411, 533, 3778, 16, 203, 5411, 2254, 5034, 16, 203, 5411, 1426, 16, 203, 5411, 1426, 203, 3639, 262, 203, 565, 288, 203, 3639, 22023, 2502, 9322, 273, 24475, 63, 67, 16282, 548, 15533, 203, 3639, 327, 261, 203, 5411, 9322, 18, 16282, 559, 16, 203, 5411, 9322, 18, 877, 9716, 16, 203, 5411, 9322, 18, 8949, 16, 203, 5411, 9322, 18, 8443, 16, 203, 5411, 9322, 18, 625, 2556, 1887, 16, 7010, 3639, 389, 16282, 548, 16, 7010, 3639, 9322, 18, 3668, 16, 7010, 3639, 9322, 18, 10927, 13614, 3727, 203, 565, 11272, 203, 97, 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 ]
// SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.4; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "../escrow/NFTEscrow.sol"; import "../interfaces/ICryptoPunks.sol"; /// @title CryptoPunks NFTVault helper contract /// @notice Allows compatibility between CryptoPunks and {NFTVault} /// @dev CryptoPunks IERC721 compatibility. /// Meant to only be used by {NFTVault}. /// This contract is NOT an ERC721 wrapper for punks and is not meant to implement the ERC721 interface fully, /// its only purpose is to serve as a proxy between {NFTVault} and CryptoPunks. /// The owner is {NFTVault} contract CryptoPunksHelper is NFTEscrow, OwnableUpgradeable { /// @param punksAddress Address of the CryptoPunks contract function initialize(address punksAddress) external initializer { __NFTEscrow_init(punksAddress); __Ownable_init(); } /// @notice Returns the owner of the punk at index `_idx` /// @dev If the owner of the punk is this contract we return the address of the {NFTVault} for compatibility /// @param _idx The punk index /// @return The owner of the punk if != `address(this)`, otherwise the the owner of this contract function ownerOf(uint256 _idx) external view returns (address) { address account = ICryptoPunks(nftAddress).punkIndexToAddress(_idx); return account == address(this) ? owner() : account; } /// @notice Function called by {NFTVault} to transfer punks. Can only be called by the owner /// @param _from The sender address /// @param _to The recipient address /// @param _idx The index of the punk to transfer function transferFrom( address _from, address _to, uint256 _idx ) external onlyOwner { _transferFrom(_from, _to, _idx); } /// @dev We aren't calling {onERC721Received} on the _to address because punks don't implement /// the {ERC721} interface, but we are including this function for compatibility with the {NFTVault} contract. /// Calling the {onERC721Received} function on the receiver contract could cause problems as we aren't sending an ERC721. /// @param _from The sender address /// @param _to The recipient address /// @param _idx The index of the punk to transfer function safeTransferFrom( address _from, address _to, uint256 _idx ) external onlyOwner { _transferFrom(_from, _to, _idx); } /// @dev Implementation of {transferFrom} and {safeTransferFrom}. We are using {NFTEscrow} for atomic transfers. /// See {NFTEscrow} for more info /// @param _from The sender address /// @param _to The recipient address /// @param _idx The index of the punk to transfer function _transferFrom( address _from, address _to, uint256 _idx ) internal { ICryptoPunks punks = ICryptoPunks(nftAddress); address account = punks.punkIndexToAddress(_idx); //if the owner is this address we don't need to go through {NFTEscrow} if (account != address(this)) { _executeTransfer(_from, _idx); } assert( punks.punkIndexToAddress(_idx) == address(this) //this should never be false" ); //If _to is the owner ({NFTVault}), we aren't sending the punk //since we'd have no way to get it back if (_to != owner()) punks.transferPunk(_to, _idx); } /// @dev Prevent the owner from renouncing ownership. Having no owner would render this contract unusable function renounceOwnership() public view override onlyOwner { revert("Cannot renounce ownership"); } /// @dev The {transferPunk} function is used as the escrow's payload. /// @param _idx The index of the punk that's going to be transferred using {NFTEscrow} function _encodeFlashEscrowPayload(uint256 _idx) internal view override returns (bytes memory) { return abi.encodeWithSignature( "transferPunk(address,uint256)", address(this), _idx ); } } // 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: GPL-3.0 pragma solidity ^0.8.4; import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; //inspired by https://github.com/thousandetherhomepage/ketherhomepage/blob/master/contracts/KetherNFT.sol /// @title FlashEscrow contract /// @notice This contract sends and receives non ERC721 NFTs /// @dev Deployed for each NFT, its address is calculated by {NFTEscrow} prior to it being deployed to allow atomic non ERC721 transfers contract FlashEscrow { /// @dev The contract selfdestructs in the constructor, its only purpose is to perform one call to the `target` address using `payload` as the payload /// @param target The call recipient /// @param payload The payload to use for the call constructor(address target, bytes memory payload) { (bool success, ) = target.call(payload); require(success, "FlashEscrow: call_failed"); selfdestruct(payable(target)); } } /// @title Escrow contract for non ERC721 NFTs /// @notice Handles atomic non ERC721 NFT transfers by using {FlashEscrow} /// @dev NFTEscrow allows an atomic, 2 step mechanism to transfer non ERC721 NFTs without requiring prior reservation. /// - Users send the NFT to a precomputed address (calculated using the owner's address as salt) that can be fetched by calling the `precompute` function /// - The child contract can then call the `_executeTransfer` function to deploy an instance of the {FlashEscrow} contract, deployed at the address calculated in the previous step /// This allows atomic transfers, as the address calculated by the `precompute` function is unique and changes depending by the `_owner` address and the NFT index (`_idx`). /// This is an alternative to the classic "reservation" method, which requires users to call 3 functions in a specifc order (making the process non atomic) abstract contract NFTEscrow is Initializable { /// @notice The address of the non ERC721 NFT supported by the child contract address public nftAddress; /// @dev Initializer function, see https://docs.openzeppelin.com/upgrades-plugins/1.x/writing-upgradeable /// @param _nftAddress See `nftAddress` function __NFTEscrow_init(address _nftAddress) internal initializer { nftAddress = _nftAddress; } /// @dev Computes the bytecode of the {FlashEscrow} instance to deploy /// @param _idx The index of the NFT that's going to be sent to the {FlashEscrow} instance /// @return The bytecode of the {FlashEscrow} instance relative to the NFT at index `_idx` function _encodeFlashEscrow(uint256 _idx) internal view returns (bytes memory) { return abi.encodePacked( type(FlashEscrow).creationCode, abi.encode(nftAddress, _encodeFlashEscrowPayload(_idx)) ); } /// @dev Virtual function, should return the `payload` to use in {FlashEscrow}'s constructor /// @param _idx The index of the NFT that's going to be sent to the {FlashEscrow} instance function _encodeFlashEscrowPayload(uint256 _idx) internal view virtual returns (bytes memory); /// @dev Deploys a {FlashEscrow} instance relative to owner `_owner` and index `_idx` /// @param _owner The owner of the NFT at index `_idx` /// @param _idx The index of the NFT owned by `_owner` function _executeTransfer(address _owner, uint256 _idx) internal { (bytes32 salt, ) = precompute(_owner, _idx); new FlashEscrow{salt: salt}( nftAddress, _encodeFlashEscrowPayload(_idx) ); } /// @notice This function returns the address where user `_owner` should send the `_idx` NFT to /// @dev `precompute` computes the salt and the address relative to NFT at index `_idx` owned by `_owner` /// @param _owner The owner of the NFT at index `_idx` /// @param _idx The index of the NFT owner by `_owner` /// @return salt The salt that's going to be used to deploy the {FlashEscrow} instance /// @return predictedAddress The address where the {FlashEscrow} instance relative to `_owner` and `_idx` will be deployed to function precompute(address _owner, uint256 _idx) public view returns (bytes32 salt, address predictedAddress) { require( _owner != address(this) && _owner != address(0), "NFTEscrow: invalid_owner" ); salt = sha256(abi.encodePacked(_owner)); bytes memory bytecode = _encodeFlashEscrow(_idx); //hash from which the contract address can be derived bytes32 hash = keccak256( abi.encodePacked( bytes1(0xff), address(this), salt, keccak256(bytecode) ) ); predictedAddress = address(uint160(uint256(hash))); return (salt, predictedAddress); } uint256[50] private __gap; } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.4; interface ICryptoPunks { function transferPunk(address _to, uint256 _punkIndex) external; function punkIndexToAddress(uint256 _punkIndex) external view returns (address); } // 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 (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 (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); } } } }
@notice Returns the owner of the punk at index `_idx` @dev If the owner of the punk is this contract we return the address of the {NFTVault} for compatibility @param _idx The punk index @return The owner of the punk if != `address(this)`, otherwise the the owner of this contract
function ownerOf(uint256 _idx) external view returns (address) { address account = ICryptoPunks(nftAddress).punkIndexToAddress(_idx); return account == address(this) ? owner() : account; }
11,878,094
[ 1, 1356, 326, 3410, 434, 326, 293, 1683, 622, 770, 1375, 67, 3465, 68, 225, 971, 326, 3410, 434, 326, 293, 1683, 353, 333, 6835, 732, 327, 326, 1758, 434, 326, 288, 50, 4464, 12003, 97, 364, 8926, 225, 389, 3465, 1021, 293, 1683, 770, 327, 1021, 3410, 434, 326, 293, 1683, 309, 480, 1375, 2867, 12, 2211, 13, 9191, 3541, 326, 326, 3410, 434, 333, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 3410, 951, 12, 11890, 5034, 389, 3465, 13, 3903, 1476, 1135, 261, 2867, 13, 288, 203, 3639, 1758, 2236, 273, 467, 18048, 52, 1683, 87, 12, 82, 1222, 1887, 2934, 84, 1683, 1016, 774, 1887, 24899, 3465, 1769, 203, 203, 3639, 327, 2236, 422, 1758, 12, 2211, 13, 692, 3410, 1435, 294, 2236, 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 ]
./full_match/3/0x78F624ea3337b8d28970c51048f63a545f95354C/sources/testcontract.sol
dogsperwalletInWholeDuration
uint public constant DOGS_WALLET_PRESALE_LIMIT = 10;
8,118,813
[ 1, 2896, 564, 457, 19177, 382, 2888, 790, 5326, 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, 1071, 5381, 5467, 16113, 67, 59, 1013, 15146, 67, 3670, 5233, 900, 67, 8283, 273, 1728, 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 ]
./full_match/43114/0x085A3fe57D71057a8DD1B673E4A794CFFc724c2c/sources/AVABIRD.sol
No timelock for these people TO DO, manually whitelist thisisFeeExempt[_presaleContract] = true;isTxLimitExempt[_presaleContract] = true;isDividendExempt[_presaleContract] = true; NICE!
constructor () Auth(msg.sender) { router = IDEXRouter(0xE54Ca86531e17Ef3616d22Ca28b0D458b6C89106); pair = IDEXFactory(router.factory()).createPair(WAVAX, address(this)); _allowances[address(this)][address(router)] = uint256(-1); distributor = new DividendDistributor(address(router)); isFeeExempt[msg.sender] = true; isTxLimitExempt[msg.sender] = true; isTxLimitExempt[DEAD] = true; isTimelockExempt[msg.sender] = true; isTimelockExempt[DEAD] = true; isTimelockExempt[address(this)] = true; isDividendExempt[pair] = true; isDividendExempt[address(this)] = true; isDividendExempt[DEAD] = true; autoLiquidityReceiver = DEAD; marketingFeeReceiver = 0x4222A3AF3338B5d077E3C94a97f21796b75e044B; _balances[msg.sender] = _totalSupply; emit Transfer(address(0), msg.sender, _totalSupply); }
4,587,496
[ 1, 2279, 1658, 292, 975, 364, 4259, 16951, 8493, 5467, 16, 10036, 10734, 333, 291, 14667, 424, 5744, 63, 67, 12202, 5349, 8924, 65, 273, 638, 31, 291, 4188, 3039, 424, 5744, 63, 67, 12202, 5349, 8924, 65, 273, 638, 31, 291, 7244, 26746, 424, 5744, 63, 67, 12202, 5349, 8924, 65, 273, 638, 31, 423, 11774, 5, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 3885, 1832, 3123, 12, 3576, 18, 15330, 13, 288, 203, 3639, 4633, 273, 1599, 2294, 8259, 12, 20, 17432, 6564, 23508, 5292, 25, 6938, 73, 4033, 41, 74, 5718, 2313, 72, 3787, 23508, 6030, 70, 20, 40, 7950, 28, 70, 26, 39, 6675, 22135, 1769, 203, 3639, 3082, 273, 1599, 2294, 1733, 12, 10717, 18, 6848, 1435, 2934, 2640, 4154, 12, 59, 5856, 2501, 16, 1758, 12, 2211, 10019, 203, 3639, 389, 5965, 6872, 63, 2867, 12, 2211, 13, 6362, 2867, 12, 10717, 25887, 273, 2254, 5034, 19236, 21, 1769, 203, 203, 3639, 1015, 19293, 273, 394, 21411, 26746, 1669, 19293, 12, 2867, 12, 10717, 10019, 203, 203, 3639, 353, 14667, 424, 5744, 63, 3576, 18, 15330, 65, 273, 638, 31, 203, 3639, 353, 4188, 3039, 424, 5744, 63, 3576, 18, 15330, 65, 273, 638, 31, 203, 3639, 353, 4188, 3039, 424, 5744, 63, 1639, 1880, 65, 273, 638, 31, 203, 203, 3639, 353, 10178, 292, 975, 424, 5744, 63, 3576, 18, 15330, 65, 273, 638, 31, 203, 3639, 353, 10178, 292, 975, 424, 5744, 63, 1639, 1880, 65, 273, 638, 31, 203, 3639, 353, 10178, 292, 975, 424, 5744, 63, 2867, 12, 2211, 25887, 273, 638, 31, 203, 203, 203, 203, 3639, 353, 7244, 26746, 424, 5744, 63, 6017, 65, 273, 638, 31, 203, 3639, 353, 7244, 26746, 424, 5744, 63, 2867, 12, 2211, 25887, 273, 638, 31, 203, 3639, 353, 7244, 26746, 424, 5744, 63, 1639, 1880, 65, 273, 638, 31, 203, 203, 3639, 3656, 48, 18988, 24237, 12952, 273, 2030, 2 ]
pragma solidity ^0.5.0; // It's important to avoid vulnerabilities due to numeric overflow bugs // OpenZeppelin's SafeMath library, when used correctly, protects agains such bugs // More info: https://www.nccgroup.trust/us/about-us/newsroom-and-events/blog/2018/november/smart-contract-insecurity-bad-arithmetic/ import "../core/Ownable.sol"; import "../../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol"; /************************************************** */ /* FlightSurety Smart Contract */ /************************************************** */ contract FlightSuretyApp is Ownable { using SafeMath for uint256; // Allow SafeMath functions to be called for all uint256 types (similar to "prototype" in Javascript) using SafeMath for uint8; // Allow SafeMath functions to be called for all uint256 types (similar to "prototype" in Javascript) /********************************************************************************************/ /* DATA VARIABLES */ /********************************************************************************************/ // Flight status codees uint8 private constant STATUS_CODE_UNKNOWN = 0; uint8 private constant STATUS_CODE_ON_TIME = 10; uint8 private constant STATUS_CODE_LATE_AIRLINE = 20; uint8 private constant STATUS_CODE_LATE_WEATHER = 30; uint8 private constant STATUS_CODE_LATE_TECHNICAL = 40; uint8 private constant STATUS_CODE_LATE_OTHER = 50; // FlightSuretyData contract FlightSuretyData flightSuretyData; //address private contractOwner; // Account used to deploy contract /*struct Flight { bool isRegistered; bytes32 code; uint8 statusCode; uint256 updatedTimestamp; address airline; bytes32 departure; bytes32 arrival; }*/ //mapping(bytes32 => Flight) private flights; /********************************************************************************************/ /* EVENT DEFINITIONS */ /********************************************************************************************/ event AirlineSubmittedFund (address airlineAdress, uint256 fund); event AirlineRegistration (uint8 state, uint256 airlinesRegistered); event MultipartyConsensusAirlineRegisterVote (address airlineEmitionVoteAddress, string airlineVotedName, uint256 airlineVotes); event FlightRegistered(bytes32 flightCode, address airline, uint8 status); event BoughtInsurance(address passenger, bytes32 flightCode, uint8 status); event PassengerWithdrawStatus(address passenger,bytes32 code, uint256 amount, uint8 status); /********************************************************************************************/ /* FUNCTION MODIFIERS */ /********************************************************************************************/ // Modifiers help avoid duplication of code. They are typically used to validate something // before a function is allowed to be executed. /** * @dev Modifier that requires the "operational" boolean variable to be "true" * This is used on all state changing functions to pause the contract in * the event there is an issue that needs to be fixed */ modifier requireIsOperational() { // Modify to call data contract's status require(true, "Contract is currently not operational"); _; // All modifiers require an "_" which indicates where the function body will be added } /** * @dev Modifier that requires enough fund to an airline to start operation in contract */ modifier airlinePaidEnoughFundToOperate() { uint256 _minFound = flightSuretyData.getMinSubmitionFund(); require(msg.value >= _minFound, "Paid amount not sufficient to register the airline"); _; } /** * @dev Modifier that requires enough fund to an airline to start operation in contract */ modifier checkAirlineFundValue() { _; uint256 _minFound = flightSuretyData.getMinSubmitionFund(); uint amountToReturn = msg.value - _minFound; msg.sender.transfer(amountToReturn); } /** * @dev Modifier that requires enough fund to an airline to start operation in contract */ modifier requireEnoughFundsInContract(address passenger, bytes32 flightCode) { (bytes32 code, uint256 amount, uint8 status) = flightSuretyData.fetchInsuranceInfoByPassengerAndCode(msg.sender, flightCode); require(address(this).balance >= amount.mul(15).div(10), "Contract funds not enough to withdraw the insurance"); _; } /********************************************************************************************/ /* CONSTRUCTOR */ /********************************************************************************************/ /** * @dev Contract constructor * */ constructor ( address flightSuretyDataContract ) public { flightSuretyData = FlightSuretyData(flightSuretyDataContract); } /********************************************************************************************/ /* UTILITY FUNCTIONS */ /********************************************************************************************/ function isOperational() public pure returns(bool) { return true; // Modify to call data contract's status } function getBalanceAppContract () onlyOwner() external view returns(uint256) { return address(this).balance; } function fetchDataContractConfiguration() onlyOwner() requireIsOperational() external returns(bool operational, uint8 minAirlinesNumberMutipartyConsensus, uint256 minSubmitionFund, uint256 registeredAirlines) { (operational, minAirlinesNumberMutipartyConsensus, minSubmitionFund, registeredAirlines) = flightSuretyData.fetchDataContractConfiguration(); return ( operational, minAirlinesNumberMutipartyConsensus, minSubmitionFund, registeredAirlines ); } /********************************************************************************************/ /* SMART CONTRACT FUNCTIONS */ /********************************************************************************************/ /** * @dev Add an airline to the registration queue * */ function registerAirline ( address airlineAddressToRegister, string calldata airlineName ) external requireIsOperational() { uint8 state; uint256 airlinesRegistered; if (flightSuretyData.getRegisteredAirlines() < flightSuretyData.getMinAirlinesNumberMutipartyConsensus()) { (state, airlinesRegistered) = flightSuretyData.registerAirline(msg.sender, airlineAddressToRegister, airlineName, false); } else { (state, airlinesRegistered) = flightSuretyData.registerAirline(msg.sender, airlineAddressToRegister, airlineName, true); } emit AirlineRegistration(state, airlinesRegistered); } /** * @dev Add an airline to the registration queue * */ function submitFundAirline() requireIsOperational() airlinePaidEnoughFundToOperate() checkAirlineFundValue() external payable { flightSuretyData.updateFundFieldAirline(msg.sender); emit AirlineSubmittedFund(msg.sender, msg.value); } /** * @dev Vote to register a new airline for multiparty consensus * */ function multipartyConsensusVote ( address airlineAddressToBeRegister, bool vote ) external requireIsOperational() { // Fetch airline data by address (string memory _airlineName, uint8 _airlineState, uint256 _airlineVotes) = flightSuretyData.fetchAirlineByAddress(airlineAddressToBeRegister); // Check that the airline is in registration process state require(_airlineState == 0, "Airline not in process to be resgistered"); if (vote) { flightSuretyData.voteToRegisterAirline(msg.sender, airlineAddressToBeRegister); _airlineVotes = _airlineVotes.add(1); } // Emit the proper event emit MultipartyConsensusAirlineRegisterVote (msg.sender, _airlineName, _airlineVotes); } /** * @dev Register a future flight for insuring. * */ function registerFlight ( bytes32 code, uint256 updatedTimestamp, bytes32 departure, bytes32 arrival ) external requireIsOperational() { (bytes32 flightCode, address airline, uint8 status) = flightSuretyData.registerFlight(code, updatedTimestamp, msg.sender, departure, arrival); emit FlightRegistered(flightCode, airline, status); } /** * @dev Fetch flights codes. * */ function fetchFlightsCodes() external view requireIsOperational() returns(bytes32[] memory) { return flightSuretyData.fetchRegisteredFlightsCodes(); } /** * @dev Fetch flight info by code. * */ function fetchFlightInfoByCode ( bytes32 flightCode ) external view requireIsOperational() returns(bytes32, string memory, bytes32, bytes32) { (bytes32 code, string memory airlineName, bytes32 departure, bytes32 arrival) = flightSuretyData.fetchRegisteredFlightInfoByCode(flightCode); return ( code, airlineName, departure, arrival ); } /** * @dev Register a future flight for insuring. * */ function buyInsurance ( bytes32 flightCode ) external payable requireIsOperational() { (address returnPassenger, bytes32 returnFlightCode, uint8 returnState) = flightSuretyData.buyInsurance(msg.sender, msg.value, flightCode); emit BoughtInsurance(returnPassenger, returnFlightCode, returnState); } /** * @dev Fetch insurances codes for a passenger. * */ function fetchActiveInsurancesKeysForPassenger() external view requireIsOperational() returns(bytes32[] memory) { return flightSuretyData.fetchActiveInsurancesKeysByPassenger(msg.sender); } /** * @dev Fetch insurances info for a passenger and code. * */ function fetchInsurancesInfoForPassengerAndCode ( bytes32 flightCode ) external view requireIsOperational() returns(bytes32, uint256, uint8) { (bytes32 code, uint256 amount, uint8 status) = flightSuretyData.fetchInsuranceInfoByPassengerAndCode(msg.sender, flightCode); return ( code, amount, status ); } /** * @dev Called after oracle has updated flight status * */ function processFlightStatus ( uint8 index, address airline, bytes32 flight, uint256 timestamp, uint8 statusCode ) internal requireIsOperational() { bytes32 key = keccak256(abi.encodePacked(index, airline, flight, timestamp)); // Close the response in order to handel only once oracleResponses[key].isOpen = false; if (statusCode == STATUS_CODE_UNKNOWN) { // Reopen again the request for response oracleResponses[key].isOpen = true; } else { // Fetch passengers array address[] memory passengersList = flightSuretyData.fetchRegisteredPassengers(); for (uint256 paxIndex = 0; paxIndex < passengersList.length; paxIndex = paxIndex.add(1)) { flightSuretyData.creditInsurees (passengersList[paxIndex], flight, statusCode); } } } /** * @dev Passenger can withdraw any funds owed to them as a result of receiving credit for insurance payout * */ function passengerWithdraw ( bytes32 flightCode ) public payable requireIsOperational() { bytes32 code; uint256 amount; uint8 status; // Fetch amount paid for the insurance to calculate the withdraw payment amount (code, amount, status) = flightSuretyData.fetchInsuranceInfoByPassengerAndCode(msg.sender, flightCode); // Check if contract balance has enough ethers require(address(this).balance >= amount.mul(15).div(10), "Contract funds not enough to withdraw the insurance"); // Update the insurance status before to transfer withdraw to passenger bool returnUpdateStatus = flightSuretyData.paymentWithdraw(msg.sender, flightCode); if(returnUpdateStatus) { msg.sender.transfer(amount.mul(15).div(10)); } // Fetch current status for insurance after withdraw (code, amount, status) = flightSuretyData.fetchInsuranceInfoByPassengerAndCode(msg.sender, flightCode); // Emit proper event emit PassengerWithdrawStatus(msg.sender, code, amount.mul(15).div(10), status); } // Generate a request for oracles to fetch flight information function fetchFlightStatus ( address airline, bytes32 flight, uint256 timestamp ) external { uint8 index = getRandomIndex(msg.sender); // Generate a unique key for storing the request bytes32 key = keccak256(abi.encodePacked(index, airline, flight, timestamp)); oracleResponses[key] = ResponseInfo({ requester: msg.sender, isOpen: true }); emit OracleRequest(index, airline, flight, timestamp); } // region ORACLE MANAGEMENT // Incremented to add pseudo-randomness at various points uint8 private nonce = 0; // Fee to be paid when registering oracle uint256 public constant REGISTRATION_FEE = 1 ether; // Number of oracles that must respond for valid status uint256 private constant MIN_RESPONSES = 2; struct Oracle { bool isRegistered; uint8[3] indexes; } // Track all registered oracles mapping(address => Oracle) private oracles; // Model for responses from oracles struct ResponseInfo { address requester; // Account that requested status bool isOpen; // If open, oracle responses are accepted mapping(uint8 => address[]) responses; // Mapping key is the status code reported // This lets us group responses and identify // the response that majority of the oracles } // Track all oracle responses // Key = hash(index, flight, timestamp) mapping(bytes32 => ResponseInfo) private oracleResponses; // Event fired each time an oracle submits a response event FlightStatusInfo(address airline, bytes32 flight, uint256 timestamp, uint8 status); event OracleReport(address airline, bytes32 flight, uint256 timestamp, uint8 status); // Event fired when flight status request is submitted // Oracles track this and if they have a matching index // they fetch data and submit a response event OracleRequest(uint8 index, address airline, bytes32 flight, uint256 timestamp); // Register an oracle with the contract function registerOracle ( ) external payable { // Require registration fee require(msg.value >= REGISTRATION_FEE, "Registration fee is required"); uint8[3] memory indexes = generateIndexes(msg.sender); oracles[msg.sender] = Oracle({ isRegistered: true, indexes: indexes }); } function getMyIndexes ( ) view external returns(uint8[3] memory) { require(oracles[msg.sender].isRegistered, "Not registered as an oracle"); return oracles[msg.sender].indexes; } // Called by oracle when a response is available to an outstanding request // For the response to be accepted, there must be a pending request that is open // and matches one of the three Indexes randomly assigned to the oracle at the // time of registration (i.e. uninvited oracles are not welcome) function submitOracleResponse ( uint8 index, address airline, bytes32 flight, uint256 timestamp, uint8 statusCode ) external { require((oracles[msg.sender].indexes[0] == index) || (oracles[msg.sender].indexes[1] == index) || (oracles[msg.sender].indexes[2] == index), "Index does not match oracle request"); bytes32 key = keccak256(abi.encodePacked(index, airline, flight, timestamp)); require(oracleResponses[key].isOpen, "Flight or timestamp do not match oracle request OR reponse in processing"); oracleResponses[key].responses[statusCode].push(msg.sender); // Information isn't considered verified until at least MIN_RESPONSES // oracles respond with the *** same *** information emit OracleReport(airline, flight, timestamp, statusCode); if (oracleResponses[key].responses[statusCode].length >= MIN_RESPONSES) { emit FlightStatusInfo(airline, flight, timestamp, statusCode); // Handle flight status as appropriate processFlightStatus(index, airline, flight, timestamp, statusCode); } } function getFlightKey ( address airline, string memory flight, uint256 timestamp ) pure internal returns(bytes32) { return keccak256(abi.encodePacked(airline, flight, timestamp)); } // Returns array of three non-duplicating integers from 0-9 function generateIndexes ( address account ) internal returns(uint8[3] memory) { uint8[3] memory indexes; indexes[0] = getRandomIndex(account); indexes[1] = indexes[0]; while(indexes[1] == indexes[0]) { indexes[1] = getRandomIndex(account); } indexes[2] = indexes[1]; while((indexes[2] == indexes[0]) || (indexes[2] == indexes[1])) { indexes[2] = getRandomIndex(account); } return indexes; } // Returns array of three non-duplicating integers from 0-9 function getRandomIndex ( address account ) internal returns (uint8) { uint8 maxValue = 10; // Pseudo random number...the incrementing nonce adds variation uint8 random = uint8(uint256(keccak256(abi.encodePacked(blockhash(block.number - nonce++), account))) % maxValue); if (nonce > 250) { nonce = 0; // Can only fetch blockhashes for last 256 blocks so we adapt } return random; } // endregion } // ABI FlightSuretyData contract contract FlightSuretyData { function registerAirline (address, address, string calldata, bool) external returns (uint8, uint256); function fetchDataContractConfiguration () external returns (bool, uint8, uint256, uint256); function isOperational () public view returns(bool); function getMinAirlinesNumberMutipartyConsensus () external view returns (uint8); function getMinSubmitionFund () external view returns (uint256); function getRegisteredAirlines () external view returns (uint256); function updateFundFieldAirline (address) external; function fetchAirlineByAddress (address airlineAddress) external view returns (string memory, uint8, uint256); function voteToRegisterAirline (address airlineAddressOrigin, address airlineAddressToBeVoted) external; function registerFlight (bytes32 code, uint256 updatedTimestamp, address airline, bytes32, bytes32) external returns (bytes32, address, uint8); function buyInsurance (address passenger, uint256 amountPaid, bytes32 flightCode) external payable returns (address, bytes32, uint8); function fetchRegisteredFlightsCodes () external view returns(bytes32[] memory); function fetchRegisteredFlightInfoByCode (bytes32 flightCode) external view returns (bytes32, string memory, bytes32, bytes32); function fetchActiveInsurancesKeysByPassenger (address passenger) external view returns(bytes32[] memory); function fetchRegisteredPassengers () external view returns(address[] memory); function fetchInsuranceInfoByPassengerAndCode (address passenger, bytes32 flightCode) external view returns(bytes32, uint256, uint8); function creditInsurees (address passenger, bytes32 flightCodeInsurance, uint8 flightStatus) external; function paymentWithdraw (address passenger, bytes32 flightCodeInsuranceCode) external returns(bool); }
* @dev Fetch flights codes./
{ return flightSuretyData.fetchRegisteredFlightsCodes(); }
1,806,614
[ 1, 5005, 1183, 10730, 6198, 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, 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, 288, 203, 3639, 327, 25187, 55, 594, 4098, 751, 18, 5754, 10868, 2340, 10730, 6295, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2021-04-05 */ // File: @openzeppelin/contracts/utils/Context.sol 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; } } // File: @openzeppelin/contracts/access/Ownable.sol pragma solidity >=0.6.0 <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 () 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; } } // File: @openzeppelin/contracts/math/SafeMath.sol 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; } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol 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); } // File: @openzeppelin/contracts/utils/Address.sol 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); } } } } // File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol pragma solidity >=0.6.0 <0.8.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using 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"); } } } // File: contracts/Ignition.sol pragma solidity 0.6.11; pragma experimental ABIEncoderV2; struct Whitelist { address wallet; uint256 amount; uint256 rewardedAmount; uint256 tier; bool whitelist; bool redeemed; } struct Tier { uint256 paidAmount; uint256 maxPayableAmount; } contract Ignition is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; mapping(address => Whitelist) public whitelist; mapping(uint256 => Tier) public tiers; IERC20 private _token; IERC20 private _paidToken; bool public isFinalized; uint256 public soldAmount; uint256 public totalRaise; constructor() public { // Tiers tiers[1] = Tier(0, 48943074310269700); tiers[2] = Tier(0, 97886148620539400); tiers[3] = Tier(0, 146829222930809000); } /** * Crowdsale Token */ function setTokenAddress(IERC20 token) external onlyOwner returns (bool) { _token = token; return true; } /** * Crowdsale Token */ function setPAIDTokenAddress(IERC20 token) external onlyOwner returns (bool) { _paidToken = token; return true; } /** * Add Whitelist * * @param {address[]} * @return {bool} */ function addWhitelist(address[] memory addresses, uint256 tier) external onlyOwner returns (bool) { uint256 addressesLength = addresses.length; for (uint256 i = 0; i < addressesLength; i++) { address address_ = addresses[i]; Whitelist memory whitelist_ = Whitelist(address_, 0, 0, tier, true, false); whitelist[address_] = whitelist_; } return true; } /** * Get Contract Address * * Crowdsale token * @return {address} address */ function getContractAddress() public view returns (address) { return address(this); } /** * Get Total Token * * @return {uint256} totalToken */ function getTotalToken() public view returns (uint256) { return _token.balanceOf(getContractAddress()); } /** * Get Start Time * * @return {uint256} timestamp */ function getStartTime() public pure returns (uint256) { return 1617623940; // DEEPER TIMESTAMP DAO Maker } /** * Is Sale Start */ function isStart() public view returns (bool) { uint256 startTime = getStartTime(); uint256 timestamp = block.timestamp; return timestamp > startTime; } function muldiv(uint256 x, uint256 yPercentage) internal pure returns (uint256 c) { return x.mul(yPercentage).div(10e10); } /** * Get Rate * * 1 Ether = ? Token * Example: 1 Ether = 30 Token * @return {uint256} rate */ function getRate() public view returns (uint256) { return 170265833300000000000000; } /** * Calculate Token */ function calculateAmount(uint256 amount) public view returns (uint256) { uint256 rate = getRate(); uint256 oneEther = 1 ether; uint256 rate_30perct = rate * 3 / 10; uint256 etherMul = muldiv(amount, rate_30perct).div(10e6); return etherMul; } /** * Finalize to sale * * @return {uint256} timestamp */ function finalize() external onlyOwner returns (bool) { isFinalized = true; return isFinalized; } /** * Redeem Rewarded Tokens */ function redeemTokens() external returns (bool) { require(whitelist[_msgSender()].whitelist, "Sender isn't in whitelist"); Whitelist memory whitelistWallet = whitelist[_msgSender()]; require(isFinalized, "Sale isn't finalized yet"); require(!whitelistWallet.redeemed, "Redeemed before"); require(whitelistWallet.rewardedAmount > 0, "No token"); whitelist[_msgSender()].redeemed = true; _token.safeTransfer( whitelistWallet.wallet, whitelistWallet.rewardedAmount ); } /** * Get whitelist wallet */ function getWhitelist(address _address) public view returns ( address, uint256, uint256, bool, bool, uint256 ) { if (whitelist[_address].whitelist) { Whitelist memory whitelistWallet = whitelist[_address]; return ( whitelistWallet.wallet, whitelistWallet.amount, whitelistWallet.rewardedAmount, whitelistWallet.redeemed, true, whitelistWallet.tier ); } return (address(0), 0, 0, false, false, 0); } /** * PAID Token Control */ function controlPAIDTokens() public view returns (bool) { address sender = _msgSender(); uint256 tier = whitelist[sender].tier; return _paidToken.balanceOf(sender) >= tiers[tier].paidAmount; } /** * Revert receive ether without buyTokens */ fallback() external { revert(); } function withdraw() external onlyOwner { // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = _msgSender().call{value: address(this).balance}(""); require( success, "Address: unable to send value, recipient may have reverted" ); } /** * buyTokens */ function buyTokens() external payable { address sender = _msgSender(); uint256 value = msg.value; require(isStart(), "Sale isn't started yet"); require(!isFinalized, "Sale is finished"); require(whitelist[sender].whitelist, "You're not in whitelist"); uint256 tier = whitelist[sender].tier; require( value <= tiers[tier].maxPayableAmount, "You can't send ether more than max payable amount" ); // Require removed because is not being use on DEEPER pools //require(controlPAIDTokens(), "You dont have enough paid token"); uint256 totalToken = getTotalToken(); uint256 rewardedAmount = calculateAmount(value); require( soldAmount.add(rewardedAmount) <= totalToken, "Insufficient token" ); whitelist[sender].amount = value; whitelist[sender].rewardedAmount = rewardedAmount; soldAmount = soldAmount.add(rewardedAmount); totalRaise = totalRaise.add(value); } }
* Finalize to sale @return {uint256} timestamp/
function finalize() external onlyOwner returns (bool) { isFinalized = true; return isFinalized; }
2,027,996
[ 1, 7951, 554, 358, 272, 5349, 327, 288, 11890, 5034, 97, 2858, 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, 445, 12409, 1435, 3903, 1338, 5541, 1135, 261, 6430, 13, 288, 203, 3639, 29200, 1235, 273, 638, 31, 203, 3639, 327, 29200, 1235, 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, -100 ]
/* * PAT Token Smart Contract. Copyright © 2017 by ABDK Consulting. * Author: Mikhail Vladimirov <[email protected]> */ pragma solidity ^0.4.16; import "./AbstractToken.sol"; /** * PAT Token Smart Contract. */ contract PATToken is AbstractToken { uint256 constant internal TOKENS_COUNT = 42000000000e18; /** * Create PAT Token smart contract with given central bank address. * * @param _centralBank central bank address */ function PATToken (address _centralBank) AbstractToken () { accounts [_centralBank] = TOKENS_COUNT; // Limit emission to 42G } /** * Get total number of tokens in circulation. * * @return total number of tokens in circulation */ function totalSupply () constant returns (uint256 supply) { return TOKENS_COUNT; } /** * Get name of this token. * * @return name of this token */ function name () public pure returns (string) { return "Pangea Arbitration Token"; } /** * Get symbol of this token. * * @return symbol of this token */ function symbol () public pure returns (string) { return "PAT"; } /** * Get number of decimals for this token. * * @return number of decimals for this token */ function decimals () public pure returns (uint8) { return 18; } }
Limit emission to 42G
accounts [_centralBank] = TOKENS_COUNT;
5,468,173
[ 1, 3039, 801, 19710, 358, 14856, 43, 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, 9484, 306, 67, 71, 12839, 16040, 65, 273, 14275, 55, 67, 7240, 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 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.7; import "../lendingpool/DataTypes.sol"; import "../credit/CreditSystem.sol"; import "./KyokoMath.sol"; import "./PercentageMath.sol"; import "./ReserveLogic.sol"; import "./GenericLogic.sol"; import "@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol"; /** * @title ReserveLogic library * @notice Implements functions to validate the different actions of the protocol */ library ValidationLogic { using ReserveLogic for DataTypes.ReserveData; using SafeMathUpgradeable for uint256; using KyokoMath for uint256; using PercentageMath for uint256; uint256 public constant REBALANCE_UP_LIQUIDITY_RATE_THRESHOLD = 4000; uint256 public constant REBALANCE_UP_USAGE_RATIO_THRESHOLD = 0.95 * 1e27; //usage ratio of 95% /** * @dev Validates a deposit action * @param reserve The reserve object on which the user is depositing * @param amount The amount to be deposited */ function validateDeposit(DataTypes.ReserveData storage reserve, uint256 amount) external view { bool isActive = reserve.getActive(); require(amount != 0, "VL_INVALID_AMOUNT"); require(isActive, "VL_NO_ACTIVE_RESERVE"); } /** * @dev Validates a withdraw action * @param reserveAddress The address of the reserve * @param amount The amount to be withdrawn * @param userBalance The balance of the user * @param reservesData The reserves state */ function validateWithdraw( address reserveAddress, uint256 amount, uint256 userBalance, mapping(address => DataTypes.ReserveData) storage reservesData ) external view { require(amount != 0, "VL_INVALID_AMOUNT"); require(amount <= userBalance, "VL_NOT_ENOUGH_AVAILABLE_USER_BALANCE"); bool isActive = reservesData[reserveAddress].getActive(); require(isActive, "VL_NO_ACTIVE_RESERVE"); } struct ValidateBorrowLocalVars { uint256 userBorrowBalance; uint256 availableLiquidity; bool isActive; } /** * @dev Validates a borrow action * @param availableBorrowsInWEI available borrows in WEI * @param reserve The reserve state from which the user is borrowing * @param amount The amount to be borrowed */ function validateBorrow( uint256 availableBorrowsInWEI, DataTypes.ReserveData storage reserve, uint256 amount ) external view { ValidateBorrowLocalVars memory vars; require(availableBorrowsInWEI > 0, "available credit line not enough"); uint256 decimals_ = 1 ether; uint256 borrowsAmountInWEI = amount.div(10**reserve.decimals).mul(uint256(decimals_)); require(borrowsAmountInWEI <= availableBorrowsInWEI, "borrows exceed credit line"); vars.isActive = reserve.getActive(); require(vars.isActive, "VL_NO_ACTIVE_RESERVE"); require(amount > 0, "VL_INVALID_AMOUNT"); } /** * @dev Validates a repay action * @param reserve The reserve state from which the user is repaying * @param amountSent The amount sent for the repayment. Can be an actual value or type(uint256).min * @param onBehalfOf The address of the user msg.sender is repaying for * @param variableDebt The borrow balance of the user */ function validateRepay( DataTypes.ReserveData storage reserve, uint256 amountSent, address onBehalfOf, uint256 variableDebt ) external view { bool isActive = reserve.getActive(); require(isActive, "VL_NO_ACTIVE_RESERVE"); require(amountSent > 0, "VL_INVALID_AMOUNT"); require(variableDebt > 0, "VL_NO_DEBT_OF_SELECTED_TYPE"); require( amountSent != type(uint256).max || msg.sender == onBehalfOf, "VL_NO_EXPLICIT_AMOUNT_TO_REPAY_ON_BEHALF" ); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.7; import "../lendingpool/DataTypes.sol"; import "../interfaces/IVariableDebtToken.sol"; import "../interfaces/IReserveInterestRateStrategy.sol"; import "./MathUtils.sol"; import "./KyokoMath.sol"; import "./PercentageMath.sol"; import "../interfaces/IKToken.sol"; import "@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol"; /** * @title ReserveLogic library * @notice Implements the logic to update the reserves state */ library ReserveLogic { using SafeMathUpgradeable for uint256; using KyokoMath for uint256; using PercentageMath for uint256; /** * @dev Emitted when the state of a reserve is updated * @param asset The address of the underlying asset of the reserve * @param liquidityRate The new liquidity rate * @param variableBorrowRate The new variable borrow rate * @param liquidityIndex The new liquidity index * @param variableBorrowIndex The new variable borrow index **/ event ReserveDataUpdated( address indexed asset, uint256 liquidityRate, uint256 variableBorrowRate, uint256 liquidityIndex, uint256 variableBorrowIndex ); uint256 constant MAX_VALID_RESERVE_FACTOR = 65535; using ReserveLogic for DataTypes.ReserveData; /** * @dev Initializes a reserve * @param reserve The reserve object * @param kTokenAddress The address of the overlying ktoken contract * @param variableDebtTokenAddress The address of the variable debt token * @param interestRateStrategyAddress The address of the interest rate strategy contract **/ function init( DataTypes.ReserveData storage reserve, address kTokenAddress, address variableDebtTokenAddress, address interestRateStrategyAddress ) external { require(reserve.kTokenAddress == address(0), "the reserve already initialized"); reserve.isActive = true; reserve.liquidityIndex = uint128(KyokoMath.ray()); reserve.variableBorrowIndex = uint128(KyokoMath.ray()); reserve.kTokenAddress = kTokenAddress; reserve.variableDebtTokenAddress = variableDebtTokenAddress; reserve.interestRateStrategyAddress = interestRateStrategyAddress; } /** * @dev Updates the liquidity cumulative index and the variable borrow index. * @param reserve the reserve object **/ function updateState(DataTypes.ReserveData storage reserve) internal { uint256 scaledVariableDebt = IVariableDebtToken(reserve.variableDebtTokenAddress).scaledTotalSupply(); uint256 previousVariableBorrowIndex = reserve.variableBorrowIndex; uint256 previousLiquidityIndex = reserve.liquidityIndex; uint40 lastUpdatedTimestamp = reserve.lastUpdateTimestamp; (uint256 newLiquidityIndex, uint256 newVariableBorrowIndex) = _updateIndexes( reserve, scaledVariableDebt, previousLiquidityIndex, previousVariableBorrowIndex, lastUpdatedTimestamp ); _mintToTreasury( reserve, scaledVariableDebt, previousVariableBorrowIndex, newLiquidityIndex, newVariableBorrowIndex ); } /** * @dev Updates the reserve indexes and the timestamp of the update * @param reserve The reserve reserve to be updated * @param scaledVariableDebt The scaled variable debt * @param liquidityIndex The last stored liquidity index * @param variableBorrowIndex The last stored variable borrow index * @param timestamp The last operate time of reserve **/ function _updateIndexes( DataTypes.ReserveData storage reserve, uint256 scaledVariableDebt, uint256 liquidityIndex, uint256 variableBorrowIndex, uint40 timestamp ) internal returns (uint256, uint256) { uint256 currentLiquidityRate = reserve.currentLiquidityRate; uint256 newLiquidityIndex = liquidityIndex; uint256 newVariableBorrowIndex = variableBorrowIndex; //only cumulating if there is any income being produced if (currentLiquidityRate > 0) { // 1 + ratePerSecond * (delta_t / seconds in a year) uint256 cumulatedLiquidityInterest = MathUtils.calculateLinearInterest(currentLiquidityRate, timestamp); newLiquidityIndex = cumulatedLiquidityInterest.rayMul(liquidityIndex); require(newLiquidityIndex <= type(uint128).max, "RL_LIQUIDITY_INDEX_OVERFLOW"); reserve.liquidityIndex = uint128(newLiquidityIndex); //we need to ensure that there is actual variable debt before accumulating if (scaledVariableDebt != 0) { uint256 cumulatedVariableBorrowInterest = MathUtils.calculateCompoundedInterest(reserve.currentVariableBorrowRate, timestamp); newVariableBorrowIndex = cumulatedVariableBorrowInterest.rayMul(variableBorrowIndex); require( newVariableBorrowIndex <= type(uint128).max, "RL_VARIABLE_BORROW_INDEX_OVERFLOW" ); reserve.variableBorrowIndex = uint128(newVariableBorrowIndex); } } //solium-disable-next-line reserve.lastUpdateTimestamp = uint40(block.timestamp); return (newLiquidityIndex, newVariableBorrowIndex); } struct MintToTreasuryLocalVars { uint256 currentVariableDebt; uint256 previousVariableDebt; uint256 totalDebtAccrued; uint256 amountToMint; uint16 reserveFactor; uint40 stableSupplyUpdatedTimestamp; } /** * @dev Mints part of the repaid interest to the reserve treasury as a function of the reserveFactor for the * specific asset. * @param reserve The reserve reserve to be updated * @param scaledVariableDebt The current scaled total variable debt * @param previousVariableBorrowIndex The variable borrow index before the last accumulation of the interest * @param newLiquidityIndex The new liquidity index * @param newVariableBorrowIndex The variable borrow index after the last accumulation of the interest **/ function _mintToTreasury( DataTypes.ReserveData storage reserve, uint256 scaledVariableDebt, uint256 previousVariableBorrowIndex, uint256 newLiquidityIndex, uint256 newVariableBorrowIndex ) internal { MintToTreasuryLocalVars memory vars; vars.reserveFactor = getReserveFactor(reserve); if (vars.reserveFactor == 0) { return; } //calculate the last principal variable debt vars.previousVariableDebt = scaledVariableDebt.rayMul(previousVariableBorrowIndex); //calculate the new total supply after accumulation of the index vars.currentVariableDebt = scaledVariableDebt.rayMul(newVariableBorrowIndex); //debt accrued is the sum of the current debt minus the sum of the debt at the last update vars.totalDebtAccrued = vars .currentVariableDebt .sub(vars.previousVariableDebt); vars.amountToMint = vars.totalDebtAccrued.percentMul(vars.reserveFactor); if (vars.amountToMint != 0) { IKToken(reserve.kTokenAddress).mintToTreasury(vars.amountToMint, newLiquidityIndex); } } struct UpdateInterestRatesLocalVars { uint256 availableLiquidity; uint256 newLiquidityRate; uint256 newVariableRate; uint256 totalVariableDebt; } /** * @dev Updates the reserve current stable borrow rate, the current variable borrow rate and the current liquidity rate * @param reserve The address of the reserve to be updated * @param liquidityAdded The amount of liquidity added to the protocol (deposit or repay) in the previous action * @param liquidityTaken The amount of liquidity taken from the protocol (redeem or borrow) **/ function updateInterestRates( DataTypes.ReserveData storage reserve, address reserveAddress, address kTokenAddress, uint256 liquidityAdded, uint256 liquidityTaken ) internal { UpdateInterestRatesLocalVars memory vars; //calculates the total variable debt locally using the scaled total supply instead //of totalSupply(), as it's noticeably cheaper. Also, the index has been //updated by the previous updateState() call vars.totalVariableDebt = IVariableDebtToken(reserve.variableDebtTokenAddress) .scaledTotalSupply() .rayMul(reserve.variableBorrowIndex); ( vars.newLiquidityRate, vars.newVariableRate ) = IReserveInterestRateStrategy(reserve.interestRateStrategyAddress).calculateInterestRates( reserveAddress, kTokenAddress, liquidityAdded, liquidityTaken, vars.totalVariableDebt, getReserveFactor(reserve) ); require(vars.newLiquidityRate <= type(uint128).max, "RL_LIQUIDITY_RATE_OVERFLOW"); require(vars.newVariableRate <= type(uint128).max, "RL_VARIABLE_BORROW_RATE_OVERFLOW"); reserve.currentLiquidityRate = uint128(vars.newLiquidityRate); reserve.currentVariableBorrowRate = uint128(vars.newVariableRate); emit ReserveDataUpdated( reserveAddress, vars.newLiquidityRate, vars.newVariableRate, reserve.liquidityIndex, reserve.variableBorrowIndex ); } /** * @dev Returns the ongoing normalized variable debt for the reserve * A value of 1e27 means there is no debt. As time passes, the income is accrued * A value of 2*1e27 means that for each unit of debt, one unit worth of interest has been accumulated * @param reserve The reserve object * @return The normalized variable debt. expressed in ray **/ function getNormalizedDebt(DataTypes.ReserveData storage reserve) internal view returns (uint256) { uint40 timestamp = reserve.lastUpdateTimestamp; //solium-disable-next-line if (timestamp == uint40(block.timestamp)) { //if the index was updated in the same block, no need to perform any calculation return reserve.variableBorrowIndex; } uint256 cumulated = MathUtils.calculateCompoundedInterest(reserve.currentVariableBorrowRate, timestamp).rayMul( reserve.variableBorrowIndex ); return cumulated; } /** * @dev Returns the ongoing normalized income for the reserve * A value of 1e27 means there is no income. As time passes, the income is accrued * A value of 2*1e27 means for each unit of asset one unit of income has been accrued * @param reserve The reserve object * @return the normalized income. expressed in ray **/ function getNormalizedIncome(DataTypes.ReserveData storage reserve) internal view returns (uint256) { uint40 timestamp = reserve.lastUpdateTimestamp; //solium-disable-next-line if (timestamp == uint40(block.timestamp)) { //if the index was updated in the same block, no need to perform any calculation return reserve.liquidityIndex; } uint256 cumulated = MathUtils.calculateLinearInterest(reserve.currentLiquidityRate, timestamp).rayMul( reserve.liquidityIndex ); return cumulated; } /** * @dev Sets the active state of the reserve * @param self The reserve configuration * @param active The active state **/ function setActive(DataTypes.ReserveData storage self, bool active) internal { self.isActive = active; } /** * @dev Gets the active state of the reserve * @param self The reserve configuration * @return The active state **/ function getActive(DataTypes.ReserveData storage self) internal view returns (bool) { return self.isActive; } /** * @dev Sets the reserve factor of the reserve * @param self The reserve configuration * @param reserveFactor The reserve factor **/ function setReserveFactor(DataTypes.ReserveData storage self, uint16 reserveFactor) internal { require(reserveFactor <= MAX_VALID_RESERVE_FACTOR, "RC_INVALID_RESERVE_FACTOR"); self.factor = reserveFactor; } /** * @dev Gets the reserve factor of the reserve * @param self The reserve configuration * @return The reserve factor **/ function getReserveFactor(DataTypes.ReserveData storage self) internal view returns (uint16) { return self.factor; } /** * @dev Gets the decimals of the underlying asset of the reserve * @param self The reserve configuration * @return The decimals of the asset **/ function getDecimal(DataTypes.ReserveData storage self) internal view returns (uint8) { return self.decimals; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.7; /** * @title PercentageMath library * @notice Provides functions to perform percentage calculations * @dev Percentages are defined by default with 2 decimals of precision (100.00). The precision is indicated by PERCENTAGE_FACTOR * @dev Operations are rounded half up **/ library PercentageMath { uint256 constant PERCENTAGE_FACTOR = 1e4; //percentage plus two decimals uint256 constant HALF_PERCENT = PERCENTAGE_FACTOR / 2; /** * @dev Executes a percentage multiplication * @param value The value of which the percentage needs to be calculated * @param percentage The percentage of the value to be calculated * @return The percentage of value **/ function percentMul(uint256 value, uint256 percentage) internal pure returns (uint256) { if (value == 0 || percentage == 0) { return 0; } require( value <= (type(uint256).max - HALF_PERCENT) / percentage, "MATH_MULTIPLICATION_OVERFLOW" ); return (value * percentage + HALF_PERCENT) / PERCENTAGE_FACTOR; } /** * @dev Executes a percentage division * @param value The value of which the percentage needs to be calculated * @param percentage The percentage of the value to be calculated * @return The value divided the percentage **/ function percentDiv(uint256 value, uint256 percentage) internal pure returns (uint256) { require(percentage != 0, "MATH_DIVISION_BY_ZERO"); uint256 halfPercentage = percentage / 2; require( value <= (type(uint256).max - halfPercentage) / PERCENTAGE_FACTOR, "MATH_MULTIPLICATION_OVERFLOW" ); return (value * PERCENTAGE_FACTOR + halfPercentage) / percentage; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.7; import "@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol"; import "./KyokoMath.sol"; library MathUtils { using SafeMathUpgradeable for uint256; using KyokoMath for uint256; /// @dev Ignoring leap years uint256 internal constant SECONDS_PER_YEAR = 365 days; /** * @dev Function to calculate the interest accumulated using a linear interest rate formula * @param rate The interest rate, in ray * @param lastUpdateTimestamp The timestamp of the last update of the interest * @return The interest rate linearly accumulated during the timeDelta, in ray **/ function calculateLinearInterest(uint256 rate, uint40 lastUpdateTimestamp) internal view returns (uint256) { //solium-disable-next-line uint256 timeDifference = block.timestamp.sub(uint256(lastUpdateTimestamp)); return (rate.mul(timeDifference) / SECONDS_PER_YEAR).add(KyokoMath.ray()); } /** * @dev Function to calculate the interest using a compounded interest rate formula * To avoid expensive exponentiation, the calculation is performed using a binomial approximation: * * (1+x)^n = 1+n*x+[n/2*(n-1)]*x^2+[n/6*(n-1)*(n-2)*x^3... * * The approximation slightly underpays liquidity providers and undercharges borrowers, with the advantage of great gas cost reductions * The whitepaper contains reference to the approximation and a table showing the margin of error per different time periods * * @param rate The interest rate, in ray * @param lastUpdateTimestamp The timestamp of the last update of the interest * @return The interest rate compounded during the timeDelta, in ray **/ function calculateCompoundedInterest( uint256 rate, uint40 lastUpdateTimestamp, uint256 currentTimestamp ) internal pure returns (uint256) { //solium-disable-next-line uint256 exp = currentTimestamp.sub(uint256(lastUpdateTimestamp)); if (exp == 0) { return KyokoMath.ray(); } uint256 expMinusOne = exp - 1; uint256 expMinusTwo = exp > 2 ? exp - 2 : 0; uint256 ratePerSecond = rate / SECONDS_PER_YEAR; uint256 basePowerTwo = ratePerSecond.rayMul(ratePerSecond); uint256 basePowerThree = basePowerTwo.rayMul(ratePerSecond); uint256 secondTerm = exp.mul(expMinusOne).mul(basePowerTwo) / 2; uint256 thirdTerm = exp.mul(expMinusOne).mul(expMinusTwo).mul(basePowerThree) / 6; return KyokoMath.ray().add(ratePerSecond.mul(exp)).add(secondTerm).add(thirdTerm); } /** * @dev Calculates the compounded interest between the timestamp of the last update and the current block timestamp * @param rate The interest rate (in ray) * @param lastUpdateTimestamp The timestamp from which the interest accumulation needs to be calculated **/ function calculateCompoundedInterest(uint256 rate, uint40 lastUpdateTimestamp) internal view returns (uint256) { return calculateCompoundedInterest(rate, lastUpdateTimestamp, block.timestamp); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.7; library KyokoMath { uint256 internal constant WAD = 1e18; uint256 internal constant halfWAD = WAD / 2; uint256 internal constant RAY = 1e27; uint256 internal constant halfRAY = RAY / 2; uint256 internal constant WAD_RAY_RATIO = 1e9; /** * @return One ray, 1e27 **/ function ray() internal pure returns (uint256) { return RAY; } /** * @return One wad, 1e18 **/ function wad() internal pure returns (uint256) { return WAD; } /** * @return Half ray, 1e27/2 **/ function halfRay() internal pure returns (uint256) { return halfRAY; } /** * @return Half ray, 1e18/2 **/ function halfWad() internal pure returns (uint256) { return halfWAD; } /** * @dev Multiplies two wad, rounding half up to the nearest wad * @param a Wad * @param b Wad * @return The result of a*b, in wad **/ function wadMul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0 || b == 0) { return 0; } require(a <= (type(uint256).max - halfWAD) / b, "MATH_MULTIPLICATION_OVERFLOW"); return (a * b + halfWAD) / WAD; } /** * @dev Divides two wad, rounding half up to the nearest wad * @param a Wad * @param b Wad * @return The result of a/b, in wad **/ function wadDiv(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "MATH_DIVISION_BY_ZERO"); uint256 halfB = b / 2; require(a <= (type(uint256).max - halfB) / WAD, "MATH_MULTIPLICATION_OVERFLOW"); return (a * WAD + halfB) / b; } /** * @dev Multiplies two ray, rounding half up to the nearest ray * @param a Ray * @param b Ray * @return The result of a*b, in ray **/ function rayMul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0 || b == 0) { return 0; } require(a <= (type(uint256).max - halfRAY) / b, "MATH_MULTIPLICATION_OVERFLOW"); return (a * b + halfRAY) / RAY; } /** * @dev Divides two ray, rounding half up to the nearest ray * @param a Ray * @param b Ray * @return The result of a/b, in ray **/ function rayDiv(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "MATH_DIVISION_BY_ZERO"); uint256 halfB = b / 2; require(a <= (type(uint256).max - halfB) / RAY, "MATH_MULTIPLICATION_OVERFLOW"); return (a * RAY + halfB) / b; } /** * @dev Casts ray down to wad * @param a Ray * @return a casted to wad, rounded half up to the nearest wad **/ function rayToWad(uint256 a) internal pure returns (uint256) { uint256 halfRatio = WAD_RAY_RATIO / 2; uint256 result = halfRatio + a; require(result >= halfRatio, "MATH_ADDITION_OVERFLOW"); return result / WAD_RAY_RATIO; } /** * @dev Converts wad up to ray * @param a Wad * @return a converted in ray **/ function wadToRay(uint256 a) internal pure returns (uint256) { uint256 result = a * WAD_RAY_RATIO; require(result / WAD_RAY_RATIO == a, "MATH_MULTIPLICATION_OVERFLOW"); return result; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.7; import "../lendingpool/DataTypes.sol"; import "./KyokoMath.sol"; import "./PercentageMath.sol"; import "./ReserveLogic.sol"; import "@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; library GenericLogic { using ReserveLogic for DataTypes.ReserveData; using SafeMathUpgradeable for uint256; using KyokoMath for uint256; using PercentageMath for uint256; struct CalculateUserAccountDataVars { uint256 decimals; uint256 tokenUnit; uint256 compoundedBorrowBalance; uint256 totalDebtInWEI; uint256 i; address currentReserveAddress; } /** * @dev Calculates the user total Debt in WEI across the reserves. * @param user The address of the user * @param reservesData Data of all the reserves * @param reserves The list of the available reserves * @param reservesCount the count of reserves * @return The total debt of the user in WEI **/ function calculateUserAccountData( address user, mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reserves, uint256 reservesCount ) internal view returns (uint256) { CalculateUserAccountDataVars memory vars; for (vars.i = 0; vars.i < reservesCount; vars.i++) { vars.currentReserveAddress = reserves[vars.i]; DataTypes.ReserveData storage currentReserve = reservesData[vars.currentReserveAddress]; vars.decimals = currentReserve.getDecimal(); uint256 decimals_ = 1 ether; vars.tokenUnit = uint256(decimals_).div(10**vars.decimals); uint256 currentReserveBorrows = IERC20Upgradeable(currentReserve.variableDebtTokenAddress).balanceOf(user); if (currentReserveBorrows > 0) { vars.totalDebtInWEI = vars.totalDebtInWEI.add( uint256(1).mul(currentReserveBorrows).mul(vars.tokenUnit) ); } } return vars.totalDebtInWEI; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.7; library DataTypes { struct ReserveData { //this current state of the asset; bool isActive; //the liquidity index. Expressed in ray uint128 liquidityIndex; //variable borrow index. Expressed in ray uint128 variableBorrowIndex; //the current supply rate. Expressed in ray uint128 currentLiquidityRate; //the current variable borrow rate. Expressed in ray uint128 currentVariableBorrowRate; //the last update time of the reserve uint40 lastUpdateTimestamp; //address of the ktoken address kTokenAddress; //address of the debt token address variableDebtTokenAddress; //address of the interest rate strategy address interestRateStrategyAddress; // Reserve factor uint16 factor; uint8 decimals; //the id of the reserve.Represents the position in the list of the active reserves. uint8 id; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.7; import "./IScaledBalanceToken.sol"; import "./IInitializableDebtToken.sol"; interface IVariableDebtToken is IScaledBalanceToken, IInitializableDebtToken { /** * @dev Emitted after the mint action * @param from The address performing the mint * @param onBehalfOf The address of the user on which behalf minting has been performed * @param value The amount to be minted * @param index The last index of the reserve **/ event Mint(address indexed from, address indexed onBehalfOf, uint256 value, uint256 index); /** * @dev Mints debt token to the `onBehalfOf` address * @param user The address receiving the borrowed underlying, being the delegatee in case * of credit delegate, or same as `onBehalfOf` otherwise * @param onBehalfOf The address receiving the debt tokens * @param amount The amount of debt being minted * @param index The variable debt index of the reserve * @return `true` if the the previous balance of the user is 0 **/ function mint( address user, address onBehalfOf, uint256 amount, uint256 index ) external returns (bool); /** * @dev Emitted when variable debt is burnt * @param user The user which debt has been burned * @param amount The amount of debt being burned * @param index The index of the user **/ event Burn(address indexed user, uint256 amount, uint256 index); /** * @dev Burns user variable debt * @param user The user which debt is burnt * @param index The variable debt index of the reserve **/ function burn( address user, uint256 amount, uint256 index ) external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.7; interface IScaledBalanceToken { /** * @dev Returns the scaled balance of the user. The scaled balance is the sum of all the * updated stored balance divided by the reserve's liquidity index at the moment of the update * @param user The user whose balance is calculated * @return The scaled balance of the user **/ function scaledBalanceOf(address user) external view returns (uint256); /** * @dev Returns the scaled balance of the user and the scaled total supply. * @param user The address of the user * @return The scaled balance of the user * @return The scaled balance and the scaled total supply **/ function getScaledUserBalanceAndSupply(address user) external view returns (uint256, uint256); /** * @dev Returns the scaled total supply of the variable debt token. Represents sum(debt/index) * @return The scaled total supply **/ function scaledTotalSupply() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.8.7; interface IReserveInterestRateStrategy { function baseVariableBorrowRate() external view returns (uint256); function getMaxVariableBorrowRate() external view returns (uint256); function calculateInterestRates( uint256 availableLiquidity, uint256 totalVariableDebt, uint256 reserveFactor ) external view returns ( uint256, uint256 ); function calculateInterestRates( address reserve, address kToken, uint256 liquidityAdded, uint256 liquidityTaken, uint256 totalVariableDebt, uint256 reserveFactor ) external view returns ( uint256 liquidityRate, uint256 variableBorrowRate ); } // SPDX-License-Identifier: MIT pragma solidity 0.8.7; import "../lendingpool/DataTypes.sol"; interface ILendingPool { /** * @dev Emitted on deposit() * @param reserve The address of the underlying asset of the reserve * @param user The address initiating the deposit * @param onBehalfOf The beneficiary of the deposit, receiving the kTokens * @param amount The amount deposited **/ event Deposit( address indexed reserve, address user, address indexed onBehalfOf, uint256 amount ); /** * @dev Emitted on withdraw() * @param reserve The address of the underlyng asset being withdrawn * @param user The address initiating the withdrawal, owner of kTokens * @param to Address that will receive the underlying * @param amount The amount to be withdrawn **/ event Withdraw( address indexed reserve, address indexed user, address indexed to, uint256 amount ); /** * @dev Emitted on borrow() and flashLoan() when debt needs to be opened * @param reserve The address of the underlying asset being borrowed * @param user The address of the user initiating the borrow(), receiving the funds on borrow() * @param onBehalfOf The address that will be getting the debt * @param amount The amount borrowed out * @param borrowRate The numeric rate at which the user has borrowed **/ event Borrow( address indexed reserve, address user, address indexed onBehalfOf, uint256 amount, uint256 borrowRate ); /** * @dev Emitted on repay() * @param reserve The address of the underlying asset of the reserve * @param user The beneficiary of the repayment, getting his debt reduced * @param repayer The address of the user initiating the repay(), providing the funds * @param amount The amount repaid **/ event Repay( address indexed reserve, address indexed user, address indexed repayer, uint256 amount ); /** * @dev Emitted on initReserve() **/ event InitReserve( address asset, address kTokenAddress, address variableDebtAddress, address interestRateStrategyAddress, uint8 reserveDecimals, uint16 reserveFactor ); /** * @dev Emitted when the pause is triggered. */ event Paused(); /** * @dev Emitted when the pause is lifted. */ event Unpaused(); /** * @dev Emitted when the state of a reserve is updated. NOTE: This event is actually declared * in the ReserveLogic library and emitted in the updateInterestRates() function. Since the function is internal, * the event will actually be fired by the LendingPool contract. The event is therefore replicated here so it * gets added to the LendingPool ABI * @param reserve The address of the underlying asset of the reserve * @param liquidityRate The new liquidity rate * @param variableBorrowRate The new variable borrow rate * @param liquidityIndex The new liquidity index * @param variableBorrowIndex The new variable borrow index **/ event ReserveDataUpdated( address indexed reserve, uint256 liquidityRate, uint256 variableBorrowRate, uint256 liquidityIndex, uint256 variableBorrowIndex ); /** * @dev Emitted when a reserve factor is updated * @param asset The address of the underlying asset of the reserve * @param factor The new reserve factor **/ event ReserveFactorChanged(address indexed asset, uint256 factor); /** * @dev Emitted when a reserve active state is updated * @param asset The address of the underlying asset of the reserve * @param active The new reserve active state **/ event ReserveActiveChanged(address indexed asset, bool active); /** * @dev Emitted when credit system is updated * @param creditContract The address of the new credit system **/ event CreditStrategyChanged(address creditContract); /** * @dev Deposits an `amount` of underlying asset into the reserve, receiving in return overlying kTokens. * - E.g. User deposits 100 USDT and gets in return 100 kUSDT * @param asset The address of the underlying asset to deposit * @param amount The amount to be deposited * @param onBehalfOf The address that will receive the kTokens, same as msg.sender if the user * wants to receive them on his own wallet, or a different address if the beneficiary of kTokens * is a different wallet **/ function deposit( address asset, uint256 amount, address onBehalfOf ) external; /** * @dev Withdraws an `amount` of underlying asset from the reserve, burning the equivalent kTokens owned * E.g. User has 100 kUSDT, calls withdraw() and receives 100 USDT, burning the 100 aUSDT * @param asset The address of the underlying asset to withdraw * @param amount The underlying amount to be withdrawn * - Send the value type(uint256).max in order to withdraw the whole kToken balance * @param to Address that will receive the underlying, same as msg.sender if the user * wants to receive it on his own wallet, or a different address if the beneficiary is a * different wallet * @return The final amount withdrawn **/ function withdraw( address asset, uint256 amount, address to ) external returns (uint256); /** * @dev Allows users to borrow a specific `amount` of the reserve underlying asset, provided that the borrower * already had a credit line, or he was given enough allowance by a credit delegator on the * corresponding debt token * - E.g. User borrows 100 USDT passing as `onBehalfOf` his own address, receiving the 100 USDT in his wallet * and 100 variable debt tokens * @param asset The address of the underlying asset to borrow * @param amount The amount to be borrowed * @param onBehalfOf Address of the user who will receive the debt. Should be the address of the borrower itself * calling the function if he wants to borrow against his own credit, or the address of the credit delegator * if he has been given credit delegation allowance **/ function borrow( address asset, uint256 amount, address onBehalfOf ) external; /** * @notice Repays a borrowed `amount` on a specific reserve, burning the equivalent debt tokens owned * - E.g. User repays 100 USDT, burning 100 variable/stable debt tokens of the `onBehalfOf` address * @param asset The address of the borrowed underlying asset previously borrowed * @param amount The amount to repay * - Send the value type(uint256).max in order to repay the whole debt for `asset` * @param onBehalfOf Address of the user who will get his debt reduced/removed. Should be the address of the * user calling the function if he wants to reduce/remove his own debt, or the address of any other * other borrower whose debt should be removed * @return The final amount repaid **/ function repay( address asset, uint256 amount, address onBehalfOf ) external returns (uint256); /** * @dev Returns the user account data across all the reserves * @param user The address of the user * @return totalDebtInWEI the total debt in WEI of the user * @return availableBorrowsInWEI the borrowing power left of the user **/ function getUserAccountData(address user) external view returns (uint256 totalDebtInWEI, uint256 availableBorrowsInWEI); function initReserve( address reserve, address kTokenAddress, address variableDebtAddress, address interestRateStrategyAddress, uint8 reserveDecimals, uint16 reserveFactor ) external; function setReserveInterestRateStrategyAddress( address reserve, address rateStrategyAddress ) external; /** * @dev Returns the normalized income normalized income of the reserve * @param asset The address of the underlying asset of the reserve * @return The reserve's normalized income */ function getReserveNormalizedIncome(address asset) external view returns (uint256); /** * @dev Returns the normalized variable debt per unit of asset * @param asset The address of the underlying asset of the reserve * @return The reserve normalized variable debt */ function getReserveNormalizedVariableDebt(address asset) external view returns (uint256); /** * @dev Returns the state and configuration of the reserve * @param asset The address of the underlying asset of the reserve * @return The state of the reserve **/ function getReserveData(address asset) external view returns (DataTypes.ReserveData memory); function getReservesList() external view returns (address[] memory); function setPause(bool val) external; function paused() external view returns (bool); function getActive(address asset) external view returns (bool); function setCreditStrategy(address creditContract) external; function getCreditStrategy() external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity 0.8.7; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; import "./IScaledBalanceToken.sol"; import "./IInitializableKToken.sol"; interface IKToken is IERC20Upgradeable, IScaledBalanceToken, IInitializableKToken { /** * @dev Emitted after the mint action * @param from The address performing the mint * @param value The amount being * @param index The new liquidity index of the reserve **/ event Mint(address indexed from, uint256 value, uint256 index); /** * @dev Mints `amount` kTokens to `user` * @param user The address receiving the minted tokens * @param amount The amount of tokens getting minted * @param index The new liquidity index of the reserve * @return `true` if the the previous balance of the user was 0 */ function mint( address user, uint256 amount, uint256 index ) external returns (bool); /** * @dev Emitted after kTokens are burned * @param from The owner of the kTokens, getting them burned * @param target The address that will receive the underlying * @param value The amount being burned * @param index The new liquidity index of the reserve **/ event Burn(address indexed from, address indexed target, uint256 value, uint256 index); /** * @dev Emitted during the transfer action * @param from The user whose tokens are being transferred * @param to The recipient * @param value The amount being transferred * @param index The new liquidity index of the reserve **/ event BalanceTransfer(address indexed from, address indexed to, uint256 value, uint256 index); /** * @dev Burns kTokens from `user` and sends the equivalent amount of underlying to `receiverOfUnderlying` * @param user The owner of the kTokens, getting them burned * @param receiverOfUnderlying The address that will receive the underlying * @param amount The amount being burned * @param index The new liquidity index of the reserve **/ function burn( address user, address receiverOfUnderlying, uint256 amount, uint256 index ) external; /** * @dev Mints kTokens to the reserve treasury * @param amount The amount of tokens getting minted * @param index The new liquidity index of the reserve */ function mintToTreasury(uint256 amount, uint256 index) external; /** * @dev Transfers the underlying asset to `target`. Used by the LendingPool to transfer * assets in borrow(), withdraw() and flashLoan() * @param user The recipient of the underlying * @param amount The amount getting transferred * @return The amount transferred **/ function transferUnderlyingTo(address user, uint256 amount) external returns (uint256); /** * @dev Invoked to execute actions on the kToken side after a repayment. * @param user The user executing the repayment * @param amount The amount getting repaid **/ function handleRepayment(address user, uint256 amount) external; /** * @dev Returns the address of the underlying asset of this kToken (E.g. USDT for kUSDT) **/ function UNDERLYING_ASSET_ADDRESS() external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity 0.8.7; import "./ILendingPool.sol"; interface IInitializableKToken { /** * @dev Emitted when an kToken is initialized * @param underlyingAsset The address of the underlying asset * @param pool The address of the associated lending pool * @param treasury The address of the treasury * @param kTokenDecimals the decimals of the underlying * @param kTokenName the name of the kToken * @param kTokenSymbol the symbol of the kToken * @param params A set of encoded parameters for additional initialization **/ event Initialized( address indexed underlyingAsset, address indexed pool, address treasury, uint8 kTokenDecimals, string kTokenName, string kTokenSymbol, bytes params ); /** * @dev Initializes the kToken * @param pool The address of the lending pool where this kToken will be used * @param treasury The address of the Kyoko treasury, receiving the fees on this kToken * @param underlyingAsset The address of the underlying asset of this kToken (E.g. USDT for kUSDT) * @param kTokenDecimals The decimals of the kToken, same as the underlying asset's * @param kTokenName The name of the kToken * @param kTokenSymbol The symbol of the kToken */ function initialize( ILendingPool pool, address treasury, address underlyingAsset, uint8 kTokenDecimals, string calldata kTokenName, string calldata kTokenSymbol, bytes calldata params ) external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.7; import "./ILendingPool.sol"; interface IInitializableDebtToken { /** * @dev Emitted when a debt token is initialized * @param underlyingAsset The address of the underlying asset * @param pool The address of the associated lending pool * @param debtTokenDecimals the decimals of the debt token * @param debtTokenName the name of the debt token * @param debtTokenSymbol the symbol of the debt token * @param params A set of encoded parameters for additional initialization **/ event Initialized( address indexed underlyingAsset, address indexed pool, uint8 debtTokenDecimals, string debtTokenName, string debtTokenSymbol, bytes params ); /** * @dev Initializes the debt token. * @param pool The address of the lending pool where this kToken will be used * @param underlyingAsset The address of the underlying asset of this kToken (E.g. USDT for kUSDT) * @param debtTokenDecimals The decimals of the debtToken, same as the underlying asset's * @param debtTokenName The name of the token * @param debtTokenSymbol The symbol of the token */ function initialize( ILendingPool pool, address underlyingAsset, uint8 debtTokenDecimals, string memory debtTokenName, string memory debtTokenSymbol, bytes calldata params ) external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.7; import "@openzeppelin/contracts-upgradeable/access/AccessControlEnumerableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol"; /** * @dev this contract represents the credit line in the whitelist. * @dev the guild's credit line amount * @dev the decimals is 1e18. */ contract CreditSystem is AccessControlEnumerableUpgradeable { using SafeMathUpgradeable for uint256; using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet; /// the role manage total credit manager bytes32 public constant ROLE_CREDIT_MANAGER = keccak256("ROLE_CREDIT_MANAGER"); uint8 public constant G2G_MASK = 0x0E; uint8 public constant CCAL_MASK = 0x0D; uint8 constant IS_G2G_START_BIT_POSITION = 0; uint8 constant IS_CCAL_START_BIT_POSITION = 1; struct CreditInfo { //ERC20 credit line uint256 g2gCreditLine; //ccal module credit line uint256 ccalCreditLine; //bit 0: g2g isActive flag(0==false, 1==true) //bit 1: ccal isActive flag(0==false, 1==true) uint8 flag; } // the credit line mapping(address => CreditInfo) whiteList; //g2g whiteList Set EnumerableSetUpgradeable.AddressSet private g2gWhiteSet; //ccal whiteList Set EnumerableSetUpgradeable.AddressSet private ccalWhiteSet; event SetG2GCreditLine(address user, uint256 amount); event SetCCALCreditLine(address user, uint256 amount); // event SetPaused(address user, bool flag); event SetG2GActive(address user, bool active); event SetCCALActive(address user, bool active); event RemoveG2GCredit(address user); event RemoveCCALCredit(address user); modifier onlyCreditManager() { require( hasRole(ROLE_CREDIT_MANAGER, _msgSender()), "only the manager has permission to perform this operation." ); _; } // constructor() { // _grantRole(DEFAULT_ADMIN_ROLE, _msgSender()); // } function initialize() public initializer { __AccessControlEnumerable_init(); _grantRole(DEFAULT_ADMIN_ROLE, _msgSender()); } /** * set the address's g2g module credit line * @dev user the guild in the whiteList * @dev amount the guild credit line amount * @dev 1U = 1e18 */ function setG2GCreditLine(address user, uint256 amount) public onlyCreditManager { whiteList[user].g2gCreditLine = amount; setG2GActive(user, amount > 0); emit SetG2GCreditLine(user, amount); } /** * @dev set the address's g2g module credit active status */ function setG2GActive(address user, bool active) public onlyCreditManager { //set user flag setG2GFlag(user, active); //set user white set if (active) { uint256 userG2GCreditLine = getG2GCreditLine(user); userG2GCreditLine > 0 ? g2gWhiteSet.add(user) : g2gWhiteSet.remove(user); } else { g2gWhiteSet.remove(user); } emit SetG2GActive(user, active); } function setG2GFlag(address user, bool active) private { uint8 flag = whiteList[user].flag; flag = (flag & G2G_MASK) | (uint8(active ? 1 : 0) << IS_G2G_START_BIT_POSITION); whiteList[user].flag = flag; } /** * set the address's ccal module credit line * @dev user the guild in the whiteList * @dev amount the guild credit line amount * @dev 1U = 1e18 */ function setCCALCreditLine(address user, uint256 amount) public onlyCreditManager { whiteList[user].ccalCreditLine = amount; setCCALActive(user, amount > 0); emit SetCCALCreditLine(user, amount); } /** * @dev set the address's ccal module credit active status */ function setCCALActive(address user, bool active) public onlyCreditManager { //set user flag setCCALFlag(user, active); //set user white set if (active) { uint256 userCCALCreditLine = getCCALCreditLine(user); userCCALCreditLine > 0 ? ccalWhiteSet.add(user) : ccalWhiteSet.remove(user); } else { ccalWhiteSet.remove(user); } emit SetCCALActive(user, active); } function setCCALFlag(address user, bool active) private { uint8 flag = whiteList[user].flag; flag = (flag & CCAL_MASK) | (uint8(active ? 1 : 0) << IS_CCAL_START_BIT_POSITION); whiteList[user].flag = flag; } /** * remove the address's g2g module credit line */ function removeG2GCredit(address user) public onlyCreditManager { whiteList[user].g2gCreditLine = 0; setG2GActive(user, false); emit RemoveG2GCredit(user); } /** * remove the address's ccal module credit line */ function removeCCALCredit(address user) public onlyCreditManager { whiteList[user].ccalCreditLine = 0; setCCALActive(user, false); emit RemoveCCALCredit(user); } /** * @dev query the user credit line * @param user the address which to query * @return G2G credit line */ function getG2GCreditLine(address user) public view returns (uint256) { CreditInfo memory credit = whiteList[user]; return credit.g2gCreditLine; } /** * @dev query the user credit line * @param user the address which to query * @return CCAL credit line */ function getCCALCreditLine(address user) public view returns (uint256) { CreditInfo memory credit = whiteList[user]; return credit.ccalCreditLine; } /** * @dev query the white list addresses in G2G */ function getG2GWhiteList() public view returns (address[] memory) { return g2gWhiteSet.values(); } /** * @dev query the white list addresses in CCAL */ function getCCALWhiteList() public view returns (address[] memory) { return ccalWhiteSet.values(); } /** * @dev query the address state */ function getState(address user) public view returns (bool, bool) { uint8 activeFlag = whiteList[user].flag; return ( activeFlag & ~G2G_MASK != 0, activeFlag & ~CCAL_MASK != 0 ); } } // 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 EnumerableSetUpgradeable { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; if (lastIndex != toDeleteIndex) { bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex } // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { return set._values[index]; } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function _values(Set storage set) private view returns (bytes32[] memory) { return set._values; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(Bytes32Set storage set) internal view returns (bytes32[] memory) { return _values(set._inner); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(AddressSet storage set) internal view returns (address[] memory) { bytes32[] memory store = _values(set._inner); address[] memory result; assembly { result := store } return result; } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(UintSet storage set) internal view returns (uint256[] memory) { bytes32[] memory store = _values(set._inner); uint256[] memory result; assembly { result := store } return result; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol) pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler * now has built in overflow checking. */ library SafeMathUpgradeable { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // 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); } // 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 { __ERC165_init_unchained(); } 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; } 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/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 { __Context_init_unchained(); } 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; } uint256[50] private __gap; } // 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 AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol) pragma solidity ^0.8.0; import "../IERC20Upgradeable.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20MetadataUpgradeable is IERC20Upgradeable { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/ERC20.sol) pragma solidity ^0.8.0; import "./IERC20Upgradeable.sol"; import "./extensions/IERC20MetadataUpgradeable.sol"; import "../../utils/ContextUpgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead 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 ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable { 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 default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ function __ERC20_init(string memory name_, string memory symbol_) internal onlyInitializing { __Context_init_unchained(); __ERC20_init_unchained(name_, symbol_); } function __ERC20_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override 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 * overridden; * * 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 override 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"); unchecked { _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"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This 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"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(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: * * - `account` 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); _afterTokenTransfer(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"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(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 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 {} /** * @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, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been 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 _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} uint256[45] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (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 a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the * initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() initializer {} * ``` * ==== */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { // 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/IAccessControl.sol) pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControlUpgradeable { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/IAccessControlEnumerable.sol) pragma solidity ^0.8.0; import "./IAccessControlUpgradeable.sol"; /** * @dev External interface of AccessControlEnumerable declared to support ERC165 detection. */ interface IAccessControlEnumerableUpgradeable is IAccessControlUpgradeable { /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) external view returns (address); /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) external view returns (uint256); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/AccessControl.sol) pragma solidity ^0.8.0; import "./IAccessControlUpgradeable.sol"; import "../utils/ContextUpgradeable.sol"; import "../utils/StringsUpgradeable.sol"; import "../utils/introspection/ERC165Upgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable { function __AccessControl_init() internal onlyInitializing { __Context_init_unchained(); __ERC165_init_unchained(); __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal onlyInitializing { } struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", StringsUpgradeable.toHexString(uint160(account), 20), " is missing role ", StringsUpgradeable.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been revoked `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== * * NOTE: This function is deprecated in favor of {_grantRole}. */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } /** * @dev Grants `role` to `account`. * * Internal function without access restriction. */ function _grantRole(bytes32 role, address account) internal virtual { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } /** * @dev Revokes `role` from `account`. * * Internal function without access restriction. */ function _revokeRole(bytes32 role, address account) internal virtual { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/AccessControlEnumerable.sol) pragma solidity ^0.8.0; import "./IAccessControlEnumerableUpgradeable.sol"; import "./AccessControlUpgradeable.sol"; import "../utils/structs/EnumerableSetUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Extension of {AccessControl} that allows enumerating the members of each role. */ abstract contract AccessControlEnumerableUpgradeable is Initializable, IAccessControlEnumerableUpgradeable, AccessControlUpgradeable { function __AccessControlEnumerable_init() internal onlyInitializing { __Context_init_unchained(); __ERC165_init_unchained(); __AccessControl_init_unchained(); __AccessControlEnumerable_init_unchained(); } function __AccessControlEnumerable_init_unchained() internal onlyInitializing { } using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet; mapping(bytes32 => EnumerableSetUpgradeable.AddressSet) private _roleMembers; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlEnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view override returns (address) { return _roleMembers[role].at(index); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view override returns (uint256) { return _roleMembers[role].length(); } /** * @dev Overload {_grantRole} to track enumerable memberships */ function _grantRole(bytes32 role, address account) internal virtual override { super._grantRole(role, account); _roleMembers[role].add(account); } /** * @dev Overload {_revokeRole} to track enumerable memberships */ function _revokeRole(bytes32 role, address account) internal virtual override { super._revokeRole(role, account); _roleMembers[role].remove(account); } uint256[49] private __gap; }
* @dev Function to calculate the interest using a compounded interest rate formula To avoid expensive exponentiation, the calculation is performed using a binomial approximation: (1+x)^n = 1+nx+[n/2(n-1)]x^2+[n/6(n-1)(n-2)x^3... The approximation slightly underpays liquidity providers and undercharges borrowers, with the advantage of great gas cost reductions The whitepaper contains reference to the approximation and a table showing the margin of error per different time periods @param rate The interest rate, in ray @param lastUpdateTimestamp The timestamp of the last update of the interest @return The interest rate compounded during the timeDelta, in ray/solium-disable-next-line
function calculateCompoundedInterest( uint256 rate, uint40 lastUpdateTimestamp, uint256 currentTimestamp ) internal pure returns (uint256) { uint256 exp = currentTimestamp.sub(uint256(lastUpdateTimestamp)); if (exp == 0) { return KyokoMath.ray(); } uint256 expMinusOne = exp - 1; uint256 expMinusTwo = exp > 2 ? exp - 2 : 0; uint256 ratePerSecond = rate / SECONDS_PER_YEAR; uint256 basePowerTwo = ratePerSecond.rayMul(ratePerSecond); uint256 basePowerThree = basePowerTwo.rayMul(ratePerSecond); uint256 secondTerm = exp.mul(expMinusOne).mul(basePowerTwo) / 2; uint256 thirdTerm = exp.mul(expMinusOne).mul(expMinusTwo).mul(basePowerThree) / 6; return KyokoMath.ray().add(ratePerSecond.mul(exp)).add(secondTerm).add(thirdTerm); }
11,804,930
[ 1, 2083, 358, 4604, 326, 16513, 1450, 279, 1161, 12002, 16513, 4993, 8013, 2974, 4543, 19326, 9100, 7072, 16, 326, 11096, 353, 9591, 1450, 279, 4158, 11496, 24769, 30, 225, 261, 21, 15, 92, 13, 66, 82, 273, 404, 15, 16769, 15, 63, 82, 19, 22, 12, 82, 17, 21, 25887, 92, 66, 22, 15, 63, 82, 19, 26, 12, 82, 17, 21, 21433, 82, 17, 22, 13, 92, 66, 23, 2777, 1021, 24769, 21980, 3613, 84, 8271, 4501, 372, 24237, 9165, 471, 3613, 3001, 2852, 29759, 414, 16, 598, 326, 1261, 7445, 410, 434, 18825, 16189, 6991, 20176, 87, 1021, 600, 305, 881, 7294, 1914, 2114, 358, 326, 24769, 471, 279, 1014, 17253, 326, 7333, 434, 555, 1534, 3775, 813, 12777, 225, 4993, 1021, 16513, 4993, 16, 316, 14961, 225, 1142, 1891, 4921, 1021, 2858, 434, 326, 1142, 1089, 434, 326, 16513, 327, 1021, 16513, 4993, 1161, 12002, 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, 4604, 2945, 12002, 29281, 12, 203, 3639, 2254, 5034, 4993, 16, 203, 3639, 2254, 7132, 1142, 1891, 4921, 16, 203, 3639, 2254, 5034, 783, 4921, 203, 565, 262, 2713, 16618, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 2254, 5034, 1329, 273, 783, 4921, 18, 1717, 12, 11890, 5034, 12, 2722, 1891, 4921, 10019, 203, 203, 3639, 309, 261, 2749, 422, 374, 13, 288, 203, 5411, 327, 1475, 93, 601, 83, 10477, 18, 435, 5621, 203, 3639, 289, 203, 203, 3639, 2254, 5034, 1329, 18434, 3335, 273, 1329, 300, 404, 31, 203, 203, 3639, 2254, 5034, 1329, 18434, 11710, 273, 1329, 405, 576, 692, 1329, 300, 576, 294, 374, 31, 203, 203, 3639, 2254, 5034, 4993, 2173, 8211, 273, 4993, 342, 17209, 67, 3194, 67, 15137, 31, 203, 203, 3639, 2254, 5034, 1026, 13788, 11710, 273, 4993, 2173, 8211, 18, 435, 27860, 12, 5141, 2173, 8211, 1769, 203, 3639, 2254, 5034, 1026, 13788, 28019, 273, 1026, 13788, 11710, 18, 435, 27860, 12, 5141, 2173, 8211, 1769, 203, 203, 3639, 2254, 5034, 2205, 4065, 273, 1329, 18, 16411, 12, 2749, 18434, 3335, 2934, 16411, 12, 1969, 13788, 11710, 13, 342, 576, 31, 203, 3639, 2254, 5034, 12126, 4065, 273, 1329, 18, 16411, 12, 2749, 18434, 3335, 2934, 16411, 12, 2749, 18434, 11710, 2934, 16411, 12, 1969, 13788, 28019, 13, 342, 1666, 31, 203, 203, 3639, 327, 1475, 93, 601, 83, 10477, 18, 435, 7675, 1289, 12, 5141, 2173, 8211, 18, 16411, 12, 2749, 13, 2934, 1289, 12, 8538, 4065, 2934, 1289, 12, 451, 2 ]
./full_match/5/0xE8350dAEbeD840c4413B07d5F1aD2a86714b28Fc/sources/project_/contracts/CoinFlip.sol
getting randomness IF DENIED GAME return NFTS
function startOrDenyCoinFlipGame(uint256 _gameId, bool status) public nonReentrant returns (uint256) { require(_gameIdToCoinFlip[_gameId].creator == msg.sender, "You must be creator to start match"); require(_gameIdToCoinFlip[_gameId].inProgress == false, "Cannot start a match thats started in progress"); require(_gameIdToCoinFlip[_gameId].playerJoined == true, "Cannot start a match with no players joined"); require(_gameIdToCoinFlip[_gameId].played == false, "Cannot start a match thats started already"); CoinFlipGame storage coinFlipGame = _gameIdToCoinFlip[_gameId]; if (status) { gamesInProgress += 1; coinFlipGame.inProgress = true; uint256 requestId = requestRandomness(callbackGasLimit, requestConfirmations, numWords); coinFlipGame.requestId = requestId; _requestIdtoGameId[requestId] = CoinStruct(_gameId); _addressToUser[coinFlipGame.player].gamesplayed += 1; emit CoinFlipStarted(_gameId, coinFlipGame.creator, coinFlipGame.player, requestId); return requestId; gamesWithPlayers -= 1; for (uint256 i = 0; i < coinFlipGame.nfts.length; i++) { IERC721(coinFlipGame.nfts[i].nftContract).transferFrom(coinFlipGame.nfts[i].owner, address(this), coinFlipGame.nfts[i].tokenId); } emit CoinFlipDenied(_gameId, coinFlipGame.creator, coinFlipGame.player, true); return 1; } }
1,899,229
[ 1, 588, 1787, 2744, 4496, 11083, 463, 1157, 29229, 611, 1642, 327, 423, 4464, 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 ]
[ 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, 225, 445, 787, 1162, 8517, 93, 27055, 28535, 12496, 12, 11890, 5034, 389, 13957, 548, 16, 1426, 1267, 13, 1071, 1661, 426, 8230, 970, 1135, 261, 11890, 5034, 13, 288, 203, 1377, 2583, 24899, 13957, 28803, 27055, 28535, 63, 67, 13957, 548, 8009, 20394, 422, 1234, 18, 15330, 16, 315, 6225, 1297, 506, 11784, 358, 787, 845, 8863, 203, 1377, 2583, 24899, 13957, 28803, 27055, 28535, 63, 67, 13957, 548, 8009, 267, 5491, 422, 629, 16, 315, 4515, 787, 279, 845, 716, 87, 5746, 316, 4007, 8863, 203, 1377, 2583, 24899, 13957, 28803, 27055, 28535, 63, 67, 13957, 548, 8009, 14872, 4572, 329, 422, 638, 16, 315, 4515, 787, 279, 845, 598, 1158, 18115, 12114, 8863, 203, 1377, 2583, 24899, 13957, 28803, 27055, 28535, 63, 67, 13957, 548, 8009, 1601, 329, 422, 629, 16, 315, 4515, 787, 279, 845, 716, 87, 5746, 1818, 8863, 203, 203, 3639, 28932, 28535, 12496, 2502, 13170, 28535, 12496, 273, 389, 13957, 28803, 27055, 28535, 63, 67, 13957, 548, 15533, 203, 203, 3639, 309, 261, 2327, 13, 288, 203, 1850, 28422, 13434, 1011, 404, 31, 203, 1850, 13170, 28535, 12496, 18, 267, 5491, 273, 638, 31, 203, 203, 1850, 2254, 5034, 14459, 273, 590, 8529, 4496, 12, 3394, 27998, 3039, 16, 590, 11269, 1012, 16, 818, 7363, 1769, 203, 1850, 13170, 28535, 12496, 18, 2293, 548, 273, 14459, 31, 203, 203, 1850, 389, 2293, 548, 869, 12496, 548, 63, 2293, 548, 65, 273, 28932, 3823, 24899, 13957, 548, 1769, 203, 203, 1850, 389, 2867, 774, 1299, 63, 12645, 28535, 2 ]
./full_match/3/0x08a6D4d01544826c2350572412D38Cf8b947FEEF/sources/contracts/UniswapV2Router02.sol
given some amount of an asset and pair reserves, returns an equivalent amount of the other asset
function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) { require(amountA > 0, 'CryptoSwap Library: INSUFFICIENT_AMOUNT'); require(reserveA > 0 && reserveB > 0, 'CryptoSwap Library: INSUFFICIENT_LIQUIDITY'); amountB = amountA.mul(reserveB) / reserveA; }
8,228,660
[ 1, 10822, 2690, 3844, 434, 392, 3310, 471, 3082, 400, 264, 3324, 16, 1135, 392, 7680, 3844, 434, 326, 1308, 3310, 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, 3862, 12, 11890, 3844, 37, 16, 2254, 20501, 37, 16, 2254, 20501, 38, 13, 2713, 16618, 1135, 261, 11890, 3844, 38, 13, 288, 203, 3639, 2583, 12, 8949, 37, 405, 374, 16, 296, 18048, 12521, 18694, 30, 2120, 6639, 42, 1653, 7266, 2222, 67, 2192, 51, 5321, 8284, 203, 3639, 2583, 12, 455, 6527, 37, 405, 374, 597, 20501, 38, 405, 374, 16, 296, 18048, 12521, 18694, 30, 2120, 6639, 42, 1653, 7266, 2222, 67, 2053, 53, 3060, 4107, 8284, 203, 3639, 3844, 38, 273, 3844, 37, 18, 16411, 12, 455, 6527, 38, 13, 342, 20501, 37, 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 ]
/** * Source Code first verified at https://etherscan.io on Monday, February 4, 2019 (UTC) */ pragma solidity ^0.4.24; /** * @title Owned * @dev Basic contract to define an owner. * @author Julien Niset - <[email protected]> */ contract Owned { // The owner address public owner; event OwnerChanged(address indexed _newOwner); /** * @dev Throws if the sender is not the owner. */ modifier onlyOwner { require(msg.sender == owner, "Must be owner"); _; } constructor() public { owner = msg.sender; } /** * @dev Lets the owner transfer ownership of the contract to a new owner. * @param _newOwner The new owner. */ function changeOwner(address _newOwner) external onlyOwner { require(_newOwner != address(0), "Address must not be null"); owner = _newOwner; emit OwnerChanged(_newOwner); } } /** * @title Managed * @dev Basic contract that defines a set of managers. Only the owner can add/remove managers. * @author Julien Niset - <[email protected]> */ contract Managed is Owned { // The managers mapping (address => bool) public managers; /** * @dev Throws if the sender is not a manager. */ modifier onlyManager { require(managers[msg.sender] == true, "M: Must be manager"); _; } event ManagerAdded(address indexed _manager); event ManagerRevoked(address indexed _manager); /** * @dev Adds a manager. * @param _manager The address of the manager. */ function addManager(address _manager) external onlyOwner { require(_manager != address(0), "M: Address must not be null"); if(managers[_manager] == false) { managers[_manager] = true; emit ManagerAdded(_manager); } } /** * @dev Revokes a manager. * @param _manager The address of the manager. */ function revokeManager(address _manager) external onlyOwner { require(managers[_manager] == true, "M: Target must be an existing manager"); delete managers[_manager]; emit ManagerRevoked(_manager); } } /** * ENS Registry interface. */ contract ENSRegistry { function owner(bytes32 _node) public view returns (address); function resolver(bytes32 _node) public view returns (address); function ttl(bytes32 _node) public view returns (uint64); function setOwner(bytes32 _node, address _owner) public; function setSubnodeOwner(bytes32 _node, bytes32 _label, address _owner) public; function setResolver(bytes32 _node, address _resolver) public; function setTTL(bytes32 _node, uint64 _ttl) public; } /** * ENS Resolver interface. */ contract ENSResolver { function addr(bytes32 _node) public view returns (address); function setAddr(bytes32 _node, address _addr) public; function name(bytes32 _node) public view returns (string); function setName(bytes32 _node, string _name) public; } /** * ENS Reverse Registrar interface. */ contract ENSReverseRegistrar { function claim(address _owner) public returns (bytes32 _node); function claimWithResolver(address _owner, address _resolver) public returns (bytes32); function setName(string _name) public returns (bytes32); function node(address _addr) public view returns (bytes32); } /* * @title String & slice utility library for Solidity contracts. * @author Nick Johnson <[email protected]> * * @dev Functionality in this library is largely implemented using an * abstraction called a 'slice'. A slice represents a part of a string - * anything from the entire string to a single character, or even no * characters at all (a 0-length slice). Since a slice only has to specify * an offset and a length, copying and manipulating slices is a lot less * expensive than copying and manipulating the strings they reference. * * To further reduce gas costs, most functions on slice that need to return * a slice modify the original one instead of allocating a new one; for * instance, `s.split(".")` will return the text up to the first '.', * modifying s to only contain the remainder of the string after the '.'. * In situations where you do not want to modify the original slice, you * can make a copy first with `.copy()`, for example: * `s.copy().split(".")`. Try and avoid using this idiom in loops; since * Solidity has no memory management, it will result in allocating many * short-lived slices that are later discarded. * * Functions that return two slices come in two versions: a non-allocating * version that takes the second slice as an argument, modifying it in * place, and an allocating version that allocates and returns the second * slice; see `nextRune` for example. * * Functions that have to copy string data will return strings rather than * slices; these can be cast back to slices for further processing if * required. * * For convenience, some functions are provided with non-modifying * variants that create a new slice and return both; for instance, * `s.splitNew('.')` leaves s unmodified, and returns two values * corresponding to the left and right parts of the string. */ /* solium-disable */ library strings { struct slice { uint _len; uint _ptr; } function memcpy(uint dest, uint src, uint len) private pure { // Copy word-length chunks while possible for(; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } // Copy remaining bytes uint mask = 256 ** (32 - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } } /* * @dev Returns a slice containing the entire string. * @param self The string to make a slice from. * @return A newly allocated slice containing the entire string. */ function toSlice(string memory self) internal pure returns (slice memory) { uint ptr; assembly { ptr := add(self, 0x20) } return slice(bytes(self).length, ptr); } /* * @dev Returns the length of a null-terminated bytes32 string. * @param self The value to find the length of. * @return The length of the string, from 0 to 32. */ function len(bytes32 self) internal pure returns (uint) { uint ret; if (self == 0) return 0; if (self & 0xffffffffffffffffffffffffffffffff == 0) { ret += 16; self = bytes32(uint(self) / 0x100000000000000000000000000000000); } if (self & 0xffffffffffffffff == 0) { ret += 8; self = bytes32(uint(self) / 0x10000000000000000); } if (self & 0xffffffff == 0) { ret += 4; self = bytes32(uint(self) / 0x100000000); } if (self & 0xffff == 0) { ret += 2; self = bytes32(uint(self) / 0x10000); } if (self & 0xff == 0) { ret += 1; } return 32 - ret; } /* * @dev Returns a slice containing the entire bytes32, interpreted as a * null-terminated utf-8 string. * @param self The bytes32 value to convert to a slice. * @return A new slice containing the value of the input argument up to the * first null. */ function toSliceB32(bytes32 self) internal pure returns (slice memory ret) { // Allocate space for `self` in memory, copy it there, and point ret at it assembly { let ptr := mload(0x40) mstore(0x40, add(ptr, 0x20)) mstore(ptr, self) mstore(add(ret, 0x20), ptr) } ret._len = len(self); } /* * @dev Returns a new slice containing the same data as the current slice. * @param self The slice to copy. * @return A new slice containing the same data as `self`. */ function copy(slice memory self) internal pure returns (slice memory) { return slice(self._len, self._ptr); } /* * @dev Copies a slice to a new string. * @param self The slice to copy. * @return A newly allocated string containing the slice's text. */ function toString(slice memory self) internal pure returns (string memory) { string memory ret = new string(self._len); uint retptr; assembly { retptr := add(ret, 32) } memcpy(retptr, self._ptr, self._len); return ret; } /* * @dev Returns the length in runes of the slice. Note that this operation * takes time proportional to the length of the slice; avoid using it * in loops, and call `slice.empty()` if you only need to know whether * the slice is empty or not. * @param self The slice to operate on. * @return The length of the slice in runes. */ function len(slice memory self) internal pure returns (uint l) { // Starting at ptr-31 means the LSB will be the byte we care about uint ptr = self._ptr - 31; uint end = ptr + self._len; for (l = 0; ptr < end; l++) { uint8 b; assembly { b := and(mload(ptr), 0xFF) } if (b < 0x80) { ptr += 1; } else if(b < 0xE0) { ptr += 2; } else if(b < 0xF0) { ptr += 3; } else if(b < 0xF8) { ptr += 4; } else if(b < 0xFC) { ptr += 5; } else { ptr += 6; } } } /* * @dev Returns true if the slice is empty (has a length of 0). * @param self The slice to operate on. * @return True if the slice is empty, False otherwise. */ function empty(slice memory self) internal pure returns (bool) { return self._len == 0; } /* * @dev Returns a positive number if `other` comes lexicographically after * `self`, a negative number if it comes before, or zero if the * contents of the two slices are equal. Comparison is done per-rune, * on unicode codepoints. * @param self The first slice to compare. * @param other The second slice to compare. * @return The result of the comparison. */ function compare(slice memory self, slice memory other) internal pure returns (int) { uint shortest = self._len; if (other._len < self._len) shortest = other._len; uint selfptr = self._ptr; uint otherptr = other._ptr; for (uint idx = 0; idx < shortest; idx += 32) { uint a; uint b; assembly { a := mload(selfptr) b := mload(otherptr) } if (a != b) { // Mask out irrelevant bytes and check again uint256 mask = uint256(-1); // 0xffff... if(shortest < 32) { mask = ~(2 ** (8 * (32 - shortest + idx)) - 1); } uint256 diff = (a & mask) - (b & mask); if (diff != 0) return int(diff); } selfptr += 32; otherptr += 32; } return int(self._len) - int(other._len); } /* * @dev Returns true if the two slices contain the same text. * @param self The first slice to compare. * @param self The second slice to compare. * @return True if the slices are equal, false otherwise. */ function equals(slice memory self, slice memory other) internal pure returns (bool) { return compare(self, other) == 0; } /* * @dev Extracts the first rune in the slice into `rune`, advancing the * slice to point to the next rune and returning `self`. * @param self The slice to operate on. * @param rune The slice that will contain the first rune. * @return `rune`. */ function nextRune(slice memory self, slice memory rune) internal pure returns (slice memory) { rune._ptr = self._ptr; if (self._len == 0) { rune._len = 0; return rune; } uint l; uint b; // Load the first byte of the rune into the LSBs of b assembly { b := and(mload(sub(mload(add(self, 32)), 31)), 0xFF) } if (b < 0x80) { l = 1; } else if(b < 0xE0) { l = 2; } else if(b < 0xF0) { l = 3; } else { l = 4; } // Check for truncated codepoints if (l > self._len) { rune._len = self._len; self._ptr += self._len; self._len = 0; return rune; } self._ptr += l; self._len -= l; rune._len = l; return rune; } /* * @dev Returns the first rune in the slice, advancing the slice to point * to the next rune. * @param self The slice to operate on. * @return A slice containing only the first rune from `self`. */ function nextRune(slice memory self) internal pure returns (slice memory ret) { nextRune(self, ret); } /* * @dev Returns the number of the first codepoint in the slice. * @param self The slice to operate on. * @return The number of the first codepoint in the slice. */ function ord(slice memory self) internal pure returns (uint ret) { if (self._len == 0) { return 0; } uint word; uint length; uint divisor = 2 ** 248; // Load the rune into the MSBs of b assembly { word:= mload(mload(add(self, 32))) } uint b = word / divisor; if (b < 0x80) { ret = b; length = 1; } else if(b < 0xE0) { ret = b & 0x1F; length = 2; } else if(b < 0xF0) { ret = b & 0x0F; length = 3; } else { ret = b & 0x07; length = 4; } // Check for truncated codepoints if (length > self._len) { return 0; } for (uint i = 1; i < length; i++) { divisor = divisor / 256; b = (word / divisor) & 0xFF; if (b & 0xC0 != 0x80) { // Invalid UTF-8 sequence return 0; } ret = (ret * 64) | (b & 0x3F); } return ret; } /* * @dev Returns the keccak-256 hash of the slice. * @param self The slice to hash. * @return The hash of the slice. */ function keccak(slice memory self) internal pure returns (bytes32 ret) { assembly { ret := keccak256(mload(add(self, 32)), mload(self)) } } /* * @dev Returns true if `self` starts with `needle`. * @param self The slice to operate on. * @param needle The slice to search for. * @return True if the slice starts with the provided text, false otherwise. */ function startsWith(slice memory self, slice memory needle) internal pure returns (bool) { if (self._len < needle._len) { return false; } if (self._ptr == needle._ptr) { return true; } bool equal; assembly { let length := mload(needle) let selfptr := mload(add(self, 0x20)) let needleptr := mload(add(needle, 0x20)) equal := eq(keccak256(selfptr, length), keccak256(needleptr, length)) } return equal; } /* * @dev If `self` starts with `needle`, `needle` is removed from the * beginning of `self`. Otherwise, `self` is unmodified. * @param self The slice to operate on. * @param needle The slice to search for. * @return `self` */ function beyond(slice memory self, slice memory needle) internal pure returns (slice memory) { if (self._len < needle._len) { return self; } bool equal = true; if (self._ptr != needle._ptr) { assembly { let length := mload(needle) let selfptr := mload(add(self, 0x20)) let needleptr := mload(add(needle, 0x20)) equal := eq(keccak256(selfptr, length), keccak256(needleptr, length)) } } if (equal) { self._len -= needle._len; self._ptr += needle._len; } return self; } /* * @dev Returns true if the slice ends with `needle`. * @param self The slice to operate on. * @param needle The slice to search for. * @return True if the slice starts with the provided text, false otherwise. */ function endsWith(slice memory self, slice memory needle) internal pure returns (bool) { if (self._len < needle._len) { return false; } uint selfptr = self._ptr + self._len - needle._len; if (selfptr == needle._ptr) { return true; } bool equal; assembly { let length := mload(needle) let needleptr := mload(add(needle, 0x20)) equal := eq(keccak256(selfptr, length), keccak256(needleptr, length)) } return equal; } /* * @dev If `self` ends with `needle`, `needle` is removed from the * end of `self`. Otherwise, `self` is unmodified. * @param self The slice to operate on. * @param needle The slice to search for. * @return `self` */ function until(slice memory self, slice memory needle) internal pure returns (slice memory) { if (self._len < needle._len) { return self; } uint selfptr = self._ptr + self._len - needle._len; bool equal = true; if (selfptr != needle._ptr) { assembly { let length := mload(needle) let needleptr := mload(add(needle, 0x20)) equal := eq(keccak256(selfptr, length), keccak256(needleptr, length)) } } if (equal) { self._len -= needle._len; } return self; } // Returns the memory address of the first byte of the first occurrence of // `needle` in `self`, or the first byte after `self` if not found. function findPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private pure returns (uint) { uint ptr = selfptr; uint idx; if (needlelen <= selflen) { if (needlelen <= 32) { bytes32 mask = bytes32(~(2 ** (8 * (32 - needlelen)) - 1)); bytes32 needledata; assembly { needledata := and(mload(needleptr), mask) } uint end = selfptr + selflen - needlelen; bytes32 ptrdata; assembly { ptrdata := and(mload(ptr), mask) } while (ptrdata != needledata) { if (ptr >= end) return selfptr + selflen; ptr++; assembly { ptrdata := and(mload(ptr), mask) } } return ptr; } else { // For long needles, use hashing bytes32 hash; assembly { hash := keccak256(needleptr, needlelen) } for (idx = 0; idx <= selflen - needlelen; idx++) { bytes32 testHash; assembly { testHash := keccak256(ptr, needlelen) } if (hash == testHash) return ptr; ptr += 1; } } } return selfptr + selflen; } // Returns the memory address of the first byte after the last occurrence of // `needle` in `self`, or the address of `self` if not found. function rfindPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private pure returns (uint) { uint ptr; if (needlelen <= selflen) { if (needlelen <= 32) { bytes32 mask = bytes32(~(2 ** (8 * (32 - needlelen)) - 1)); bytes32 needledata; assembly { needledata := and(mload(needleptr), mask) } ptr = selfptr + selflen - needlelen; bytes32 ptrdata; assembly { ptrdata := and(mload(ptr), mask) } while (ptrdata != needledata) { if (ptr <= selfptr) return selfptr; ptr--; assembly { ptrdata := and(mload(ptr), mask) } } return ptr + needlelen; } else { // For long needles, use hashing bytes32 hash; assembly { hash := keccak256(needleptr, needlelen) } ptr = selfptr + (selflen - needlelen); while (ptr >= selfptr) { bytes32 testHash; assembly { testHash := keccak256(ptr, needlelen) } if (hash == testHash) return ptr + needlelen; ptr -= 1; } } } return selfptr; } /* * @dev Modifies `self` to contain everything from the first occurrence of * `needle` to the end of the slice. `self` is set to the empty slice * if `needle` is not found. * @param self The slice to search and modify. * @param needle The text to search for. * @return `self`. */ function find(slice memory self, slice memory needle) internal pure returns (slice memory) { uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr); self._len -= ptr - self._ptr; self._ptr = ptr; return self; } /* * @dev Modifies `self` to contain the part of the string from the start of * `self` to the end of the first occurrence of `needle`. If `needle` * is not found, `self` is set to the empty slice. * @param self The slice to search and modify. * @param needle The text to search for. * @return `self`. */ function rfind(slice memory self, slice memory needle) internal pure returns (slice memory) { uint ptr = rfindPtr(self._len, self._ptr, needle._len, needle._ptr); self._len = ptr - self._ptr; return self; } /* * @dev Splits the slice, setting `self` to everything after the first * occurrence of `needle`, and `token` to everything before it. If * `needle` does not occur in `self`, `self` is set to the empty slice, * and `token` is set to the entirety of `self`. * @param self The slice to split. * @param needle The text to search for in `self`. * @param token An output parameter to which the first token is written. * @return `token`. */ function split(slice memory self, slice memory needle, slice memory token) internal pure returns (slice memory) { uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr); token._ptr = self._ptr; token._len = ptr - self._ptr; if (ptr == self._ptr + self._len) { // Not found self._len = 0; } else { self._len -= token._len + needle._len; self._ptr = ptr + needle._len; } return token; } /* * @dev Splits the slice, setting `self` to everything after the first * occurrence of `needle`, and returning everything before it. If * `needle` does not occur in `self`, `self` is set to the empty slice, * and the entirety of `self` is returned. * @param self The slice to split. * @param needle The text to search for in `self`. * @return The part of `self` up to the first occurrence of `delim`. */ function split(slice memory self, slice memory needle) internal pure returns (slice memory token) { split(self, needle, token); } /* * @dev Splits the slice, setting `self` to everything before the last * occurrence of `needle`, and `token` to everything after it. If * `needle` does not occur in `self`, `self` is set to the empty slice, * and `token` is set to the entirety of `self`. * @param self The slice to split. * @param needle The text to search for in `self`. * @param token An output parameter to which the first token is written. * @return `token`. */ function rsplit(slice memory self, slice memory needle, slice memory token) internal pure returns (slice memory) { uint ptr = rfindPtr(self._len, self._ptr, needle._len, needle._ptr); token._ptr = ptr; token._len = self._len - (ptr - self._ptr); if (ptr == self._ptr) { // Not found self._len = 0; } else { self._len -= token._len + needle._len; } return token; } /* * @dev Splits the slice, setting `self` to everything before the last * occurrence of `needle`, and returning everything after it. If * `needle` does not occur in `self`, `self` is set to the empty slice, * and the entirety of `self` is returned. * @param self The slice to split. * @param needle The text to search for in `self`. * @return The part of `self` after the last occurrence of `delim`. */ function rsplit(slice memory self, slice memory needle) internal pure returns (slice memory token) { rsplit(self, needle, token); } /* * @dev Counts the number of nonoverlapping occurrences of `needle` in `self`. * @param self The slice to search. * @param needle The text to search for in `self`. * @return The number of occurrences of `needle` found in `self`. */ function count(slice memory self, slice memory needle) internal pure returns (uint cnt) { uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr) + needle._len; while (ptr <= self._ptr + self._len) { cnt++; ptr = findPtr(self._len - (ptr - self._ptr), ptr, needle._len, needle._ptr) + needle._len; } } /* * @dev Returns True if `self` contains `needle`. * @param self The slice to search. * @param needle The text to search for in `self`. * @return True if `needle` is found in `self`, false otherwise. */ function contains(slice memory self, slice memory needle) internal pure returns (bool) { return rfindPtr(self._len, self._ptr, needle._len, needle._ptr) != self._ptr; } /* * @dev Returns a newly allocated string containing the concatenation of * `self` and `other`. * @param self The first slice to concatenate. * @param other The second slice to concatenate. * @return The concatenation of the two strings. */ function concat(slice memory self, slice memory other) internal pure returns (string memory) { string memory ret = new string(self._len + other._len); uint retptr; assembly { retptr := add(ret, 32) } memcpy(retptr, self._ptr, self._len); memcpy(retptr + self._len, other._ptr, other._len); return ret; } /* * @dev Joins an array of slices, using `self` as a delimiter, returning a * newly allocated string. * @param self The delimiter to use. * @param parts A list of slices to join. * @return A newly allocated string containing all the slices in `parts`, * joined with `self`. */ function join(slice memory self, slice[] memory parts) internal pure returns (string memory) { if (parts.length == 0) return ""; uint length = self._len * (parts.length - 1); for(uint i = 0; i < parts.length; i++) length += parts[i]._len; string memory ret = new string(length); uint retptr; assembly { retptr := add(ret, 32) } for(i = 0; i < parts.length; i++) { memcpy(retptr, parts[i]._ptr, parts[i]._len); retptr += parts[i]._len; if (i < parts.length - 1) { memcpy(retptr, self._ptr, self._len); retptr += self._len; } } return ret; } } /** * @title ENSConsumer * @dev Helper contract to resolve ENS names. * @author Julien Niset - <[email protected]> */ contract ENSConsumer { using strings for *; // namehash('addr.reverse') bytes32 constant public ADDR_REVERSE_NODE = 0x91d1777781884d03a6757a803996e38de2a42967fb37eeaca72729271025a9e2; // the address of the ENS registry address ensRegistry; /** * @dev No address should be provided when deploying on Mainnet to avoid storage cost. The * contract will use the hardcoded value. */ constructor(address _ensRegistry) public { ensRegistry = _ensRegistry; } /** * @dev Resolves an ENS name to an address. * @param _node The namehash of the ENS name. */ function resolveEns(bytes32 _node) public view returns (address) { address resolver = getENSRegistry().resolver(_node); return ENSResolver(resolver).addr(_node); } /** * @dev Gets the official ENS registry. */ function getENSRegistry() public view returns (ENSRegistry) { return ENSRegistry(ensRegistry); } /** * @dev Gets the official ENS reverse registrar. */ function getENSReverseRegistrar() public view returns (ENSReverseRegistrar) { return ENSReverseRegistrar(getENSRegistry().owner(ADDR_REVERSE_NODE)); } } /** * @dev Interface for an ENS Mananger. */ interface IENSManager { function changeRootnodeOwner(address _newOwner) external; function register(string _label, address _owner) external; function isAvailable(bytes32 _subnode) external view returns(bool); } /** * @title Proxy * @dev Basic proxy that delegates all calls to a fixed implementing contract. * The implementing contract cannot be upgraded. * @author Julien Niset - <[email protected]> */ contract Proxy { address implementation; event Received(uint indexed value, address indexed sender, bytes data); constructor(address _implementation) public { implementation = _implementation; } function() external payable { if(msg.data.length == 0 && msg.value > 0) { emit Received(msg.value, msg.sender, msg.data); } else { // solium-disable-next-line security/no-inline-assembly assembly { let target := sload(0) calldatacopy(0, 0, calldatasize()) let result := delegatecall(gas, target, 0, calldatasize(), 0, 0) returndatacopy(0, 0, returndatasize()) switch result case 0 {revert(0, returndatasize())} default {return (0, returndatasize())} } } } } /** * @title Module * @dev Interface for a module. * A module MUST implement the addModule() method to ensure that a wallet with at least one module * can never end up in a "frozen" state. * @author Julien Niset - <[email protected]> */ interface Module { /** * @dev Inits a module for a wallet by e.g. setting some wallet specific parameters in storage. * @param _wallet The wallet. */ function init(BaseWallet _wallet) external; /** * @dev Adds a module to a wallet. * @param _wallet The target wallet. * @param _module The modules to authorise. */ function addModule(BaseWallet _wallet, Module _module) external; /** * @dev Utility method to recover any ERC20 token that was sent to the * module by mistake. * @param _token The token to recover. */ function recoverToken(address _token) external; } /** * @title BaseWallet * @dev Simple modular wallet that authorises modules to call its invoke() method. * Based on https://gist.github.com/Arachnid/a619d31f6d32757a4328a428286da186 by * @author Julien Niset - <[email protected]> */ contract BaseWallet { // The implementation of the proxy address public implementation; // The owner address public owner; // The authorised modules mapping (address => bool) public authorised; // The enabled static calls mapping (bytes4 => address) public enabled; // The number of modules uint public modules; event AuthorisedModule(address indexed module, bool value); event EnabledStaticCall(address indexed module, bytes4 indexed method); event Invoked(address indexed module, address indexed target, uint indexed value, bytes data); event Received(uint indexed value, address indexed sender, bytes data); event OwnerChanged(address owner); /** * @dev Throws if the sender is not an authorised module. */ modifier moduleOnly { require(authorised[msg.sender], "BW: msg.sender not an authorized module"); _; } /** * @dev Inits the wallet by setting the owner and authorising a list of modules. * @param _owner The owner. * @param _modules The modules to authorise. */ function init(address _owner, address[] _modules) external { require(owner == address(0) && modules == 0, "BW: wallet already initialised"); require(_modules.length > 0, "BW: construction requires at least 1 module"); owner = _owner; modules = _modules.length; for(uint256 i = 0; i < _modules.length; i++) { require(authorised[_modules[i]] == false, "BW: module is already added"); authorised[_modules[i]] = true; Module(_modules[i]).init(this); emit AuthorisedModule(_modules[i], true); } } /** * @dev Enables/Disables a module. * @param _module The target module. * @param _value Set to true to authorise the module. */ function authoriseModule(address _module, bool _value) external moduleOnly { if (authorised[_module] != _value) { if(_value == true) { modules += 1; authorised[_module] = true; Module(_module).init(this); } else { modules -= 1; require(modules > 0, "BW: wallet must have at least one module"); delete authorised[_module]; } emit AuthorisedModule(_module, _value); } } /** * @dev Enables a static method by specifying the target module to which the call * must be delegated. * @param _module The target module. * @param _method The static method signature. */ function enableStaticCall(address _module, bytes4 _method) external moduleOnly { require(authorised[_module], "BW: must be an authorised module for static call"); enabled[_method] = _module; emit EnabledStaticCall(_module, _method); } /** * @dev Sets a new owner for the wallet. * @param _newOwner The new owner. */ function setOwner(address _newOwner) external moduleOnly { require(_newOwner != address(0), "BW: address cannot be null"); owner = _newOwner; emit OwnerChanged(_newOwner); } /** * @dev Performs a generic transaction. * @param _target The address for the transaction. * @param _value The value of the transaction. * @param _data The data of the transaction. */ function invoke(address _target, uint _value, bytes _data) external moduleOnly { // solium-disable-next-line security/no-call-value require(_target.call.value(_value)(_data), "BW: call to target failed"); emit Invoked(msg.sender, _target, _value, _data); } /** * @dev This method makes it possible for the wallet to comply to interfaces expecting the wallet to * implement specific static methods. It delegates the static call to a target contract if the data corresponds * to an enabled method, or logs the call otherwise. */ function() public payable { if(msg.data.length > 0) { address module = enabled[msg.sig]; if(module == address(0)) { emit Received(msg.value, msg.sender, msg.data); } else { require(authorised[module], "BW: must be an authorised module for static call"); // solium-disable-next-line security/no-inline-assembly assembly { calldatacopy(0, 0, calldatasize()) let result := staticcall(gas, module, 0, calldatasize(), 0, 0) returndatacopy(0, 0, returndatasize()) switch result case 0 {revert(0, returndatasize())} default {return (0, returndatasize())} } } } } } /** * ERC20 contract interface. */ contract ERC20 { function totalSupply() public view returns (uint); function decimals() public view returns (uint); function balanceOf(address tokenOwner) public view returns (uint balance); function allowance(address tokenOwner, address spender) public view 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); } /** * @title ModuleRegistry * @dev Registry of authorised modules. * Modules must be registered before they can be authorised on a wallet. * @author Julien Niset - <[email protected]> */ contract ModuleRegistry is Owned { mapping (address => Info) internal modules; mapping (address => Info) internal upgraders; event ModuleRegistered(address indexed module, bytes32 name); event ModuleDeRegistered(address module); event UpgraderRegistered(address indexed upgrader, bytes32 name); event UpgraderDeRegistered(address upgrader); struct Info { bool exists; bytes32 name; } /** * @dev Registers a module. * @param _module The module. * @param _name The unique name of the module. */ function registerModule(address _module, bytes32 _name) external onlyOwner { require(!modules[_module].exists, "MR: module already exists"); modules[_module] = Info({exists: true, name: _name}); emit ModuleRegistered(_module, _name); } /** * @dev Deregisters a module. * @param _module The module. */ function deregisterModule(address _module) external onlyOwner { require(modules[_module].exists, "MR: module does not exists"); delete modules[_module]; emit ModuleDeRegistered(_module); } /** * @dev Registers an upgrader. * @param _upgrader The upgrader. * @param _name The unique name of the upgrader. */ function registerUpgrader(address _upgrader, bytes32 _name) external onlyOwner { require(!upgraders[_upgrader].exists, "MR: upgrader already exists"); upgraders[_upgrader] = Info({exists: true, name: _name}); emit UpgraderRegistered(_upgrader, _name); } /** * @dev Deregisters an upgrader. * @param _upgrader The _upgrader. */ function deregisterUpgrader(address _upgrader) external onlyOwner { require(upgraders[_upgrader].exists, "MR: upgrader does not exists"); delete upgraders[_upgrader]; emit UpgraderDeRegistered(_upgrader); } /** * @dev Utility method enbaling the owner of the registry to claim any ERC20 token that was sent to the * registry. * @param _token The token to recover. */ function recoverToken(address _token) external onlyOwner { uint total = ERC20(_token).balanceOf(address(this)); ERC20(_token).transfer(msg.sender, total); } /** * @dev Gets the name of a module from its address. * @param _module The module address. * @return the name. */ function moduleInfo(address _module) external view returns (bytes32) { return modules[_module].name; } /** * @dev Gets the name of an upgrader from its address. * @param _upgrader The upgrader address. * @return the name. */ function upgraderInfo(address _upgrader) external view returns (bytes32) { return upgraders[_upgrader].name; } /** * @dev Checks if a module is registered. * @param _module The module address. * @return true if the module is registered. */ function isRegisteredModule(address _module) external view returns (bool) { return modules[_module].exists; } /** * @dev Checks if a list of modules are registered. * @param _modules The list of modules address. * @return true if all the modules are registered. */ function isRegisteredModule(address[] _modules) external view returns (bool) { for(uint i = 0; i < _modules.length; i++) { if (!modules[_modules[i]].exists) { return false; } } return true; } /** * @dev Checks if an upgrader is registered. * @param _upgrader The upgrader address. * @return true if the upgrader is registered. */ function isRegisteredUpgrader(address _upgrader) external view returns (bool) { return upgraders[_upgrader].exists; } } /** * @title WalletFactory * @dev The WalletFactory contract creates and assigns wallets to accounts. * @author Julien Niset - <[email protected]> */ contract WalletFactory is Owned, Managed, ENSConsumer { // The address of the module registry address public moduleRegistry; // The address of the base wallet implementation address public walletImplementation; // The address of the ENS manager address public ensManager; // The address of the ENS resolver address public ensResolver; // *************** Events *************************** // event ModuleRegistryChanged(address addr); event WalletImplementationChanged(address addr); event ENSManagerChanged(address addr); event ENSResolverChanged(address addr); event WalletCreated(address indexed _wallet, address indexed _owner); // *************** Constructor ********************** // /** * @dev Default constructor. */ constructor( address _ensRegistry, address _moduleRegistry, address _walletImplementation, address _ensManager, address _ensResolver ) ENSConsumer(_ensRegistry) public { moduleRegistry = _moduleRegistry; walletImplementation = _walletImplementation; ensManager = _ensManager; ensResolver = _ensResolver; } // *************** External Functions ********************* // /** * @dev Lets the manager create a wallet for an account. The wallet is initialised with a list of modules. * @param _owner The account address. * @param _modules The list of modules. * @param _label Optional ENS label of the new wallet (e.g. franck). */ function createWallet(address _owner, address[] _modules, string _label) external onlyManager { require(_owner != address(0), "WF: owner cannot be null"); require(_modules.length > 0, "WF: cannot assign with less than 1 module"); require(ModuleRegistry(moduleRegistry).isRegisteredModule(_modules), "WF: one or more modules are not registered"); // create the proxy Proxy proxy = new Proxy(walletImplementation); address wallet = address(proxy); // check for ENS bytes memory labelBytes = bytes(_label); if (labelBytes.length != 0) { // add the factory to the modules so it can claim the reverse ENS address[] memory extendedModules = new address[](_modules.length + 1); extendedModules[0] = address(this); for(uint i = 0; i < _modules.length; i++) { extendedModules[i + 1] = _modules[i]; } // initialise the wallet with the owner and the extended modules BaseWallet(wallet).init(_owner, extendedModules); // register ENS registerWalletENS(wallet, _label); // remove the factory from the authorised modules BaseWallet(wallet).authoriseModule(address(this), false); } else { // initialise the wallet with the owner and the modules BaseWallet(wallet).init(_owner, _modules); } emit WalletCreated(wallet, _owner); } /** * @dev Lets the owner change the address of the module registry contract. * @param _moduleRegistry The address of the module registry contract. */ function changeModuleRegistry(address _moduleRegistry) external onlyOwner { require(_moduleRegistry != address(0), "WF: address cannot be null"); moduleRegistry = _moduleRegistry; emit ModuleRegistryChanged(_moduleRegistry); } /** * @dev Lets the owner change the address of the implementing contract. * @param _walletImplementation The address of the implementing contract. */ function changeWalletImplementation(address _walletImplementation) external onlyOwner { require(_walletImplementation != address(0), "WF: address cannot be null"); walletImplementation = _walletImplementation; emit WalletImplementationChanged(_walletImplementation); } /** * @dev Lets the owner change the address of the ENS manager contract. * @param _ensManager The address of the ENS manager contract. */ function changeENSManager(address _ensManager) external onlyOwner { require(_ensManager != address(0), "WF: address cannot be null"); ensManager = _ensManager; emit ENSManagerChanged(_ensManager); } /** * @dev Lets the owner change the address of the ENS resolver contract. * @param _ensResolver The address of the ENS resolver contract. */ function changeENSResolver(address _ensResolver) external onlyOwner { require(_ensResolver != address(0), "WF: address cannot be null"); ensResolver = _ensResolver; emit ENSResolverChanged(_ensResolver); } /** * @dev Register an ENS subname to a wallet. * @param _wallet The wallet address. * @param _label ENS label of the new wallet (e.g. franck). */ function registerWalletENS(address _wallet, string _label) internal { // claim reverse bytes memory methodData = abi.encodeWithSignature("claimWithResolver(address,address)", ensManager, ensResolver); BaseWallet(_wallet).invoke(getENSReverseRegistrar(), 0, methodData); // register with ENS manager IENSManager(ensManager).register(_label, _wallet); } /** * @dev Inits the module for a wallet by logging an event. * The method can only be called by the wallet itself. * @param _wallet The wallet. */ function init(BaseWallet _wallet) external pure { //do nothing } }
* @title WalletFactory @dev The WalletFactory contract creates and assigns wallets to accounts. @author Julien Niset - <[email protected]>/ The address of the module registry The address of the base wallet implementation The address of the ENS manager The address of the ENS resolver *************** Events *************************** *************** Constructor **********************
contract WalletFactory is Owned, Managed, ENSConsumer { address public moduleRegistry; address public walletImplementation; address public ensManager; address public ensResolver; event ModuleRegistryChanged(address addr); event WalletImplementationChanged(address addr); event ENSManagerChanged(address addr); event ENSResolverChanged(address addr); event WalletCreated(address indexed _wallet, address indexed _owner); constructor( address _ensRegistry, address _moduleRegistry, address _walletImplementation, address _ensManager, address _ensResolver ) ENSConsumer(_ensRegistry) public { moduleRegistry = _moduleRegistry; walletImplementation = _walletImplementation; ensManager = _ensManager; ensResolver = _ensResolver; } function createWallet(address _owner, address[] _modules, string _label) external onlyManager { require(_owner != address(0), "WF: owner cannot be null"); require(_modules.length > 0, "WF: cannot assign with less than 1 module"); require(ModuleRegistry(moduleRegistry).isRegisteredModule(_modules), "WF: one or more modules are not registered"); Proxy proxy = new Proxy(walletImplementation); address wallet = address(proxy); bytes memory labelBytes = bytes(_label); if (labelBytes.length != 0) { address[] memory extendedModules = new address[](_modules.length + 1); extendedModules[0] = address(this); for(uint i = 0; i < _modules.length; i++) { extendedModules[i + 1] = _modules[i]; } } emit WalletCreated(wallet, _owner); } function createWallet(address _owner, address[] _modules, string _label) external onlyManager { require(_owner != address(0), "WF: owner cannot be null"); require(_modules.length > 0, "WF: cannot assign with less than 1 module"); require(ModuleRegistry(moduleRegistry).isRegisteredModule(_modules), "WF: one or more modules are not registered"); Proxy proxy = new Proxy(walletImplementation); address wallet = address(proxy); bytes memory labelBytes = bytes(_label); if (labelBytes.length != 0) { address[] memory extendedModules = new address[](_modules.length + 1); extendedModules[0] = address(this); for(uint i = 0; i < _modules.length; i++) { extendedModules[i + 1] = _modules[i]; } } emit WalletCreated(wallet, _owner); } function createWallet(address _owner, address[] _modules, string _label) external onlyManager { require(_owner != address(0), "WF: owner cannot be null"); require(_modules.length > 0, "WF: cannot assign with less than 1 module"); require(ModuleRegistry(moduleRegistry).isRegisteredModule(_modules), "WF: one or more modules are not registered"); Proxy proxy = new Proxy(walletImplementation); address wallet = address(proxy); bytes memory labelBytes = bytes(_label); if (labelBytes.length != 0) { address[] memory extendedModules = new address[](_modules.length + 1); extendedModules[0] = address(this); for(uint i = 0; i < _modules.length; i++) { extendedModules[i + 1] = _modules[i]; } } emit WalletCreated(wallet, _owner); } BaseWallet(wallet).init(_owner, extendedModules); registerWalletENS(wallet, _label); BaseWallet(wallet).authoriseModule(address(this), false); } else { BaseWallet(wallet).init(_owner, _modules); function changeModuleRegistry(address _moduleRegistry) external onlyOwner { require(_moduleRegistry != address(0), "WF: address cannot be null"); moduleRegistry = _moduleRegistry; emit ModuleRegistryChanged(_moduleRegistry); } function changeWalletImplementation(address _walletImplementation) external onlyOwner { require(_walletImplementation != address(0), "WF: address cannot be null"); walletImplementation = _walletImplementation; emit WalletImplementationChanged(_walletImplementation); } function changeENSManager(address _ensManager) external onlyOwner { require(_ensManager != address(0), "WF: address cannot be null"); ensManager = _ensManager; emit ENSManagerChanged(_ensManager); } function changeENSResolver(address _ensResolver) external onlyOwner { require(_ensResolver != address(0), "WF: address cannot be null"); ensResolver = _ensResolver; emit ENSResolverChanged(_ensResolver); } function registerWalletENS(address _wallet, string _label) internal { bytes memory methodData = abi.encodeWithSignature("claimWithResolver(address,address)", ensManager, ensResolver); BaseWallet(_wallet).invoke(getENSReverseRegistrar(), 0, methodData); IENSManager(ensManager).register(_label, _wallet); } function init(BaseWallet _wallet) external pure { } }
12,791,892
[ 1, 16936, 1733, 225, 1021, 20126, 1733, 6835, 3414, 471, 22698, 17662, 2413, 358, 9484, 18, 225, 804, 14826, 275, 423, 291, 278, 300, 411, 28034, 275, 36, 3175, 319, 18, 17177, 16893, 1021, 1758, 434, 326, 1605, 4023, 1021, 1758, 434, 326, 1026, 9230, 4471, 1021, 1758, 434, 326, 512, 3156, 3301, 1021, 1758, 434, 326, 512, 3156, 5039, 225, 9043, 565, 11417, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 16351, 20126, 1733, 353, 14223, 11748, 16, 10024, 16, 512, 3156, 5869, 288, 203, 203, 565, 1758, 1071, 1605, 4243, 31, 203, 565, 1758, 1071, 9230, 13621, 31, 203, 565, 1758, 1071, 19670, 1318, 31, 203, 565, 1758, 1071, 19670, 4301, 31, 203, 203, 203, 565, 871, 5924, 4243, 5033, 12, 2867, 3091, 1769, 203, 565, 871, 20126, 13621, 5033, 12, 2867, 3091, 1769, 203, 565, 871, 512, 3156, 1318, 5033, 12, 2867, 3091, 1769, 203, 565, 871, 512, 3156, 4301, 5033, 12, 2867, 3091, 1769, 203, 565, 871, 20126, 6119, 12, 2867, 8808, 389, 19177, 16, 1758, 8808, 389, 8443, 1769, 203, 203, 203, 565, 3885, 12, 203, 3639, 1758, 389, 773, 4243, 16, 7010, 3639, 1758, 389, 2978, 4243, 16, 203, 3639, 1758, 389, 19177, 13621, 16, 7010, 3639, 1758, 389, 773, 1318, 16, 7010, 3639, 1758, 389, 773, 4301, 203, 565, 262, 7010, 3639, 512, 3156, 5869, 24899, 773, 4243, 13, 7010, 3639, 1071, 7010, 565, 288, 203, 3639, 1605, 4243, 273, 389, 2978, 4243, 31, 203, 3639, 9230, 13621, 273, 389, 19177, 13621, 31, 203, 3639, 19670, 1318, 273, 389, 773, 1318, 31, 203, 3639, 19670, 4301, 273, 389, 773, 4301, 31, 203, 565, 289, 203, 203, 203, 565, 445, 752, 16936, 12, 2867, 389, 8443, 16, 1758, 8526, 389, 6400, 16, 533, 389, 1925, 13, 3903, 1338, 1318, 288, 203, 3639, 2583, 24899, 8443, 480, 1758, 12, 20, 3631, 315, 59, 42, 30, 3410, 2780, 506, 446, 8863, 203, 3639, 2583, 24899, 6400, 18, 2469, 405, 374, 16, 315, 2 ]
./full_match/5/0x58A47EE9Acb7d618BE57F275f1FA717aC8F74bf3/sources/browser/token.sol
Increase the number of tokens
event IncreaseSupply(address indexed addr, uint256 value);
1,907,475
[ 1, 382, 11908, 326, 1300, 434, 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 ]
[ 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, 871, 657, 11908, 3088, 1283, 12, 2867, 8808, 3091, 16, 2254, 5034, 460, 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 ]
pragma solidity ^0.4.25; /** KPI is 100k USD (~ETH rate fix at start of contract) target selling period is 45 days*/ /** If NCryptBit reached 100k before 45 days -> payoff immediately 10% commission through `claim` function */ /** Pay 4k USD (in ETH) first installment of comission fee immediately after startTime (confirm purchased) `ONE day` (through claimFirstInstallment()) Remaining installment fee will be paid dependTime on KPI below: - Trunk payment period when reach partial KPI * 0 -> 15 date reach >=25k -> 1/3 Remaining Installment Fee (~2k USD) * 15 -> 30 date reach >=25k -> 1/3 Remaining Installment Fee (~2k USD) * 45 reach >=25k -> 1/3 Remaining Installment Fee (~2k USD) NOTE: Remaining ETH will refund to Triip through `refund` function at endTime of this campaign */ contract TriipInvestorsServices { event ConfirmPurchase(address _sender, uint _startTime, uint _amount); event Payoff(address _seller, uint _amount, uint _kpi); event Refund(address _buyer, uint _amount); event Claim(address _sender, uint _counting, uint _buyerWalletBalance); enum PaidStage { NONE, FIRST_PAYMENT, SECOND_PAYMENT, FINAL_PAYMENT } uint public KPI_0k = 0; uint public KPI_25k = 25; uint public KPI_50k = 50; uint public KPI_100k = 100; address public seller; // NCriptBit address public buyer; // Triip Protocol wallet use for refunding address public buyerWallet; // Triip Protocol's raising ETH wallet uint public startTime = 0; uint public endTime = 0; bool public isEnd = false; uint decimals = 18; uint unit = 10 ** decimals; uint public paymentAmount = 69 * unit; // 69 ETH equals to 10k USD upfront, fixed at deploy of contract manually uint public targetSellingAmount = 10 * paymentAmount; // 690 ETH equals to 100k USD upfront uint claimCounting = 0; PaidStage public paidStage = PaidStage.NONE; uint public balance; // Begin: only for testing // function setPaymentAmount(uint _paymentAmount) public returns (bool) { // paymentAmount = _paymentAmount; // return true; // } // function setStartTime(uint _startTime) public returns (bool) { // startTime = _startTime; // return true; // } // function setEndTime(uint _endTime) public returns (bool) { // endTime = _endTime; // return true; // } // function getNow() public view returns (uint) { // return now; // } // End: only for testing constructor(address _buyer, address _seller, address _buyerWallet) public { seller = _seller; buyer = _buyer; buyerWallet = _buyerWallet; } modifier whenNotEnd() { require(!isEnd, "This contract should not be endTime") ; _; } function confirmPurchase() public payable { // Trigger by Triip with the ETH amount agreed for installment require(startTime == 0); require(msg.value == paymentAmount, "Not equal installment fee"); startTime = now; endTime = startTime + ( 45 * 1 days ); balance += msg.value; emit ConfirmPurchase(msg.sender, startTime, balance); } function contractEthBalance() public view returns (uint) { return balance; } function buyerWalletBalance() public view returns (uint) { return address(buyerWallet).balance; } function claimFirstInstallment() public whenNotEnd returns (bool) { require(paidStage == PaidStage.NONE, "First installment has already been claimed"); require(now >= startTime + 1 days, "Require first installment fee to be claimed after startTime + 1 day"); uint payoffAmount = balance * 40 / 100; // 40% of agreed commission // update balance balance = balance - payoffAmount; // ~5k gas as of writing seller.transfer(payoffAmount); // ~21k gas as of writing emit Payoff(seller, payoffAmount, KPI_0k ); emit Claim(msg.sender, claimCounting, buyerWalletBalance()); return true; } function claim() public whenNotEnd returns (uint) { claimCounting = claimCounting + 1; uint payoffAmount = 0; uint sellingAmount = targetSellingAmount; uint buyerBalance = buyerWalletBalance(); emit Claim(msg.sender, claimCounting, buyerWalletBalance()); if ( buyerBalance >= sellingAmount ) { payoffAmount = balance; seller.transfer(payoffAmount); paidStage = PaidStage.FINAL_PAYMENT; balance = 0; endContract(); emit Payoff(seller, payoffAmount, KPI_100k); } else { payoffAmount = claimByKPI(); } return payoffAmount; } function claimByKPI() private returns (uint) { uint payoffAmount = 0; uint sellingAmount = targetSellingAmount; uint buyerBalance = buyerWalletBalance(); if ( buyerBalance >= ( sellingAmount * KPI_50k / 100) && now >= (startTime + ( 30 * 1 days) ) ) { uint paidPercent = 66; if ( paidStage == PaidStage.NONE) { paidPercent = 66; // 66% of 6k installment equals 4k }else if( paidStage == PaidStage.FIRST_PAYMENT) { // 33 % of total balance // 50% of remaining balance paidPercent = 50; } payoffAmount = balance * paidPercent / 100; // update balance balance = balance - payoffAmount; seller.transfer(payoffAmount); emit Payoff(seller, payoffAmount, KPI_50k); paidStage = PaidStage.SECOND_PAYMENT; } if( buyerBalance >= ( sellingAmount * KPI_25k / 100) && now >= (startTime + (15 * 1 days) ) && paidStage == PaidStage.NONE ) { payoffAmount = balance * 33 / 100; // update balance balance = balance - payoffAmount; seller.transfer(payoffAmount); emit Payoff(seller, payoffAmount, KPI_25k ); paidStage = PaidStage.FIRST_PAYMENT; } if(now >= (startTime + (45 * 1 days) )) { endContract(); } return payoffAmount; } function endContract() private { isEnd = true; } function refund() public returns (uint) { require(now >= endTime); // refund remaining balance uint refundAmount = address(this).balance; buyer.transfer(refundAmount); emit Refund(buyer, refundAmount); return refundAmount; } }
690 ETH equals to 100k USD upfront
uint public targetSellingAmount = 10 * paymentAmount;
7,321,068
[ 1, 8148, 20, 512, 2455, 1606, 358, 2130, 79, 587, 9903, 731, 10211, 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, 2254, 1071, 1018, 55, 1165, 310, 6275, 273, 1728, 380, 5184, 6275, 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 ]
./full_match/42/0x6A54479384df17514d4A2f8E02268a6B5136001a/sources/contracts/Presale-ETH.sol
Defining Initial Parameters */
function deposit(uint amount) payable public { require(stakingStart < block.timestamp, "Presale not started"); require(end > block.timestamp, "Presale ended"); IERC20(depositToken).transferFrom(_msgSender(), address(this), amount); if(presale_contribution[msg.sender] == 0) { currentPoolParticipants = currentPoolParticipants.add(1); } accounting_contribution[msg.sender] = accounting_contribution[msg.sender].add(amount); presale_contribution[msg.sender] = presale_contribution[msg.sender].add(amount); currentPoolAmount = currentPoolAmount.add(amount); }
16,233,632
[ 1, 6443, 310, 10188, 7012, 342, 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, 443, 1724, 12, 11890, 3844, 13, 8843, 429, 1071, 288, 203, 3639, 2583, 12, 334, 6159, 1685, 411, 1203, 18, 5508, 16, 315, 12236, 5349, 486, 5746, 8863, 203, 3639, 2583, 12, 409, 405, 1203, 18, 5508, 16, 315, 12236, 5349, 16926, 8863, 203, 203, 3639, 467, 654, 39, 3462, 12, 323, 1724, 1345, 2934, 13866, 1265, 24899, 3576, 12021, 9334, 1758, 12, 2211, 3631, 3844, 1769, 203, 540, 203, 3639, 309, 12, 12202, 5349, 67, 591, 4027, 63, 3576, 18, 15330, 65, 422, 374, 13, 288, 203, 5411, 783, 2864, 1988, 27620, 273, 783, 2864, 1988, 27620, 18, 1289, 12, 21, 1769, 203, 3639, 289, 203, 540, 203, 3639, 2236, 310, 67, 591, 4027, 63, 3576, 18, 15330, 65, 273, 2236, 310, 67, 591, 4027, 63, 3576, 18, 15330, 8009, 1289, 12, 8949, 1769, 203, 3639, 4075, 5349, 67, 591, 4027, 63, 3576, 18, 15330, 65, 273, 4075, 5349, 67, 591, 4027, 63, 3576, 18, 15330, 8009, 1289, 12, 8949, 1769, 203, 3639, 783, 2864, 6275, 273, 783, 2864, 6275, 18, 1289, 12, 8949, 1769, 27699, 565, 289, 21281, 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 ]
/** *Submitted for verification at Etherscan.io on 2018-06-12 */ pragma solidity ^0.4.13; library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } 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 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; } /** * @dev Allows the current owner to relinquish control of the contract. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } } 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 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 ); } library ArrayUtils { /** * Replace bytes in an array with bytes in another array, guarded by a bitmask * Efficiency of this function is a bit unpredictable because of the EVM's word-specific model (arrays under 32 bytes will be slower) * * @dev Mask must be the size of the byte array. A nonzero byte means the byte array can be changed. * @param array The original array * @param desired The target array * @param mask The mask specifying which bits can be changed * @return The updated byte array (the parameter will be modified inplace) */ function guardedArrayReplace(bytes memory array, bytes memory desired, bytes memory mask) internal pure { require(array.length == desired.length); require(array.length == mask.length); uint words = array.length / 0x20; uint index = words * 0x20; assert(index / 0x20 == words); uint i; for (i = 0; i < words; i++) { /* Conceptually: array[i] = (!mask[i] && array[i]) || (mask[i] && desired[i]), bitwise in word chunks. */ assembly { let commonIndex := mul(0x20, add(1, i)) let maskValue := mload(add(mask, commonIndex)) mstore(add(array, commonIndex), or(and(not(maskValue), mload(add(array, commonIndex))), and(maskValue, mload(add(desired, commonIndex))))) } } /* Deal with the last section of the byte array. */ if (words > 0) { /* This overlaps with bytes already set but is still more efficient than iterating through each of the remaining bytes individually. */ i = words; assembly { let commonIndex := mul(0x20, add(1, i)) let maskValue := mload(add(mask, commonIndex)) mstore(add(array, commonIndex), or(and(not(maskValue), mload(add(array, commonIndex))), and(maskValue, mload(add(desired, commonIndex))))) } } else { /* If the byte array is shorter than a word, we must unfortunately do the whole thing bytewise. (bounds checks could still probably be optimized away in assembly, but this is a rare case) */ for (i = index; i < array.length; i++) { array[i] = ((mask[i] ^ 0xff) & array[i]) | (mask[i] & desired[i]); } } } /** * Test if two arrays are equal * Source: https://github.com/GNSPS/solidity-bytes-utils/blob/master/contracts/BytesLib.sol * * @dev Arrays must be of equal length, otherwise will return false * @param a First array * @param b Second array * @return Whether or not all bytes in the arrays are equal */ function arrayEq(bytes memory a, bytes memory b) internal pure returns (bool) { bool success = true; assembly { let length := mload(a) // if lengths don't match the arrays are not equal switch eq(length, mload(b)) case 1 { // cb is a circuit breaker in the for loop since there's // no said feature for inline assembly loops // cb = 1 - don't breaker // cb = 0 - break let cb := 1 let mc := add(a, 0x20) let end := add(mc, length) for { let cc := add(b, 0x20) // the next line is the loop condition: // while(uint(mc < end) + cb == 2) } eq(add(lt(mc, end), cb), 2) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { // if any of these checks fails then arrays are not equal if iszero(eq(mload(mc), mload(cc))) { // unsuccess: success := 0 cb := 0 } } } default { // unsuccess: success := 0 } } return success; } /** * Unsafe write byte array into a memory location * * @param index Memory location * @param source Byte array to write * @return End memory index */ function unsafeWriteBytes(uint index, bytes source) internal pure returns (uint) { if (source.length > 0) { assembly { let length := mload(source) let end := add(source, add(0x20, length)) let arrIndex := add(source, 0x20) let tempIndex := index for { } eq(lt(arrIndex, end), 1) { arrIndex := add(arrIndex, 0x20) tempIndex := add(tempIndex, 0x20) } { mstore(tempIndex, mload(arrIndex)) } index := add(index, length) } } return index; } /** * Unsafe write address into a memory location * * @param index Memory location * @param source Address to write * @return End memory index */ function unsafeWriteAddress(uint index, address source) internal pure returns (uint) { uint conv = uint(source) << 0x60; assembly { mstore(index, conv) index := add(index, 0x14) } return index; } /** * Unsafe write uint into a memory location * * @param index Memory location * @param source uint to write * @return End memory index */ function unsafeWriteUint(uint index, uint source) internal pure returns (uint) { assembly { mstore(index, source) index := add(index, 0x20) } return index; } /** * Unsafe write uint8 into a memory location * * @param index Memory location * @param source uint8 to write * @return End memory index */ function unsafeWriteUint8(uint index, uint8 source) internal pure returns (uint) { assembly { mstore8(index, source) index := add(index, 0x1) } return index; } } contract ReentrancyGuarded { bool reentrancyLock = false; /* Prevent a contract function from being reentrant-called. */ modifier reentrancyGuard { if (reentrancyLock) { revert(); } reentrancyLock = true; _; reentrancyLock = false; } } contract TokenRecipient { event ReceivedEther(address indexed sender, uint amount); event ReceivedTokens(address indexed from, uint256 value, address indexed token, bytes extraData); /** * @dev Receive tokens and generate a log event * @param from Address from which to transfer tokens * @param value Amount of tokens to transfer * @param token Address of token * @param extraData Additional data to log */ function receiveApproval(address from, uint256 value, address token, bytes extraData) public { ERC20 t = ERC20(token); require(t.transferFrom(from, this, value)); emit ReceivedTokens(from, value, token, extraData); } /** * @dev Receive Ether and generate a log event */ function () payable public { emit ReceivedEther(msg.sender, msg.value); } } contract ExchangeCore is ReentrancyGuarded, Ownable { /* The token used to pay exchange fees. */ ERC20 public exchangeToken; /* User registry. */ ProxyRegistry public registry; /* Token transfer proxy. */ TokenTransferProxy public tokenTransferProxy; /* Cancelled / finalized orders, by hash. */ mapping(bytes32 => bool) public cancelledOrFinalized; /* Orders verified by on-chain approval (alternative to ECDSA signatures so that smart contracts can place orders directly). */ mapping(bytes32 => bool) public approvedOrders; /* For split fee orders, minimum required protocol maker fee, in basis points. Paid to owner (who can change it). */ uint public minimumMakerProtocolFee = 0; /* For split fee orders, minimum required protocol taker fee, in basis points. Paid to owner (who can change it). */ uint public minimumTakerProtocolFee = 0; /* Recipient of protocol fees. */ address public protocolFeeRecipient; /* Fee method: protocol fee or split fee. */ enum FeeMethod { ProtocolFee, SplitFee } /* Inverse basis point. */ uint public constant INVERSE_BASIS_POINT = 10000; /* An ECDSA signature. */ struct Sig { /* v parameter */ uint8 v; /* r parameter */ bytes32 r; /* s parameter */ bytes32 s; } /* An order on the exchange. */ struct Order { /* Exchange address, intended as a versioning mechanism. */ address exchange; /* Order maker address. */ address maker; /* Order taker address, if specified. */ address taker; /* Maker relayer fee of the order, unused for taker order. */ uint makerRelayerFee; /* Taker relayer fee of the order, or maximum taker fee for a taker order. */ uint takerRelayerFee; /* Maker protocol fee of the order, unused for taker order. */ uint makerProtocolFee; /* Taker protocol fee of the order, or maximum taker fee for a taker order. */ uint takerProtocolFee; /* Order fee recipient or zero address for taker order. */ address feeRecipient; /* Fee method (protocol token or split fee). */ FeeMethod feeMethod; /* Side (buy/sell). */ SaleKindInterface.Side side; /* Kind of sale. */ SaleKindInterface.SaleKind saleKind; /* Target. */ address target; /* HowToCall. */ AuthenticatedProxy.HowToCall howToCall; /* Calldata. */ bytes calldata; /* Calldata replacement pattern, or an empty byte array for no replacement. */ bytes replacementPattern; /* Static call target, zero-address for no static call. */ address staticTarget; /* Static call extra data. */ bytes staticExtradata; /* Token used to pay for the order, or the zero-address as a sentinel value for Ether. */ address paymentToken; /* Base price of the order (in paymentTokens). */ uint basePrice; /* Auction extra parameter - minimum bid increment for English auctions, starting/ending price difference. */ uint extra; /* Listing timestamp. */ uint listingTime; /* Expiration timestamp - 0 for no expiry. */ uint expirationTime; /* Order salt, used to prevent duplicate hashes. */ uint salt; } event OrderApprovedPartOne (bytes32 indexed hash, address exchange, address indexed maker, address taker, uint makerRelayerFee, uint takerRelayerFee, uint makerProtocolFee, uint takerProtocolFee, address indexed feeRecipient, FeeMethod feeMethod, SaleKindInterface.Side side, SaleKindInterface.SaleKind saleKind, address target); event OrderApprovedPartTwo (bytes32 indexed hash, AuthenticatedProxy.HowToCall howToCall, bytes calldata, bytes replacementPattern, address staticTarget, bytes staticExtradata, address paymentToken, uint basePrice, uint extra, uint listingTime, uint expirationTime, uint salt, bool orderbookInclusionDesired); event OrderCancelled (bytes32 indexed hash); event OrdersMatched (bytes32 buyHash, bytes32 sellHash, address indexed maker, address indexed taker, uint price, bytes32 indexed metadata); /** * @dev Change the minimum maker fee paid to the protocol (owner only) * @param newMinimumMakerProtocolFee New fee to set in basis points */ function changeMinimumMakerProtocolFee(uint newMinimumMakerProtocolFee) public onlyOwner { minimumMakerProtocolFee = newMinimumMakerProtocolFee; } /** * @dev Change the minimum taker fee paid to the protocol (owner only) * @param newMinimumTakerProtocolFee New fee to set in basis points */ function changeMinimumTakerProtocolFee(uint newMinimumTakerProtocolFee) public onlyOwner { minimumTakerProtocolFee = newMinimumTakerProtocolFee; } /** * @dev Change the protocol fee recipient (owner only) * @param newProtocolFeeRecipient New protocol fee recipient address */ function changeProtocolFeeRecipient(address newProtocolFeeRecipient) public onlyOwner { protocolFeeRecipient = newProtocolFeeRecipient; } /** * @dev Transfer tokens * @param token Token to transfer * @param from Address to charge fees * @param to Address to receive fees * @param amount Amount of protocol tokens to charge */ function transferTokens(address token, address from, address to, uint amount) internal { if (amount > 0) { require(tokenTransferProxy.transferFrom(token, from, to, amount)); } } /** * @dev Charge a fee in protocol tokens * @param from Address to charge fees * @param to Address to receive fees * @param amount Amount of protocol tokens to charge */ function chargeProtocolFee(address from, address to, uint amount) internal { transferTokens(exchangeToken, from, to, amount); } /** * @dev Execute a STATICCALL (introduced with Ethereum Metropolis, non-state-modifying external call) * @param target Contract to call * @param calldata Calldata (appended to extradata) * @param extradata Base data for STATICCALL (probably function selector and argument encoding) * @return The result of the call (success or failure) */ function staticCall(address target, bytes memory calldata, bytes memory extradata) public view returns (bool result) { bytes memory combined = new bytes(calldata.length + extradata.length); uint index; assembly { index := add(combined, 0x20) } index = ArrayUtils.unsafeWriteBytes(index, extradata); ArrayUtils.unsafeWriteBytes(index, calldata); assembly { result := staticcall(gas, target, add(combined, 0x20), mload(combined), mload(0x40), 0) } return result; } /** * Calculate size of an order struct when tightly packed * * @param order Order to calculate size of * @return Size in bytes */ function sizeOf(Order memory order) internal pure returns (uint) { return ((0x14 * 7) + (0x20 * 9) + 4 + order.calldata.length + order.replacementPattern.length + order.staticExtradata.length); } /** * @dev Hash an order, returning the canonical order hash, without the message prefix * @param order Order to hash * @return Hash of order */ function hashOrder(Order memory order) internal pure returns (bytes32 hash) { /* Unfortunately abi.encodePacked doesn't work here, stack size constraints. */ uint size = sizeOf(order); bytes memory array = new bytes(size); uint index; assembly { index := add(array, 0x20) } index = ArrayUtils.unsafeWriteAddress(index, order.exchange); index = ArrayUtils.unsafeWriteAddress(index, order.maker); index = ArrayUtils.unsafeWriteAddress(index, order.taker); index = ArrayUtils.unsafeWriteUint(index, order.makerRelayerFee); index = ArrayUtils.unsafeWriteUint(index, order.takerRelayerFee); index = ArrayUtils.unsafeWriteUint(index, order.makerProtocolFee); index = ArrayUtils.unsafeWriteUint(index, order.takerProtocolFee); index = ArrayUtils.unsafeWriteAddress(index, order.feeRecipient); index = ArrayUtils.unsafeWriteUint8(index, uint8(order.feeMethod)); index = ArrayUtils.unsafeWriteUint8(index, uint8(order.side)); index = ArrayUtils.unsafeWriteUint8(index, uint8(order.saleKind)); index = ArrayUtils.unsafeWriteAddress(index, order.target); index = ArrayUtils.unsafeWriteUint8(index, uint8(order.howToCall)); index = ArrayUtils.unsafeWriteBytes(index, order.calldata); index = ArrayUtils.unsafeWriteBytes(index, order.replacementPattern); index = ArrayUtils.unsafeWriteAddress(index, order.staticTarget); index = ArrayUtils.unsafeWriteBytes(index, order.staticExtradata); index = ArrayUtils.unsafeWriteAddress(index, order.paymentToken); index = ArrayUtils.unsafeWriteUint(index, order.basePrice); index = ArrayUtils.unsafeWriteUint(index, order.extra); index = ArrayUtils.unsafeWriteUint(index, order.listingTime); index = ArrayUtils.unsafeWriteUint(index, order.expirationTime); index = ArrayUtils.unsafeWriteUint(index, order.salt); assembly { hash := keccak256(add(array, 0x20), size) } return hash; } /** * @dev Hash an order, returning the hash that a client must sign, including the standard message prefix * @param order Order to hash * @return Hash of message prefix and order hash per Ethereum format */ function hashToSign(Order memory order) internal pure returns (bytes32) { return keccak256("\x19Ethereum Signed Message:\n32", hashOrder(order)); } /** * @dev Assert an order is valid and return its hash * @param order Order to validate * @param sig ECDSA signature */ function requireValidOrder(Order memory order, Sig memory sig) internal view returns (bytes32) { bytes32 hash = hashToSign(order); require(validateOrder(hash, order, sig)); return hash; } /** * @dev Validate order parameters (does *not* check signature validity) * @param order Order to validate */ function validateOrderParameters(Order memory order) internal view returns (bool) { /* Order must be targeted at this protocol version (this Exchange contract). */ if (order.exchange != address(this)) { return false; } /* Order must possess valid sale kind parameter combination. */ if (!SaleKindInterface.validateParameters(order.saleKind, order.expirationTime)) { return false; } /* If using the split fee method, order must have sufficient protocol fees. */ if (order.feeMethod == FeeMethod.SplitFee && (order.makerProtocolFee < minimumMakerProtocolFee || order.takerProtocolFee < minimumTakerProtocolFee)) { return false; } return true; } /** * @dev Validate a provided previously approved / signed order, hash, and signature. * @param hash Order hash (already calculated, passed to avoid recalculation) * @param order Order to validate * @param sig ECDSA signature */ function validateOrder(bytes32 hash, Order memory order, Sig memory sig) internal view returns (bool) { /* Not done in an if-conditional to prevent unnecessary ecrecover evaluation, which seems to happen even though it should short-circuit. */ /* Order must have valid parameters. */ if (!validateOrderParameters(order)) { return false; } /* Order must have not been canceled or already filled. */ if (cancelledOrFinalized[hash]) { return false; } /* Order authentication. Order must be either: /* (a) previously approved */ if (approvedOrders[hash]) { return true; } /* or (b) ECDSA-signed by maker. */ if (ecrecover(hash, sig.v, sig.r, sig.s) == order.maker) { return true; } return false; } /** * @dev Approve an order and optionally mark it for orderbook inclusion. Must be called by the maker of the order * @param order Order to approve * @param orderbookInclusionDesired Whether orderbook providers should include the order in their orderbooks */ function approveOrder(Order memory order, bool orderbookInclusionDesired) internal { /* CHECKS */ /* Assert sender is authorized to approve order. */ require(msg.sender == order.maker); /* Calculate order hash. */ bytes32 hash = hashToSign(order); /* Assert order has not already been approved. */ require(!approvedOrders[hash]); /* EFFECTS */ /* Mark order as approved. */ approvedOrders[hash] = true; /* Log approval event. Must be split in two due to Solidity stack size limitations. */ { emit OrderApprovedPartOne(hash, order.exchange, order.maker, order.taker, order.makerRelayerFee, order.takerRelayerFee, order.makerProtocolFee, order.takerProtocolFee, order.feeRecipient, order.feeMethod, order.side, order.saleKind, order.target); } { emit OrderApprovedPartTwo(hash, order.howToCall, order.calldata, order.replacementPattern, order.staticTarget, order.staticExtradata, order.paymentToken, order.basePrice, order.extra, order.listingTime, order.expirationTime, order.salt, orderbookInclusionDesired); } } /** * @dev Cancel an order, preventing it from being matched. Must be called by the maker of the order * @param order Order to cancel * @param sig ECDSA signature */ function cancelOrder(Order memory order, Sig memory sig) internal { /* CHECKS */ /* Calculate order hash. */ bytes32 hash = requireValidOrder(order, sig); /* Assert sender is authorized to cancel order. */ require(msg.sender == order.maker); /* EFFECTS */ /* Mark order as cancelled, preventing it from being matched. */ cancelledOrFinalized[hash] = true; /* Log cancel event. */ emit OrderCancelled(hash); } /** * @dev Calculate the current price of an order (convenience function) * @param order Order to calculate the price of * @return The current price of the order */ function calculateCurrentPrice (Order memory order) internal view returns (uint) { return SaleKindInterface.calculateFinalPrice(order.side, order.saleKind, order.basePrice, order.extra, order.listingTime, order.expirationTime); } /** * @dev Calculate the price two orders would match at, if in fact they would match (otherwise fail) * @param buy Buy-side order * @param sell Sell-side order * @return Match price */ function calculateMatchPrice(Order memory buy, Order memory sell) view internal returns (uint) { /* Calculate sell price. */ uint sellPrice = SaleKindInterface.calculateFinalPrice(sell.side, sell.saleKind, sell.basePrice, sell.extra, sell.listingTime, sell.expirationTime); /* Calculate buy price. */ uint buyPrice = SaleKindInterface.calculateFinalPrice(buy.side, buy.saleKind, buy.basePrice, buy.extra, buy.listingTime, buy.expirationTime); /* Require price cross. */ require(buyPrice >= sellPrice); /* Maker/taker priority. */ return sell.feeRecipient != address(0) ? sellPrice : buyPrice; } /** * @dev Execute all ERC20 token / Ether transfers associated with an order match (fees and buyer => seller transfer) * @param buy Buy-side order * @param sell Sell-side order */ function executeFundsTransfer(Order memory buy, Order memory sell) internal returns (uint) { /* Only payable in the special case of unwrapped Ether. */ if (sell.paymentToken != address(0)) { require(msg.value == 0); } /* Calculate match price. */ uint price = calculateMatchPrice(buy, sell); /* If paying using a token (not Ether), transfer tokens. This is done prior to fee payments to that a seller will have tokens before being charged fees. */ if (price > 0 && sell.paymentToken != address(0)) { transferTokens(sell.paymentToken, buy.maker, sell.maker, price); } /* Amount that will be received by seller (for Ether). */ uint receiveAmount = price; /* Amount that must be sent by buyer (for Ether). */ uint requiredAmount = price; /* Determine maker/taker and charge fees accordingly. */ if (sell.feeRecipient != address(0)) { /* Sell-side order is maker. */ /* Assert taker fee is less than or equal to maximum fee specified by buyer. */ require(sell.takerRelayerFee <= buy.takerRelayerFee); if (sell.feeMethod == FeeMethod.SplitFee) { /* Assert taker fee is less than or equal to maximum fee specified by buyer. */ require(sell.takerProtocolFee <= buy.takerProtocolFee); /* Maker fees are deducted from the token amount that the maker receives. Taker fees are extra tokens that must be paid by the taker. */ if (sell.makerRelayerFee > 0) { uint makerRelayerFee = SafeMath.div(SafeMath.mul(sell.makerRelayerFee, price), INVERSE_BASIS_POINT); if (sell.paymentToken == address(0)) { receiveAmount = SafeMath.sub(receiveAmount, makerRelayerFee); sell.feeRecipient.transfer(makerRelayerFee); } else { transferTokens(sell.paymentToken, sell.maker, sell.feeRecipient, makerRelayerFee); } } if (sell.takerRelayerFee > 0) { uint takerRelayerFee = SafeMath.div(SafeMath.mul(sell.takerRelayerFee, price), INVERSE_BASIS_POINT); if (sell.paymentToken == address(0)) { requiredAmount = SafeMath.add(requiredAmount, takerRelayerFee); sell.feeRecipient.transfer(takerRelayerFee); } else { transferTokens(sell.paymentToken, buy.maker, sell.feeRecipient, takerRelayerFee); } } if (sell.makerProtocolFee > 0) { uint makerProtocolFee = SafeMath.div(SafeMath.mul(sell.makerProtocolFee, price), INVERSE_BASIS_POINT); if (sell.paymentToken == address(0)) { receiveAmount = SafeMath.sub(receiveAmount, makerProtocolFee); protocolFeeRecipient.transfer(makerProtocolFee); } else { transferTokens(sell.paymentToken, sell.maker, protocolFeeRecipient, makerProtocolFee); } } if (sell.takerProtocolFee > 0) { uint takerProtocolFee = SafeMath.div(SafeMath.mul(sell.takerProtocolFee, price), INVERSE_BASIS_POINT); if (sell.paymentToken == address(0)) { requiredAmount = SafeMath.add(requiredAmount, takerProtocolFee); protocolFeeRecipient.transfer(takerProtocolFee); } else { transferTokens(sell.paymentToken, buy.maker, protocolFeeRecipient, takerProtocolFee); } } } else { /* Charge maker fee to seller. */ chargeProtocolFee(sell.maker, sell.feeRecipient, sell.makerRelayerFee); /* Charge taker fee to buyer. */ chargeProtocolFee(buy.maker, sell.feeRecipient, sell.takerRelayerFee); } } else { /* Buy-side order is maker. */ /* Assert taker fee is less than or equal to maximum fee specified by seller. */ require(buy.takerRelayerFee <= sell.takerRelayerFee); if (sell.feeMethod == FeeMethod.SplitFee) { /* The Exchange does not escrow Ether, so direct Ether can only be used to with sell-side maker / buy-side taker orders. */ require(sell.paymentToken != address(0)); /* Assert taker fee is less than or equal to maximum fee specified by seller. */ require(buy.takerProtocolFee <= sell.takerProtocolFee); if (buy.makerRelayerFee > 0) { makerRelayerFee = SafeMath.div(SafeMath.mul(buy.makerRelayerFee, price), INVERSE_BASIS_POINT); transferTokens(sell.paymentToken, buy.maker, buy.feeRecipient, makerRelayerFee); } if (buy.takerRelayerFee > 0) { takerRelayerFee = SafeMath.div(SafeMath.mul(buy.takerRelayerFee, price), INVERSE_BASIS_POINT); transferTokens(sell.paymentToken, sell.maker, buy.feeRecipient, takerRelayerFee); } if (buy.makerProtocolFee > 0) { makerProtocolFee = SafeMath.div(SafeMath.mul(buy.makerProtocolFee, price), INVERSE_BASIS_POINT); transferTokens(sell.paymentToken, buy.maker, protocolFeeRecipient, makerProtocolFee); } if (buy.takerProtocolFee > 0) { takerProtocolFee = SafeMath.div(SafeMath.mul(buy.takerProtocolFee, price), INVERSE_BASIS_POINT); transferTokens(sell.paymentToken, sell.maker, protocolFeeRecipient, takerProtocolFee); } } else { /* Charge maker fee to buyer. */ chargeProtocolFee(buy.maker, buy.feeRecipient, buy.makerRelayerFee); /* Charge taker fee to seller. */ chargeProtocolFee(sell.maker, buy.feeRecipient, buy.takerRelayerFee); } } if (sell.paymentToken == address(0)) { /* Special-case Ether, order must be matched by buyer. */ require(msg.value >= requiredAmount); sell.maker.transfer(receiveAmount); /* Allow overshoot for variable-price auctions, refund difference. */ uint diff = SafeMath.sub(msg.value, requiredAmount); if (diff > 0) { buy.maker.transfer(diff); } } /* This contract should never hold Ether, however, we cannot assert this, since it is impossible to prevent anyone from sending Ether e.g. with selfdestruct. */ return price; } /** * @dev Return whether or not two orders can be matched with each other by basic parameters (does not check order signatures / calldata or perform static calls) * @param buy Buy-side order * @param sell Sell-side order * @return Whether or not the two orders can be matched */ function ordersCanMatch(Order memory buy, Order memory sell) internal view returns (bool) { return ( /* Must be opposite-side. */ (buy.side == SaleKindInterface.Side.Buy && sell.side == SaleKindInterface.Side.Sell) && /* Must use same fee method. */ (buy.feeMethod == sell.feeMethod) && /* Must use same payment token. */ (buy.paymentToken == sell.paymentToken) && /* Must match maker/taker addresses. */ (sell.taker == address(0) || sell.taker == buy.maker) && (buy.taker == address(0) || buy.taker == sell.maker) && /* One must be maker and the other must be taker (no bool XOR in Solidity). */ ((sell.feeRecipient == address(0) && buy.feeRecipient != address(0)) || (sell.feeRecipient != address(0) && buy.feeRecipient == address(0))) && /* Must match target. */ (buy.target == sell.target) && /* Must match howToCall. */ (buy.howToCall == sell.howToCall) && /* Buy-side order must be settleable. */ SaleKindInterface.canSettleOrder(buy.listingTime, buy.expirationTime) && /* Sell-side order must be settleable. */ SaleKindInterface.canSettleOrder(sell.listingTime, sell.expirationTime) ); } /** * @dev Atomically match two orders, ensuring validity of the match, and execute all associated state transitions. Protected against reentrancy by a contract-global lock. * @param buy Buy-side order * @param buySig Buy-side order signature * @param sell Sell-side order * @param sellSig Sell-side order signature */ function atomicMatch(Order memory buy, Sig memory buySig, Order memory sell, Sig memory sellSig, bytes32 metadata) internal reentrancyGuard { /* CHECKS */ /* Ensure buy order validity and calculate hash if necessary. */ bytes32 buyHash; if (buy.maker == msg.sender) { require(validateOrderParameters(buy)); } else { buyHash = requireValidOrder(buy, buySig); } /* Ensure sell order validity and calculate hash if necessary. */ bytes32 sellHash; if (sell.maker == msg.sender) { require(validateOrderParameters(sell)); } else { sellHash = requireValidOrder(sell, sellSig); } /* Must be matchable. */ require(ordersCanMatch(buy, sell)); /* Target must exist (prevent malicious selfdestructs just prior to order settlement). */ uint size; address target = sell.target; assembly { size := extcodesize(target) } require(size > 0); /* Must match calldata after replacement, if specified. */ if (buy.replacementPattern.length > 0) { ArrayUtils.guardedArrayReplace(buy.calldata, sell.calldata, buy.replacementPattern); } if (sell.replacementPattern.length > 0) { ArrayUtils.guardedArrayReplace(sell.calldata, buy.calldata, sell.replacementPattern); } require(ArrayUtils.arrayEq(buy.calldata, sell.calldata)); /* Retrieve delegateProxy contract. */ OwnableDelegateProxy delegateProxy = registry.proxies(sell.maker); /* Proxy must exist. */ require(delegateProxy != address(0)); /* Assert implementation. */ require(delegateProxy.implementation() == registry.delegateProxyImplementation()); /* Access the passthrough AuthenticatedProxy. */ AuthenticatedProxy proxy = AuthenticatedProxy(delegateProxy); /* EFFECTS */ /* Mark previously signed or approved orders as finalized. */ if (msg.sender != buy.maker) { cancelledOrFinalized[buyHash] = true; } if (msg.sender != sell.maker) { cancelledOrFinalized[sellHash] = true; } /* INTERACTIONS */ /* Execute funds transfer and pay fees. */ uint price = executeFundsTransfer(buy, sell); /* Execute specified call through proxy. */ require(proxy.proxy(sell.target, sell.howToCall, sell.calldata)); /* Static calls are intentionally done after the effectful call so they can check resulting state. */ /* Handle buy-side static call if specified. */ if (buy.staticTarget != address(0)) { require(staticCall(buy.staticTarget, sell.calldata, buy.staticExtradata)); } /* Handle sell-side static call if specified. */ if (sell.staticTarget != address(0)) { require(staticCall(sell.staticTarget, sell.calldata, sell.staticExtradata)); } /* Log match event. */ emit OrdersMatched(buyHash, sellHash, sell.feeRecipient != address(0) ? sell.maker : buy.maker, sell.feeRecipient != address(0) ? buy.maker : sell.maker, price, metadata); } } contract Exchange is ExchangeCore { /** * @dev Call guardedArrayReplace - library function exposed for testing. */ function guardedArrayReplace(bytes array, bytes desired, bytes mask) public pure returns (bytes) { ArrayUtils.guardedArrayReplace(array, desired, mask); return array; } /** * Test copy byte array * * @param arrToCopy Array to copy * @return byte array */ function testCopy(bytes arrToCopy) public pure returns (bytes) { bytes memory arr = new bytes(arrToCopy.length); uint index; assembly { index := add(arr, 0x20) } ArrayUtils.unsafeWriteBytes(index, arrToCopy); return arr; } /** * Test write address to bytes * * @param addr Address to write * @return byte array */ function testCopyAddress(address addr) public pure returns (bytes) { bytes memory arr = new bytes(0x14); uint index; assembly { index := add(arr, 0x20) } ArrayUtils.unsafeWriteAddress(index, addr); return arr; } /** * @dev Call calculateFinalPrice - library function exposed for testing. */ function calculateFinalPrice(SaleKindInterface.Side side, SaleKindInterface.SaleKind saleKind, uint basePrice, uint extra, uint listingTime, uint expirationTime) public view returns (uint) { return SaleKindInterface.calculateFinalPrice(side, saleKind, basePrice, extra, listingTime, expirationTime); } /** * @dev Call hashOrder - Solidity ABI encoding limitation workaround, hopefully temporary. */ function hashOrder_( address[7] addrs, uint[9] uints, FeeMethod feeMethod, SaleKindInterface.Side side, SaleKindInterface.SaleKind saleKind, AuthenticatedProxy.HowToCall howToCall, bytes calldata, bytes replacementPattern, bytes staticExtradata) public pure returns (bytes32) { return hashOrder( Order(addrs[0], addrs[1], addrs[2], uints[0], uints[1], uints[2], uints[3], addrs[3], feeMethod, side, saleKind, addrs[4], howToCall, calldata, replacementPattern, addrs[5], staticExtradata, ERC20(addrs[6]), uints[4], uints[5], uints[6], uints[7], uints[8]) ); } /** * @dev Call hashToSign - Solidity ABI encoding limitation workaround, hopefully temporary. */ function hashToSign_( address[7] addrs, uint[9] uints, FeeMethod feeMethod, SaleKindInterface.Side side, SaleKindInterface.SaleKind saleKind, AuthenticatedProxy.HowToCall howToCall, bytes calldata, bytes replacementPattern, bytes staticExtradata) public pure returns (bytes32) { return hashToSign( Order(addrs[0], addrs[1], addrs[2], uints[0], uints[1], uints[2], uints[3], addrs[3], feeMethod, side, saleKind, addrs[4], howToCall, calldata, replacementPattern, addrs[5], staticExtradata, ERC20(addrs[6]), uints[4], uints[5], uints[6], uints[7], uints[8]) ); } /** * @dev Call validateOrderParameters - Solidity ABI encoding limitation workaround, hopefully temporary. */ function validateOrderParameters_ ( address[7] addrs, uint[9] uints, FeeMethod feeMethod, SaleKindInterface.Side side, SaleKindInterface.SaleKind saleKind, AuthenticatedProxy.HowToCall howToCall, bytes calldata, bytes replacementPattern, bytes staticExtradata) view public returns (bool) { Order memory order = Order(addrs[0], addrs[1], addrs[2], uints[0], uints[1], uints[2], uints[3], addrs[3], feeMethod, side, saleKind, addrs[4], howToCall, calldata, replacementPattern, addrs[5], staticExtradata, ERC20(addrs[6]), uints[4], uints[5], uints[6], uints[7], uints[8]); return validateOrderParameters( order ); } /** * @dev Call validateOrder - Solidity ABI encoding limitation workaround, hopefully temporary. */ function validateOrder_ ( address[7] addrs, uint[9] uints, FeeMethod feeMethod, SaleKindInterface.Side side, SaleKindInterface.SaleKind saleKind, AuthenticatedProxy.HowToCall howToCall, bytes calldata, bytes replacementPattern, bytes staticExtradata, uint8 v, bytes32 r, bytes32 s) view public returns (bool) { Order memory order = Order(addrs[0], addrs[1], addrs[2], uints[0], uints[1], uints[2], uints[3], addrs[3], feeMethod, side, saleKind, addrs[4], howToCall, calldata, replacementPattern, addrs[5], staticExtradata, ERC20(addrs[6]), uints[4], uints[5], uints[6], uints[7], uints[8]); return validateOrder( hashToSign(order), order, Sig(v, r, s) ); } /** * @dev Call approveOrder - Solidity ABI encoding limitation workaround, hopefully temporary. */ function approveOrder_ ( address[7] addrs, uint[9] uints, FeeMethod feeMethod, SaleKindInterface.Side side, SaleKindInterface.SaleKind saleKind, AuthenticatedProxy.HowToCall howToCall, bytes calldata, bytes replacementPattern, bytes staticExtradata, bool orderbookInclusionDesired) public { Order memory order = Order(addrs[0], addrs[1], addrs[2], uints[0], uints[1], uints[2], uints[3], addrs[3], feeMethod, side, saleKind, addrs[4], howToCall, calldata, replacementPattern, addrs[5], staticExtradata, ERC20(addrs[6]), uints[4], uints[5], uints[6], uints[7], uints[8]); return approveOrder(order, orderbookInclusionDesired); } /** * @dev Call cancelOrder - Solidity ABI encoding limitation workaround, hopefully temporary. */ function cancelOrder_( address[7] addrs, uint[9] uints, FeeMethod feeMethod, SaleKindInterface.Side side, SaleKindInterface.SaleKind saleKind, AuthenticatedProxy.HowToCall howToCall, bytes calldata, bytes replacementPattern, bytes staticExtradata, uint8 v, bytes32 r, bytes32 s) public { return cancelOrder( Order(addrs[0], addrs[1], addrs[2], uints[0], uints[1], uints[2], uints[3], addrs[3], feeMethod, side, saleKind, addrs[4], howToCall, calldata, replacementPattern, addrs[5], staticExtradata, ERC20(addrs[6]), uints[4], uints[5], uints[6], uints[7], uints[8]), Sig(v, r, s) ); } /** * @dev Call calculateCurrentPrice - Solidity ABI encoding limitation workaround, hopefully temporary. */ function calculateCurrentPrice_( address[7] addrs, uint[9] uints, FeeMethod feeMethod, SaleKindInterface.Side side, SaleKindInterface.SaleKind saleKind, AuthenticatedProxy.HowToCall howToCall, bytes calldata, bytes replacementPattern, bytes staticExtradata) public view returns (uint) { return calculateCurrentPrice( Order(addrs[0], addrs[1], addrs[2], uints[0], uints[1], uints[2], uints[3], addrs[3], feeMethod, side, saleKind, addrs[4], howToCall, calldata, replacementPattern, addrs[5], staticExtradata, ERC20(addrs[6]), uints[4], uints[5], uints[6], uints[7], uints[8]) ); } /** * @dev Call ordersCanMatch - Solidity ABI encoding limitation workaround, hopefully temporary. */ function ordersCanMatch_( address[14] addrs, uint[18] uints, uint8[8] feeMethodsSidesKindsHowToCalls, bytes calldataBuy, bytes calldataSell, bytes replacementPatternBuy, bytes replacementPatternSell, bytes staticExtradataBuy, bytes staticExtradataSell) public view returns (bool) { Order memory buy = Order(addrs[0], addrs[1], addrs[2], uints[0], uints[1], uints[2], uints[3], addrs[3], FeeMethod(feeMethodsSidesKindsHowToCalls[0]), SaleKindInterface.Side(feeMethodsSidesKindsHowToCalls[1]), SaleKindInterface.SaleKind(feeMethodsSidesKindsHowToCalls[2]), addrs[4], AuthenticatedProxy.HowToCall(feeMethodsSidesKindsHowToCalls[3]), calldataBuy, replacementPatternBuy, addrs[5], staticExtradataBuy, ERC20(addrs[6]), uints[4], uints[5], uints[6], uints[7], uints[8]); Order memory sell = Order(addrs[7], addrs[8], addrs[9], uints[9], uints[10], uints[11], uints[12], addrs[10], FeeMethod(feeMethodsSidesKindsHowToCalls[4]), SaleKindInterface.Side(feeMethodsSidesKindsHowToCalls[5]), SaleKindInterface.SaleKind(feeMethodsSidesKindsHowToCalls[6]), addrs[11], AuthenticatedProxy.HowToCall(feeMethodsSidesKindsHowToCalls[7]), calldataSell, replacementPatternSell, addrs[12], staticExtradataSell, ERC20(addrs[13]), uints[13], uints[14], uints[15], uints[16], uints[17]); return ordersCanMatch( buy, sell ); } /** * @dev Return whether or not two orders' calldata specifications can match * @param buyCalldata Buy-side order calldata * @param buyReplacementPattern Buy-side order calldata replacement mask * @param sellCalldata Sell-side order calldata * @param sellReplacementPattern Sell-side order calldata replacement mask * @return Whether the orders' calldata can be matched */ function orderCalldataCanMatch(bytes buyCalldata, bytes buyReplacementPattern, bytes sellCalldata, bytes sellReplacementPattern) public pure returns (bool) { if (buyReplacementPattern.length > 0) { ArrayUtils.guardedArrayReplace(buyCalldata, sellCalldata, buyReplacementPattern); } if (sellReplacementPattern.length > 0) { ArrayUtils.guardedArrayReplace(sellCalldata, buyCalldata, sellReplacementPattern); } return ArrayUtils.arrayEq(buyCalldata, sellCalldata); } /** * @dev Call calculateMatchPrice - Solidity ABI encoding limitation workaround, hopefully temporary. */ function calculateMatchPrice_( address[14] addrs, uint[18] uints, uint8[8] feeMethodsSidesKindsHowToCalls, bytes calldataBuy, bytes calldataSell, bytes replacementPatternBuy, bytes replacementPatternSell, bytes staticExtradataBuy, bytes staticExtradataSell) public view returns (uint) { Order memory buy = Order(addrs[0], addrs[1], addrs[2], uints[0], uints[1], uints[2], uints[3], addrs[3], FeeMethod(feeMethodsSidesKindsHowToCalls[0]), SaleKindInterface.Side(feeMethodsSidesKindsHowToCalls[1]), SaleKindInterface.SaleKind(feeMethodsSidesKindsHowToCalls[2]), addrs[4], AuthenticatedProxy.HowToCall(feeMethodsSidesKindsHowToCalls[3]), calldataBuy, replacementPatternBuy, addrs[5], staticExtradataBuy, ERC20(addrs[6]), uints[4], uints[5], uints[6], uints[7], uints[8]); Order memory sell = Order(addrs[7], addrs[8], addrs[9], uints[9], uints[10], uints[11], uints[12], addrs[10], FeeMethod(feeMethodsSidesKindsHowToCalls[4]), SaleKindInterface.Side(feeMethodsSidesKindsHowToCalls[5]), SaleKindInterface.SaleKind(feeMethodsSidesKindsHowToCalls[6]), addrs[11], AuthenticatedProxy.HowToCall(feeMethodsSidesKindsHowToCalls[7]), calldataSell, replacementPatternSell, addrs[12], staticExtradataSell, ERC20(addrs[13]), uints[13], uints[14], uints[15], uints[16], uints[17]); return calculateMatchPrice( buy, sell ); } /** * @dev Call atomicMatch - Solidity ABI encoding limitation workaround, hopefully temporary. */ function atomicMatch_( address[14] addrs, uint[18] uints, uint8[8] feeMethodsSidesKindsHowToCalls, bytes calldataBuy, bytes calldataSell, bytes replacementPatternBuy, bytes replacementPatternSell, bytes staticExtradataBuy, bytes staticExtradataSell, uint8[2] vs, bytes32[5] rssMetadata) public payable { return atomicMatch( Order(addrs[0], addrs[1], addrs[2], uints[0], uints[1], uints[2], uints[3], addrs[3], FeeMethod(feeMethodsSidesKindsHowToCalls[0]), SaleKindInterface.Side(feeMethodsSidesKindsHowToCalls[1]), SaleKindInterface.SaleKind(feeMethodsSidesKindsHowToCalls[2]), addrs[4], AuthenticatedProxy.HowToCall(feeMethodsSidesKindsHowToCalls[3]), calldataBuy, replacementPatternBuy, addrs[5], staticExtradataBuy, ERC20(addrs[6]), uints[4], uints[5], uints[6], uints[7], uints[8]), Sig(vs[0], rssMetadata[0], rssMetadata[1]), Order(addrs[7], addrs[8], addrs[9], uints[9], uints[10], uints[11], uints[12], addrs[10], FeeMethod(feeMethodsSidesKindsHowToCalls[4]), SaleKindInterface.Side(feeMethodsSidesKindsHowToCalls[5]), SaleKindInterface.SaleKind(feeMethodsSidesKindsHowToCalls[6]), addrs[11], AuthenticatedProxy.HowToCall(feeMethodsSidesKindsHowToCalls[7]), calldataSell, replacementPatternSell, addrs[12], staticExtradataSell, ERC20(addrs[13]), uints[13], uints[14], uints[15], uints[16], uints[17]), Sig(vs[1], rssMetadata[2], rssMetadata[3]), rssMetadata[4] ); } } contract WyvernExchange is Exchange { string public constant name = "Project Wyvern Exchange"; string public constant version = "2.2"; string public constant codename = "Lambton Worm"; /** * @dev Initialize a WyvernExchange instance * @param registryAddress Address of the registry instance which this Exchange instance will use * @param tokenAddress Address of the token used for protocol fees */ constructor (ProxyRegistry registryAddress, TokenTransferProxy tokenTransferProxyAddress, ERC20 tokenAddress, address protocolFeeAddress) public { registry = registryAddress; tokenTransferProxy = tokenTransferProxyAddress; exchangeToken = tokenAddress; protocolFeeRecipient = protocolFeeAddress; owner = msg.sender; } } library SaleKindInterface { /** * Side: buy or sell. */ enum Side { Buy, Sell } /** * Currently supported kinds of sale: fixed price, Dutch auction. * English auctions cannot be supported without stronger escrow guarantees. * Future interesting options: Vickrey auction, nonlinear Dutch auctions. */ enum SaleKind { FixedPrice, DutchAuction } /** * @dev Check whether the parameters of a sale are valid * @param saleKind Kind of sale * @param expirationTime Order expiration time * @return Whether the parameters were valid */ function validateParameters(SaleKind saleKind, uint expirationTime) pure internal returns (bool) { /* Auctions must have a set expiration date. */ return (saleKind == SaleKind.FixedPrice || expirationTime > 0); } /** * @dev Return whether or not an order can be settled * @dev Precondition: parameters have passed validateParameters * @param listingTime Order listing time * @param expirationTime Order expiration time */ function canSettleOrder(uint listingTime, uint expirationTime) view internal returns (bool) { return (listingTime < now) && (expirationTime == 0 || now < expirationTime); } /** * @dev Calculate the settlement price of an order * @dev Precondition: parameters have passed validateParameters. * @param side Order side * @param saleKind Method of sale * @param basePrice Order base price * @param extra Order extra price data * @param listingTime Order listing time * @param expirationTime Order expiration time */ function calculateFinalPrice(Side side, SaleKind saleKind, uint basePrice, uint extra, uint listingTime, uint expirationTime) view internal returns (uint finalPrice) { if (saleKind == SaleKind.FixedPrice) { return basePrice; } else if (saleKind == SaleKind.DutchAuction) { uint diff = SafeMath.div(SafeMath.mul(extra, SafeMath.sub(now, listingTime)), SafeMath.sub(expirationTime, listingTime)); if (side == Side.Sell) { /* Sell-side - start price: basePrice. End price: basePrice - extra. */ return SafeMath.sub(basePrice, diff); } else { /* Buy-side - start price: basePrice. End price: basePrice + extra. */ return SafeMath.add(basePrice, diff); } } } } contract ProxyRegistry is Ownable { /* DelegateProxy implementation contract. Must be initialized. */ address public delegateProxyImplementation; /* Authenticated proxies by user. */ mapping(address => OwnableDelegateProxy) public proxies; /* Contracts pending access. */ mapping(address => uint) public pending; /* Contracts allowed to call those proxies. */ mapping(address => bool) public contracts; /* Delay period for adding an authenticated contract. This mitigates a particular class of potential attack on the Wyvern DAO (which owns this registry) - if at any point the value of assets held by proxy contracts exceeded the value of half the WYV supply (votes in the DAO), a malicious but rational attacker could buy half the Wyvern and grant themselves access to all the proxy contracts. A delay period renders this attack nonthreatening - given two weeks, if that happened, users would have plenty of time to notice and transfer their assets. */ uint public DELAY_PERIOD = 2 weeks; /** * Start the process to enable access for specified contract. Subject to delay period. * * @dev ProxyRegistry owner only * @param addr Address to which to grant permissions */ function startGrantAuthentication (address addr) public onlyOwner { require(!contracts[addr] && pending[addr] == 0); pending[addr] = now; } /** * End the process to nable access for specified contract after delay period has passed. * * @dev ProxyRegistry owner only * @param addr Address to which to grant permissions */ function endGrantAuthentication (address addr) public onlyOwner { require(!contracts[addr] && pending[addr] != 0 && ((pending[addr] + DELAY_PERIOD) < now)); pending[addr] = 0; contracts[addr] = true; } /** * Revoke access for specified contract. Can be done instantly. * * @dev ProxyRegistry owner only * @param addr Address of which to revoke permissions */ function revokeAuthentication (address addr) public onlyOwner { contracts[addr] = false; } /** * Register a proxy contract with this registry * * @dev Must be called by the user which the proxy is for, creates a new AuthenticatedProxy * @return New AuthenticatedProxy contract */ function registerProxy() public returns (OwnableDelegateProxy proxy) { require(proxies[msg.sender] == address(0)); proxy = new OwnableDelegateProxy(msg.sender, delegateProxyImplementation, abi.encodeWithSignature("initialize(address,address)", msg.sender, address(this))); proxies[msg.sender] = proxy; return proxy; } } contract TokenTransferProxy { /* Authentication registry. */ ProxyRegistry public registry; /** * Call ERC20 `transferFrom` * * @dev Authenticated contract only * @param token ERC20 token address * @param from From address * @param to To address * @param amount Transfer amount */ function transferFrom(address token, address from, address to, uint amount) public returns (bool) { require(registry.contracts(msg.sender)); return ERC20(token).transferFrom(from, to, amount); } } contract OwnedUpgradeabilityStorage { // Current implementation address internal _implementation; // Owner of the contract address private _upgradeabilityOwner; /** * @dev Tells the address of the owner * @return the address of the owner */ function upgradeabilityOwner() public view returns (address) { return _upgradeabilityOwner; } /** * @dev Sets the address of the owner */ function setUpgradeabilityOwner(address newUpgradeabilityOwner) internal { _upgradeabilityOwner = newUpgradeabilityOwner; } /** * @dev Tells the address of the current implementation * @return address of the current implementation */ function implementation() public view returns (address) { return _implementation; } /** * @dev Tells the proxy type (EIP 897) * @return Proxy type, 2 for forwarding proxy */ function proxyType() public pure returns (uint256 proxyTypeId) { return 2; } } contract AuthenticatedProxy is TokenRecipient, OwnedUpgradeabilityStorage { /* Whether initialized. */ bool initialized = false; /* Address which owns this proxy. */ address public user; /* Associated registry with contract authentication information. */ ProxyRegistry public registry; /* Whether access has been revoked. */ bool public revoked; /* Delegate call could be used to atomically transfer multiple assets owned by the proxy contract with one order. */ enum HowToCall { Call, DelegateCall } /* Event fired when the proxy access is revoked or unrevoked. */ event Revoked(bool revoked); /** * Initialize an AuthenticatedProxy * * @param addrUser Address of user on whose behalf this proxy will act * @param addrRegistry Address of ProxyRegistry contract which will manage this proxy */ function initialize (address addrUser, ProxyRegistry addrRegistry) public { require(!initialized); initialized = true; user = addrUser; registry = addrRegistry; } /** * Set the revoked flag (allows a user to revoke ProxyRegistry access) * * @dev Can be called by the user only * @param revoke Whether or not to revoke access */ function setRevoke(bool revoke) public { require(msg.sender == user); revoked = revoke; emit Revoked(revoke); } /** * Execute a message call from the proxy contract * * @dev Can be called by the user, or by a contract authorized by the registry as long as the user has not revoked access * @param dest Address to which the call will be sent * @param howToCall Which kind of call to make * @param calldata Calldata to send * @return Result of the call (success or failure) */ function proxy(address dest, HowToCall howToCall, bytes calldata) public returns (bool result) { require(msg.sender == user || (!revoked && registry.contracts(msg.sender))); if (howToCall == HowToCall.Call) { result = dest.call(calldata); } else if (howToCall == HowToCall.DelegateCall) { result = dest.delegatecall(calldata); } return result; } /** * Execute a message call and assert success * * @dev Same functionality as `proxy`, just asserts the return value * @param dest Address to which the call will be sent * @param howToCall What kind of call to make * @param calldata Calldata to send */ function proxyAssert(address dest, HowToCall howToCall, bytes calldata) public { require(proxy(dest, howToCall, calldata)); } } contract Proxy { /** * @dev Tells the address of the implementation where every call will be delegated. * @return address of the implementation to which it will be delegated */ function implementation() public view returns (address); /** * @dev Tells the type of proxy (EIP 897) * @return Type of proxy, 2 for upgradeable proxy */ function proxyType() public pure returns (uint256 proxyTypeId); /** * @dev Fallback function allowing to perform a delegatecall to the given implementation. * This function will return whatever the implementation call returns */ function () payable public { address _impl = implementation(); require(_impl != address(0)); assembly { let ptr := mload(0x40) calldatacopy(ptr, 0, calldatasize) let result := delegatecall(gas, _impl, ptr, calldatasize, 0, 0) let size := returndatasize returndatacopy(ptr, 0, size) switch result case 0 { revert(ptr, size) } default { return(ptr, size) } } } } contract OwnedUpgradeabilityProxy is Proxy, OwnedUpgradeabilityStorage { /** * @dev Event to show ownership has been transferred * @param previousOwner representing the address of the previous owner * @param newOwner representing the address of the new owner */ event ProxyOwnershipTransferred(address previousOwner, address newOwner); /** * @dev This event will be emitted every time the implementation gets upgraded * @param implementation representing the address of the upgraded implementation */ event Upgraded(address indexed implementation); /** * @dev Upgrades the implementation address * @param implementation representing the address of the new implementation to be set */ function _upgradeTo(address implementation) internal { require(_implementation != implementation); _implementation = implementation; emit Upgraded(implementation); } /** * @dev Throws if called by any account other than the owner. */ modifier onlyProxyOwner() { require(msg.sender == proxyOwner()); _; } /** * @dev Tells the address of the proxy owner * @return the address of the proxy owner */ function proxyOwner() public view returns (address) { return upgradeabilityOwner(); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferProxyOwnership(address newOwner) public onlyProxyOwner { require(newOwner != address(0)); emit ProxyOwnershipTransferred(proxyOwner(), newOwner); setUpgradeabilityOwner(newOwner); } /** * @dev Allows the upgradeability owner to upgrade the current implementation of the proxy. * @param implementation representing the address of the new implementation to be set. */ function upgradeTo(address implementation) public onlyProxyOwner { _upgradeTo(implementation); } /** * @dev Allows the upgradeability owner to upgrade the current implementation of the proxy * and delegatecall the new implementation for initialization. * @param implementation representing the address of the new implementation to be set. * @param data represents the msg.data to bet sent in the low level call. This parameter may include the function * signature of the implementation to be called with the needed payload */ function upgradeToAndCall(address implementation, bytes data) payable public onlyProxyOwner { upgradeTo(implementation); require(address(this).delegatecall(data)); } } contract OwnableDelegateProxy is OwnedUpgradeabilityProxy { constructor(address owner, address initialImplementation, bytes calldata) public { setUpgradeabilityOwner(owner); _upgradeTo(initialImplementation); require(initialImplementation.delegatecall(calldata)); } }
* @dev Atomically match two orders, ensuring validity of the match, and execute all associated state transitions. Protected against reentrancy by a contract-global lock. @param buy Buy-side order @param buySig Buy-side order signature @param sell Sell-side order @param sellSig Sell-side order signature/ CHECKS */ Ensure buy order validity and calculate hash if necessary. */ Must match calldata after replacement, if specified. */ Mark previously signed or approved orders as finalized. */ Handle buy-side static call if specified. */ Handle sell-side static call if specified. */
function atomicMatch(Order memory buy, Sig memory buySig, Order memory sell, Sig memory sellSig, bytes32 metadata) internal reentrancyGuard { bytes32 buyHash; if (buy.maker == msg.sender) { require(validateOrderParameters(buy)); buyHash = requireValidOrder(buy, buySig); } if (sell.maker == msg.sender) { require(validateOrderParameters(sell)); sellHash = requireValidOrder(sell, sellSig); } address target = sell.target; assembly { size := extcodesize(target) } require(size > 0); if (buy.replacementPattern.length > 0) { ArrayUtils.guardedArrayReplace(buy.calldata, sell.calldata, buy.replacementPattern); } if (sell.replacementPattern.length > 0) { ArrayUtils.guardedArrayReplace(sell.calldata, buy.calldata, sell.replacementPattern); } require(ArrayUtils.arrayEq(buy.calldata, sell.calldata)); if (msg.sender != buy.maker) { cancelledOrFinalized[buyHash] = true; } if (msg.sender != sell.maker) { cancelledOrFinalized[sellHash] = true; } if (buy.staticTarget != address(0)) { require(staticCall(buy.staticTarget, sell.calldata, buy.staticExtradata)); } if (sell.staticTarget != address(0)) { require(staticCall(sell.staticTarget, sell.calldata, sell.staticExtradata)); } }
5,836,533
[ 1, 3641, 6478, 845, 2795, 11077, 16, 24831, 13800, 434, 326, 845, 16, 471, 1836, 777, 3627, 919, 13136, 18, 1186, 1050, 5314, 283, 8230, 12514, 635, 279, 6835, 17, 6347, 2176, 18, 225, 30143, 605, 9835, 17, 5564, 1353, 225, 30143, 8267, 605, 9835, 17, 5564, 1353, 3372, 225, 357, 80, 348, 1165, 17, 5564, 1353, 225, 357, 80, 8267, 348, 1165, 17, 5564, 1353, 3372, 19, 14565, 55, 342, 7693, 30143, 1353, 13800, 471, 4604, 1651, 309, 4573, 18, 342, 6753, 845, 745, 892, 1839, 6060, 16, 309, 1269, 18, 342, 6622, 7243, 6726, 578, 20412, 11077, 487, 727, 1235, 18, 342, 5004, 30143, 17, 5564, 760, 745, 309, 1269, 18, 342, 5004, 357, 80, 17, 5564, 760, 745, 309, 1269, 18, 342, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 7960, 2060, 12, 2448, 3778, 30143, 16, 21911, 3778, 30143, 8267, 16, 4347, 3778, 357, 80, 16, 21911, 3778, 357, 80, 8267, 16, 1731, 1578, 1982, 13, 203, 3639, 2713, 203, 3639, 283, 8230, 12514, 16709, 203, 565, 288, 203, 203, 3639, 1731, 1578, 30143, 2310, 31, 203, 3639, 309, 261, 70, 9835, 18, 29261, 422, 1234, 18, 15330, 13, 288, 203, 5411, 2583, 12, 5662, 2448, 2402, 12, 70, 9835, 10019, 203, 5411, 30143, 2310, 273, 2583, 1556, 2448, 12, 70, 9835, 16, 30143, 8267, 1769, 203, 3639, 289, 203, 203, 3639, 309, 261, 87, 1165, 18, 29261, 422, 1234, 18, 15330, 13, 288, 203, 5411, 2583, 12, 5662, 2448, 2402, 12, 87, 1165, 10019, 203, 5411, 357, 80, 2310, 273, 2583, 1556, 2448, 12, 87, 1165, 16, 357, 80, 8267, 1769, 203, 3639, 289, 203, 203, 203, 3639, 1758, 1018, 273, 357, 80, 18, 3299, 31, 203, 3639, 19931, 288, 203, 5411, 963, 519, 1110, 7000, 554, 12, 3299, 13, 203, 3639, 289, 203, 3639, 2583, 12, 1467, 405, 374, 1769, 203, 203, 3639, 309, 261, 70, 9835, 18, 24394, 3234, 18, 2469, 405, 374, 13, 288, 203, 1850, 20548, 18, 6891, 17212, 1076, 5729, 12, 70, 9835, 18, 1991, 892, 16, 357, 80, 18, 1991, 892, 16, 30143, 18, 24394, 3234, 1769, 203, 3639, 289, 203, 3639, 309, 261, 87, 1165, 18, 24394, 3234, 18, 2469, 405, 374, 13, 288, 203, 1850, 20548, 18, 6891, 17212, 1076, 5729, 12, 87, 1165, 18, 1991, 892, 16, 30143, 18, 1991, 892, 2 ]
./full_match/1/0x1F033Cb8A2Df08a147BC512723fd0da3FEc5cCA7/sources/autopay/contracts/Autopay.sol
time difference between report timestamp and start of interval
uint256 _timeDiff = _timestamp - _c;
4,950,770
[ 1, 957, 7114, 3086, 2605, 2858, 471, 787, 434, 3673, 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, 2254, 5034, 389, 957, 5938, 273, 389, 5508, 300, 389, 71, 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 ]
/** *Submitted for verification at BscScan.com on 2021-08-26 */ pragma solidity 0.8.3; // 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 virtual view returns (address) { return msg.sender; } function _msgData() internal virtual view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @dev Interface of the BEP20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval( address indexed owner, address indexed spender, uint256 value ); } /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // 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-block.timestamp/[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); } } } } /** * @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() { 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; } } interface Token { function transfer(address, uint256) external returns (bool); } contract Canopy is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; string private _name = "Canopy"; string private _symbol = "TREE"; uint8 private _decimals = 18; mapping(address => uint256) internal _reflectionBalance; mapping(address => uint256) internal _tokenBalance; mapping(address => mapping(address => uint256)) internal _allowances; uint256 private constant MAX = ~uint256(0); uint256 internal _tokenTotal = 1000000 *10**18; // 1 million totalSupply uint256 internal _reflectionTotal = (MAX - (MAX % _tokenTotal)); mapping(address => bool) isExcludedFromFee; mapping(address => bool) internal _isExcluded; address[] internal _excluded; uint256 public _taxFee = 200; // 200 = 2% uint256 public _charityFee = 100; // 100 = 1% uint256 public _refferalFee = 300; // 300 = 3% uint256 public _taxFeeTotal; uint256 public _charityFeeTotal; uint256 public _refferalFeeTotal; address public charityAddress = 0x80F4aea6A4390f5265A690B68E6E3f822F7879b2; // TREE Charity Address address public refferalAddress = 0x69d96053Ec00Fa5413AAd33A19f9380CC7F75456; // refferalAddress event RewardsDistributed(uint256 amount); constructor() { isExcludedFromFee[_msgSender()] = true; isExcludedFromFee[address(this)] = true; _reflectionBalance[_msgSender()] = _reflectionTotal; emit Transfer(address(0), _msgSender(), _tokenTotal); } 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; } function totalSupply() public override view returns (uint256) { return _tokenTotal; } function balanceOf(address account) public override view returns (uint256) { if (_isExcluded[account]) return _tokenBalance[account]; return tokenFromReflection(_reflectionBalance[account]); } function transfer(address recipient, uint256 amount) public override virtual returns (bool) { _transfer(_msgSender(),recipient,amount); return true; } function allowance(address owner, address spender) public override view returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override virtual 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, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } 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; } function isExcluded(address account) public view returns (bool) { return _isExcluded[account]; } function reflectionFromToken(uint256 tokenAmount, bool deductTransferFee) public view returns (uint256) { require(tokenAmount <= _tokenTotal, "Amount must be less than supply"); if (!deductTransferFee) { return tokenAmount.mul(_getReflectionRate()); } else { return tokenAmount.sub(tokenAmount.mul(_taxFee).div(10000)).mul(_getReflectionRate()); } } function tokenFromReflection(uint256 reflectionAmount) public view returns (uint256) { require(reflectionAmount <= _reflectionTotal, "Amount must be less than total reflections"); uint256 currentRate = _getReflectionRate(); return reflectionAmount.div(currentRate); } function excludeAccount(address account) external onlyOwner() { require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D,"NEURO: Uniswap router cannot be excluded."); require(account != address(this), 'NEURO: The contract it self cannot be excluded'); require(!_isExcluded[account], "NEURO: Account is already excluded"); if (_reflectionBalance[account] > 0) { _tokenBalance[account] = tokenFromReflection( _reflectionBalance[account] ); } _isExcluded[account] = true; _excluded.push(account); } function includeAccount(address account) external onlyOwner() { require(_isExcluded[account], "NEURO: Account is already included"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tokenBalance[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } 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 sender, address recipient, uint256 amount) private { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); uint256 transferAmount = amount; uint256 rate = _getReflectionRate(); if(!isExcludedFromFee[sender] && !isExcludedFromFee[recipient]){ transferAmount = collectFee(sender,amount,rate); } //@dev Transfer reflection _reflectionBalance[sender] = _reflectionBalance[sender].sub(amount.mul(rate)); _reflectionBalance[recipient] = _reflectionBalance[recipient].add(transferAmount.mul(rate)); //@dev If any account belongs to the excludedAccount transfer token if (_isExcluded[sender]) { _tokenBalance[sender] = _tokenBalance[sender].sub(amount); } if (_isExcluded[recipient]) { _tokenBalance[recipient] = _tokenBalance[recipient].add(transferAmount); } emit Transfer(sender, recipient, transferAmount); } function _burn(address account, uint256 amount) public onlyOwner { require(account != address(0), "ERC20: burn from the zero address"); require(account == msg.sender); _reflectionBalance[account] = _reflectionBalance[account].sub(amount, "ERC20: burn amount exceeds balance"); _tokenTotal = _tokenTotal.sub(amount); emit Transfer(account, address(0), amount); } function collectFee(address account, uint256 amount, uint256 rate) private returns (uint256) { uint256 transferAmount = amount; uint256 charityFee = amount.mul(_charityFee).div(10000); uint256 refferalFee = amount.mul(_refferalFee).div(10000); uint256 taxFee = amount.mul(_taxFee).div(10000); //@dev Tax fee if (taxFee > 0) { transferAmount = transferAmount.sub(taxFee); _reflectionTotal = _reflectionTotal.sub(taxFee.mul(rate)); _taxFeeTotal = _taxFeeTotal.add(taxFee); emit RewardsDistributed(taxFee); } //@dev Charity fee if(charityFee > 0){ transferAmount = transferAmount.sub(charityFee); _reflectionBalance[charityAddress] = _reflectionBalance[charityAddress].add(charityFee.mul(rate)); _charityFeeTotal = _charityFeeTotal.add(charityFee); emit Transfer(account,charityAddress,charityFee); } //@dev refferalFee fee if(refferalFee > 0){ transferAmount = transferAmount.sub(refferalFee); _reflectionBalance[refferalAddress] = _reflectionBalance[refferalAddress].add(refferalFee.mul(rate)); _charityFeeTotal = _refferalFeeTotal.add(refferalFee); emit Transfer(account,refferalAddress,refferalFee); } return transferAmount; } function _getReflectionRate() private view returns (uint256) { uint256 reflectionSupply = _reflectionTotal; uint256 tokenSupply = _tokenTotal; for (uint256 i = 0; i < _excluded.length; i++) { if ( _reflectionBalance[_excluded[i]] > reflectionSupply || _tokenBalance[_excluded[i]] > tokenSupply ) return _reflectionTotal.div(_tokenTotal); reflectionSupply = reflectionSupply.sub( _reflectionBalance[_excluded[i]] ); tokenSupply = tokenSupply.sub(_tokenBalance[_excluded[i]]); } if (reflectionSupply < _reflectionTotal.div(_tokenTotal)) return _reflectionTotal.div(_tokenTotal); return reflectionSupply.div(tokenSupply); } function ExcludedFromFee(address account, bool) public onlyOwner { isExcludedFromFee[account] = true; } function IncludeFromFee(address account, bool) public onlyOwner { isExcludedFromFee[account] = false; } function setTaxFee(uint256 fee) public onlyOwner { _taxFee = fee; } function setCharityFee(uint256 fee) public onlyOwner { _charityFee = fee; } function setRefferalAddress(address _Address) public onlyOwner { require(_Address != refferalAddress); refferalAddress = _Address; } function setRefferalFee(uint256 fee) public onlyOwner { _refferalFee = fee; } function setCharityAddress(address _Address) public onlyOwner { require(_Address != charityAddress); charityAddress = _Address; } // function to allow admin to transfer ERC20 tokens from this contract function transferAnyERC20Tokens(address _tokenAddress, address _to, uint256 _amount) public onlyOwner { Token(_tokenAddress).transfer(_to, _amount); } receive() external payable {} }
* @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); }
221,544
[ 1, 8650, 487, 288, 22044, 17, 1887, 17, 915, 26356, 620, 17, 2867, 17, 3890, 17, 11890, 5034, 17, 20294, 68, 915, 26356, 620, 68, 6487, 1496, 598, 1375, 1636, 1079, 68, 487, 279, 5922, 15226, 3971, 1347, 1375, 3299, 68, 15226, 87, 18, 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, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 445, 26356, 620, 12, 203, 3639, 1758, 1018, 16, 203, 3639, 1731, 3778, 501, 16, 203, 3639, 2254, 5034, 460, 16, 203, 3639, 533, 3778, 9324, 203, 565, 262, 2713, 1135, 261, 3890, 3778, 13, 288, 203, 3639, 2583, 12, 203, 5411, 1758, 12, 2211, 2934, 12296, 1545, 460, 16, 203, 5411, 315, 1887, 30, 2763, 11339, 11013, 364, 745, 6, 203, 3639, 11272, 203, 3639, 327, 389, 915, 26356, 620, 12, 3299, 16, 501, 16, 460, 16, 9324, 1769, 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 ]
./full_match/1/0x553F52DFA1ec7cAfd7209dCD7c9c455b75112Db3/sources/Lowkey.sol
Calculate fee of the transaction amount for mevs
burnAmount = amount * BURN_FEE_PERCENT_MEV / 100;
4,928,373
[ 1, 8695, 14036, 434, 326, 2492, 3844, 364, 1791, 6904, 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, 7734, 18305, 6275, 273, 3844, 380, 605, 8521, 67, 8090, 41, 67, 3194, 19666, 67, 958, 58, 342, 2130, 31, 282, 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 ]
./partial_match/1/0xe433F992F2d282d63a1F1acC54d4B37D9546F819/sources/Oracle.sol
* @title The Chainlink Oracle contract @notice Node operators can deploy this contract to fulfill requests sent to them/ We initialize fields to 1 instead of 0 so that the first invocation does not cost more gas.
contract Oracle is ChainlinkRequestInterface, OracleInterface, Ownable { using SafeMathChainlink for uint256; uint256 constant public EXPIRY_TIME = 5 minutes; uint256 constant private MINIMUM_CONSUMER_GAS_LIMIT = 400000; uint256 constant private ONE_FOR_CONSISTENT_GAS_COST = 1; uint256 constant private SELECTOR_LENGTH = 4; uint256 constant private EXPECTED_REQUEST_WORDS = 2; uint256 constant private MINIMUM_REQUEST_LENGTH = SELECTOR_LENGTH + (32 * EXPECTED_REQUEST_WORDS); LinkTokenInterface internal LinkToken; mapping(bytes32 => bytes32) private commitments; mapping(address => bool) private authorizedNodes; uint256 private withdrawableTokens = ONE_FOR_CONSISTENT_GAS_COST; event OracleRequest( bytes32 indexed specId, address requester, bytes32 requestId, uint256 payment, address callbackAddr, bytes4 callbackFunctionId, uint256 cancelExpiration, uint256 dataVersion, bytes data ); event CancelOracleRequest( bytes32 indexed requestId ); constructor(address _link) public Ownable() { } function onTokenTransfer( address _sender, uint256 _amount, bytes _data ) public onlyLINK validRequestLength(_data) permittedFunctionsForLINK(_data) { } }
9,176,021
[ 1, 1986, 7824, 1232, 28544, 6835, 225, 2029, 12213, 848, 7286, 333, 6835, 358, 22290, 3285, 3271, 358, 2182, 19, 1660, 4046, 1466, 358, 404, 3560, 434, 374, 1427, 716, 326, 1122, 9495, 1552, 486, 6991, 1898, 16189, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 28544, 353, 7824, 1232, 13398, 16, 28544, 1358, 16, 14223, 6914, 288, 203, 225, 1450, 14060, 10477, 3893, 1232, 364, 2254, 5034, 31, 203, 203, 225, 2254, 5034, 5381, 1071, 31076, 9590, 67, 4684, 273, 1381, 6824, 31, 203, 225, 2254, 5034, 5381, 3238, 6989, 18605, 67, 31668, 67, 43, 3033, 67, 8283, 273, 1059, 11706, 31, 203, 225, 2254, 5034, 5381, 3238, 15623, 67, 7473, 67, 2248, 28175, 67, 43, 3033, 67, 28343, 273, 404, 31, 203, 225, 2254, 5034, 5381, 3238, 9111, 916, 67, 7096, 273, 1059, 31, 203, 225, 2254, 5034, 5381, 3238, 5675, 23615, 67, 5519, 67, 23287, 273, 576, 31, 203, 225, 2254, 5034, 5381, 3238, 6989, 18605, 67, 5519, 67, 7096, 273, 9111, 916, 67, 7096, 397, 261, 1578, 380, 5675, 23615, 67, 5519, 67, 23287, 1769, 203, 203, 225, 4048, 1345, 1358, 2713, 4048, 1345, 31, 203, 225, 2874, 12, 3890, 1578, 516, 1731, 1578, 13, 3238, 3294, 1346, 31, 203, 225, 2874, 12, 2867, 516, 1426, 13, 3238, 10799, 3205, 31, 203, 225, 2254, 5034, 3238, 598, 9446, 429, 5157, 273, 15623, 67, 7473, 67, 2248, 28175, 67, 43, 3033, 67, 28343, 31, 203, 203, 225, 871, 28544, 691, 12, 203, 565, 1731, 1578, 8808, 857, 548, 16, 203, 565, 1758, 19961, 16, 203, 565, 1731, 1578, 14459, 16, 203, 565, 2254, 5034, 5184, 16, 203, 565, 1758, 1348, 3178, 16, 203, 565, 1731, 24, 1348, 2083, 548, 16, 203, 565, 2254, 5034, 3755, 12028, 16, 203, 565, 2254, 5034, 501, 1444, 16, 203, 565, 2 ]
./full_match/137/0xB24Aa2E03E66cfe46121BF852aa08045a124dd6D/sources/sol-defifactory-token/CrossChainBridge.sol
allow to bridge to polygon
bulkFees[3] = BulkFeeDependingOnDestinationChainId(0xdef1fac7Bf08f173D286BbBDcBeeADe695129840, MATIC_MAINNET_CHAIN_ID, 25000 * 1e18);
4,743,028
[ 1, 5965, 358, 10105, 358, 7154, 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, 5411, 8280, 2954, 281, 63, 23, 65, 273, 18184, 14667, 4584, 310, 1398, 5683, 3893, 548, 12, 20, 92, 536, 21, 11639, 27, 38, 74, 6840, 74, 31331, 40, 22, 5292, 38, 70, 18096, 71, 27997, 37, 758, 8148, 13757, 29, 28585, 16, 490, 11781, 67, 19803, 14843, 67, 1792, 6964, 67, 734, 16, 6969, 3784, 380, 404, 73, 2643, 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 ]
./partial_match/56/0x95C17381581332cbA6c7D65CfA76B14cC0780f7d/sources/SHOCHU.sol
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 override { SHOCHU if (transferBurnRate > 0 && _transferBurnExceptAddresses[sender] != true && _transferBurnExceptAddresses[recipient] != true && recipient != address(0)) { uint256 _burntAmount = amount * transferBurnRate / 100; super._burn(sender, _burntAmount); amount = amount - _burntAmount; } super._transfer(sender, recipient, amount); _moveDelegates(_delegates[sender], _delegates[recipient], amount); }
11,178,724
[ 1, 73, 18, 75, 18, 2348, 5859, 1147, 1656, 281, 16, 9026, 310, 1791, 28757, 16, 5527, 18, 7377, 1282, 279, 288, 5912, 97, 871, 18, 29076, 30, 300, 1375, 15330, 68, 2780, 506, 326, 3634, 1758, 18, 300, 1375, 20367, 68, 2780, 506, 326, 3634, 1758, 18, 300, 1375, 15330, 68, 1297, 1240, 279, 11013, 434, 622, 4520, 1375, 8949, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 389, 13866, 12, 2867, 5793, 16, 1758, 8027, 16, 2254, 5034, 3844, 13, 2713, 5024, 3849, 288, 203, 2664, 51, 1792, 57, 203, 3639, 309, 261, 13866, 38, 321, 4727, 405, 374, 597, 389, 13866, 38, 321, 30212, 7148, 63, 15330, 65, 480, 638, 597, 389, 13866, 38, 321, 30212, 7148, 63, 20367, 65, 480, 638, 597, 8027, 480, 1758, 12, 20, 3719, 288, 203, 5411, 2254, 5034, 389, 70, 321, 88, 6275, 273, 3844, 380, 7412, 38, 321, 4727, 342, 2130, 31, 203, 5411, 2240, 6315, 70, 321, 12, 15330, 16, 389, 70, 321, 88, 6275, 1769, 203, 5411, 3844, 273, 3844, 300, 389, 70, 321, 88, 6275, 31, 203, 3639, 289, 203, 203, 3639, 2240, 6315, 13866, 12, 15330, 16, 8027, 16, 3844, 1769, 203, 3639, 389, 8501, 15608, 815, 24899, 3771, 1332, 815, 63, 15330, 6487, 389, 3771, 1332, 815, 63, 20367, 6487, 3844, 1769, 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 ]
// contracts/GLDToken.sol // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; import "@openzeppelin/contracts/utils/introspection/ERC165.sol"; import "./IPangolinRouter.sol"; import "./IBeefyVault.sol"; import "./IKalao.sol"; import "./Ownable.sol"; contract contractv1 is ERC165, IERC721Receiver { address public usdcAddr; address public ustAddr; // Init addresses address public constant PANGOLIN_ROUTER = 0xE54Ca86531e17Ef3616d22Ca28b0D458b6C89106; address public constant BEEFY_STAKE = 0x6399A5E96CD627404b203Ea80517C3F8F9F78Fe6; address public constant USDC_UST_LP = 0x3c0ECf5F430bbE6B16A8911CB25d898Ef20805cF; address public constant WAVAX = 0xB31f66AA3C1e785363F0875A1B74E27b85FD66c7; address public constant KALAO = 0x11AC3118309A7215c6d87c7C396e2DF333Ae3A9C; bool public strategyActive; // Init instances of Pangolin and Beefy for staking and changing tokens IPangolinRouter pangolinRouter = IPangolinRouter(PANGOLIN_ROUTER); IBeefyVault beefyVault = IBeefyVault(BEEFY_STAKE); IKalao kalao = IKalao(KALAO); // Declares the struct that will be used to store the staked amount of every user struct User { uint256 stakedAmount; } // Mapping the User struct to the address of the user mapping(address => User) data; uint256 public totalStake; // Initializing events event Staked(address indexed _from, uint256 _value); event Withdrawn(address indexed _to, uint256 _value); // Initializing errors error NotEnoughUSDC(); error NotEnoughUSDCTransfered(); error NoNFTsSpecified(); // Init UST and USDC addresses constructor(address _usdcAddr, address _ustAddr) { usdcAddr = _usdcAddr; ustAddr = _ustAddr; } // Modifier to verify if there is enought USDC available modifier enoughUSDCAvailable(uint256 maxUsdcAmountToSpend) { uint256 currentBalance = IERC20(usdcAddr).balanceOf(address(this)); uint256 maxUsdcAvailableToSpend = currentBalance / 2; if (maxUsdcAvailableToSpend < maxUsdcAmountToSpend) { revert NotEnoughUSDC(); } _; } /** * Starts the farming process by putting the funds into the pool * checks if the funds are available and checks the USDT-USDC difference for errors * * @param maxUsdcAmountToSpend defines the max amount you are allowed to spend * @param minUstAmountToBuy defines the minimal amount of UST we need to buy * */ function _startFarm(uint256 maxUsdcAmountToSpend, uint256 minUstAmountToBuy) internal enoughUSDCAvailable(maxUsdcAmountToSpend) { address[] memory path = new address[](2); path[0] = usdcAddr; path[1] = ustAddr; // Sets a deadline for the process uint256 deadline = block.timestamp; // If the transaction is under the max amount we want to spend, we approve the transaction if (IERC20(usdcAddr).allowance(address(this), PANGOLIN_ROUTER) < maxUsdcAmountToSpend) { IERC20(usdcAddr).approve(PANGOLIN_ROUTER, type(uint256).max); } // Change USDC to UST and keep the amount of UST we get uint256 boughtUST = pangolinRouter.swapExactTokensForTokens(maxUsdcAmountToSpend, minUstAmountToBuy, path, address(this), deadline)[1]; if (IERC20(ustAddr).allowance(address(this), PANGOLIN_ROUTER) < boughtUST) { IERC20(ustAddr).approve(PANGOLIN_ROUTER, type(uint256).max); } // Add liquidity to the UST/USDC pool (, , uint256 liquidity) = pangolinRouter.addLiquidity(usdcAddr, ustAddr, maxUsdcAmountToSpend, boughtUST, 0, 0, address(this), deadline); if (IERC20(USDC_UST_LP).allowance(address(this), PANGOLIN_ROUTER) < liquidity) { IERC20(USDC_UST_LP).approve(BEEFY_STAKE, type(uint256).max); } // Deposit the funds inside the vault beefyVault.depositAll(); } /** * Transfers the specifided amount to the pool, * incrementing the total supply * * emits a message on success * * @param amount defines the amount to stake * */ function stake(uint256 amount) public { IERC20(usdcAddr).transferFrom(msg.sender, address(this), amount); adding_values(msg.sender, amount); totalStake += amount; emit Staked(msg.sender, amount); } /** * Withdraws money from the pool * -> change the BEEFY token to UST/USDC pool token to UST and USDC tokens to USDC token * -> give back the USDC to the user * reducing the total supply * * emits a message on success with the address and the amount withdrawn * * @param useraddr specifies the address of the user wanting to withdraw * @param amount specifies the amount the user wants to withdraw * @param amountMinUST The minimum amount of UST that must be received for the transaction not to revert. * @param amountMinUSDC The minimum amount of USDC that must be received for the transaction not to revert. * @param minAmountUSDCTradeEND ?¿ * */ function withdraw( address useraddr, uint256 amount, uint256 amountMinUST, uint256 amountMinUSDC, uint256 minAmountUSDCTradeEND ) public { if (strategyActive) { withdrawBeefy(useraddr, amount, amountMinUST, amountMinUSDC, minAmountUSDCTradeEND); } else { withdrawUnsettled(useraddr, amount); } } function withdrawBeefy( address useraddr, uint256 amount, uint256 amountMinUST, uint256 amountMinUSDC, uint256 minAmountUSDCTradeEND ) internal { data[useraddr].stakedAmount -= amount; uint256 totalBeefy = IERC20(BEEFY_STAKE).balanceOf(address(this)); uint256 withdrawalAmount = (totalBeefy * amount) / totalStake; totalStake -= amount; // unstake beefy token if (IERC20(BEEFY_STAKE).allowance(address(this), BEEFY_STAKE) < withdrawalAmount) { IERC20(BEEFY_STAKE).approve(BEEFY_STAKE, type(uint256).max); } beefyVault.withdraw(withdrawalAmount); // init deadline uint256 deadline = block.timestamp; // get the balance of USDC_UST_LP uint256 pairBalance = IERC20(USDC_UST_LP).balanceOf(address(this)); if (IERC20(USDC_UST_LP).allowance(address(this), PANGOLIN_ROUTER) < pairBalance) { IERC20(USDC_UST_LP).approve(PANGOLIN_ROUTER, type(uint256).max); } // removeLiquidity of the pool and get the amount of UST and USDC we receive (uint256 amountUST, uint256 amountUSDC) = pangolinRouter.removeLiquidity( ustAddr, usdcAddr, pairBalance, amountMinUST, amountMinUSDC, address(this), deadline ); address[] memory path = new address[](2); path[0] = ustAddr; path[1] = usdcAddr; // change our UST into USDC token uint256 boughtUSDC = pangolinRouter.swapExactTokensForTokens(amountUST, 0, path, address(this), deadline)[1]; // send all the USDC to the user if (boughtUSDC + amountUSDC < minAmountUSDCTradeEND) { revert NotEnoughUSDCTransfered(); } IERC20(usdcAddr).transfer(msg.sender, boughtUSDC + amountUSDC); emit Withdrawn(msg.sender, boughtUSDC + amountUSDC); } function withdrawUnsettled(address useraddr, uint256 amount) internal { data[useraddr].stakedAmount -= amount; totalStake -= amount; IERC20(usdcAddr).transfer(msg.sender, amount); emit Withdrawn(msg.sender, amount); } /** * Define how much money is needed to buy the NFTs and put the other part in staking * * @param maxUsdcAmount defines the max USDC we are allowing the contract to spend * @param minUstAmount defines the lowest UST we want to get from this transaction * */ function settle( uint256 maxUsdcAmount, uint256 minUstAmount, uint256[] calldata nftsToBuy, uint256[] calldata priceToPay ) public { uint256 toStake = (9000 * maxUsdcAmount) / 10000; uint256 toBuyNFT = maxUsdcAmount - toStake; if (nftsToBuy.length == 0) { revert NoNFTsSpecified(); } uint256 totalSumToPay; for (uint256 i = 0; i < priceToPay.length; i++) { totalSumToPay += priceToPay[i]; } // swap to avax address[] memory path = new address[](2); path[0] = usdcAddr; path[1] = WAVAX; if (IERC20(usdcAddr).allowance(address(this), PANGOLIN_ROUTER) < toBuyNFT) { IERC20(usdcAddr).approve(PANGOLIN_ROUTER, type(uint256).max); } uint256 boughtAVAX = pangolinRouter.swapTokensForExactAVAX(totalSumToPay, toBuyNFT, path, address(this), block.timestamp)[1]; for (uint256 i = 0; i < nftsToBuy.length; i++) { kalao.buyNFT{ value: priceToPay[i] }(nftsToBuy[i]); } _startFarm(toStake, minUstAmount); } receive() external payable {} /** * Adds value to the user table, * values being the address and the amount staked * * @param useraddr defines the address of the user we want to add to the table * @param stakedAmount defines the amount the user has staked * */ function adding_values(address useraddr, uint256 stakedAmount) public { User storage user = data[useraddr]; user.stakedAmount += stakedAmount; } /** * Retrieves data from the storage * * @param useraddr defines the address of the user we want to get information from * @return data returns the amount staked from the user specified by the address passed as argument * */ function get_user_data(address useraddr) public view returns (User memory) { return data[useraddr]; } function onERC721Received( address, address, uint256, bytes memory ) public virtual override returns (bytes4) { return this.onERC721Received.selector; } }
Add liquidity to the UST/USDC pool
(, , uint256 liquidity) = pangolinRouter.addLiquidity(usdcAddr, ustAddr, maxUsdcAmountToSpend, boughtUST, 0, 0, address(this), deadline);
2,506,702
[ 1, 986, 4501, 372, 24237, 358, 326, 587, 882, 19, 3378, 5528, 2845, 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, 261, 16, 269, 2254, 5034, 4501, 372, 24237, 13, 273, 293, 539, 355, 267, 8259, 18, 1289, 48, 18988, 24237, 12, 407, 7201, 3178, 16, 582, 334, 3178, 16, 943, 3477, 7201, 6275, 774, 27223, 16, 800, 9540, 5996, 16, 374, 16, 374, 16, 1758, 12, 2211, 3631, 14096, 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 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.8.4; import {SDaoRegistrar} from '../SDaoRegistrar.sol'; import {ISDaoRegistrarCodeAccessible} from './interfaces/ISDaoRegistrarCodeAccessible.sol'; import '@openzeppelin/contracts/utils/cryptography/ECDSA.sol'; /** * @title SDaoRegistrarCodeAccessible contract. * @dev Implementation of the {ISDaoRegistrarCodeAccessible}. */ abstract contract SDaoRegistrarCodeAccessible is SDaoRegistrar, ISDaoRegistrarCodeAccessible { using ECDSA for bytes32; mapping(bytes32 => bool) public _consumed; address public _codeSigner; struct EIP712Domain { string name; string version; uint256 chainId; address verifyingContract; } struct CodeOrigin { address recipient; uint256 groupId; } bytes32 constant EIP712DOMAIN_TYPEHASH = keccak256( 'EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)' ); bytes32 constant CODE_ORIGIN_TYPEHASH = keccak256('CodeOrigin(address recipient,uint256 groupId)'); bytes32 immutable DOMAIN_SEPARATOR; /** * @dev Constructor. * @param name The name field of the EIP712 Domain. * @param version The version field of the EIP712 Domain. * @param codeSigner The address of the code signer. */ constructor( string memory name, string memory version, address codeSigner ) { DOMAIN_SEPARATOR = _hash( EIP712Domain({ name: name, version: version, chainId: block.chainid, verifyingContract: address(this) }) ); _restricted = true; _codeSigner = codeSigner; } /** * @notice Register a name and mints a DAO token using an access code. * @dev Can only be called by the recipient of the access code generated by the code signer. * @param label The label to register. * @param label Address of the recipient of the registration. * @param accessCode The EIP712 signature corresponding to a groupId and the recipient address. */ function registerWithAccessCode( string memory label, address recipient, bytes memory accessCode ) external override { uint256 groupId = _getCurrentGroupId(); CodeOrigin memory codeOrigin = CodeOrigin({ recipient: recipient, groupId: groupId }); bytes32 digest = DOMAIN_SEPARATOR.toTypedDataHash(_hash(codeOrigin)); require( !_consumed[digest], 'SDAO_REGISTRAR_LIMITED_CODE_ACCESSIBLE: ACCESS_CODE_ALREADY_CONSUMED' ); require( digest.recover(accessCode) == _codeSigner, 'SDAO_REGISTRAR_LIMITED_CODE_ACCESSIBLE: INVALID_ACCESS_CODE OR INVALID_SENDER' ); _register(recipient, label); _consumed[digest] = true; emit AccessCodeConsumed(groupId, accessCode); } /** * @notice Update the code signer. * @dev Can only be called by the owner. * @param codeSigner The address of the code signer. */ function updateCodeSigner(address codeSigner) public override onlyOwner { _codeSigner = codeSigner; emit CodeSignerUpdated(codeSigner); } /** * @dev Encode and hash an EIP712Domain structure. * @return The hash of the encoding of the EIP712Domain structure. */ function _hash(EIP712Domain memory eip712Domain) internal pure returns (bytes32) { return keccak256( abi.encode( EIP712DOMAIN_TYPEHASH, keccak256(bytes(eip712Domain.name)), keccak256(bytes(eip712Domain.version)), eip712Domain.chainId, eip712Domain.verifyingContract ) ); } /** * @dev Encode and hash an CodeOrigin structure. * @return The hash of the encoding of the CodeOrigin structure. */ function _hash(CodeOrigin memory codeOrigin) internal pure returns (bytes32) { return keccak256( abi.encode( CODE_ORIGIN_TYPEHASH, codeOrigin.recipient, codeOrigin.groupId ) ); } /** * @dev Get the current group ID. * @return The current group ID. */ function _getCurrentGroupId() internal virtual returns (uint256); }
* @dev Encode and hash an CodeOrigin structure. @return The hash of the encoding of the CodeOrigin structure./
function _hash(CodeOrigin memory codeOrigin) internal pure returns (bytes32) { return keccak256( abi.encode( CODE_ORIGIN_TYPEHASH, codeOrigin.recipient, codeOrigin.groupId ) ); }
1,023,355
[ 1, 5509, 471, 1651, 392, 3356, 7571, 3695, 18, 327, 1021, 1651, 434, 326, 2688, 434, 326, 3356, 7571, 3695, 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 ]
[ 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, 225, 445, 389, 2816, 12, 1085, 7571, 3778, 981, 7571, 13, 2713, 16618, 1135, 261, 3890, 1578, 13, 288, 203, 565, 327, 203, 1377, 417, 24410, 581, 5034, 12, 203, 3639, 24126, 18, 3015, 12, 203, 1850, 11128, 67, 24685, 67, 2399, 15920, 16, 203, 1850, 981, 7571, 18, 20367, 16, 203, 1850, 981, 7571, 18, 27547, 203, 3639, 262, 203, 1377, 11272, 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 ]
./full_match/83/0xCFac462FDdaA0cC29Cd24Fa36243cA0e2Eefd5F4/sources/contracts/Upgradeable/BaseV1-bribesUpgradeable.sol
@notice The number of checkpoints for each account
mapping(uint256 => uint256) public numCheckpoints;
9,560,944
[ 1, 1986, 1300, 434, 26402, 364, 1517, 2236, 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, 2874, 12, 11890, 5034, 516, 2254, 5034, 13, 1071, 818, 1564, 4139, 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 ]
./full_match/11155111/0xe491E0bA5a8fc0015e3a4a50FaD2a6f94cD825c5/sources/project_/contracts/Tsunami.sol
allows y to participate. c, s should be a Schnorr signature on "this"
function register(bytes32[2] calldata y_tuple, uint256 c, uint256 s) external { Utils.G1Point memory y = Utils.G1Point(y_tuple[0], y_tuple[1]); Utils.G1Point memory K = Utils.g().pMul(s).pAdd(y.pMul(c.gNeg())); uint256 challenge = uint256(keccak256(abi.encode(address(this), y, K))).gMod(); require(challenge == c, "Invalid signature!"); bytes32 yHash = keccak256(abi.encode(y)); require(!registered(yHash), "Account already registered!"); users.add(yHash); totalTransactions += 1; emit RegisterSuccess(y_tuple); }
3,788,553
[ 1, 5965, 87, 677, 358, 30891, 340, 18, 276, 16, 272, 1410, 506, 279, 348, 343, 29561, 86, 3372, 603, 315, 2211, 6, 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 ]
[ 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, 0, 0 ]
[ 1, 565, 445, 1744, 12, 3890, 1578, 63, 22, 65, 745, 892, 677, 67, 8052, 16, 2254, 5034, 276, 16, 2254, 5034, 272, 13, 3903, 288, 203, 203, 3639, 6091, 18, 43, 21, 2148, 3778, 677, 273, 6091, 18, 43, 21, 2148, 12, 93, 67, 8052, 63, 20, 6487, 677, 67, 8052, 63, 21, 19226, 203, 3639, 6091, 18, 43, 21, 2148, 3778, 1475, 273, 6091, 18, 75, 7675, 84, 27860, 12, 87, 2934, 84, 986, 12, 93, 18, 84, 27860, 12, 71, 18, 75, 14337, 1435, 10019, 203, 3639, 2254, 5034, 12948, 273, 2254, 5034, 12, 79, 24410, 581, 5034, 12, 21457, 18, 3015, 12, 2867, 12, 2211, 3631, 677, 16, 1475, 3719, 2934, 75, 1739, 5621, 203, 3639, 2583, 12, 25092, 422, 276, 16, 315, 1941, 3372, 4442, 1769, 203, 3639, 1731, 1578, 677, 2310, 273, 417, 24410, 581, 5034, 12, 21457, 18, 3015, 12, 93, 10019, 203, 3639, 2583, 12, 5, 14327, 12, 93, 2310, 3631, 315, 3032, 1818, 4104, 4442, 1769, 203, 203, 3639, 3677, 18, 1289, 12, 93, 2310, 1769, 203, 203, 3639, 2078, 14186, 1011, 404, 31, 203, 3639, 3626, 5433, 4510, 12, 93, 67, 8052, 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 ]
./partial_match/1/0xeB40E25AF8F5F22Bb201f53971480beA0094Cd65/sources/src/v0.8/functions/dev/1_0_0/FunctionsSubscriptions.sol
@inheritdoc IFunctionsSubscriptions
function getSubscriptionCount() external view override returns (uint64) { return s_currentSubscriptionId; }
4,322,412
[ 1, 36, 10093, 467, 7503, 15440, 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, 225, 445, 7040, 3100, 1380, 1435, 3903, 1476, 3849, 1135, 261, 11890, 1105, 13, 288, 203, 565, 327, 272, 67, 2972, 6663, 548, 31, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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 pragma solidity 0.8.1; import "./unlockItems.sol"; /** * @title Market * @notice Here you can sell your items against ETH. You create a selling order and when someone buys it, * you can come and withdraw your ETH. You can emit whitlested selling orders * @dev This contract allows the player to exchange his NFT against ETH. Here he can make selling order * whitlested or not. */ contract marketPlace is unlockItems{ ///@dev The basis one which the sold are made.Here everithing is in Ether uint base = 1 ether; /** * @dev The structure of a market order. * @param name is the name of the item * @param idItem is the tokenId, * @param price requested is the price wished for the items * param level is the level of the item * @param active indicate if the order is on or off */ struct MarketOrder{ string name; uint8 level; uint idItem; uint priceRequested; bool active; } /** * @dev whitelisted Order structure, * @param the adress whitelisted * @param active indicate if the order is on or off */ struct whitelistOrder{ string name; uint8 level; uint idItem; uint priceRequested; address whitelistAddress; bool active; } ///@dev Mapping linking the orderId and the whitelistOrder structure. mapping (uint => whitelistOrder) public orderWithWithelist; ///@dev Mapping of the accounts of sellers mapping (address => uint ) public balancePlayer; ///@dev Mapping of all the selling orders mapping (uint => MarketOrder) public marketOrders; event myNewMarketOrder (address indexed _from); event myNewMarketOrderWithlisted (address indexed _from); event newMarketOrder (uint tokenId); event newMarketOrderWithlisted (uint tokenId); event soldMade(uint tokenId); event soldMadeWhitelisted(uint tokenId); event orderCanceled(uint tokenId, address indexed _from); event moneyWithdrawn(uint amount, address indexed _from); ///@dev Get a list of all the owners by continent of items. On the front this will make a rank function getRankByContinent(uint _numContinent) public view returns(address[] memory) { uint numberItemsOnContinent; uint counterOwner; for (uint i = 0; i < items.length ;i++ ){ if((ownerOf(items[i].tokenId) != _administrator) && items[i].continent == _numContinent ){ numberItemsOnContinent ++; } } address[] memory ownerOfItem = new address[](numberItemsOnContinent); for (uint i = 0; i < items.length ;i++ ){ if((ownerOf(items[i].tokenId) != _administrator) && items[i].continent == _numContinent ){ ownerOfItem[counterOwner] = ownerOf(items[i].tokenId); counterOwner ++; } } return ownerOfItem; } ///@dev Get access to the customized map of a player function getItemsOfPlayer(address _itemsOwner) public view returns(uint[] memory){ uint numberItem = balanceOf(_itemsOwner); uint[] memory idsItemsOwned = new uint[](numberItem); for (uint i=0; i < numberItem; i++){ idsItemsOwned[i] = tokenOfOwnerByIndex(_itemsOwner,i); } return idsItemsOwned; } ///@dev Allows owners to set a market order for selling function setMarketOrder(uint _amountWhished, uint _idItemSold) public{ require(ownerOf(_idItemSold) == msg.sender, "Not the owner of the item"); require(!items[_idItemSold].onSold, "this item is already on sold"); string memory nameItem = items[_idItemSold].name; uint8 levelOrder = items[_idItemSold].levelItem; marketOrders[_idItemSold] = MarketOrder(nameItem,levelOrder,_idItemSold,_amountWhished, true); items[_idItemSold].onSold = true; emit newMarketOrder (_idItemSold); emit myNewMarketOrder (msg.sender); } ///@dev Allows owners to set a whitelisted market order function setMarketOrderWhitelisted(uint _amountWhished, uint _idItemSold, address _whitelistAddress) public{ require(ownerOf(_idItemSold) == msg.sender, "Not the owner of the item"); require(!items[_idItemSold].onSold, "this item is already on sold"); string memory nameItem = items[_idItemSold].name; uint8 levelOrder = items[_idItemSold].levelItem; orderWithWithelist[_idItemSold] = whitelistOrder(nameItem,levelOrder,_idItemSold,_amountWhished, _whitelistAddress, true); items[_idItemSold].onSold = true; emit newMarketOrderWithlisted(_idItemSold); emit myNewMarketOrderWithlisted(msg.sender); } ///@dev Allows anyone to buy an existing selling function getOrder(uint _idOrder) public payable{ require(!orderWithWithelist[_idOrder].active, "order whitlisted" ); require(marketOrders[_idOrder].active, "this order does not exist"); require(msg.value == (marketOrders[_idOrder].priceRequested * base), "price not exact"); items[_idOrder].onSold = false; balancePlayer[ownerOf(_idOrder)] = balancePlayer[ownerOf(_idOrder)] + msg.value; _endOrder(_idOrder); _transfer(ownerOf(_idOrder),msg.sender, _idOrder); emit soldMade(_idOrder); } ///@dev Allows the whitlisted address only to get the item function getWhitelistedOrder(uint _idOrder) public payable{ require(!marketOrders[_idOrder].active, "this order is in the open market"); require(orderWithWithelist[_idOrder].active, "This address doesn't exist" ); require(orderWithWithelist[_idOrder].whitelistAddress == msg.sender , "Not the selected reiceiver"); require(msg.value == (orderWithWithelist[_idOrder].priceRequested * base), "price not exact"); items[_idOrder].onSold = false; balancePlayer[ownerOf(_idOrder)] = balancePlayer[ownerOf(_idOrder)] + msg.value; _endOrder(_idOrder); _transfer(ownerOf(_idOrder),msg.sender, _idOrder); emit soldMadeWhitelisted(_idOrder); } ///@dev A seller can cancel a pending selling order function cancelOrder(uint _idOrder) public { require (ownerOf(_idOrder) == msg.sender); items[_idOrder].onSold = false; _endOrder(_idOrder); emit orderCanceled(_idOrder, msg.sender); } ///@dev End an order function _endOrder(uint _idOrder) private { delete marketOrders[_idOrder]; delete orderWithWithelist[_idOrder]; } ///@dev Allows the seller withdraw all his money from selling function withdrawAmount() public { require (balancePlayer[msg.sender] != 0, "nothing to withdraw"); uint amount = balancePlayer[msg.sender]; balancePlayer[msg.sender] = 0; (bool success, ) = msg.sender.call{value: amount}(""); require(success, 'transfer failed'); emit moneyWithdrawn(amount, msg.sender); } }
@dev Mapping of all the selling orders
mapping (uint => MarketOrder) public marketOrders;
1,002,114
[ 1, 3233, 434, 777, 326, 357, 2456, 11077, 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, 202, 6770, 261, 11890, 516, 6622, 278, 2448, 13, 1071, 13667, 16528, 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 ]
/** *Submitted for verification at Etherscan.io on 2022-03-17 */ // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; // Global Enums and Structs struct StrategyParams { uint256 performanceFee; uint256 activation; uint256 debtRatio; uint256 minDebtPerHarvest; uint256 maxDebtPerHarvest; uint256 lastReport; uint256 totalDebt; uint256 totalGain; uint256 totalLoss; } // Part: ILiquidityPool /// @title Interface for Pool /// @notice Allows users to deposit ERC-20 tokens to be deployed to market makers. /// @notice Mints 1:1 tAsset on deposit, represeting an IOU for the undelrying token that is freely transferable. /// @notice Holders of tAsset earn rewards based on duration their tokens were deployed and the demand for that asset. /// @notice Holders of tAsset can redeem for underlying asset after issuing requestWithdrawal and waiting for the next cycle. interface ILiquidityPool { struct WithdrawalInfo { uint256 minCycle; uint256 amount; } event WithdrawalRequested(address requestor, uint256 amount); event DepositsPaused(); event DepositsUnpaused(); /// @notice Transfers amount of underlying token from user to this pool and mints fToken to the msg.sender. /// @notice Depositor must have previously granted transfer approval to the pool via underlying token contract. /// @notice Liquidity deposited is deployed on the next cycle - unless a withdrawal request is submitted, in which case the liquidity will be withheld. function deposit(uint256 amount) external; /// @notice Transfers amount of underlying token from user to this pool and mints fToken to the account. /// @notice Depositor must have previously granted transfer approval to the pool via underlying token contract. /// @notice Liquidity deposited is deployed on the next cycle - unless a withdrawal request is submitted, in which case the liquidity will be withheld. function depositFor(address account, uint256 amount) external; /// @notice Requests that the manager prepare funds for withdrawal next cycle /// @notice Invoking this function when sender already has a currently pending request will overwrite that requested amount and reset the cycle timer /// @param amount Amount of fTokens requested to be redeemed function requestWithdrawal(uint256 amount) external; function approveManager(uint256 amount) external; /// @notice Sender must first invoke requestWithdrawal in a previous cycle /// @notice This function will burn the fAsset and transfers underlying asset back to sender /// @notice Will execute a partial withdrawal if either available liquidity or previously requested amount is insufficient /// @param amount Amount of fTokens to redeem, value can be in excess of available tokens, operation will be reduced to maximum permissible function withdraw(uint256 amount) external; /// @return Reference to the underlying ERC-20 contract function underlyer() external view returns (address); /// @return Amount of liquidity that should not be deployed for market making (this liquidity will be used for completing requested withdrawals) function withheldLiquidity() external view returns (uint256); /// @notice Get withdraw requests for an account /// @param account User account to check /// @return minCycle Cycle - block number - that must be active before withdraw is allowed, amount Token amount requested function requestedWithdrawals(address account) external view returns (uint256, uint256); /// @notice Pause deposits on the pool. Withdraws still allowed function pause() external; /// @notice Unpause deposits on the pool. function unpause() external; // @notice Pause deposits only on the pool. function pauseDeposit() external; // @notice Unpause deposits only on the pool. function unpauseDeposit() external; } // Part: IManager interface IManager { // bytes can take on the form of deploying or recovering liquidity struct ControllerTransferData { bytes32 controllerId; // controller to target bytes data; // data the controller will pass } struct PoolTransferData { address pool; // pool to target uint256 amount; // amount to transfer } struct MaintenanceExecution { ControllerTransferData[] cycleSteps; } struct RolloverExecution { PoolTransferData[] poolData; ControllerTransferData[] cycleSteps; address[] poolsForWithdraw; //Pools to target for manager -> pool transfer bool complete; //Whether to mark the rollover complete string rewardsIpfsHash; } event ControllerRegistered(bytes32 id, address controller); event ControllerUnregistered(bytes32 id, address controller); event PoolRegistered(address pool); event PoolUnregistered(address pool); event CycleDurationSet(uint256 duration); event LiquidityMovedToManager(address pool, uint256 amount); event DeploymentStepExecuted(bytes32 controller, address adapaterAddress, bytes data); event LiquidityMovedToPool(address pool, uint256 amount); event CycleRolloverStarted(uint256 blockNumber); event CycleRolloverComplete(uint256 blockNumber); event DestinationsSet(address destinationOnL1, address destinationOnL2); event EventSendSet(bool eventSendSet); /// @notice Registers controller /// @param id Bytes32 id of controller /// @param controller Address of controller function registerController(bytes32 id, address controller) external; /// @notice Registers pool /// @param pool Address of pool function registerPool(address pool) external; /// @notice Unregisters controller /// @param id Bytes32 controller id function unRegisterController(bytes32 id) external; /// @notice Unregisters pool /// @param pool Address of pool function unRegisterPool(address pool) external; ///@notice Gets addresses of all pools registered ///@return Memory array of pool addresses function getPools() external view returns (address[] memory); ///@notice Gets ids of all controllers registered ///@return Memory array of Bytes32 controller ids function getControllers() external view returns (bytes32[] memory); ///@notice Allows for owner to set cycle duration ///@param duration Block durtation of cycle function setCycleDuration(uint256 duration) external; ///@notice Starts cycle rollover ///@dev Sets rolloverStarted state boolean to true function startCycleRollover() external; ///@notice Allows for controller commands to be executed midcycle ///@param params Contains data for controllers and params function executeMaintenance(MaintenanceExecution calldata params) external; ///@notice Allows for withdrawals and deposits for pools along with liq deployment ///@param params Contains various data for executing against pools and controllers function executeRollover(RolloverExecution calldata params) external; ///@notice Completes cycle rollover, publishes rewards hash to ipfs ///@param rewardsIpfsHash rewards hash uploaded to ipfs function completeRollover(string calldata rewardsIpfsHash) external; ///@notice Gets reward hash by cycle index ///@param index Cycle index to retrieve rewards hash ///@return String memory hash function cycleRewardsHashes(uint256 index) external view returns (string memory); ///@notice Gets current starting block ///@return uint256 with block number function getCurrentCycle() external view returns (uint256); ///@notice Gets current cycle index ///@return uint256 current cycle number function getCurrentCycleIndex() external view returns (uint256); ///@notice Gets current cycle duration ///@return uint256 in block of cycle duration function getCycleDuration() external view returns (uint256); ///@notice Gets cycle rollover status, true for rolling false for not ///@return Bool representing whether cycle is rolling over or not function getRolloverStatus() external view returns (bool); function setDestinations(address destinationOnL1, address destinationOnL2) external; /// @notice Sets state variable that tells contract if it can send data to EventProxy /// @param eventSendSet Bool to set state variable to function setEventSend(bool eventSendSet) external; } // Part: ITradeFactory interface ITradeFactory { function enable(address, address) external; } // Part: OpenZeppelin/[email protected]/Address /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // Part: OpenZeppelin/[email protected]/IERC20 /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // Part: OpenZeppelin/[email protected]/Math /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // Part: OpenZeppelin/[email protected]/SafeMath /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // Part: yearn/[email protected]/HealthCheck interface HealthCheck { function check( uint256 profit, uint256 loss, uint256 debtPayment, uint256 debtOutstanding, uint256 totalDebt ) external view returns (bool); } // Part: IRewards interface IRewards { struct EIP712Domain { string name; string version; uint256 chainId; address verifyingContract; } struct Recipient { uint256 chainId; uint256 cycle; address wallet; uint256 amount; } event SignerSet(address newSigner); event Claimed(uint256 cycle, address recipient, uint256 amount); /// @notice Get the underlying token rewards are paid in /// @return Token address function tokeToken() external view returns (IERC20); /// @notice Get the current payload signer; /// @return Signer address function rewardsSigner() external view returns (address); /// @notice Check the amount an account has already claimed /// @param account Account to check /// @return Amount already claimed function claimedAmounts(address account) external view returns (uint256); /// @notice Get the amount that is claimable based on the provided payload /// @param recipient Published rewards payload /// @return Amount claimable if the payload is signed function getClaimableAmount(Recipient calldata recipient) external view returns (uint256); /// @notice Change the signer used to validate payloads /// @param newSigner The new address that will be signing rewards payloads function setSigner(address newSigner) external; /// @notice Claim your rewards /// @param recipient Published rewards payload /// @param v v component of the payload signature /// @param r r component of the payload signature /// @param s s component of the payload signature function claim( Recipient calldata recipient, uint8 v, bytes32 r, bytes32 s ) external; } // Part: OpenZeppelin/[email protected]/SafeERC20 /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // Part: yearn/[email protected]/VaultAPI interface VaultAPI is IERC20 { function name() external view returns (string calldata); function symbol() external view returns (string calldata); function decimals() external view returns (uint256); function apiVersion() external pure returns (string memory); function permit( address owner, address spender, uint256 amount, uint256 expiry, bytes calldata signature ) external returns (bool); // NOTE: Vyper produces multiple signatures for a given function with "default" args function deposit() external returns (uint256); function deposit(uint256 amount) external returns (uint256); function deposit(uint256 amount, address recipient) external returns (uint256); // NOTE: Vyper produces multiple signatures for a given function with "default" args function withdraw() external returns (uint256); function withdraw(uint256 maxShares) external returns (uint256); function withdraw(uint256 maxShares, address recipient) external returns (uint256); function token() external view returns (address); function strategies(address _strategy) external view returns (StrategyParams memory); function pricePerShare() external view returns (uint256); function totalAssets() external view returns (uint256); function depositLimit() external view returns (uint256); function maxAvailableShares() external view returns (uint256); /** * View how much the Vault would increase this Strategy's borrow limit, * based on its present performance (since its last report). Can be used to * determine expectedReturn in your Strategy. */ function creditAvailable() external view returns (uint256); /** * View how much the Vault would like to pull back from the Strategy, * based on its present performance (since its last report). Can be used to * determine expectedReturn in your Strategy. */ function debtOutstanding() external view returns (uint256); /** * View how much the Vault expect this Strategy to return at the current * block, based on its present performance (since its last report). Can be * used to determine expectedReturn in your Strategy. */ function expectedReturn() external view returns (uint256); /** * This is the main contact point where the Strategy interacts with the * Vault. It is critical that this call is handled as intended by the * Strategy. Therefore, this function will be called by BaseStrategy to * make sure the integration is correct. */ function report( uint256 _gain, uint256 _loss, uint256 _debtPayment ) external returns (uint256); /** * This function should only be used in the scenario where the Strategy is * being retired but no migration of the positions are possible, or in the * extreme scenario that the Strategy needs to be put into "Emergency Exit" * mode in order for it to exit as quickly as possible. The latter scenario * could be for any reason that is considered "critical" that the Strategy * exits its position as fast as possible, such as a sudden change in * market conditions leading to losses, or an imminent failure in an * external dependency. */ function revokeStrategy() external; /** * View the governance address of the Vault to assert privileged functions * can only be called by governance. The Strategy serves the Vault, so it * is subject to governance defined by the Vault. */ function governance() external view returns (address); /** * View the management address of the Vault to assert privileged functions * can only be called by management. The Strategy serves the Vault, so it * is subject to management defined by the Vault. */ function management() external view returns (address); /** * View the guardian address of the Vault to assert privileged functions * can only be called by guardian. The Strategy serves the Vault, so it * is subject to guardian defined by the Vault. */ function guardian() external view returns (address); } // Part: yearn/[email protected]/BaseStrategy /** * @title Yearn Base Strategy * @author yearn.finance * @notice * BaseStrategy implements all of the required functionality to interoperate * closely with the Vault contract. This contract should be inherited and the * abstract methods implemented to adapt the Strategy to the particular needs * it has to create a return. * * Of special interest is the relationship between `harvest()` and * `vault.report()'. `harvest()` may be called simply because enough time has * elapsed since the last report, and not because any funds need to be moved * or positions adjusted. This is critical so that the Vault may maintain an * accurate picture of the Strategy's performance. See `vault.report()`, * `harvest()`, and `harvestTrigger()` for further details. */ abstract contract BaseStrategy { using SafeMath for uint256; using SafeERC20 for IERC20; string public metadataURI; // health checks bool public doHealthCheck; address public healthCheck; /** * @notice * Used to track which version of `StrategyAPI` this Strategy * implements. * @dev The Strategy's version must match the Vault's `API_VERSION`. * @return A string which holds the current API version of this contract. */ function apiVersion() public pure returns (string memory) { return "0.4.3"; } /** * @notice This Strategy's name. * @dev * You can use this field to manage the "version" of this Strategy, e.g. * `StrategySomethingOrOtherV1`. However, "API Version" is managed by * `apiVersion()` function above. * @return This Strategy's name. */ function name() external view virtual returns (string memory); /** * @notice * The amount (priced in want) of the total assets managed by this strategy should not count * towards Yearn's TVL calculations. * @dev * You can override this field to set it to a non-zero value if some of the assets of this * Strategy is somehow delegated inside another part of of Yearn's ecosystem e.g. another Vault. * Note that this value must be strictly less than or equal to the amount provided by * `estimatedTotalAssets()` below, as the TVL calc will be total assets minus delegated assets. * Also note that this value is used to determine the total assets under management by this * strategy, for the purposes of computing the management fee in `Vault` * @return * The amount of assets this strategy manages that should not be included in Yearn's Total Value * Locked (TVL) calculation across it's ecosystem. */ function delegatedAssets() external view virtual returns (uint256) { return 0; } VaultAPI public vault; address public strategist; address public rewards; address public keeper; IERC20 public want; // So indexers can keep track of this event Harvested(uint256 profit, uint256 loss, uint256 debtPayment, uint256 debtOutstanding); event UpdatedStrategist(address newStrategist); event UpdatedKeeper(address newKeeper); event UpdatedRewards(address rewards); event UpdatedMinReportDelay(uint256 delay); event UpdatedMaxReportDelay(uint256 delay); event UpdatedProfitFactor(uint256 profitFactor); event UpdatedDebtThreshold(uint256 debtThreshold); event EmergencyExitEnabled(); event UpdatedMetadataURI(string metadataURI); // The minimum number of seconds between harvest calls. See // `setMinReportDelay()` for more details. uint256 public minReportDelay; // The maximum number of seconds between harvest calls. See // `setMaxReportDelay()` for more details. uint256 public maxReportDelay; // The minimum multiple that `callCost` must be above the credit/profit to // be "justifiable". See `setProfitFactor()` for more details. uint256 public profitFactor; // Use this to adjust the threshold at which running a debt causes a // harvest trigger. See `setDebtThreshold()` for more details. uint256 public debtThreshold; // See note on `setEmergencyExit()`. bool public emergencyExit; // modifiers modifier onlyAuthorized() { require(msg.sender == strategist || msg.sender == governance(), "!authorized"); _; } modifier onlyEmergencyAuthorized() { require( msg.sender == strategist || msg.sender == governance() || msg.sender == vault.guardian() || msg.sender == vault.management(), "!authorized" ); _; } modifier onlyStrategist() { require(msg.sender == strategist, "!strategist"); _; } modifier onlyGovernance() { require(msg.sender == governance(), "!authorized"); _; } modifier onlyKeepers() { require( msg.sender == keeper || msg.sender == strategist || msg.sender == governance() || msg.sender == vault.guardian() || msg.sender == vault.management(), "!authorized" ); _; } modifier onlyVaultManagers() { require(msg.sender == vault.management() || msg.sender == governance(), "!authorized"); _; } constructor(address _vault) public { _initialize(_vault, msg.sender, msg.sender, msg.sender); } /** * @notice * Initializes the Strategy, this is called only once, when the * contract is deployed. * @dev `_vault` should implement `VaultAPI`. * @param _vault The address of the Vault responsible for this Strategy. * @param _strategist The address to assign as `strategist`. * The strategist is able to change the reward address * @param _rewards The address to use for pulling rewards. * @param _keeper The adddress of the _keeper. _keeper * can harvest and tend a strategy. */ function _initialize( address _vault, address _strategist, address _rewards, address _keeper ) internal { require(address(want) == address(0), "Strategy already initialized"); vault = VaultAPI(_vault); want = IERC20(vault.token()); want.safeApprove(_vault, uint256(-1)); // Give Vault unlimited access (might save gas) strategist = _strategist; rewards = _rewards; keeper = _keeper; // initialize variables minReportDelay = 0; maxReportDelay = 86400; profitFactor = 100; debtThreshold = 0; vault.approve(rewards, uint256(-1)); // Allow rewards to be pulled } function setHealthCheck(address _healthCheck) external onlyVaultManagers { healthCheck = _healthCheck; } function setDoHealthCheck(bool _doHealthCheck) external onlyVaultManagers { doHealthCheck = _doHealthCheck; } /** * @notice * Used to change `strategist`. * * This may only be called by governance or the existing strategist. * @param _strategist The new address to assign as `strategist`. */ function setStrategist(address _strategist) external onlyAuthorized { require(_strategist != address(0)); strategist = _strategist; emit UpdatedStrategist(_strategist); } /** * @notice * Used to change `keeper`. * * `keeper` is the only address that may call `tend()` or `harvest()`, * other than `governance()` or `strategist`. However, unlike * `governance()` or `strategist`, `keeper` may *only* call `tend()` * and `harvest()`, and no other authorized functions, following the * principle of least privilege. * * This may only be called by governance or the strategist. * @param _keeper The new address to assign as `keeper`. */ function setKeeper(address _keeper) external onlyAuthorized { require(_keeper != address(0)); keeper = _keeper; emit UpdatedKeeper(_keeper); } /** * @notice * Used to change `rewards`. EOA or smart contract which has the permission * to pull rewards from the vault. * * This may only be called by the strategist. * @param _rewards The address to use for pulling rewards. */ function setRewards(address _rewards) external onlyStrategist { require(_rewards != address(0)); vault.approve(rewards, 0); rewards = _rewards; vault.approve(rewards, uint256(-1)); emit UpdatedRewards(_rewards); } /** * @notice * Used to change `minReportDelay`. `minReportDelay` is the minimum number * of blocks that should pass for `harvest()` to be called. * * For external keepers (such as the Keep3r network), this is the minimum * time between jobs to wait. (see `harvestTrigger()` * for more details.) * * This may only be called by governance or the strategist. * @param _delay The minimum number of seconds to wait between harvests. */ function setMinReportDelay(uint256 _delay) external onlyAuthorized { minReportDelay = _delay; emit UpdatedMinReportDelay(_delay); } /** * @notice * Used to change `maxReportDelay`. `maxReportDelay` is the maximum number * of blocks that should pass for `harvest()` to be called. * * For external keepers (such as the Keep3r network), this is the maximum * time between jobs to wait. (see `harvestTrigger()` * for more details.) * * This may only be called by governance or the strategist. * @param _delay The maximum number of seconds to wait between harvests. */ function setMaxReportDelay(uint256 _delay) external onlyAuthorized { maxReportDelay = _delay; emit UpdatedMaxReportDelay(_delay); } /** * @notice * Used to change `profitFactor`. `profitFactor` is used to determine * if it's worthwhile to harvest, given gas costs. (See `harvestTrigger()` * for more details.) * * This may only be called by governance or the strategist. * @param _profitFactor A ratio to multiply anticipated * `harvest()` gas cost against. */ function setProfitFactor(uint256 _profitFactor) external onlyAuthorized { profitFactor = _profitFactor; emit UpdatedProfitFactor(_profitFactor); } /** * @notice * Sets how far the Strategy can go into loss without a harvest and report * being required. * * By default this is 0, meaning any losses would cause a harvest which * will subsequently report the loss to the Vault for tracking. (See * `harvestTrigger()` for more details.) * * This may only be called by governance or the strategist. * @param _debtThreshold How big of a loss this Strategy may carry without * being required to report to the Vault. */ function setDebtThreshold(uint256 _debtThreshold) external onlyAuthorized { debtThreshold = _debtThreshold; emit UpdatedDebtThreshold(_debtThreshold); } /** * @notice * Used to change `metadataURI`. `metadataURI` is used to store the URI * of the file describing the strategy. * * This may only be called by governance or the strategist. * @param _metadataURI The URI that describe the strategy. */ function setMetadataURI(string calldata _metadataURI) external onlyAuthorized { metadataURI = _metadataURI; emit UpdatedMetadataURI(_metadataURI); } /** * Resolve governance address from Vault contract, used to make assertions * on protected functions in the Strategy. */ function governance() internal view returns (address) { return vault.governance(); } /** * @notice * Provide an accurate conversion from `_amtInWei` (denominated in wei) * to `want` (using the native decimal characteristics of `want`). * @dev * Care must be taken when working with decimals to assure that the conversion * is compatible. As an example: * * given 1e17 wei (0.1 ETH) as input, and want is USDC (6 decimals), * with USDC/ETH = 1800, this should give back 1800000000 (180 USDC) * * @param _amtInWei The amount (in wei/1e-18 ETH) to convert to `want` * @return The amount in `want` of `_amtInEth` converted to `want` **/ function ethToWant(uint256 _amtInWei) public view virtual returns (uint256); /** * @notice * Provide an accurate estimate for the total amount of assets * (principle + return) that this Strategy is currently managing, * denominated in terms of `want` tokens. * * This total should be "realizable" e.g. the total value that could * *actually* be obtained from this Strategy if it were to divest its * entire position based on current on-chain conditions. * @dev * Care must be taken in using this function, since it relies on external * systems, which could be manipulated by the attacker to give an inflated * (or reduced) value produced by this function, based on current on-chain * conditions (e.g. this function is possible to influence through * flashloan attacks, oracle manipulations, or other DeFi attack * mechanisms). * * It is up to governance to use this function to correctly order this * Strategy relative to its peers in the withdrawal queue to minimize * losses for the Vault based on sudden withdrawals. This value should be * higher than the total debt of the Strategy and higher than its expected * value to be "safe". * @return The estimated total assets in this Strategy. */ function estimatedTotalAssets() public view virtual returns (uint256); /* * @notice * Provide an indication of whether this strategy is currently "active" * in that it is managing an active position, or will manage a position in * the future. This should correlate to `harvest()` activity, so that Harvest * events can be tracked externally by indexing agents. * @return True if the strategy is actively managing a position. */ function isActive() public view returns (bool) { return vault.strategies(address(this)).debtRatio > 0 || estimatedTotalAssets() > 0; } /** * Perform any Strategy unwinding or other calls necessary to capture the * "free return" this Strategy has generated since the last time its core * position(s) were adjusted. Examples include unwrapping extra rewards. * This call is only used during "normal operation" of a Strategy, and * should be optimized to minimize losses as much as possible. * * This method returns any realized profits and/or realized losses * incurred, and should return the total amounts of profits/losses/debt * payments (in `want` tokens) for the Vault's accounting (e.g. * `want.balanceOf(this) >= _debtPayment + _profit`). * * `_debtOutstanding` will be 0 if the Strategy is not past the configured * debt limit, otherwise its value will be how far past the debt limit * the Strategy is. The Strategy's debt limit is configured in the Vault. * * NOTE: `_debtPayment` should be less than or equal to `_debtOutstanding`. * It is okay for it to be less than `_debtOutstanding`, as that * should only used as a guide for how much is left to pay back. * Payments should be made to minimize loss from slippage, debt, * withdrawal fees, etc. * * See `vault.debtOutstanding()`. */ function prepareReturn(uint256 _debtOutstanding) internal virtual returns ( uint256 _profit, uint256 _loss, uint256 _debtPayment ); /** * Perform any adjustments to the core position(s) of this Strategy given * what change the Vault made in the "investable capital" available to the * Strategy. Note that all "free capital" in the Strategy after the report * was made is available for reinvestment. Also note that this number * could be 0, and you should handle that scenario accordingly. * * See comments regarding `_debtOutstanding` on `prepareReturn()`. */ function adjustPosition(uint256 _debtOutstanding) internal virtual; /** * Liquidate up to `_amountNeeded` of `want` of this strategy's positions, * irregardless of slippage. Any excess will be re-invested with `adjustPosition()`. * This function should return the amount of `want` tokens made available by the * liquidation. If there is a difference between them, `_loss` indicates whether the * difference is due to a realized loss, or if there is some other sitution at play * (e.g. locked funds) where the amount made available is less than what is needed. * * NOTE: The invariant `_liquidatedAmount + _loss <= _amountNeeded` should always be maintained */ function liquidatePosition(uint256 _amountNeeded) internal virtual returns (uint256 _liquidatedAmount, uint256 _loss); /** * Liquidate everything and returns the amount that got freed. * This function is used during emergency exit instead of `prepareReturn()` to * liquidate all of the Strategy's positions back to the Vault. */ function liquidateAllPositions() internal virtual returns (uint256 _amountFreed); /** * @notice * Provide a signal to the keeper that `tend()` should be called. The * keeper will provide the estimated gas cost that they would pay to call * `tend()`, and this function should use that estimate to make a * determination if calling it is "worth it" for the keeper. This is not * the only consideration into issuing this trigger, for example if the * position would be negatively affected if `tend()` is not called * shortly, then this can return `true` even if the keeper might be * "at a loss" (keepers are always reimbursed by Yearn). * @dev * `callCostInWei` must be priced in terms of `wei` (1e-18 ETH). * * This call and `harvestTrigger()` should never return `true` at the same * time. * @param callCostInWei The keeper's estimated gas cost to call `tend()` (in wei). * @return `true` if `tend()` should be called, `false` otherwise. */ function tendTrigger(uint256 callCostInWei) public view virtual returns (bool) { // We usually don't need tend, but if there are positions that need // active maintainence, overriding this function is how you would // signal for that. // If your implementation uses the cost of the call in want, you can // use uint256 callCost = ethToWant(callCostInWei); return false; } /** * @notice * Adjust the Strategy's position. The purpose of tending isn't to * realize gains, but to maximize yield by reinvesting any returns. * * See comments on `adjustPosition()`. * * This may only be called by governance, the strategist, or the keeper. */ function tend() external onlyKeepers { // Don't take profits with this call, but adjust for better gains adjustPosition(vault.debtOutstanding()); } /** * @notice * Provide a signal to the keeper that `harvest()` should be called. The * keeper will provide the estimated gas cost that they would pay to call * `harvest()`, and this function should use that estimate to make a * determination if calling it is "worth it" for the keeper. This is not * the only consideration into issuing this trigger, for example if the * position would be negatively affected if `harvest()` is not called * shortly, then this can return `true` even if the keeper might be "at a * loss" (keepers are always reimbursed by Yearn). * @dev * `callCostInWei` must be priced in terms of `wei` (1e-18 ETH). * * This call and `tendTrigger` should never return `true` at the * same time. * * See `min/maxReportDelay`, `profitFactor`, `debtThreshold` to adjust the * strategist-controlled parameters that will influence whether this call * returns `true` or not. These parameters will be used in conjunction * with the parameters reported to the Vault (see `params`) to determine * if calling `harvest()` is merited. * * It is expected that an external system will check `harvestTrigger()`. * This could be a script run off a desktop or cloud bot (e.g. * https://github.com/iearn-finance/yearn-vaults/blob/main/scripts/keep.py), * or via an integration with the Keep3r network (e.g. * https://github.com/Macarse/GenericKeep3rV2/blob/master/contracts/keep3r/GenericKeep3rV2.sol). * @param callCostInWei The keeper's estimated gas cost to call `harvest()` (in wei). * @return `true` if `harvest()` should be called, `false` otherwise. */ function harvestTrigger(uint256 callCostInWei) public view virtual returns (bool) { uint256 callCost = ethToWant(callCostInWei); StrategyParams memory params = vault.strategies(address(this)); // Should not trigger if Strategy is not activated if (params.activation == 0) return false; // Should not trigger if we haven't waited long enough since previous harvest if (block.timestamp.sub(params.lastReport) < minReportDelay) return false; // Should trigger if hasn't been called in a while if (block.timestamp.sub(params.lastReport) >= maxReportDelay) return true; // If some amount is owed, pay it back // NOTE: Since debt is based on deposits, it makes sense to guard against large // changes to the value from triggering a harvest directly through user // behavior. This should ensure reasonable resistance to manipulation // from user-initiated withdrawals as the outstanding debt fluctuates. uint256 outstanding = vault.debtOutstanding(); if (outstanding > debtThreshold) return true; // Check for profits and losses uint256 total = estimatedTotalAssets(); // Trigger if we have a loss to report if (total.add(debtThreshold) < params.totalDebt) return true; uint256 profit = 0; if (total > params.totalDebt) profit = total.sub(params.totalDebt); // We've earned a profit! // Otherwise, only trigger if it "makes sense" economically (gas cost // is <N% of value moved) uint256 credit = vault.creditAvailable(); return (profitFactor.mul(callCost) < credit.add(profit)); } /** * @notice * Harvests the Strategy, recognizing any profits or losses and adjusting * the Strategy's position. * * In the rare case the Strategy is in emergency shutdown, this will exit * the Strategy's position. * * This may only be called by governance, the strategist, or the keeper. * @dev * When `harvest()` is called, the Strategy reports to the Vault (via * `vault.report()`), so in some cases `harvest()` must be called in order * to take in profits, to borrow newly available funds from the Vault, or * otherwise adjust its position. In other cases `harvest()` must be * called to report to the Vault on the Strategy's position, especially if * any losses have occurred. */ function harvest() external onlyKeepers { uint256 profit = 0; uint256 loss = 0; uint256 debtOutstanding = vault.debtOutstanding(); uint256 debtPayment = 0; if (emergencyExit) { // Free up as much capital as possible uint256 amountFreed = liquidateAllPositions(); if (amountFreed < debtOutstanding) { loss = debtOutstanding.sub(amountFreed); } else if (amountFreed > debtOutstanding) { profit = amountFreed.sub(debtOutstanding); } debtPayment = debtOutstanding.sub(loss); } else { // Free up returns for Vault to pull (profit, loss, debtPayment) = prepareReturn(debtOutstanding); } // Allow Vault to take up to the "harvested" balance of this contract, // which is the amount it has earned since the last time it reported to // the Vault. uint256 totalDebt = vault.strategies(address(this)).totalDebt; debtOutstanding = vault.report(profit, loss, debtPayment); // Check if free returns are left, and re-invest them adjustPosition(debtOutstanding); // call healthCheck contract if (doHealthCheck && healthCheck != address(0)) { require(HealthCheck(healthCheck).check(profit, loss, debtPayment, debtOutstanding, totalDebt), "!healthcheck"); } else { doHealthCheck = true; } emit Harvested(profit, loss, debtPayment, debtOutstanding); } /** * @notice * Withdraws `_amountNeeded` to `vault`. * * This may only be called by the Vault. * @param _amountNeeded How much `want` to withdraw. * @return _loss Any realized losses */ function withdraw(uint256 _amountNeeded) external returns (uint256 _loss) { require(msg.sender == address(vault), "!vault"); // Liquidate as much as possible to `want`, up to `_amountNeeded` uint256 amountFreed; (amountFreed, _loss) = liquidatePosition(_amountNeeded); // Send it directly back (NOTE: Using `msg.sender` saves some gas here) want.safeTransfer(msg.sender, amountFreed); // NOTE: Reinvest anything leftover on next `tend`/`harvest` } /** * Do anything necessary to prepare this Strategy for migration, such as * transferring any reserve or LP tokens, CDPs, or other tokens or stores of * value. */ function prepareMigration(address _newStrategy) internal virtual; /** * @notice * Transfers all `want` from this Strategy to `_newStrategy`. * * This may only be called by the Vault. * @dev * The new Strategy's Vault must be the same as this Strategy's Vault. * The migration process should be carefully performed to make sure all * the assets are migrated to the new address, which should have never * interacted with the vault before. * @param _newStrategy The Strategy to migrate to. */ function migrate(address _newStrategy) external { require(msg.sender == address(vault)); require(BaseStrategy(_newStrategy).vault() == vault); prepareMigration(_newStrategy); want.safeTransfer(_newStrategy, want.balanceOf(address(this))); } /** * @notice * Activates emergency exit. Once activated, the Strategy will exit its * position upon the next harvest, depositing all funds into the Vault as * quickly as is reasonable given on-chain conditions. * * This may only be called by governance or the strategist. * @dev * See `vault.setEmergencyShutdown()` and `harvest()` for further details. */ function setEmergencyExit() external onlyEmergencyAuthorized { emergencyExit = true; vault.revokeStrategy(); emit EmergencyExitEnabled(); } /** * Override this to add all tokens/tokenized positions this contract * manages on a *persistent* basis (e.g. not just for swapping back to * want ephemerally). * * NOTE: Do *not* include `want`, already included in `sweep` below. * * Example: * ``` * function protectedTokens() internal override view returns (address[] memory) { * address[] memory protected = new address[](3); * protected[0] = tokenA; * protected[1] = tokenB; * protected[2] = tokenC; * return protected; * } * ``` */ function protectedTokens() internal view virtual returns (address[] memory); /** * @notice * Removes tokens from this Strategy that are not the type of tokens * managed by this Strategy. This may be used in case of accidentally * sending the wrong kind of token to this Strategy. * * Tokens will be sent to `governance()`. * * This will fail if an attempt is made to sweep `want`, or any tokens * that are protected by this Strategy. * * This may only be called by governance. * @dev * Implement `protectedTokens()` to specify any additional tokens that * should be protected from sweeping in addition to `want`. * @param _token The token to transfer out of this vault. */ function sweep(address _token) external onlyGovernance { require(_token != address(want), "!want"); require(_token != address(vault), "!shares"); address[] memory _protectedTokens = protectedTokens(); for (uint256 i; i < _protectedTokens.length; i++) require(_token != _protectedTokens[i], "!protected"); IERC20(_token).safeTransfer(governance(), IERC20(_token).balanceOf(address(this))); } } // File: Strategy.sol // NOTE: I recommend anyone wishing to use this generic strategy to first test amend 'token_1' // (and all other token_1 fixtures) in the tests for their desired 'want,' // and making sure that all tests pass. contract Strategy is BaseStrategy { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; event Cloned(address indexed clone); bool public isOriginal = true; ILiquidityPool public tokemakLiquidityPool; IERC20 public tAsset; string internal strategyName; IManager internal constant tokemakManager = IManager(0xA86e412109f77c45a3BC1c5870b880492Fb86A14); IERC20 internal constant tokeToken = IERC20(0x2e9d63788249371f1DFC918a52f8d799F4a38C94); IRewards internal constant tokemakRewards = IRewards(0x79dD22579112d8a5F7347c5ED7E609e60da713C5); address public tradeFactory = address(0); // ********** SETUP & CLONING ********** constructor( address _vault, address _tokemakLiquidityPool, string memory _strategyName ) public BaseStrategy(_vault) { _initializeStrategy(_tokemakLiquidityPool, _strategyName); } function _initializeStrategy( address _tokemakLiquidityPool, string memory _strategyName ) internal { ILiquidityPool _liquidityPool = ILiquidityPool(_tokemakLiquidityPool); require(_liquidityPool.underlyer() == address(want), "!pool_matches"); tokemakLiquidityPool = _liquidityPool; tAsset = IERC20(_tokemakLiquidityPool); strategyName = _strategyName; } // Cloning & initialization code adapted from https://github.com/yearn/yearn-vaults/blob/43a0673ab89742388369bc0c9d1f321aa7ea73f6/contracts/BaseStrategy.sol#L866 function initialize( address _vault, address _strategist, address _rewards, address _keeper, address _tokemakLiquidityPool, string memory _strategyName ) external virtual { _initialize(_vault, _strategist, _rewards, _keeper); _initializeStrategy(_tokemakLiquidityPool, _strategyName); } function clone( address _vault, address _tokemakLiquidityPool, string memory _strategyName ) external returns (address) { return this.clone( _vault, msg.sender, msg.sender, msg.sender, _tokemakLiquidityPool, _strategyName ); } function clone( address _vault, address _strategist, address _rewards, address _keeper, address _tokemakLiquidityPool, string memory _strategyName ) external returns (address newStrategy) { require(isOriginal, "!clone"); bytes20 addressBytes = bytes20(address(this)); assembly { // EIP-1167 bytecode let clone_code := mload(0x40) mstore( clone_code, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000 ) mstore(add(clone_code, 0x14), addressBytes) mstore( add(clone_code, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000 ) newStrategy := create(0, clone_code, 0x37) } Strategy(newStrategy).initialize( _vault, _strategist, _rewards, _keeper, _tokemakLiquidityPool, _strategyName ); emit Cloned(newStrategy); } // ********** CORE ********** function name() external view override returns (string memory) { return strategyName; } function estimatedTotalAssets() public view override returns (uint256) { // 1 tWant = 1 want *guaranteed* // Tokemak team confirming that a tAsset will have the same decimals as the underlying asset return tAssetBalance().add(wantBalance()); } function prepareReturn(uint256 _debtOutstanding) internal override returns ( uint256 _profit, uint256 _loss, uint256 _debtPayment ) { require(tradeFactory != address(0), "Trade factory must be set."); // How much do we owe to the vault? uint256 totalDebt = vault.strategies(address(this)).totalDebt; uint256 totalAssets = estimatedTotalAssets(); if (totalAssets >= totalDebt) { _profit = totalAssets.sub(totalDebt); } else { _loss = totalDebt.sub(totalAssets); } (uint256 _liquidatedAmount, ) = liquidatePosition(_debtOutstanding); _debtPayment = Math.min(_debtOutstanding, _liquidatedAmount); } function adjustPosition(uint256 _debtOutstanding) internal override { uint256 wantBalance = wantBalance(); if (wantBalance > _debtOutstanding) { uint256 _amountToInvest = wantBalance.sub(_debtOutstanding); _checkAllowance( address(tokemakLiquidityPool), address(want), _amountToInvest ); try tokemakLiquidityPool.deposit(_amountToInvest) {} catch {} } } function liquidatePosition(uint256 _amountNeeded) internal override returns (uint256 _liquidatedAmount, uint256 _loss) { // NOTE: Maintain invariant `_liquidatedAmount + _loss <= _amountNeeded` uint256 _existingLiquidAssets = wantBalance(); if (_existingLiquidAssets >= _amountNeeded) { return (_amountNeeded, 0); } uint256 _amountToWithdraw = _amountNeeded.sub(_existingLiquidAssets); ( uint256 _cycleIndexWhenWithdrawable, uint256 _requestedWithdrawAmount ) = tokemakLiquidityPool.requestedWithdrawals(address(this)); if ( _requestedWithdrawAmount == 0 || _cycleIndexWhenWithdrawable > tokemakManager.getCurrentCycleIndex() ) { tokemakLiquidityPool.requestWithdrawal(_amountToWithdraw); return (_existingLiquidAssets, 0); } // Cannot withdraw more than withdrawable _amountToWithdraw = Math.min( _amountToWithdraw, _requestedWithdrawAmount ); try tokemakLiquidityPool.withdraw(_amountToWithdraw) { uint256 _newLiquidAssets = wantBalance(); _liquidatedAmount = Math.min(_newLiquidAssets, _amountNeeded); if (_liquidatedAmount < _amountNeeded) { // If we couldn't liquidate the full amount needed, start the withdrawal process for the remaining tokemakLiquidityPool.requestWithdrawal( _amountNeeded.sub(_liquidatedAmount) ); } } catch { return (_existingLiquidAssets, 0); } } function liquidateAllPositions() internal override returns (uint256 _amountFreed) { (_amountFreed, ) = liquidatePosition(estimatedTotalAssets()); } // NOTE: Can override `tendTrigger` and `harvestTrigger` if necessary function prepareMigration(address _newStrategy) internal override { uint256 _tAssetToTransfer = tAssetBalance(); uint256 _tokeTokenToTransfer = tokeTokenBalance(); tAsset.safeTransfer(_newStrategy, _tAssetToTransfer); tokeToken.safeTransfer(_newStrategy, _tokeTokenToTransfer); } // Override this to add all tokens/tokenized positions this contract manages // on a *persistent* basis (e.g. not just for swapping back to want ephemerally) // NOTE: Do *not* include `want`, already included in `sweep` below // // Example: // // function protectedTokens() internal override view returns (address[] memory) { // address[] memory protected = new address[](3); // protected[0] = tokenA; // protected[1] = tokenB; // protected[2] = tokenC; // return protected; // } function protectedTokens() internal view override returns (address[] memory) {} /** * @notice * Provide an accurate conversion from `_amtInWei` (denominated in wei) * to `want` (using the native decimal characteristics of `want`). * @dev * Care must be taken when working with decimals to assure that the conversion * is compatible. As an example: * * given 1e17 wei (0.1 ETH) as input, and want is USDC (6 decimals), * with USDC/ETH = 1800, this should give back 1800000000 (180 USDC) * * @param _amtInWei The amount (in wei/1e-18 ETH) to convert to `want` * @return The amount in `want` of `_amtInEth` converted to `want` **/ function ethToWant(uint256 _amtInWei) public view virtual override returns (uint256) { // TODO create an accurate price oracle return _amtInWei; } // ----------------- TOKEMAK OPERATIONS --------- function requestWithdrawal(uint256 amount) external onlyEmergencyAuthorized { tokemakLiquidityPool.requestWithdrawal(amount); } function claimRewards( IRewards.Recipient calldata _recipient, uint8 _v, bytes32 _r, bytes32 _s // bytes calldata signature ) external onlyVaultManagers { require( _recipient.wallet == address(this), "Recipient wallet must be strategy" ); tokemakRewards.claim(_recipient, _v, _r, _s); } // ----------------- YSWAPS FUNCTIONS --------------------- function setTradeFactory(address _tradeFactory) external onlyGovernance { if (tradeFactory != address(0)) { _removeTradeFactoryPermissions(); } // approve and set up trade factory tokeToken.safeApprove(_tradeFactory, type(uint256).max); ITradeFactory tf = ITradeFactory(_tradeFactory); tf.enable(address(tokeToken), address(want)); tradeFactory = _tradeFactory; } function removeTradeFactoryPermissions() external onlyEmergencyAuthorized { _removeTradeFactoryPermissions(); } function _removeTradeFactoryPermissions() internal { tokeToken.safeApprove(tradeFactory, 0); tradeFactory = address(0); } // ----------------- SUPPORT & UTILITY FUNCTIONS ---------- function tokeTokenBalance() public view returns (uint256) { return tokeToken.balanceOf(address(this)); } function wantBalance() public view returns (uint256) { return want.balanceOf(address(this)); } function tAssetBalance() public view returns (uint256) { return tAsset.balanceOf(address(this)); } // _checkAllowance adapted from https://github.com/therealmonoloco/liquity-stability-pool-strategy/blob/1fb0b00d24e0f5621f1e57def98c26900d551089/contracts/Strategy.sol#L316 function _checkAllowance( address _contract, address _token, uint256 _amount ) internal { if (IERC20(_token).allowance(address(this), _contract) < _amount) { IERC20(_token).safeApprove(_contract, 0); IERC20(_token).safeApprove(_contract, _amount); } } }
@notice Transfers amount of underlying token from user to this pool and mints fToken to the msg.sender. @notice Depositor must have previously granted transfer approval to the pool via underlying token contract. @notice Liquidity deposited is deployed on the next cycle - unless a withdrawal request is submitted, in which case the liquidity will be withheld. @notice Transfers amount of underlying token from user to this pool and mints fToken to the account. @notice Depositor must have previously granted transfer approval to the pool via underlying token contract. @notice Liquidity deposited is deployed on the next cycle - unless a withdrawal request is submitted, in which case the liquidity will be withheld. @notice Requests that the manager prepare funds for withdrawal next cycle @notice Invoking this function when sender already has a currently pending request will overwrite that requested amount and reset the cycle timer @param amount Amount of fTokens requested to be redeemed @notice Sender must first invoke requestWithdrawal in a previous cycle @notice This function will burn the fAsset and transfers underlying asset back to sender @notice Will execute a partial withdrawal if either available liquidity or previously requested amount is insufficient @param amount Amount of fTokens to redeem, value can be in excess of available tokens, operation will be reduced to maximum permissible @return Reference to the underlying ERC-20 contract @return Amount of liquidity that should not be deployed for market making (this liquidity will be used for completing requested withdrawals) @notice Get withdraw requests for an account @param account User account to check @return minCycle Cycle - block number - that must be active before withdraw is allowed, amount Token amount requested @notice Pause deposits on the pool. Withdraws still allowed @notice Unpause deposits on the pool. @notice Pause deposits only on the pool. @notice Unpause deposits only on the pool. Part: IManager bytes can take on the form of deploying or recovering liquidity
interface IManager { function deposit(uint256 amount) external; function depositFor(address account, uint256 amount) external; function requestWithdrawal(uint256 amount) external; function approveManager(uint256 amount) external; function withdraw(uint256 amount) external; function underlyer() external view returns (address); function withheldLiquidity() external view returns (uint256); function requestedWithdrawals(address account) external view returns (uint256, uint256); function pause() external; function unpause() external; function pauseDeposit() external; function unpauseDeposit() external; } struct ControllerTransferData { } struct PoolTransferData { } struct MaintenanceExecution { ControllerTransferData[] cycleSteps; } struct RolloverExecution { PoolTransferData[] poolData; ControllerTransferData[] cycleSteps; string rewardsIpfsHash; } event ControllerRegistered(bytes32 id, address controller); event ControllerUnregistered(bytes32 id, address controller); event PoolRegistered(address pool); event PoolUnregistered(address pool); event CycleDurationSet(uint256 duration); event LiquidityMovedToManager(address pool, uint256 amount); event DeploymentStepExecuted(bytes32 controller, address adapaterAddress, bytes data); event LiquidityMovedToPool(address pool, uint256 amount); event CycleRolloverStarted(uint256 blockNumber); event CycleRolloverComplete(uint256 blockNumber); event DestinationsSet(address destinationOnL1, address destinationOnL2); event EventSendSet(bool eventSendSet); }
7,988,908
[ 1, 1429, 18881, 3844, 434, 6808, 1147, 628, 729, 358, 333, 2845, 471, 312, 28142, 284, 1345, 358, 326, 1234, 18, 15330, 18, 225, 4019, 538, 1811, 1297, 1240, 7243, 17578, 7412, 23556, 358, 326, 2845, 3970, 6808, 1147, 6835, 18, 225, 511, 18988, 24237, 443, 1724, 329, 353, 19357, 603, 326, 1024, 8589, 300, 3308, 279, 598, 9446, 287, 590, 353, 9638, 16, 316, 1492, 648, 326, 4501, 372, 24237, 903, 506, 598, 76, 488, 18, 225, 2604, 18881, 3844, 434, 6808, 1147, 628, 729, 358, 333, 2845, 471, 312, 28142, 284, 1345, 358, 326, 2236, 18, 225, 4019, 538, 1811, 1297, 1240, 7243, 17578, 7412, 23556, 358, 326, 2845, 3970, 6808, 1147, 6835, 18, 225, 511, 18988, 24237, 443, 1724, 329, 353, 19357, 603, 326, 1024, 8589, 300, 3308, 279, 598, 9446, 287, 590, 353, 9638, 16, 316, 1492, 648, 326, 4501, 372, 24237, 903, 506, 598, 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, 5831, 467, 1318, 288, 203, 203, 565, 445, 443, 1724, 12, 11890, 5034, 3844, 13, 3903, 31, 203, 203, 565, 445, 443, 1724, 1290, 12, 2867, 2236, 16, 2254, 5034, 3844, 13, 3903, 31, 203, 203, 565, 445, 590, 1190, 9446, 287, 12, 11890, 5034, 3844, 13, 3903, 31, 203, 203, 565, 445, 6617, 537, 1318, 12, 11890, 5034, 3844, 13, 3903, 31, 203, 203, 565, 445, 598, 9446, 12, 11890, 5034, 3844, 13, 3903, 31, 203, 203, 565, 445, 3613, 715, 264, 1435, 3903, 1476, 1135, 261, 2867, 1769, 203, 203, 565, 445, 598, 76, 488, 48, 18988, 24237, 1435, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 565, 445, 3764, 1190, 9446, 1031, 12, 2867, 2236, 13, 3903, 1476, 1135, 261, 11890, 5034, 16, 2254, 5034, 1769, 203, 203, 565, 445, 11722, 1435, 3903, 31, 203, 203, 565, 445, 640, 19476, 1435, 3903, 31, 203, 203, 565, 445, 11722, 758, 1724, 1435, 3903, 31, 203, 203, 565, 445, 640, 19476, 758, 1724, 1435, 3903, 31, 203, 97, 203, 203, 203, 565, 1958, 6629, 5912, 751, 288, 203, 565, 289, 203, 203, 565, 1958, 8828, 5912, 751, 288, 203, 565, 289, 203, 203, 565, 1958, 27532, 3210, 288, 203, 540, 6629, 5912, 751, 8526, 8589, 11811, 31, 203, 565, 289, 203, 203, 565, 1958, 11714, 21896, 3210, 288, 203, 3639, 8828, 5912, 751, 8526, 2845, 751, 31, 203, 3639, 6629, 5912, 751, 8526, 8589, 11811, 31, 203, 3639, 533, 283, 6397, 5273, 2556, 2310, 31, 203, 565, 289, 203, 203, 565, 871, 2 ]
./full_match/1/0x7e51C93E6e201363829c94C17dcbf1b4AdB13871/sources/ttkknn.sol
@notice A shuffle function to output a random hex string for the left square color. @param tokenId The tokenId for which a left square color value is to be generated. @return A string providing a hex color value.
function shuffleLeftSquare(uint256 tokenId) private view returns (string memory) { string[32] memory r; string[32] memory s = ["a", "3", "4", "1", "e", "7", "5", "9", "b", "d", "2", "8", "f", "0", "c", "6", "2", "8", "e", "3", "9", "6", "0", "b", "5", "d", "f", "4", "a", "1", "7", "c"]; uint l = s.length; uint i; string memory t; while (l > 0) { uint256 v = random(string(abi.encodePacked("f9d20005acf7", block.timestamp, block.difficulty, msg.sender, toString(tokenId)))); i = v % l--; t = s[l]; s[l] = s[i]; s[i] = t; } r = s; string memory j = string(abi.encodePacked(r[3],r[17],r[1],r[14],r[9],r[12])); return j; }
4,984,554
[ 1, 37, 12552, 445, 358, 876, 279, 2744, 3827, 533, 364, 326, 2002, 8576, 2036, 18, 225, 1147, 548, 1021, 1147, 548, 364, 1492, 279, 2002, 8576, 2036, 460, 353, 358, 506, 4374, 18, 327, 432, 533, 17721, 279, 3827, 2036, 460, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 445, 12552, 3910, 22255, 12, 11890, 5034, 1147, 548, 13, 3238, 1476, 1135, 261, 1080, 3778, 13, 288, 203, 1377, 533, 63, 1578, 65, 3778, 436, 31, 203, 1377, 533, 63, 1578, 65, 3778, 272, 273, 8247, 69, 3113, 315, 23, 3113, 315, 24, 3113, 315, 21, 3113, 315, 73, 3113, 315, 27, 3113, 315, 25, 3113, 315, 29, 3113, 315, 70, 3113, 315, 72, 3113, 315, 22, 3113, 315, 28, 3113, 315, 74, 3113, 315, 20, 3113, 315, 71, 3113, 315, 26, 3113, 315, 22, 3113, 315, 28, 3113, 315, 73, 3113, 315, 23, 3113, 315, 29, 3113, 315, 26, 3113, 315, 20, 3113, 315, 70, 3113, 315, 25, 3113, 315, 72, 3113, 315, 74, 3113, 315, 24, 3113, 315, 69, 3113, 315, 21, 3113, 315, 27, 3113, 315, 71, 11929, 31, 203, 203, 1377, 2254, 328, 273, 272, 18, 2469, 31, 203, 1377, 2254, 277, 31, 203, 1377, 533, 3778, 268, 31, 203, 203, 1377, 1323, 261, 80, 405, 374, 13, 288, 203, 1850, 2254, 5034, 331, 273, 2744, 12, 1080, 12, 21457, 18, 3015, 4420, 329, 2932, 74, 29, 72, 17172, 25, 21441, 27, 3113, 1203, 18, 5508, 16, 1203, 18, 5413, 21934, 16, 1234, 18, 15330, 16, 1762, 12, 2316, 548, 3719, 10019, 203, 1850, 277, 273, 331, 738, 328, 413, 31, 203, 1850, 268, 273, 272, 63, 80, 15533, 203, 1850, 272, 63, 80, 65, 273, 272, 63, 77, 15533, 203, 1850, 272, 63, 77, 65, 273, 268, 31, 203, 1377, 289, 203, 203, 1377, 436, 273, 272, 2 ]
./partial_match/1/0x28e5552e8F51DE209e18CDDf90D2A4F260f26216/sources/Pass.sol
Set the open status of claims to the given value
open = _open;
2,739,086
[ 1, 694, 326, 1696, 1267, 434, 11955, 358, 326, 864, 460, 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, 1696, 273, 389, 3190, 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 ]
//Address: 0x33537c8c6711035ed450bab4a1817511a28ee424 //Contract name: Totum //Balance: 0 Ether //Verification Date: 11/10/2017 //Transacion Count: 1 // CODE STARTS HERE pragma solidity 0.4.15; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal constant returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn'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 Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { //Variables address public owner; address public newOwner; // Modifiers /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @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)); newOwner = _newOwner; } function acceptOwnership() public { if (msg.sender == newOwner) { owner = newOwner; } } } contract TokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; } contract ERC20 is Ownable { using SafeMath for uint256; /* Public variables of the token */ string public standard; string public name; string public symbol; uint8 public decimals; uint256 public initialSupply; bool public locked; uint256 public creationBlock; mapping (address => uint256) public balances; mapping (address => mapping (address => uint256)) public allowance; /* This generates a public event on the blockchain that will notify clients */ event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed _owner, address indexed _spender, uint _value); modifier onlyPayloadSize(uint numwords) { assert(msg.data.length == numwords.mul(32).add(4)); _; } /* Initializes contract with initial supply tokens to the creator of the contract */ function ERC20( uint256 _initialSupply, string _tokenName, uint8 _decimalUnits, string _tokenSymbol, bool _transferAllSupplyToOwner, bool _locked ) { standard = "ERC20 0.1"; initialSupply = _initialSupply; if (_transferAllSupplyToOwner) { setBalance(msg.sender, initialSupply); } else { setBalance(this, initialSupply); } name = _tokenName; // Set the name for display purposes symbol = _tokenSymbol; // Set the symbol for display purposes decimals = _decimalUnits; // Amount of decimals for display purposes locked = _locked; creationBlock = block.number; } /* public methods */ function totalSupply() public constant returns (uint256) { return initialSupply; } function balanceOf(address _address) public constant returns (uint256) { return balances[_address]; } function transfer(address _to, uint256 _value) public onlyPayloadSize(2) returns (bool) { require(locked == false); bool status = transferInternal(msg.sender, _to, _value); require(status == true); return true; } function approve(address _spender, uint256 _value) public returns (bool success) { if (locked) { return false; } allowance[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { if (locked) { return false; } TokenRecipient spender = TokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { if (locked) { return false; } if (allowance[_from][msg.sender] < _value) { return false; } bool _success = transferInternal(_from, _to, _value); if (_success) { allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value); } return _success; } /* internal balances */ function setBalance(address _holder, uint256 _amount) internal { balances[_holder] = _amount; } function transferInternal(address _from, address _to, uint256 _value) internal returns (bool success) { if (_value == 0) { Transfer(_from, _to, 0); return true; } if (balances[_from] < _value) { return false; } setBalance(_from, balances[_from].sub(_value)); setBalance(_to, balances[_to].add(_value)); Transfer(_from, _to, _value); return true; } } /* This contract manages the minters and the modifier to allow mint to happen only if called by minters This contract contains basic minting functionality though */ contract MintingERC20 is ERC20 { using SafeMath for uint256; uint256 public maxSupply; mapping (address => bool) public minters; modifier onlyMinters () { require(true == minters[msg.sender]); _; } function MintingERC20( uint256 _initialSupply, uint256 _maxSupply, string _tokenName, uint8 _decimals, string _symbol, bool _transferAllSupplyToOwner, bool _locked ) ERC20(_initialSupply, _tokenName, _decimals, _symbol, _transferAllSupplyToOwner, _locked) { minters[msg.sender] = true; maxSupply = _maxSupply; } function addMinter(address _newMinter) public onlyOwner { minters[_newMinter] = true; } function removeMinter(address _minter) public onlyOwner { minters[_minter] = false; } function mint(address _addr, uint256 _amount) public onlyMinters returns (uint256) { if (_amount == uint256(0)) { return uint256(0); } if (totalSupply().add(_amount) > maxSupply) { return uint256(0); } initialSupply = initialSupply.add(_amount); balances[_addr] = balances[_addr].add(_amount); Transfer(0, _addr, _amount); return _amount; } } contract Totum is MintingERC20 { using SafeMath for uint256; TotumPhases public totumPhases; // Block token transfers till ICO end. bool public transferFrozen = true; function Totum( uint256 _maxSupply, string _tokenName, string _tokenSymbol, uint8 _precision, bool _locked ) MintingERC20(0, _maxSupply, _tokenName, _precision, _tokenSymbol, false, _locked) { standard = "Totum 0.1"; } function setLocked(bool _locked) public onlyOwner { locked = _locked; } function setTotumPhases(address _totumPhases) public onlyOwner { totumPhases = TotumPhases(_totumPhases); } function unfreeze() public onlyOwner { if (totumPhases != address(0) && totumPhases.isFinished(1)) { transferFrozen = false; } } function buyBack(address _address) public onlyMinters returns (uint256) { require(address(_address) != 0x0); uint256 balance = balanceOf(_address); setBalance(_address, 0); setBalance(this, balanceOf(this).add(balance)); Transfer(_address, this, balance); return balance; } function transfer(address _to, uint _value) public returns (bool) { require(!transferFrozen); return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint _value) public returns (bool success) { require(!transferFrozen); return super.transferFrom(_from, _to, _value); } } contract TotumAllocation is Ownable { using SafeMath for uint256; address public bountyAddress; address public teamAddress; address public preICOAddress; address public icoAddress; address public icoAddress1; function TotumAllocation( address _bountyAddress, //5% address _teamAddress, //7% address _preICOAddress, address _icoAddress, //50% address _icoAddress1 //50% ) { require((address(_bountyAddress) != 0x0) && (address(_teamAddress) != 0x0)); require((address(_preICOAddress) != 0x0) && (address(_icoAddress) != 0x0) && (address(_icoAddress1) != 0x0)); bountyAddress = _bountyAddress; teamAddress = _teamAddress; preICOAddress = _preICOAddress; icoAddress = _icoAddress; icoAddress1 = _icoAddress1; } } contract TotumPhases is Ownable { using SafeMath for uint256; Totum public totum; TotumAllocation public totumAllocation; Phase[] public phases; uint256 public constant DAY = 86400; uint256 public collectedEthers; uint256 public soldTokens; uint256 public investorsCount; mapping (address => uint256) public icoEtherBalances; mapping (address => bool) private investors; event Refund(address holder, uint256 ethers, uint256 tokens); struct Phase { uint256 price; uint256 minInvest; uint256 softCap; uint256 hardCap; uint256 since; uint256 till; bool isSucceed; } function TotumPhases( address _totum, uint256 _minInvest, uint256 _tokenPrice, //0.0033 ethers uint256 _preIcoMaxCap, uint256 _preIcoSince, uint256 _preIcoTill, uint256 _icoMinCap, uint256 _icoMaxCap, uint256 _icoSince, uint256 _icoTill ) { require(address(_totum) != 0x0); totum = Totum(address(_totum)); require((_preIcoSince < _preIcoTill) && (_icoSince < _icoTill) && (_preIcoTill <= _icoSince)); require((_preIcoMaxCap < _icoMaxCap) && (_icoMaxCap < totum.maxSupply())); phases.push(Phase(_tokenPrice, _minInvest, 0, _preIcoMaxCap, _preIcoSince, _preIcoTill, false)); phases.push(Phase(_tokenPrice, _minInvest, _icoMinCap, _icoMaxCap, _icoSince, _icoTill, false)); } function() public payable { require(buy(msg.sender, msg.value) == true); } function setCurrentRate(uint256 _rate) public onlyOwner { require(_rate > 0); for (uint i = 0; i < phases.length; i++) { Phase storage phase = phases[i]; phase.price = _rate; } } function setTotum(address _totum) public onlyOwner { totum = Totum(_totum); } function setTotumAllocation(address _totumAllocation) public onlyOwner { totumAllocation = TotumAllocation(_totumAllocation); } function setPhase( uint8 _phaseId, uint256 _since, uint256 _till, uint256 _price, uint256 _softCap, uint256 _hardCap ) public onlyOwner returns (bool) { require((phases.length > _phaseId) && (_price > 0)); require((_till > _since) && (_since > 0)); require((totum.maxSupply() > _hardCap) && (_hardCap > _softCap) && (_softCap >= 0)); Phase storage phase = phases[_phaseId]; if (phase.isSucceed == true) { return false; } phase.since = _since; phase.till = _till; phase.price = _price; phase.softCap = _softCap; phase.hardCap = _hardCap; return true; } function sendToAddress(address _address, uint256 _tokens) public onlyOwner returns (bool) { if (_tokens == 0 || address(_address) == 0x0) { return false; } uint256 totalAmount = _tokens.add(getBonusAmount(_tokens, now)); if (getTokens().add(totalAmount) > totum.maxSupply()) { return false; } bool status = (totalAmount != totum.mint(_address, totalAmount)); if (status) { soldTokens = soldTokens.add(totalAmount); increaseInvestorsCount(_address); } return status; } function sendToAddressWithTime(address _address, uint256 _tokens, uint256 _time) public onlyOwner returns (bool) { if (_tokens == 0 || address(_address) == 0x0 || _time == 0) { return false; } uint256 totalAmount = _tokens.add(getBonusAmount(_tokens, _time)); if (getTokens().add(totalAmount) > totum.maxSupply()) { return false; } bool status = (totalAmount != totum.mint(_address, totalAmount)); if (status) { soldTokens = soldTokens.add(totalAmount); increaseInvestorsCount(_address); } return status; } function sendToAddressWithBonus( address _address, uint256 _tokens, uint256 _bonus ) public onlyOwner returns (bool) { if (_tokens == 0 || address(_address) == 0x0 || _bonus == 0) { return false; } uint256 totalAmount = _tokens.add(_bonus); if (getTokens().add(totalAmount) > totum.maxSupply()) { return false; } bool status = (totalAmount != totum.mint(_address, totalAmount)); if (status) { soldTokens = soldTokens.add(totalAmount); increaseInvestorsCount(_address); } return status; } function getCurrentPhase(uint256 _time) public constant returns (uint8) { if (_time == 0) { return uint8(phases.length); } for (uint8 i = 0; i < phases.length; i++) { Phase storage phase = phases[i]; if (phase.since > _time) { continue; } if (phase.till < _time) { continue; } return i; } return uint8(phases.length); } function getTokens() public constant returns (uint256) { return totum.totalSupply(); } function getSoldToken() public constant returns (uint256) { return soldTokens; } function getAllInvestors() public constant returns (uint256) { return investorsCount; } function getBalanceContract() public constant returns (uint256) { return collectedEthers; } function isSucceed(uint8 _phaseId) public returns (bool) { if (phases.length <= _phaseId) { return false; } Phase storage phase = phases[_phaseId]; if (phase.isSucceed == true) { return true; } if (phase.till > now) { return false; } if (phase.softCap != 0 && phase.softCap > getTokens()) { return false; } phase.isSucceed = true; if (_phaseId == 1) { allocateBounty(); } return true; } function refund() public returns (bool) { Phase storage icoPhase = phases[1]; if (icoPhase.till > now) { return false; } if (icoPhase.softCap < getTokens()) { return false; } if (icoEtherBalances[msg.sender] == 0) { return false; } uint256 refundAmount = icoEtherBalances[msg.sender]; uint256 tokens = totum.buyBack(msg.sender); icoEtherBalances[msg.sender] = 0; msg.sender.transfer(refundAmount); Refund(msg.sender, refundAmount, tokens); return true; } function isFinished(uint8 _phaseId) public constant returns (bool) { if (phases.length <= _phaseId) { return false; } Phase storage phase = phases[_phaseId]; return (phase.isSucceed || now > phase.till); } function buy(address _address, uint256 _value) internal returns (bool) { if (_value == 0) { return false; } uint8 currentPhase = getCurrentPhase(now); if (phases.length <= currentPhase) { return false; } uint256 amount = getTokensAmount(_value, currentPhase); if (amount == 0) { return false; } uint256 bonus = getBonusAmount(amount, now); if (currentPhase == 1) { bonus = bonus.add(getVolumeBasedBonusAmount(_value, amount)); } amount = amount.add(bonus); bool status = (amount == totum.mint(_address, amount)); if (status) { onSuccessfulBuy(_address, _value, amount, currentPhase); allocate(currentPhase); } return status; } function onSuccessfulBuy(address _address, uint256 _value, uint256 _amount, uint8 _currentPhase) internal { collectedEthers = collectedEthers.add(_value); soldTokens = soldTokens.add(_amount); increaseInvestorsCount(_address); if (_currentPhase == 1) { icoEtherBalances[_address] = icoEtherBalances[_address].add(_value); } } function increaseInvestorsCount(address _address) internal { if (address(_address) != 0x0 && investors[_address] == false) { investors[_address] = true; investorsCount = investorsCount.add(1); } } function getVolumeBasedBonusAmount(uint256 _value, uint256 _amount) internal returns (uint256) { if (_amount == 0) { return 0; } if (_value < 3 ether) { return 0; } else if (_value < 15 ether) { return _amount.mul(3).div(100); } else if (_value < 30 ether) { return _amount.mul(5).div(100); } else { return _amount.mul(7).div(100); } } function getTokensAmount(uint256 _value, uint8 _currentPhase) internal returns (uint256) { if (_value == 0 || phases.length <= _currentPhase) { return uint256(0); } Phase storage phase = phases[_currentPhase]; uint256 amount = _value.mul(uint256(10) ** totum.decimals()).div(phase.price); if (amount < phase.minInvest) { return uint256(0); } if (getTokens().add(amount) > phase.hardCap) { return uint256(0); } return amount; } function getBonusAmount(uint256 _amount, uint256 _time) internal returns (uint256) { uint8 currentPhase = getCurrentPhase(_time); if (_amount == 0 || _time == 0 || phases.length <= currentPhase) { return uint256(0); } if (currentPhase == 0) { return _amount.mul(50).div(100); } if (currentPhase == 1) { return getICOBonusAmount(_amount, _time); } return uint256(0); } function getICOBonusAmount(uint256 _amount, uint256 _time) internal returns (uint256) { Phase storage ico = phases[1]; if (_time.sub(ico.since) < 11 * DAY) {// 11d since ico => reward 20%; return _amount.mul(20).div(100); } if (_time.sub(ico.since) < 21 * DAY) {// 21d since ico => reward 15% return _amount.mul(15).div(100); } if (_time.sub(ico.since) < 31 * DAY) {// 31d since ico => reward 10% return _amount.mul(10).div(100); } if (_time.sub(ico.since) < 41 * DAY) {// 41d since ico => reward 5% return _amount.mul(5).div(100); } return 0; } function allocate(uint8 _currentPhase) internal { if (this.balance > 0 && phases.length > _currentPhase) { Phase storage phase = phases[_currentPhase]; if (_currentPhase == 0) { totumAllocation.preICOAddress().transfer(this.balance); } else if (_currentPhase == 1 && soldTokens >= phase.softCap) { totumAllocation.icoAddress().transfer(this.balance.mul(5).div(10)); totumAllocation.icoAddress1().transfer(this.balance); } } } function allocateBounty() internal { if (isFinished(1)) { uint256 amount = totum.maxSupply().mul(5).div(100); uint256 mintedAmount = totum.mint(totumAllocation.bountyAddress(), amount); require(mintedAmount == amount); amount = totum.maxSupply().mul(7).div(100); mintedAmount = totum.mint(totumAllocation.teamAddress(), amount); require(mintedAmount == amount); } } }
Public variables of the token */ This generates a public event on the blockchain that will notify clients */
modifier onlyPayloadSize(uint numwords) { assert(msg.data.length == numwords.mul(32).add(4)); _; }
2,503,478
[ 1, 4782, 3152, 434, 326, 1147, 342, 1220, 6026, 279, 1071, 871, 603, 326, 16766, 716, 903, 5066, 7712, 342, 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 ]
[ 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, 0 ]
[ 1, 565, 9606, 1338, 6110, 1225, 12, 11890, 818, 3753, 13, 288, 203, 3639, 1815, 12, 3576, 18, 892, 18, 2469, 422, 818, 3753, 18, 16411, 12, 1578, 2934, 1289, 12, 24, 10019, 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 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "../../ImplBase.sol"; import "../../helpers/errors.sol"; import "../../interfaces/hop/IHopL1Bridge.sol"; /** // @title Hop Protocol Implementation. // @notice This is the L1 implementation, so this is used when transferring from l1 to supported l2s // Called by the registry if the selected bridge is HOP. // @dev Follows the interface of ImplBase. // @author Movr Network. */ contract HopImpl is ImplBase, ReentrancyGuard { using SafeERC20 for IERC20; // solhint-disable-next-line constructor(address _registry) ImplBase(_registry) {} /** // @notice Function responsible for cross chain transfers from L1 to L2. // @dev When calling the registry the allowance should be given to this contract, // that is the implementation contract for HOP. // @param _amount amount to be transferred to L2. // @param _from userAddress or address from which the transfer was made. // @param _receiverAddress address that will receive the funds on the destination chain. // @param _token address of the token to be used for cross chain transfer. // @param _toChainId chain Id for the destination chain // @param _extraData parameters required to call the hop function in bytes */ function outboundTransferTo( uint256 _amount, address _from, address _receiverAddress, address _token, uint256 _toChainId, bytes memory _extraData ) external payable override onlyRegistry nonReentrant { // decode extra data ( address _l1bridgeAddr, address _relayer, uint256 _amountOutMin, uint256 _relayerFee, uint256 _deadline ) = abi.decode( _extraData, (address, address, uint256, uint256, uint256) ); if (_token == NATIVE_TOKEN_ADDRESS) { require(msg.value == _amount, MovrErrors.VALUE_NOT_EQUAL_TO_AMOUNT); IHopL1Bridge(_l1bridgeAddr).sendToL2{value: _amount}( _toChainId, _receiverAddress, _amount, _amountOutMin, _deadline, _relayer, _relayerFee ); return; } require(msg.value == 0, MovrErrors.VALUE_SHOULD_BE_ZERO); IERC20(_token).safeTransferFrom(_from, address(this), _amount); IERC20(_token).safeIncreaseAllowance(_l1bridgeAddr, _amount); // perform bridging IHopL1Bridge(_l1bridgeAddr).sendToL2( _toChainId, _receiverAddress, _amount, _amountOutMin, _deadline, _relayer, _relayerFee ); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // 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.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "./helpers/errors.sol"; /** @title Abstract Implementation Contract. @notice All Bridge Implementation will follow this interface. */ abstract contract ImplBase is Ownable { using SafeERC20 for IERC20; address public registry; address public constant NATIVE_TOKEN_ADDRESS = address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE); event UpdateRegistryAddress(address indexed registryAddress); constructor(address _registry) Ownable() { registry = _registry; } modifier onlyRegistry() { require(msg.sender == registry, MovrErrors.INVALID_SENDER); _; } function updateRegistryAddress(address newRegistry) external onlyOwner { registry = newRegistry; emit UpdateRegistryAddress(newRegistry); } function rescueFunds( address token, address userAddress, uint256 amount ) external onlyOwner { IERC20(token).safeTransfer(userAddress, amount); } function outboundTransferTo( uint256 _amount, address _from, address _receiverAddress, address _token, uint256 _toChainId, bytes memory _extraData ) external payable virtual; } // SPDX-License-Identifier: MIT pragma solidity >=0.8.0; library MovrErrors { string internal constant ADDRESS_0_PROVIDED = "ADDRESS_0_PROVIDED"; string internal constant EMPTY_INPUT = "EMPTY_INPUT"; string internal constant LENGTH_MISMATCH = "LENGTH_MISMATCH"; string internal constant INVALID_VALUE = "INVALID_VALUE"; string internal constant INVALID_AMT = "INVALID_AMT"; string internal constant IMPL_NOT_FOUND = "IMPL_NOT_FOUND"; string internal constant ROUTE_NOT_FOUND = "ROUTE_NOT_FOUND"; string internal constant IMPL_NOT_ALLOWED = "IMPL_NOT_ALLOWED"; string internal constant ROUTE_NOT_ALLOWED = "ROUTE_NOT_ALLOWED"; string internal constant INVALID_CHAIN_DATA = "INVALID_CHAIN_DATA"; string internal constant CHAIN_NOT_SUPPORTED = "CHAIN_NOT_SUPPORTED"; string internal constant TOKEN_NOT_SUPPORTED = "TOKEN_NOT_SUPPORTED"; string internal constant NOT_IMPLEMENTED = "NOT_IMPLEMENTED"; string internal constant INVALID_SENDER = "INVALID_SENDER"; string internal constant INVALID_BRIDGE_ID = "INVALID_BRIDGE_ID"; string internal constant MIDDLEWARE_ACTION_FAILED = "MIDDLEWARE_ACTION_FAILED"; string internal constant VALUE_SHOULD_BE_ZERO = "VALUE_SHOULD_BE_ZERO"; string internal constant VALUE_SHOULD_NOT_BE_ZERO = "VALUE_SHOULD_NOT_BE_ZERO"; string internal constant VALUE_NOT_ENOUGH = "VALUE_NOT_ENOUGH"; string internal constant VALUE_NOT_EQUAL_TO_AMOUNT = "VALUE_NOT_EQUAL_TO_AMOUNT"; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; /** @title L1Bridge Hop Interface @notice L1 Hop Bridge, Used to transfer from L1 to L2s. */ interface IHopL1Bridge { function sendToL2( uint256 chainId, address recipient, uint256 amount, uint256 amountOutMin, uint256 deadline, address relayer, uint256 relayerFee ) external payable; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; 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 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* @dev Collection of functions related to the address type/
library Address { function outboundTransferTo( uint256 _amount, address _from, address _receiverAddress, address _token, uint256 _toChainId, bytes memory _extraData ) external payable virtual; } pragma solidity >=0.8.0; } pragma solidity ^0.8.4; @title L1Bridge Hop Interface @notice L1 Hop Bridge, Used to transfer from L1 to L2s. } pragma solidity ^0.8.0; function isContract(address account) internal view returns (bool) { uint256 size; return size > 0; } assembly { size := extcodesize(account) } function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); require(success, "Address: unable to send value, recipient may have reverted"); } (bool success, ) = recipient.call{ value: amount }(""); function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } function functionCallWithValue(address target, bytes memory data, uint256 value, 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"); return _verifyCallResult(success, returndata, errorMessage); } (bool success, bytes memory returndata) = target.call{ value: value }(data); function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } 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); } function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; if (returndata.length > 0) { assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } revert(errorMessage); } } } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; if (returndata.length > 0) { assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } revert(errorMessage); } } } } else { function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; if (returndata.length > 0) { assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } revert(errorMessage); } } } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; if (returndata.length > 0) { assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } revert(errorMessage); } } } } else { }
14,580,796
[ 1, 3118, 28826, 17, 13211, 17, 3004, 30, 490, 1285, 225, 2200, 434, 4186, 3746, 358, 326, 1758, 618, 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 ]
[ 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, 0 ]
[ 1, 12083, 5267, 288, 203, 565, 445, 11663, 5912, 774, 12, 203, 3639, 2254, 5034, 389, 8949, 16, 203, 3639, 1758, 389, 2080, 16, 203, 3639, 1758, 389, 24454, 1887, 16, 203, 3639, 1758, 389, 2316, 16, 203, 3639, 2254, 5034, 389, 869, 3893, 548, 16, 203, 3639, 1731, 3778, 389, 7763, 751, 203, 565, 262, 3903, 8843, 429, 5024, 31, 203, 97, 203, 203, 683, 9454, 18035, 560, 1545, 20, 18, 28, 18, 20, 31, 203, 203, 97, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 24, 31, 203, 203, 36, 2649, 511, 21, 13691, 670, 556, 6682, 203, 36, 20392, 511, 21, 670, 556, 24219, 16, 10286, 358, 7412, 628, 511, 21, 358, 511, 22, 87, 18, 225, 203, 97, 203, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 20, 31, 203, 203, 565, 445, 353, 8924, 12, 2867, 2236, 13, 2713, 1476, 1135, 261, 6430, 13, 288, 203, 203, 3639, 2254, 5034, 963, 31, 203, 3639, 327, 963, 405, 374, 31, 203, 565, 289, 203, 203, 3639, 19931, 288, 963, 519, 1110, 7000, 554, 12, 4631, 13, 289, 203, 565, 445, 1366, 620, 12, 2867, 8843, 429, 8027, 16, 2254, 5034, 3844, 13, 2713, 288, 203, 3639, 2583, 12, 2867, 12, 2211, 2934, 12296, 1545, 3844, 16, 315, 1887, 30, 2763, 11339, 11013, 8863, 203, 203, 3639, 2583, 12, 4768, 16, 315, 1887, 30, 13496, 358, 1366, 460, 16, 8027, 2026, 1240, 15226, 329, 8863, 203, 565, 289, 203, 203, 3639, 261, 6430, 2216, 16, 262, 2 ]
pragma solidity ^0.4.18; // ---------------------------------------------------------------------------- // 'Aurum' token contract // // Deployed to : 0xD658f5D40bb13DF4244dA85f2DAbA82467b22EDD // Symbol : ARM // Name : Aurum // Total supply: 1000000000000 // Decimals : 3 // // Enjoy. // // (c) by Moritz Neto with BokkyPooBah / Bok Consulting Pty Ltd Au 2017. The MIT Licence. // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- // 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 // ---------------------------------------------------------------------------- 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; } // ---------------------------------------------------------------------------- // Owned contract // ---------------------------------------------------------------------------- contract Owned { address public owner; address public newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); function Owned() 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); OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); } } // ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and assisted // token transfers // ---------------------------------------------------------------------------- contract Aurum 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 // ------------------------------------------------------------------------ function Aurum() public { symbol = "ARM"; name = "Aurum"; decimals = 18; _totalSupply = 100000000000000000000000000; balances[0xD658f5D40bb13DF4244dA85f2DAbA82467b22EDD] = _totalSupply; Transfer(address(0), 0xD658f5D40bb13DF4244dA85f2DAbA82467b22EDD, _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); 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; 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); 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; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public 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 Aurum 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; function Aurum() public { symbol = "ARM"; name = "Aurum"; decimals = 18; _totalSupply = 100000000000000000000000000; balances[0xD658f5D40bb13DF4244dA85f2DAbA82467b22EDD] = _totalSupply; Transfer(address(0), 0xD658f5D40bb13DF4244dA85f2DAbA82467b22EDD, _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); Transfer(msg.sender, to, tokens); return true; } function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; 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); 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; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } function () public payable { revert(); } function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
1,093,170
[ 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, 432, 14480, 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, 445, 432, 14480, 1435, 1071, 288, 203, 3639, 3273, 273, 315, 26120, 14432, 203, 3639, 508, 273, 315, 37, 14480, 14432, 203, 3639, 15105, 273, 6549, 31, 203, 3639, 389, 4963, 3088, 1283, 273, 2130, 12648, 12648, 12648, 31, 203, 3639, 324, 26488, 63, 20, 17593, 26, 8204, 74, 25, 40, 7132, 9897, 3437, 4577, 24, 3247, 24, 72, 37, 7140, 74, 22, 40, 5895, 37, 28, 3247, 9599, 70, 3787, 2056, 40, 65, 273, 389, 4963, 3088, 1283, 31, 203, 3639, 12279, 12, 2867, 12, 20, 3631, 374, 17593, 26, 8204, 74, 25, 40, 7132, 9897, 3437, 4577, 24, 3247, 24, 72, 37, 7140, 74, 22, 40, 5895, 37, 28, 3247, 9599, 70, 3787, 2056, 40, 16, 389, 4963, 3088, 1283, 1769, 203, 565, 289, 203, 203, 203, 565, 445, 2078, 3088, 1283, 1435, 1071, 5381, 1135, 261, 11890, 13, 288, 203, 3639, 327, 389, 4963, 3088, 1283, 225, 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, 5381, 1135, 261, 11890, 11013, 2 ]
pragma solidity ^0.8.0; import "@openzeppelin/contracts/utils/Context.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; // https://github.com/Uniswap/v2-core/tree/master/contracts/interfaces import "./IERC20.sol"; import "./IUniswapV2Pair.sol"; import "./IUniswapV2Router.sol"; import "./IUniswapV2Factory.sol"; import "./LiquiditySack.sol"; // SPDX-License-Identifier: MIT contract LCTMI is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; mapping(address => uint256) private _rOwned; mapping(address => uint256) private _tOwned; mapping(address => mapping(address => uint256)) private _allowances; mapping(address => bool) private _isExcludedFromFee; mapping(address => bool) private _isExcluded; address[] private _excluded; uint256 private constant MAX = ~uint256(0); uint256 private _tTotal = 1 * 10**9 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; string private _name = "lctmi"; string private _symbol = "lctmi"; uint8 private _decimals = 9; uint256 public _taxFee = 24; uint256 private _previousTaxFee = _taxFee; uint256 public _liquidityFee = 64; uint256 private _previousLiquidityFee = _liquidityFee; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable otherToken; address public immutable uniswapV2Pair; address public constant burnAddress = 0x000000000000000000000000000000000000dEaD; // 1 weird trick LiquiditySack public liqSack; bool inSwapAndLiquify; bool public swapAndLiquifyEnabled = true; uint256 public _maxTxAmount = 5 * 10**6 * 10**9; uint256 private numTokensSellToAddToLiquidity = 5 * 10**6 * 10**9; uint256 public _maxWalletAmount = 1 * 10**7 * 10**9; // 1 percent of total address private constant _UNISWAPV2_ROUTER_ADDR = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; // 0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F; // 🍣 address private constant DAI = 0x6B175474E89094C44Da98b954EedeAC495271d0F; // 0xaD6D458402F60fD3Bd25163575031ACDce07538D; // ropsten // welcome to hotel california bool public hotelCaliforniaMode = true; mapping(address => bool) public isHouseGuest; bool public tradingOpen = false; // sniper, no sniping uint256 public deadBlocks = 4; uint256 public launchedAt = 0; event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap); event SwapAndLiquifyEnabledUpdated(bool enabled); event SwapAndLiquify( uint256 tokensSwapped, uint256 othersReceived, uint256 tokensIntoLiqudity ); event CaliforniaCheckin(address guest, uint256 rentPaid); modifier lockTheSwap() { inSwapAndLiquify = true; _; inSwapAndLiquify = false; } constructor(address _stable_coin) { _rOwned[_msgSender()] = _rTotal; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02( _UNISWAPV2_ROUTER_ADDR ); otherToken = _stable_coin != address(0) ? _stable_coin : DAI; // Create a uniswap pair for this new token uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), otherToken); // set the rest of the contract variables uniswapV2Router = _uniswapV2Router; liqSack = new LiquiditySack(otherToken); // exclude owner and this contract from fee _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; emit Transfer(address(0), _msgSender(), _tTotal); } function name() public view override returns (string memory) { return _name; } function symbol() public view override returns (string memory) { return _symbol; } function decimals() public view override returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { if (_isExcluded[account]) return _tOwned[account]; return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } 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 increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue) ); return true; } 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; } function getOwner() external view override returns (address) { return owner(); } function isExcludedFromReward(address account) public view returns (bool) { return _isExcluded[account]; } function totalFees() public view returns (uint256) { return _tFeeTotal; } function deliver(uint256 tAmount) public { address sender = _msgSender(); require( !_isExcluded[sender], "Excluded addresses cannot call this function" ); (uint256 rAmount, , , , , ) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rTotal = _rTotal.sub(rAmount); _tFeeTotal = _tFeeTotal.add(tAmount); } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns (uint256) { require(tAmount <= _tTotal, "Amount must be less than supply"); if (!deductTransferFee) { (uint256 rAmount, , , , , ) = _getValues(tAmount); return rAmount; } else { (, uint256 rTransferAmount, , , , ) = _getValues(tAmount); return rTransferAmount; } } function tokenFromReflection(uint256 rAmount) public view returns (uint256) { require( rAmount <= _rTotal, "Amount must be less than total reflections" ); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function excludeFromReward(address account) public onlyOwner { // require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not exclude Uniswap router.'); require(!_isExcluded[account], "Account is already excluded"); if (_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function includeInReward(address account) external onlyOwner { require(_isExcluded[account], "Account is already excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function _transferBothExcluded( address sender, address recipient, uint256 tAmount ) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity ) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function excludeFromFee(address account) public onlyOwner { _isExcludedFromFee[account] = true; } function includeInFee(address account) public onlyOwner { _isExcludedFromFee[account] = false; } function setTaxFeePercent(uint256 taxFee) external onlyOwner { _taxFee = taxFee; } function setLiquidityFeePercent(uint256 liquidityFee) external onlyOwner { _liquidityFee = liquidityFee; } function setMaxTxPercent(uint256 maxTxPercent) external onlyOwner { _maxTxAmount = _tTotal.mul(maxTxPercent).div(10**2); } function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner { swapAndLiquifyEnabled = _enabled; emit SwapAndLiquifyEnabledUpdated(_enabled); } // enable trading function setTradingStatus(bool _status, uint256 _deadBlocks) public onlyOwner { tradingOpen = _status; if (tradingOpen && launchedAt == 0) { launchedAt = block.number; deadBlocks = _deadBlocks; } } // lobby management function setHotelCaliforniaMode(bool _status) public onlyOwner { hotelCaliforniaMode = _status; } function manageHouseGuests(address[] calldata addresses, bool status) public onlyOwner { for (uint256 i; i < addresses.length; ++i) { isHouseGuest[addresses[i]] = status; } } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } function _getValues(uint256 tAmount) private view returns ( uint256, uint256, uint256, uint256, uint256, uint256 ) { ( uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity ) = _getTValues(tAmount); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues( tAmount, tFee, tLiquidity, _getRate() ); return ( rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tLiquidity ); } function _getTValues(uint256 tAmount) private view returns ( uint256, uint256, uint256 ) { uint256 tFee = calculateTaxFee(tAmount); uint256 tLiquidity = calculateLiquidityFee(tAmount); uint256 tTransferAmount = tAmount.sub(tFee).sub(tLiquidity); return (tTransferAmount, tFee, tLiquidity); } function _getRValues( uint256 tAmount, uint256 tFee, uint256 tLiquidity, uint256 currentRate ) private pure returns ( uint256, uint256, uint256 ) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rLiquidity = tLiquidity.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rLiquidity); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns (uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns (uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; for (uint256 i = 0; i < _excluded.length; i++) { if ( _rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply ) return (_rTotal, _tTotal); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function _takeLiquidity(uint256 tLiquidity) private { uint256 currentRate = _getRate(); uint256 rLiquidity = tLiquidity.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity); if (_isExcluded[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tLiquidity); } function calculateTaxFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_taxFee).div(10**3); } function calculateLiquidityFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_liquidityFee).div(10**3); } function removeAllFee() private { if (_taxFee == 0 && _liquidityFee == 0) return; _previousTaxFee = _taxFee; _previousLiquidityFee = _liquidityFee; _taxFee = 0; _liquidityFee = 0; } function restoreAllFee() private { _taxFee = _previousTaxFee; _liquidityFee = _previousLiquidityFee; } function isExcludedFromFee(address account) public view returns (bool) { return _isExcludedFromFee[account]; } 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"); // max tx size if (from != owner() && to != owner()) { require( amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount." ); } // max wallet size uint256 currBalance = balanceOf(to); if ( from != owner() && to != owner() && to != _UNISWAPV2_ROUTER_ADDR && to != uniswapV2Pair && to != address(this) ) { require( currBalance + amount < _maxWalletAmount, "Transfer amount exceeds the maxWalletAmount." ); } // plz dont snipe with a bot if (hotelCaliforniaMode) { require(!isHouseGuest[from], "Bots cannot sell"); if ( from == uniswapV2Pair && (!tradingOpen || (launchedAt + deadBlocks) > block.number) ) { isHouseGuest[to] = true; emit CaliforniaCheckin(to, tx.gasprice); } } // is the token balance of this contract address over the min number of // tokens that we need to initiate a swap + liquidity lock? // also, don't get caught in a circular liquidity event. // also, don't swap & liquify if sender is uniswap pair. uint256 contractTokenBalance = balanceOf(address(this)); if (contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } bool overMinTokenBalance = contractTokenBalance >= numTokensSellToAddToLiquidity; if ( overMinTokenBalance && !inSwapAndLiquify && from != uniswapV2Pair && swapAndLiquifyEnabled ) { contractTokenBalance = numTokensSellToAddToLiquidity; // add liquidity swapAndLiquify(contractTokenBalance); } // indicates if fee should be deducted from transfer bool takeFee = true; // if any account belongs to _isExcludedFromFee account then remove the fee if (_isExcludedFromFee[from] || _isExcludedFromFee[to]) { takeFee = false; } // transfer amount, it will take tax, burn, liquidity fee _tokenTransfer(from, to, amount, takeFee); } function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap { // split the contract balance into halves uint256 half = contractTokenBalance.div(2); uint256 otherHalf = contractTokenBalance.sub(half); // capture the contract's current BASE balance. // this is so that we can capture exactly the amount of BASE token that the // swap creates uint256 initialBalance = IERC20(otherToken).balanceOf(address(this)); swapTokensForOther(half); liqSack.giveItBack(); // how much BASE did we just swap into? uint256 newBalance = IERC20(otherToken).balanceOf(address(this)).sub( initialBalance ); // add liquidity to uniswap addLiquidity(otherHalf, newBalance); emit SwapAndLiquify(half, newBalance, otherHalf); } function swapTokensForOther(uint256 tokenAmount) private { // generate the uniswap pair path address[] memory path = new address[](2); path[0] = address(this); path[1] = otherToken; _approve(address(this), address(uniswapV2Router), tokenAmount); // make the swap uniswapV2Router.swapExactTokensForTokensSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount path, address(liqSack), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 otherAmount) private { // approve token transfer to cover all possible scenarios _approve(address(this), address(uniswapV2Router), tokenAmount); IERC20(otherToken).approve(address(uniswapV2Router), otherAmount); // add the liquidity uniswapV2Router.addLiquidity( address(this), otherToken, tokenAmount, otherAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable burnAddress, block.timestamp ); } // this method is responsible for taking all fees, if takeFee is true function _tokenTransfer( address sender, address recipient, uint256 amount, bool takeFee ) private { if (!takeFee) removeAllFee(); if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && _isExcluded[recipient]) { _transferToExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && !_isExcluded[recipient]) { _transferStandard(sender, recipient, amount); } else if (_isExcluded[sender] && _isExcluded[recipient]) { _transferBothExcluded(sender, recipient, amount); } else { _transferStandard(sender, recipient, amount); } if (!takeFee) restoreAllFee(); } function _transferStandard( address sender, address recipient, uint256 tAmount ) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity ) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferToExcluded( address sender, address recipient, uint256 tAmount ) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity ) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferFromExcluded( address sender, address recipient, uint256 tAmount ) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity ) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } } pragma solidity ^0.8.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "./IERC20.sol"; // SPDX-License-Identifier: MIT contract LiquiditySack is Ownable { using Address for address; address otherTokenAddress; constructor(address otherToken) { otherTokenAddress = otherToken; } function giveItBack() public onlyOwner { IERC20 other = IERC20(otherTokenAddress); uint256 owned = other.balanceOf(address(this)); other.transfer(owner(), owned); } } pragma solidity >=0.5.0; // SPDX-License-Identifier: MIT interface IUniswapV2Factory { event PairCreated( address indexed token0, address indexed token1, address pair, uint256 ); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint256) external view returns (address pair); function allPairsLength() external view returns (uint256); } pragma solidity >=0.6.2; // SPDX-License-Identifier: MIT interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns ( uint256 amountA, uint256 amountB, uint256 liquidity ); function addLiquidityETH( address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external payable returns ( uint256 amountToken, uint256 amountETH, uint256 liquidity ); function removeLiquidity( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns (uint256 amountA, uint256 amountB); function removeLiquidityETH( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external returns (uint256 amountToken, uint256 amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountA, uint256 amountB); function removeLiquidityETHWithPermit( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountToken, uint256 amountETH); function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapTokensForExactTokens( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactETHForTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function swapTokensForExactETH( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactTokensForETH( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapETHForExactTokens( uint256 amountOut, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function quote( uint256 amountA, uint256 reserveA, uint256 reserveB ) external pure returns (uint256 amountB); function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) external pure returns (uint256 amountOut); function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) external pure returns (uint256 amountIn); function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts); function getAmountsIn(uint256 amountOut, address[] calldata path) external view returns (uint256[] memory amounts); } interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external returns (uint256 amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; } pragma solidity ^0.8.0; // SPDX-License-Identifier: MIT interface IUniswapV2Pair { event Approval( address indexed owner, address indexed spender, uint256 value ); event Transfer(address indexed from, address indexed to, uint256 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 (uint256); function balanceOf(address owner) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 value) external returns (bool); function transfer(address to, uint256 value) external returns (bool); function transferFrom( address from, address to, uint256 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 (uint256); function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; event Mint(address indexed sender, uint256 amount0, uint256 amount1); event Burn( address indexed sender, uint256 amount0, uint256 amount1, address indexed to ); event Swap( address indexed sender, uint256 amount0In, uint256 amount1In, uint256 amount0Out, uint256 amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint256); 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 (uint256); function price1CumulativeLast() external view returns (uint256); function kLast() external view returns (uint256); function mint(address to) external returns (uint256 liquidity); function burn(address to) external returns (uint256 amount0, uint256 amount1); function swap( uint256 amount0Out, uint256 amount1Out, address to, bytes calldata data ) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } pragma solidity ^0.8.0; // SPDX-License-Identifier: MIT interface IERC20 { event Transfer(address indexed from, address indexed to, uint256 value); event Approval( address indexed owner, address indexed spender, uint256 value ); 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); // function transferFromWithPermit(address sender, address recipient, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol) pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (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; } }
approve token transfer to cover all possible scenarios add the liquidity
function addLiquidity(uint256 tokenAmount, uint256 otherAmount) private { _approve(address(this), address(uniswapV2Router), tokenAmount); IERC20(otherToken).approve(address(uniswapV2Router), otherAmount); uniswapV2Router.addLiquidity( address(this), otherToken, tokenAmount, otherAmount, burnAddress, block.timestamp ); }
14,742,758
[ 1, 12908, 537, 1147, 7412, 358, 5590, 777, 3323, 22456, 527, 326, 4501, 372, 24237, 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, 527, 48, 18988, 24237, 12, 11890, 5034, 1147, 6275, 16, 2254, 5034, 1308, 6275, 13, 3238, 288, 203, 3639, 389, 12908, 537, 12, 2867, 12, 2211, 3631, 1758, 12, 318, 291, 91, 438, 58, 22, 8259, 3631, 1147, 6275, 1769, 203, 3639, 467, 654, 39, 3462, 12, 3011, 1345, 2934, 12908, 537, 12, 2867, 12, 318, 291, 91, 438, 58, 22, 8259, 3631, 1308, 6275, 1769, 203, 203, 3639, 640, 291, 91, 438, 58, 22, 8259, 18, 1289, 48, 18988, 24237, 12, 203, 5411, 1758, 12, 2211, 3631, 203, 5411, 1308, 1345, 16, 203, 5411, 1147, 6275, 16, 203, 5411, 1308, 6275, 16, 203, 5411, 18305, 1887, 16, 203, 5411, 1203, 18, 5508, 203, 3639, 11272, 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 ]
pragma solidity ^0.4.20; // File: attrstore/AttributeStore.sol pragma solidity^0.4.11; library AttributeStore { struct Data { mapping(bytes32 => uint) store; } function getAttribute(Data storage self, bytes32 _UUID, string _attrName) public view returns (uint) { bytes32 key = keccak256(_UUID, _attrName); return self.store[key]; } function setAttribute(Data storage self, bytes32 _UUID, string _attrName, uint _attrVal) public { bytes32 key = keccak256(_UUID, _attrName); self.store[key] = _attrVal; } } // File: dll/DLL.sol pragma solidity^0.4.11; library DLL { uint constant NULL_NODE_ID = 0; struct Node { uint next; uint prev; } struct Data { mapping(uint => Node) dll; } function isEmpty(Data storage self) public view returns (bool) { return getStart(self) == NULL_NODE_ID; } function contains(Data storage self, uint _curr) public view returns (bool) { if (isEmpty(self) || _curr == NULL_NODE_ID) { return false; } bool isSingleNode = (getStart(self) == _curr) && (getEnd(self) == _curr); bool isNullNode = (getNext(self, _curr) == NULL_NODE_ID) && (getPrev(self, _curr) == NULL_NODE_ID); return isSingleNode || !isNullNode; } function getNext(Data storage self, uint _curr) public view returns (uint) { return self.dll[_curr].next; } function getPrev(Data storage self, uint _curr) public view returns (uint) { return self.dll[_curr].prev; } function getStart(Data storage self) public view returns (uint) { return getNext(self, NULL_NODE_ID); } function getEnd(Data storage self) public view returns (uint) { return getPrev(self, NULL_NODE_ID); } /** @dev Inserts a new node between _prev and _next. When inserting a node already existing in the list it will be automatically removed from the old position. @param _prev the node which _new will be inserted after @param _curr the id of the new node being inserted @param _next the node which _new will be inserted before */ function insert(Data storage self, uint _prev, uint _curr, uint _next) public { require(_curr != NULL_NODE_ID); remove(self, _curr); require(_prev == NULL_NODE_ID || contains(self, _prev)); require(_next == NULL_NODE_ID || contains(self, _next)); require(getNext(self, _prev) == _next); require(getPrev(self, _next) == _prev); self.dll[_curr].prev = _prev; self.dll[_curr].next = _next; self.dll[_prev].next = _curr; self.dll[_next].prev = _curr; } function remove(Data storage self, uint _curr) public { if (!contains(self, _curr)) { return; } uint next = getNext(self, _curr); uint prev = getPrev(self, _curr); self.dll[next].prev = prev; self.dll[prev].next = next; delete self.dll[_curr]; } } // File: tokens/eip20/EIP20Interface.sol // Abstract contract for the full ERC 20 Token standard // https://github.com/ethereum/EIPs/issues/20 pragma solidity ^0.4.8; contract EIP20Interface { /* This is a slight change to the ERC20 base standard. function totalSupply() constant returns (uint256 supply); is replaced with: uint256 public totalSupply; This automatically creates a getter function for the totalSupply. This is moved to the base contract since public getter functions are not currently recognised as an implementation of the matching abstract function by the compiler. */ /// total amount of tokens uint256 public totalSupply; /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) public view returns (uint256 balance); /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) public returns (bool success); /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); /// @notice `msg.sender` approves `_spender` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of tokens to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) public returns (bool success); /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) public view returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } // File: zeppelin/math/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal constant returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal constant returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } // File: plcr-revival/PLCRVoting.sol /** @title Partial-Lock-Commit-Reveal Voting scheme with ERC20 tokens @author Team: Aspyn Palatnick, Cem Ozer, Yorke Rhodes */ contract PLCRVoting { // ============ // EVENTS: // ============ event _VoteCommitted(uint indexed pollID, uint numTokens, address indexed voter); event _VoteRevealed(uint indexed pollID, uint numTokens, uint votesFor, uint votesAgainst, uint indexed choice, address indexed voter); event _PollCreated(uint voteQuorum, uint commitEndDate, uint revealEndDate, uint indexed pollID, address indexed creator); event _VotingRightsGranted(uint numTokens, address indexed voter); event _VotingRightsWithdrawn(uint numTokens, address indexed voter); event _TokensRescued(uint indexed pollID, address indexed voter); // ============ // DATA STRUCTURES: // ============ using AttributeStore for AttributeStore.Data; using DLL for DLL.Data; using SafeMath for uint; struct Poll { uint commitEndDate; /// expiration date of commit period for poll uint revealEndDate; /// expiration date of reveal period for poll uint voteQuorum; /// number of votes required for a proposal to pass uint votesFor; /// tally of votes supporting proposal uint votesAgainst; /// tally of votes countering proposal mapping(address => bool) didCommit; /// indicates whether an address committed a vote for this poll mapping(address => bool) didReveal; /// indicates whether an address revealed a vote for this poll } // ============ // STATE VARIABLES: // ============ uint constant public INITIAL_POLL_NONCE = 0; uint public pollNonce; mapping(uint => Poll) public pollMap; // maps pollID to Poll struct mapping(address => uint) public voteTokenBalance; // maps user's address to voteToken balance mapping(address => DLL.Data) dllMap; AttributeStore.Data store; EIP20Interface public token; /** @dev Initializer. Can only be called once. @param _token The address where the ERC20 token contract is deployed */ function init(address _token) public { require(_token != 0 && address(token) == 0); token = EIP20Interface(_token); pollNonce = INITIAL_POLL_NONCE; } // ================ // TOKEN INTERFACE: // ================ /** @notice Loads _numTokens ERC20 tokens into the voting contract for one-to-one voting rights @dev Assumes that msg.sender has approved voting contract to spend on their behalf @param _numTokens The number of votingTokens desired in exchange for ERC20 tokens */ function requestVotingRights(uint _numTokens) public { require(token.balanceOf(msg.sender) >= _numTokens); voteTokenBalance[msg.sender] += _numTokens; require(token.transferFrom(msg.sender, this, _numTokens)); emit _VotingRightsGranted(_numTokens, msg.sender); } /** @notice Withdraw _numTokens ERC20 tokens from the voting contract, revoking these voting rights @param _numTokens The number of ERC20 tokens desired in exchange for voting rights */ function withdrawVotingRights(uint _numTokens) external { uint availableTokens = voteTokenBalance[msg.sender].sub(getLockedTokens(msg.sender)); require(availableTokens >= _numTokens); voteTokenBalance[msg.sender] -= _numTokens; require(token.transfer(msg.sender, _numTokens)); emit _VotingRightsWithdrawn(_numTokens, msg.sender); } /** @dev Unlocks tokens locked in unrevealed vote where poll has ended @param _pollID Integer identifier associated with the target poll */ function rescueTokens(uint _pollID) public { require(isExpired(pollMap[_pollID].revealEndDate)); require(dllMap[msg.sender].contains(_pollID)); dllMap[msg.sender].remove(_pollID); emit _TokensRescued(_pollID, msg.sender); } /** @dev Unlocks tokens locked in unrevealed votes where polls have ended @param _pollIDs Array of integer identifiers associated with the target polls */ function rescueTokensInMultiplePolls(uint[] _pollIDs) public { // loop through arrays, rescuing tokens from all for (uint i = 0; i < _pollIDs.length; i++) { rescueTokens(_pollIDs[i]); } } // ================= // VOTING INTERFACE: // ================= /** @notice Commits vote using hash of choice and secret salt to conceal vote until reveal @param _pollID Integer identifier associated with target poll @param _secretHash Commit keccak256 hash of voter's choice and salt (tightly packed in this order) @param _numTokens The number of tokens to be committed towards the target poll @param _prevPollID The ID of the poll that the user has voted the maximum number of tokens in which is still less than or equal to numTokens */ function commitVote(uint _pollID, bytes32 _secretHash, uint _numTokens, uint _prevPollID) public { require(commitPeriodActive(_pollID)); // if msg.sender doesn't have enough voting rights, // request for enough voting rights if (voteTokenBalance[msg.sender] < _numTokens) { uint remainder = _numTokens.sub(voteTokenBalance[msg.sender]); requestVotingRights(remainder); } // make sure msg.sender has enough voting rights require(voteTokenBalance[msg.sender] >= _numTokens); // prevent user from committing to zero node placeholder require(_pollID != 0); // prevent user from committing a secretHash of 0 require(_secretHash != 0); // Check if _prevPollID exists in the user's DLL or if _prevPollID is 0 require(_prevPollID == 0 || dllMap[msg.sender].contains(_prevPollID)); uint nextPollID = dllMap[msg.sender].getNext(_prevPollID); // edge case: in-place update if (nextPollID == _pollID) { nextPollID = dllMap[msg.sender].getNext(_pollID); } require(validPosition(_prevPollID, nextPollID, msg.sender, _numTokens)); dllMap[msg.sender].insert(_prevPollID, _pollID, nextPollID); bytes32 UUID = attrUUID(msg.sender, _pollID); store.setAttribute(UUID, "numTokens", _numTokens); store.setAttribute(UUID, "commitHash", uint(_secretHash)); pollMap[_pollID].didCommit[msg.sender] = true; emit _VoteCommitted(_pollID, _numTokens, msg.sender); } /** @notice Commits votes using hashes of choices and secret salts to conceal votes until reveal @param _pollIDs Array of integer identifiers associated with target polls @param _secretHashes Array of commit keccak256 hashes of voter's choices and salts (tightly packed in this order) @param _numsTokens Array of numbers of tokens to be committed towards the target polls @param _prevPollIDs Array of IDs of the polls that the user has voted the maximum number of tokens in which is still less than or equal to numTokens */ function commitVotes(uint[] _pollIDs, bytes32[] _secretHashes, uint[] _numsTokens, uint[] _prevPollIDs) external { // make sure the array lengths are all the same require(_pollIDs.length == _secretHashes.length); require(_pollIDs.length == _numsTokens.length); require(_pollIDs.length == _prevPollIDs.length); // loop through arrays, committing each individual vote values for (uint i = 0; i < _pollIDs.length; i++) { commitVote(_pollIDs[i], _secretHashes[i], _numsTokens[i], _prevPollIDs[i]); } } /** @dev Compares previous and next poll's committed tokens for sorting purposes @param _prevID Integer identifier associated with previous poll in sorted order @param _nextID Integer identifier associated with next poll in sorted order @param _voter Address of user to check DLL position for @param _numTokens The number of tokens to be committed towards the poll (used for sorting) @return valid Boolean indication of if the specified position maintains the sort */ function validPosition(uint _prevID, uint _nextID, address _voter, uint _numTokens) public constant returns (bool valid) { bool prevValid = (_numTokens >= getNumTokens(_voter, _prevID)); // if next is zero node, _numTokens does not need to be greater bool nextValid = (_numTokens <= getNumTokens(_voter, _nextID) || _nextID == 0); return prevValid && nextValid; } /** @notice Reveals vote with choice and secret salt used in generating commitHash to attribute committed tokens @param _pollID Integer identifier associated with target poll @param _voteOption Vote choice used to generate commitHash for associated poll @param _salt Secret number used to generate commitHash for associated poll */ function revealVote(uint _pollID, uint _voteOption, uint _salt) public { // Make sure the reveal period is active require(revealPeriodActive(_pollID)); require(pollMap[_pollID].didCommit[msg.sender]); // make sure user has committed a vote for this poll require(!pollMap[_pollID].didReveal[msg.sender]); // prevent user from revealing multiple times require(keccak256(_voteOption, _salt) == getCommitHash(msg.sender, _pollID)); // compare resultant hash from inputs to original commitHash uint numTokens = getNumTokens(msg.sender, _pollID); if (_voteOption == 1) {// apply numTokens to appropriate poll choice pollMap[_pollID].votesFor += numTokens; } else { pollMap[_pollID].votesAgainst += numTokens; } dllMap[msg.sender].remove(_pollID); // remove the node referring to this vote upon reveal pollMap[_pollID].didReveal[msg.sender] = true; emit _VoteRevealed(_pollID, numTokens, pollMap[_pollID].votesFor, pollMap[_pollID].votesAgainst, _voteOption, msg.sender); } /** @notice Reveals multiple votes with choices and secret salts used in generating commitHashes to attribute committed tokens @param _pollIDs Array of integer identifiers associated with target polls @param _voteOptions Array of vote choices used to generate commitHashes for associated polls @param _salts Array of secret numbers used to generate commitHashes for associated polls */ function revealVotes(uint[] _pollIDs, uint[] _voteOptions, uint[] _salts) external { // make sure the array lengths are all the same require(_pollIDs.length == _voteOptions.length); require(_pollIDs.length == _salts.length); // loop through arrays, revealing each individual vote values for (uint i = 0; i < _pollIDs.length; i++) { revealVote(_pollIDs[i], _voteOptions[i], _salts[i]); } } /** @param _pollID Integer identifier associated with target poll @param _salt Arbitrarily chosen integer used to generate secretHash @return correctVotes Number of tokens voted for winning option */ function getNumPassingTokens(address _voter, uint _pollID, uint _salt) public constant returns (uint correctVotes) { require(pollEnded(_pollID)); require(pollMap[_pollID].didReveal[_voter]); uint winningChoice = isPassed(_pollID) ? 1 : 0; bytes32 winnerHash = keccak256(winningChoice, _salt); bytes32 commitHash = getCommitHash(_voter, _pollID); require(winnerHash == commitHash); return getNumTokens(_voter, _pollID); } // ================== // POLLING INTERFACE: // ================== /** @dev Initiates a poll with canonical configured parameters at pollID emitted by PollCreated event @param _voteQuorum Type of majority (out of 100) that is necessary for poll to be successful @param _commitDuration Length of desired commit period in seconds @param _revealDuration Length of desired reveal period in seconds */ function startPoll(uint _voteQuorum, uint _commitDuration, uint _revealDuration) public returns (uint pollID) { pollNonce = pollNonce + 1; uint commitEndDate = block.timestamp.add(_commitDuration); uint revealEndDate = commitEndDate.add(_revealDuration); pollMap[pollNonce] = Poll({ voteQuorum: _voteQuorum, commitEndDate: commitEndDate, revealEndDate: revealEndDate, votesFor: 0, votesAgainst: 0 }); emit _PollCreated(_voteQuorum, commitEndDate, revealEndDate, pollNonce, msg.sender); return pollNonce; } /** @notice Determines if proposal has passed @dev Check if votesFor out of totalVotes exceeds votesQuorum (requires pollEnded) @param _pollID Integer identifier associated with target poll */ function isPassed(uint _pollID) constant public returns (bool passed) { require(pollEnded(_pollID)); Poll memory poll = pollMap[_pollID]; return (100 * poll.votesFor) > (poll.voteQuorum * (poll.votesFor + poll.votesAgainst)); } // ---------------- // POLLING HELPERS: // ---------------- /** @dev Gets the total winning votes for reward distribution purposes @param _pollID Integer identifier associated with target poll @return Total number of votes committed to the winning option for specified poll */ function getTotalNumberOfTokensForWinningOption(uint _pollID) constant public returns (uint numTokens) { require(pollEnded(_pollID)); if (isPassed(_pollID)) return pollMap[_pollID].votesFor; else return pollMap[_pollID].votesAgainst; } /** @notice Determines if poll is over @dev Checks isExpired for specified poll's revealEndDate @return Boolean indication of whether polling period is over */ function pollEnded(uint _pollID) constant public returns (bool ended) { require(pollExists(_pollID)); return isExpired(pollMap[_pollID].revealEndDate); } /** @notice Checks if the commit period is still active for the specified poll @dev Checks isExpired for the specified poll's commitEndDate @param _pollID Integer identifier associated with target poll @return Boolean indication of isCommitPeriodActive for target poll */ function commitPeriodActive(uint _pollID) constant public returns (bool active) { require(pollExists(_pollID)); return !isExpired(pollMap[_pollID].commitEndDate); } /** @notice Checks if the reveal period is still active for the specified poll @dev Checks isExpired for the specified poll's revealEndDate @param _pollID Integer identifier associated with target poll */ function revealPeriodActive(uint _pollID) constant public returns (bool active) { require(pollExists(_pollID)); return !isExpired(pollMap[_pollID].revealEndDate) && !commitPeriodActive(_pollID); } /** @dev Checks if user has committed for specified poll @param _voter Address of user to check against @param _pollID Integer identifier associated with target poll @return Boolean indication of whether user has committed */ function didCommit(address _voter, uint _pollID) constant public returns (bool committed) { require(pollExists(_pollID)); return pollMap[_pollID].didCommit[_voter]; } /** @dev Checks if user has revealed for specified poll @param _voter Address of user to check against @param _pollID Integer identifier associated with target poll @return Boolean indication of whether user has revealed */ function didReveal(address _voter, uint _pollID) constant public returns (bool revealed) { require(pollExists(_pollID)); return pollMap[_pollID].didReveal[_voter]; } /** @dev Checks if a poll exists @param _pollID The pollID whose existance is to be evaluated. @return Boolean Indicates whether a poll exists for the provided pollID */ function pollExists(uint _pollID) constant public returns (bool exists) { return (_pollID != 0 && _pollID <= pollNonce); } // --------------------------- // DOUBLE-LINKED-LIST HELPERS: // --------------------------- /** @dev Gets the bytes32 commitHash property of target poll @param _voter Address of user to check against @param _pollID Integer identifier associated with target poll @return Bytes32 hash property attached to target poll */ function getCommitHash(address _voter, uint _pollID) constant public returns (bytes32 commitHash) { return bytes32(store.getAttribute(attrUUID(_voter, _pollID), "commitHash")); } /** @dev Wrapper for getAttribute with attrName="numTokens" @param _voter Address of user to check against @param _pollID Integer identifier associated with target poll @return Number of tokens committed to poll in sorted poll-linked-list */ function getNumTokens(address _voter, uint _pollID) constant public returns (uint numTokens) { return store.getAttribute(attrUUID(_voter, _pollID), "numTokens"); } /** @dev Gets top element of sorted poll-linked-list @param _voter Address of user to check against @return Integer identifier to poll with maximum number of tokens committed to it */ function getLastNode(address _voter) constant public returns (uint pollID) { return dllMap[_voter].getPrev(0); } /** @dev Gets the numTokens property of getLastNode @param _voter Address of user to check against @return Maximum number of tokens committed in poll specified */ function getLockedTokens(address _voter) constant public returns (uint numTokens) { return getNumTokens(_voter, getLastNode(_voter)); } /* @dev Takes the last node in the user's DLL and iterates backwards through the list searching for a node with a value less than or equal to the provided _numTokens value. When such a node is found, if the provided _pollID matches the found nodeID, this operation is an in-place update. In that case, return the previous node of the node being updated. Otherwise return the first node that was found with a value less than or equal to the provided _numTokens. @param _voter The voter whose DLL will be searched @param _numTokens The value for the numTokens attribute in the node to be inserted @return the node which the propoded node should be inserted after */ function getInsertPointForNumTokens(address _voter, uint _numTokens, uint _pollID) constant public returns (uint prevNode) { // Get the last node in the list and the number of tokens in that node uint nodeID = getLastNode(_voter); uint tokensInNode = getNumTokens(_voter, nodeID); // Iterate backwards through the list until reaching the root node while(nodeID != 0) { // Get the number of tokens in the current node tokensInNode = getNumTokens(_voter, nodeID); if(tokensInNode <= _numTokens) { // We found the insert point! if(nodeID == _pollID) { // This is an in-place update. Return the prev node of the node being updated nodeID = dllMap[_voter].getPrev(nodeID); } // Return the insert point return nodeID; } // We did not find the insert point. Continue iterating backwards through the list nodeID = dllMap[_voter].getPrev(nodeID); } // The list is empty, or a smaller value than anything else in the list is being inserted return nodeID; } // ---------------- // GENERAL HELPERS: // ---------------- /** @dev Checks if an expiration date has been reached @param _terminationDate Integer timestamp of date to compare current timestamp with @return expired Boolean indication of whether the terminationDate has passed */ function isExpired(uint _terminationDate) constant public returns (bool expired) { return (block.timestamp > _terminationDate); } /** @dev Generates an identifier which associates a user and a poll together @param _pollID Integer identifier associated with target poll @return UUID Hash which is deterministic from _user and _pollID */ function attrUUID(address _user, uint _pollID) public pure returns (bytes32 UUID) { return keccak256(_user, _pollID); } } // File: contracts/Parameterizer.sol pragma solidity^0.4.11; contract Parameterizer { // ------ // EVENTS // ------ event _ReparameterizationProposal(string name, uint value, bytes32 propID, uint deposit, uint appEndDate, address indexed proposer); event _NewChallenge(bytes32 indexed propID, uint challengeID, uint commitEndDate, uint revealEndDate, address indexed challenger); event _ProposalAccepted(bytes32 indexed propID, string name, uint value); event _ProposalExpired(bytes32 indexed propID); event _ChallengeSucceeded(bytes32 indexed propID, uint indexed challengeID, uint rewardPool, uint totalTokens); event _ChallengeFailed(bytes32 indexed propID, uint indexed challengeID, uint rewardPool, uint totalTokens); event _RewardClaimed(uint indexed challengeID, uint reward, address indexed voter); // ------ // DATA STRUCTURES // ------ using SafeMath for uint; struct ParamProposal { uint appExpiry; uint challengeID; uint deposit; string name; address owner; uint processBy; uint value; } struct Challenge { uint rewardPool; // (remaining) pool of tokens distributed amongst winning voters address challenger; // owner of Challenge bool resolved; // indication of if challenge is resolved uint stake; // number of tokens at risk for either party during challenge uint winningTokens; // (remaining) amount of tokens used for voting by the winning side mapping(address => bool) tokenClaims; } // ------ // STATE // ------ mapping(bytes32 => uint) public params; // maps challengeIDs to associated challenge data mapping(uint => Challenge) public challenges; // maps pollIDs to intended data change if poll passes mapping(bytes32 => ParamProposal) public proposals; // Global Variables EIP20Interface public token; PLCRVoting public voting; uint public PROCESSBY = 604800; // 7 days /** @dev Initializer Can only be called once @param _token The address where the ERC20 token contract is deployed @param _plcr address of a PLCR voting contract for the provided token @notice _parameters array of canonical parameters */ function init( address _token, address _plcr, uint[] _parameters ) public { require(_token != 0 && address(token) == 0); require(_plcr != 0 && address(voting) == 0); token = EIP20Interface(_token); voting = PLCRVoting(_plcr); // minimum deposit for listing to be whitelisted set("minDeposit", _parameters[0]); // minimum deposit to propose a reparameterization set("pMinDeposit", _parameters[1]); // period over which applicants wait to be whitelisted set("applyStageLen", _parameters[2]); // period over which reparmeterization proposals wait to be processed set("pApplyStageLen", _parameters[3]); // length of commit period for voting set("commitStageLen", _parameters[4]); // length of commit period for voting in parameterizer set("pCommitStageLen", _parameters[5]); // length of reveal period for voting set("revealStageLen", _parameters[6]); // length of reveal period for voting in parameterizer set("pRevealStageLen", _parameters[7]); // percentage of losing party's deposit distributed to winning party set("dispensationPct", _parameters[8]); // percentage of losing party's deposit distributed to winning party in parameterizer set("pDispensationPct", _parameters[9]); // type of majority out of 100 necessary for candidate success set("voteQuorum", _parameters[10]); // type of majority out of 100 necessary for proposal success in parameterizer set("pVoteQuorum", _parameters[11]); } // ----------------------- // TOKEN HOLDER INTERFACE // ----------------------- /** @notice propose a reparamaterization of the key _name's value to _value. @param _name the name of the proposed param to be set @param _value the proposed value to set the param to be set */ function proposeReparameterization(string _name, uint _value) public returns (bytes32) { uint deposit = get("pMinDeposit"); bytes32 propID = keccak256(_name, _value); if (keccak256(_name) == keccak256("dispensationPct") || keccak256(_name) == keccak256("pDispensationPct")) { require(_value <= 100); } require(!propExists(propID)); // Forbid duplicate proposals require(get(_name) != _value); // Forbid NOOP reparameterizations // attach name and value to pollID proposals[propID] = ParamProposal({ appExpiry: now.add(get("pApplyStageLen")), challengeID: 0, deposit: deposit, name: _name, owner: msg.sender, processBy: now.add(get("pApplyStageLen")) .add(get("pCommitStageLen")) .add(get("pRevealStageLen")) .add(PROCESSBY), value: _value }); require(token.transferFrom(msg.sender, this, deposit)); // escrow tokens (deposit amt) emit _ReparameterizationProposal(_name, _value, propID, deposit, proposals[propID].appExpiry, msg.sender); return propID; } /** @notice challenge the provided proposal ID, and put tokens at stake to do so. @param _propID the proposal ID to challenge */ function challengeReparameterization(bytes32 _propID) public returns (uint challengeID) { ParamProposal memory prop = proposals[_propID]; uint deposit = prop.deposit; require(propExists(_propID) && prop.challengeID == 0); //start poll uint pollID = voting.startPoll( get("pVoteQuorum"), get("pCommitStageLen"), get("pRevealStageLen") ); challenges[pollID] = Challenge({ challenger: msg.sender, rewardPool: SafeMath.sub(100, get("pDispensationPct")).mul(deposit).div(100), stake: deposit, resolved: false, winningTokens: 0 }); proposals[_propID].challengeID = pollID; // update listing to store most recent challenge //take tokens from challenger require(token.transferFrom(msg.sender, this, deposit)); var (commitEndDate, revealEndDate,) = voting.pollMap(pollID); emit _NewChallenge(_propID, pollID, commitEndDate, revealEndDate, msg.sender); return pollID; } /** @notice for the provided proposal ID, set it, resolve its challenge, or delete it depending on whether it can be set, has a challenge which can be resolved, or if its "process by" date has passed @param _propID the proposal ID to make a determination and state transition for */ function processProposal(bytes32 _propID) public { ParamProposal storage prop = proposals[_propID]; address propOwner = prop.owner; uint propDeposit = prop.deposit; // Before any token transfers, deleting the proposal will ensure that if reentrancy occurs the // prop.owner and prop.deposit will be 0, thereby preventing theft if (canBeSet(_propID)) { // There is no challenge against the proposal. The processBy date for the proposal has not // passed, but the proposal's appExpirty date has passed. set(prop.name, prop.value); emit _ProposalAccepted(_propID, prop.name, prop.value); delete proposals[_propID]; require(token.transfer(propOwner, propDeposit)); } else if (challengeCanBeResolved(_propID)) { // There is a challenge against the proposal. resolveChallenge(_propID); } else if (now > prop.processBy) { // There is no challenge against the proposal, but the processBy date has passed. emit _ProposalExpired(_propID); delete proposals[_propID]; require(token.transfer(propOwner, propDeposit)); } else { // There is no challenge against the proposal, and neither the appExpiry date nor the // processBy date has passed. revert(); } assert(get("dispensationPct") <= 100); assert(get("pDispensationPct") <= 100); // verify that future proposal appExpiry and processBy times will not overflow now.add(get("pApplyStageLen")) .add(get("pCommitStageLen")) .add(get("pRevealStageLen")) .add(PROCESSBY); delete proposals[_propID]; } /** @notice Claim the tokens owed for the msg.sender in the provided challenge @param _challengeID the challenge ID to claim tokens for @param _salt the salt used to vote in the challenge being withdrawn for */ function claimReward(uint _challengeID, uint _salt) public { // ensure voter has not already claimed tokens and challenge results have been processed require(challenges[_challengeID].tokenClaims[msg.sender] == false); require(challenges[_challengeID].resolved == true); uint voterTokens = voting.getNumPassingTokens(msg.sender, _challengeID, _salt); uint reward = voterReward(msg.sender, _challengeID, _salt); // subtract voter's information to preserve the participation ratios of other voters // compared to the remaining pool of rewards challenges[_challengeID].winningTokens -= voterTokens; challenges[_challengeID].rewardPool -= reward; // ensures a voter cannot claim tokens again challenges[_challengeID].tokenClaims[msg.sender] = true; emit _RewardClaimed(_challengeID, reward, msg.sender); require(token.transfer(msg.sender, reward)); } /** @dev Called by a voter to claim their rewards for each completed vote. Someone must call updateStatus() before this can be called. @param _challengeIDs The PLCR pollIDs of the challenges rewards are being claimed for @param _salts The salts of a voter's commit hashes in the given polls */ function claimRewards(uint[] _challengeIDs, uint[] _salts) public { // make sure the array lengths are the same require(_challengeIDs.length == _salts.length); // loop through arrays, claiming each individual vote reward for (uint i = 0; i < _challengeIDs.length; i++) { claimReward(_challengeIDs[i], _salts[i]); } } // -------- // GETTERS // -------- /** @dev Calculates the provided voter's token reward for the given poll. @param _voter The address of the voter whose reward balance is to be returned @param _challengeID The ID of the challenge the voter's reward is being calculated for @param _salt The salt of the voter's commit hash in the given poll @return The uint indicating the voter's reward */ function voterReward(address _voter, uint _challengeID, uint _salt) public view returns (uint) { uint winningTokens = challenges[_challengeID].winningTokens; uint rewardPool = challenges[_challengeID].rewardPool; uint voterTokens = voting.getNumPassingTokens(_voter, _challengeID, _salt); return (voterTokens * rewardPool) / winningTokens; } /** @notice Determines whether a proposal passed its application stage without a challenge @param _propID The proposal ID for which to determine whether its application stage passed without a challenge */ function canBeSet(bytes32 _propID) view public returns (bool) { ParamProposal memory prop = proposals[_propID]; return (now > prop.appExpiry && now < prop.processBy && prop.challengeID == 0); } /** @notice Determines whether a proposal exists for the provided proposal ID @param _propID The proposal ID whose existance is to be determined */ function propExists(bytes32 _propID) view public returns (bool) { return proposals[_propID].processBy > 0; } /** @notice Determines whether the provided proposal ID has a challenge which can be resolved @param _propID The proposal ID whose challenge to inspect */ function challengeCanBeResolved(bytes32 _propID) view public returns (bool) { ParamProposal memory prop = proposals[_propID]; Challenge memory challenge = challenges[prop.challengeID]; return (prop.challengeID > 0 && challenge.resolved == false && voting.pollEnded(prop.challengeID)); } /** @notice Determines the number of tokens to awarded to the winning party in a challenge @param _challengeID The challengeID to determine a reward for */ function challengeWinnerReward(uint _challengeID) public view returns (uint) { if(voting.getTotalNumberOfTokensForWinningOption(_challengeID) == 0) { // Edge case, nobody voted, give all tokens to the challenger. return 2 * challenges[_challengeID].stake; } return (2 * challenges[_challengeID].stake) - challenges[_challengeID].rewardPool; } /** @notice gets the parameter keyed by the provided name value from the params mapping @param _name the key whose value is to be determined */ function get(string _name) public view returns (uint value) { return params[keccak256(_name)]; } /** @dev Getter for Challenge tokenClaims mappings @param _challengeID The challengeID to query @param _voter The voter whose claim status to query for the provided challengeID */ function tokenClaims(uint _challengeID, address _voter) public view returns (bool) { return challenges[_challengeID].tokenClaims[_voter]; } // ---------------- // PRIVATE FUNCTIONS // ---------------- /** @dev resolves a challenge for the provided _propID. It must be checked in advance whether the _propID has a challenge on it @param _propID the proposal ID whose challenge is to be resolved. */ function resolveChallenge(bytes32 _propID) private { ParamProposal memory prop = proposals[_propID]; Challenge storage challenge = challenges[prop.challengeID]; // winner gets back their full staked deposit, and dispensationPct*loser's stake uint reward = challengeWinnerReward(prop.challengeID); challenge.winningTokens = voting.getTotalNumberOfTokensForWinningOption(prop.challengeID); challenge.resolved = true; if (voting.isPassed(prop.challengeID)) { // The challenge failed if(prop.processBy > now) { set(prop.name, prop.value); } emit _ChallengeFailed(_propID, prop.challengeID, challenge.rewardPool, challenge.winningTokens); require(token.transfer(prop.owner, reward)); } else { // The challenge succeeded or nobody voted emit _ChallengeSucceeded(_propID, prop.challengeID, challenge.rewardPool, challenge.winningTokens); require(token.transfer(challenges[prop.challengeID].challenger, reward)); } } /** @dev sets the param keted by the provided name to the provided value @param _name the name of the param to be set @param _value the value to set the param to be set */ function set(string _name, uint _value) private { params[keccak256(_name)] = _value; } } // File: plcr-revival/ProxyFactory.sol /*** * Shoutouts: * * Bytecode origin https://www.reddit.com/r/ethereum/comments/6ic49q/any_assembly_programmers_willing_to_write_a/dj5ceuw/ * Modified version of Vitalik's https://www.reddit.com/r/ethereum/comments/6c1jui/delegatecall_forwarders_how_to_save_5098_on/ * Credits to Jorge Izquierdo (@izqui) for coming up with this design here: https://gist.github.com/izqui/7f904443e6d19c1ab52ec7f5ad46b3a8 * Credits to Stefan George (@Georgi87) for inspiration for many of the improvements from Gnosis Safe: https://github.com/gnosis/gnosis-safe-contracts * * This version has many improvements over the original @izqui's library like using REVERT instead of THROWing on failed calls. * It also implements the awesome design pattern for initializing code as seen in Gnosis Safe Factory: https://github.com/gnosis/gnosis-safe-contracts/blob/master/contracts/ProxyFactory.sol * but unlike this last one it doesn't require that you waste storage on both the proxy and the proxied contracts (v. https://github.com/gnosis/gnosis-safe-contracts/blob/master/contracts/Proxy.sol#L8 & https://github.com/gnosis/gnosis-safe-contracts/blob/master/contracts/GnosisSafe.sol#L14) * * * v0.0.2 * The proxy is now only 60 bytes long in total. Constructor included. * No functionalities were added. The change was just to make the proxy leaner. * * v0.0.3 * Thanks @dacarley for noticing the incorrect check for the subsequent call to the proxy. 🙌 * Note: I'm creating a new version of this that doesn't need that one call. * Will add tests and put this in its own repository soon™. * * v0.0.4 * All the merit in this fix + update of the factory is @dacarley 's. 🙌 * Thank you! 😄 * * Potential updates can be found at https://gist.github.com/GNSPS/ba7b88565c947cfd781d44cf469c2ddb * ***/ pragma solidity ^0.4.19; /* solhint-disable no-inline-assembly, indent, state-visibility, avoid-low-level-calls */ contract ProxyFactory { event ProxyDeployed(address proxyAddress, address targetAddress); event ProxiesDeployed(address[] proxyAddresses, address targetAddress); function createManyProxies(uint256 _count, address _target, bytes _data) public { address[] memory proxyAddresses = new address[](_count); for (uint256 i = 0; i < _count; ++i) { proxyAddresses[i] = createProxyImpl(_target, _data); } ProxiesDeployed(proxyAddresses, _target); } function createProxy(address _target, bytes _data) public returns (address proxyContract) { proxyContract = createProxyImpl(_target, _data); ProxyDeployed(proxyContract, _target); } function createProxyImpl(address _target, bytes _data) internal returns (address proxyContract) { assembly { let contractCode := mload(0x40) // Find empty storage location using "free memory pointer" mstore(add(contractCode, 0x0b), _target) // Add target address, with a 11 bytes [i.e. 23 - (32 - 20)] offset to later accomodate first part of the bytecode mstore(sub(contractCode, 0x09), 0x000000000000000000603160008181600b9039f3600080808080368092803773) // First part of the bytecode, shifted left by 9 bytes, overwrites left padding of target address mstore(add(contractCode, 0x2b), 0x5af43d828181803e808314602f57f35bfd000000000000000000000000000000) // Final part of bytecode, offset by 43 bytes proxyContract := create(0, contractCode, 60) // total length 60 bytes if iszero(extcodesize(proxyContract)) { revert(0, 0) } // check if the _data.length > 0 and if it is forward it to the newly created contract let dataLength := mload(_data) if iszero(iszero(dataLength)) { if iszero(call(gas, proxyContract, 0, add(_data, 0x20), dataLength, 0, 0)) { revert(0, 0) } } } } } // File: tokens/eip20/EIP20.sol /* Implements EIP20 token standard: https://github.com/ethereum/EIPs/issues/20 .*/ pragma solidity ^0.4.8; contract EIP20 is EIP20Interface { uint256 constant MAX_UINT256 = 2**256 - 1; /* NOTE: The following variables are OPTIONAL vanities. One does not have to include them. They allow one to customise the token contract & in no way influences the core functionality. Some wallets/interfaces might not even bother to look at this information. */ string public name; //fancy name: eg Simon Bucks uint8 public decimals; //How many decimals to show. string public symbol; //An identifier: eg SBX function EIP20( uint256 _initialAmount, string _tokenName, uint8 _decimalUnits, string _tokenSymbol ) public { balances[msg.sender] = _initialAmount; // Give the creator all initial tokens totalSupply = _initialAmount; // Update total supply name = _tokenName; // Set the name for display purposes decimals = _decimalUnits; // Amount of decimals for display purposes symbol = _tokenSymbol; // Set the symbol for display purposes } function transfer(address _to, uint256 _value) public returns (bool success) { //Default assumes totalSupply can't be over max (2^256 - 1). //If your token leaves out totalSupply and can issue more tokens as time goes on, you need to check if it doesn't wrap. //Replace the if with this one instead. //require(balances[msg.sender] >= _value && balances[_to] + _value > balances[_to]); require(balances[msg.sender] >= _value); balances[msg.sender] -= _value; balances[_to] += _value; Transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { //same as above. Replace this line with the following if you want to protect against wrapping uints. //require(balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value > balances[_to]); uint256 allowance = allowed[_from][msg.sender]; require(balances[_from] >= _value && allowance >= _value); balances[_to] += _value; balances[_from] -= _value; if (allowance < MAX_UINT256) { allowed[_from][msg.sender] -= _value; } Transfer(_from, _to, _value); return true; } function balanceOf(address _owner) view public returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) public returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) view public returns (uint256 remaining) { return allowed[_owner][_spender]; } mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; } // File: plcr-revival/PLCRFactory.sol contract PLCRFactory { event newPLCR(address creator, EIP20 token, PLCRVoting plcr); ProxyFactory public proxyFactory; PLCRVoting public canonizedPLCR; /// @dev constructor deploys a new canonical PLCRVoting contract and a proxyFactory. constructor() { canonizedPLCR = new PLCRVoting(); proxyFactory = new ProxyFactory(); } /* @dev deploys and initializes a new PLCRVoting contract that consumes a token at an address supplied by the user. @param _token an EIP20 token to be consumed by the new PLCR contract */ function newPLCRBYOToken(EIP20 _token) public returns (PLCRVoting) { PLCRVoting plcr = PLCRVoting(proxyFactory.createProxy(canonizedPLCR, "")); plcr.init(_token); emit newPLCR(msg.sender, _token, plcr); return plcr; } /* @dev deploys and initializes a new PLCRVoting contract and an EIP20 to be consumed by the PLCR's initializer. @param _supply the total number of tokens to mint in the EIP20 contract @param _name the name of the new EIP20 token @param _decimals the decimal precision to be used in rendering balances in the EIP20 token @param _symbol the symbol of the new EIP20 token */ function newPLCRWithToken( uint _supply, string _name, uint8 _decimals, string _symbol ) public returns (PLCRVoting) { // Create a new token and give all the tokens to the PLCR creator EIP20 token = new EIP20(_supply, _name, _decimals, _symbol); token.transfer(msg.sender, _supply); // Create and initialize a new PLCR contract PLCRVoting plcr = PLCRVoting(proxyFactory.createProxy(canonizedPLCR, "")); plcr.init(token); emit newPLCR(msg.sender, token, plcr); return plcr; } } // File: contracts/ParameterizerFactory.sol contract ParameterizerFactory { event NewParameterizer(address creator, address token, address plcr, Parameterizer parameterizer); PLCRFactory public plcrFactory; ProxyFactory public proxyFactory; Parameterizer public canonizedParameterizer; /// @dev constructor deploys a new canonical Parameterizer contract and a proxyFactory. constructor(PLCRFactory _plcrFactory) public { plcrFactory = _plcrFactory; proxyFactory = plcrFactory.proxyFactory(); canonizedParameterizer = new Parameterizer(); } /* @dev deploys and initializes a new Parameterizer contract that consumes a token at an address supplied by the user. @param _token an EIP20 token to be consumed by the new Parameterizer contract @param _plcr a PLCR voting contract to be consumed by the new Parameterizer contract @param _parameters array of canonical parameters */ function newParameterizerBYOToken( EIP20 _token, uint[] _parameters ) public returns (Parameterizer) { PLCRVoting plcr = plcrFactory.newPLCRBYOToken(_token); Parameterizer parameterizer = Parameterizer(proxyFactory.createProxy(canonizedParameterizer, "")); parameterizer.init( _token, plcr, _parameters ); emit NewParameterizer(msg.sender, _token, plcr, parameterizer); return parameterizer; } /* @dev deploys and initializes new EIP20, PLCRVoting, and Parameterizer contracts @param _supply the total number of tokens to mint in the EIP20 contract @param _name the name of the new EIP20 token @param _decimals the decimal precision to be used in rendering balances in the EIP20 token @param _symbol the symbol of the new EIP20 token @param _parameters array of canonical parameters */ function newParameterizerWithToken( uint _supply, string _name, uint8 _decimals, string _symbol, uint[] _parameters ) public returns (Parameterizer) { // Creates a new EIP20 token & transfers the supply to creator (msg.sender) // Deploys & initializes a new PLCRVoting contract PLCRVoting plcr = plcrFactory.newPLCRWithToken(_supply, _name, _decimals, _symbol); EIP20 token = EIP20(plcr.token()); token.transfer(msg.sender, _supply); // Create & initialize a new Parameterizer contract Parameterizer parameterizer = Parameterizer(proxyFactory.createProxy(canonizedParameterizer, "")); parameterizer.init( token, plcr, _parameters ); emit NewParameterizer(msg.sender, token, plcr, parameterizer); return parameterizer; } }
escrow tokens (deposit amt)
require(token.transferFrom(msg.sender, this, deposit));
502,141
[ 1, 742, 492, 2430, 261, 323, 1724, 25123, 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, 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, 2583, 12, 2316, 18, 13866, 1265, 12, 3576, 18, 15330, 16, 333, 16, 443, 1724, 10019, 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 ]
pragma solidity ^0.4.24; contract dapBetting { /* Types */ enum eventStatus{ open, finished, closed } struct bid{ uint id; bytes32 name; address[] whoBet; uint amountReceived; } struct betEvent{ uint id; bytes32 name; address creator; address arbitrator; bytes32 winner; uint arbitratorFee; uint256 endBlock; uint256 minBid; uint256 maxBid; bid[] bids; bet[] bets; eventStatus status; } struct bet{ address person; bytes32 bidName; uint amount; } /* Storage */ mapping (address => betEvent[]) public betEvents; mapping (address => uint) public pendingWithdrawals; /* Events */ event eventCreated(uint id, address creator); event betMade(uint value, uint id); event eventStatusChanged(uint status); event withdrawalDone(uint amount); /* Modifiers */ modifier onlyFinished(address creator, uint eventId){ if (betEvents[creator][eventId].status == eventStatus.finished || betEvents[creator][eventId].endBlock < block.number){ _; } } modifier onlyArbitrator(address creator, uint eventId){ if (betEvents[creator][eventId].arbitrator == msg.sender){ _; } } /* Methods */ function createEvent(bytes32 name, bytes32[] names, address arbitrator, uint fee, uint256 endBlock, uint256 minBid, uint256 maxBid) external{ require(fee < 100); /* check whether event with such name already exist */ bool found; for (uint8 x = 0;x<betEvents[msg.sender].length;x++){ if(betEvents[msg.sender][x].name == name){ found = true; } } require(!found); /* check names for duplicates */ for (uint8 y=0;i<names.length;i++){ require(names[y] != names[y+1]); } uint newId = betEvents[msg.sender].length++; betEvents[msg.sender][newId].id = newId; betEvents[msg.sender][newId].name = name; betEvents[msg.sender][newId].arbitrator = arbitrator; betEvents[msg.sender][newId].status = eventStatus.open; betEvents[msg.sender][newId].creator = msg.sender; betEvents[msg.sender][newId].endBlock = endBlock; betEvents[msg.sender][newId].minBid = minBid; betEvents[msg.sender][newId].maxBid = maxBid; betEvents[msg.sender][newId].arbitratorFee = fee; for (uint8 i = 0;i < names.length; i++){ uint newBidId = betEvents[msg.sender][newId].bids.length++; betEvents[msg.sender][newId].bids[newBidId].name = names[i]; betEvents[msg.sender][newId].bids[newBidId].id = newBidId; } emit eventCreated(newId, msg.sender); } function makeBet(address creator, uint eventId, bytes32 bidName) payable external{ require(betEvents[creator][eventId].status == eventStatus.open); if (betEvents[creator][eventId].endBlock > 0){ require(block.number > betEvents[creator][eventId].endBlock); } /* check whether bid with given name actually exists */ bool found; for (uint8 i=0;i<betEvents[creator][eventId].bids.length;i++){ if (betEvents[creator][eventId].bids[i].name == bidName){ bid storage foundBid = betEvents[creator][eventId].bids[i]; found = true; } } require(found); //check for block if (betEvents[creator][eventId].endBlock > 0){ require(betEvents[creator][eventId].endBlock < block.number); } //check for minimal amount if (betEvents[creator][eventId].minBid > 0){ require(msg.value > betEvents[creator][eventId].minBid); } //check for maximal amount if (betEvents[creator][eventId].maxBid > 0){ require(msg.value < betEvents[creator][eventId].maxBid); } foundBid.whoBet.push(msg.sender); foundBid.amountReceived += msg.value; uint newBetId = betEvents[creator][eventId].bets.length++; betEvents[creator][eventId].bets[newBetId].person = msg.sender; betEvents[creator][eventId].bets[newBetId].amount = msg.value; betEvents[creator][eventId].bets[newBetId].bidName = bidName; emit betMade(msg.value, newBetId); } function finishEvent(address creator, uint eventId) external{ require(betEvents[creator][eventId].status == eventStatus.open && betEvents[creator][eventId].endBlock == 0); require(msg.sender == betEvents[creator][eventId].arbitrator); betEvents[creator][eventId].status = eventStatus.finished; emit eventStatusChanged(1); } function determineWinner(address creator, uint eventId, bytes32 bidName) external onlyFinished(creator, eventId) onlyArbitrator(creator, eventId){ require (findBid(creator, eventId, bidName)); betEvent storage cEvent = betEvents[creator][eventId]; cEvent.winner = bidName; uint amountLost; uint amountWon; uint lostBetsLen; /*Calculating amount of all lost bets */ for (uint x=0;x<betEvents[creator][eventId].bids.length;x++){ if (cEvent.bids[x].name != cEvent.winner){ amountLost += cEvent.bids[x].amountReceived; } } /* Calculating amount of all won bets */ for (x=0;x<cEvent.bets.length;x++){ if(cEvent.bets[x].bidName == cEvent.winner){ uint wonBetAmount = cEvent.bets[x].amount; amountWon += wonBetAmount; pendingWithdrawals[cEvent.bets[x].person] += wonBetAmount; } else { lostBetsLen++; } } /* If we do have win bets */ if (amountWon > 0){ pendingWithdrawals[cEvent.arbitrator] += amountLost/100*cEvent.arbitratorFee; amountLost = amountLost - (amountLost/100*cEvent.arbitratorFee); for (x=0;x<cEvent.bets.length;x++){ if(cEvent.bets[x].bidName == cEvent.winner){ //uint wonBetPercentage = cEvent.bets[x].amount*100/amountWon; uint wonBetPercentage = percent(cEvent.bets[x].amount, amountWon, 2); pendingWithdrawals[cEvent.bets[x].person] += (amountLost/100)*wonBetPercentage; } } } else { /* If we dont have any bets won, we pay all the funds back except arbitrator fee */ for(x=0;x<cEvent.bets.length;x++){ pendingWithdrawals[cEvent.bets[x].person] += cEvent.bets[x].amount-((cEvent.bets[x].amount/100) * cEvent.arbitratorFee); pendingWithdrawals[cEvent.arbitrator] += (cEvent.bets[x].amount/100) * cEvent.arbitratorFee; } } cEvent.status = eventStatus.closed; emit eventStatusChanged(2); } function withdraw(address person) private{ uint amount = pendingWithdrawals[person]; pendingWithdrawals[person] = 0; person.transfer(amount); emit withdrawalDone(amount); } function requestWithdraw() external { //require(pendingWithdrawals[msg.sender] != 0); withdraw(msg.sender); } function findBid(address creator, uint eventId, bytes32 bidName) private view returns(bool){ for (uint8 i=0;i<betEvents[creator][eventId].bids.length;i++){ if(betEvents[creator][eventId].bids[i].name == bidName){ return true; } } } function calc(uint one, uint two) private pure returns(uint){ return one/two; } function percent(uint numerator, uint denominator, uint precision) public pure returns(uint quotient) { // caution, check safe-to-multiply here uint _numerator = numerator * 10 ** (precision+1); // with rounding of last digit uint _quotient = ((_numerator / denominator) + 5) / 10; return ( _quotient); } /* Getters */ function getBidsNum(address creator, uint eventId) external view returns (uint){ return betEvents[creator][eventId].bids.length; } function getBid(address creator, uint eventId, uint bidId) external view returns (uint, bytes32, uint){ bid storage foundBid = betEvents[creator][eventId].bids[bidId]; return(foundBid.id, foundBid.name, foundBid.amountReceived); } function getBetsNums(address creator, uint eventId) external view returns (uint){ return betEvents[creator][eventId].bets.length; } function getWhoBet(address creator, uint eventId, uint bidId) external view returns (address[]){ return betEvents[creator][eventId].bids[bidId].whoBet; } function getBet(address creator, uint eventId, uint betId) external view returns(address, bytes32, uint){ bet storage foundBet = betEvents[creator][eventId].bets[betId]; return (foundBet.person, foundBet.bidName, foundBet.amount); } function getEventId(address creator, bytes32 eventName) external view returns (uint, bool){ for (uint i=0;i<betEvents[creator].length;i++){ if(betEvents[creator][i].name == eventName){ return (betEvents[creator][i].id, true); } } } }
check whether event with such name already exist */ check names for duplicates */
function createEvent(bytes32 name, bytes32[] names, address arbitrator, uint fee, uint256 endBlock, uint256 minBid, uint256 maxBid) external{ require(fee < 100); bool found; for (uint8 x = 0;x<betEvents[msg.sender].length;x++){ if(betEvents[msg.sender][x].name == name){ found = true; } } require(!found); for (uint8 y=0;i<names.length;i++){ require(names[y] != names[y+1]); } uint newId = betEvents[msg.sender].length++; betEvents[msg.sender][newId].id = newId; betEvents[msg.sender][newId].name = name; betEvents[msg.sender][newId].arbitrator = arbitrator; betEvents[msg.sender][newId].status = eventStatus.open; betEvents[msg.sender][newId].creator = msg.sender; betEvents[msg.sender][newId].endBlock = endBlock; betEvents[msg.sender][newId].minBid = minBid; betEvents[msg.sender][newId].maxBid = maxBid; betEvents[msg.sender][newId].arbitratorFee = fee; for (uint8 i = 0;i < names.length; i++){ uint newBidId = betEvents[msg.sender][newId].bids.length++; betEvents[msg.sender][newId].bids[newBidId].name = names[i]; betEvents[msg.sender][newId].bids[newBidId].id = newBidId; } emit eventCreated(newId, msg.sender); }
2,449,821
[ 1, 1893, 2856, 871, 598, 4123, 508, 1818, 1005, 342, 866, 1257, 364, 11211, 342, 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, 25566, 12, 3890, 1578, 508, 16, 1731, 1578, 8526, 1257, 16, 1758, 10056, 86, 639, 16, 2254, 14036, 16, 2254, 5034, 679, 1768, 16, 2254, 5034, 1131, 17763, 16, 2254, 5034, 943, 17763, 13, 3903, 95, 203, 540, 203, 3639, 2583, 12, 21386, 411, 2130, 1769, 203, 3639, 1426, 1392, 31, 203, 3639, 364, 261, 11890, 28, 619, 273, 374, 31, 92, 32, 70, 278, 3783, 63, 3576, 18, 15330, 8009, 2469, 31, 92, 27245, 95, 203, 5411, 309, 12, 70, 278, 3783, 63, 3576, 18, 15330, 6362, 92, 8009, 529, 422, 508, 15329, 203, 7734, 1392, 273, 638, 31, 203, 5411, 289, 203, 3639, 289, 203, 3639, 2583, 12, 5, 7015, 1769, 203, 540, 203, 3639, 364, 261, 11890, 28, 677, 33, 20, 31, 77, 32, 1973, 18, 2469, 31, 77, 27245, 95, 203, 5411, 2583, 12, 1973, 63, 93, 65, 480, 1257, 63, 93, 15, 21, 19226, 203, 3639, 289, 203, 540, 203, 3639, 2254, 27598, 273, 2701, 3783, 63, 3576, 18, 15330, 8009, 2469, 9904, 31, 203, 3639, 2701, 3783, 63, 3576, 18, 15330, 6362, 2704, 548, 8009, 350, 273, 27598, 31, 203, 3639, 2701, 3783, 63, 3576, 18, 15330, 6362, 2704, 548, 8009, 529, 273, 508, 31, 203, 3639, 2701, 3783, 63, 3576, 18, 15330, 6362, 2704, 548, 8009, 297, 3682, 86, 639, 273, 10056, 86, 639, 31, 203, 3639, 2701, 3783, 63, 3576, 18, 15330, 6362, 2704, 548, 8009, 2327, 273, 871, 1482, 18, 3190, 31, 203, 3639, 2701, 3783, 63, 3576, 18, 15330, 6362, 2704, 548, 2 ]
pragma solidity ^0.5.11; /// @title Proof of Authority Whitelist Proof of Concept /// @author Jon Knight /// @author Mosaic Networks /// @notice Copyright Mosaic Networks 2019, released under the MIT license contract POA_Genesis { /// @notice Event emitted when the vote was reached a decision /// @param _nominee The address of the nominee /// @param _yesVotes The total number of yes votes cast for the nominee to date /// @param _noVotes The total number of no votes cast for the nominee to date /// @param _accepted The decision, true for added to the whitelist, false for rejected event NomineeDecision( address indexed _nominee, uint _yesVotes, uint _noVotes, bool indexed _accepted ); /// @notice Event emitted when a nominee vote is cast /// @param _nominee The address of the nominee /// @param _voter The address of the person who cast the vote /// @param _yesVotes The total number of yes votes cast for the nominee to date /// @param _noVotes The total number of no votes cast for the nominee to date /// @param _accepted The vote, true for accept, false for rejected event NomineeVoteCast( address indexed _nominee, address indexed _voter, uint _yesVotes, uint _noVotes, bool indexed _accepted ); /// @notice Event emitted when a nominee is proposed /// @param _nominee The address of the nominee /// @param _proposer The address of the person who proposed the nominee event NomineeProposed( address indexed _nominee, address indexed _proposer ); /// @notice Event emitted when the eviction vote reached a decision /// @param _nominee The address of the nominee /// @param _yesVotes The total number of yes votes cast for the nominee to date /// @param _noVotes The total number of no votes cast for the nominee to date /// @param _accepted The decision, true for eviction, false for rejected eviction event EvictionDecision( address indexed _nominee, uint _yesVotes, uint _noVotes, bool indexed _accepted ); /// @notice Event emitted when a eviction vote is cast /// @param _nominee The address of the nominee /// @param _voter The address of the person who cast the vote /// @param _yesVotes The total number of yes votes cast for the nominee to date /// @param _noVotes The total number of no votes cast for the nominee to date /// @param _accepted The vote, true for evict, false for remain event EvictionVoteCast( address indexed _nominee, address indexed _voter, uint _yesVotes, uint _noVotes, bool indexed _accepted ); /// @notice Event emitted when a nominee is proposed /// @param _nominee The address of the nominee /// @param _proposer The address of the person who proposed the nominee event EvictionProposed( address indexed _nominee, address indexed _proposer ); /// @notice Event emitted to announce a moniker /// @param _address The address of the user /// @param _moniker The moniker of the user event MonikerAnnounce( address indexed _address, bytes32 indexed _moniker ); /// @notice Event emitted on error /// @param _address The address of the user /// @param _message The error message event POA_Error( address indexed _address, string _message ); struct WhitelistPerson { address person; uint flags; } struct NomineeVote { address voter; bool accept; } struct NomineeElection{ address nominee; address proposer; uint yesVotes; uint noVotes; mapping (address => NomineeVote) vote; address[] yesArray; address[] noArray; } mapping (address => WhitelistPerson) whiteList; uint whiteListCount; address[] whiteListArray; mapping (address => NomineeElection) nomineeList; address[] nomineeArray; mapping (address => bytes32) monikerList; mapping (address => NomineeElection) evictionList; address[] evictionArray; /// @notice This is no longer required, but an empty function prevents older monetcli versions with the poa init command erroring function init () public payable checkAuthorisedModifier(msg.sender) { } /// @notice Modifier to check if a sender is on the white list. modifier checkAuthorisedModifier(address _address) { require(isWhitelisted(_address), "sender is not authorised"); _; } /// @notice Function exposed for Babble Join authority function checkAuthorised(address _address) public view returns (bool) { // needs check on whitelist to allow original validators to be booted. return isWhitelisted(_address); } /// @notice Function exposed for Babble Join authority wraps checkAuthorised function checkAuthorisedPublicKey(bytes32 _publicKey) public view returns (bool) { return checkAuthorised(address(uint160(uint256(keccak256(abi.encodePacked(_publicKey)))))); // This version works in Solidity 0.4.x, but the extra intermediate steps are required in 0.5.x // return checkAuthorised(address(keccak256(abi.encodePacked(_publicKey)))); } /// @notice wrapper function to check if an address is on the nominee list /// @param _address the address to be checked /// @return a boolean value, indicating if _address is on the nominee list function isNominee(address _address) private view returns (bool) { return (nomineeList[_address].nominee != address(0)); } /// @notice wrapper function to check if an address is on the eviction list /// @param _address the address to be checked /// @return a boolean value, indicating if _address is on the eviction list function isEvictee(address _address) private view returns (bool) { return (evictionList[_address].nominee != address(0)); } /// @notice wrapper function to check if an address is on the white list /// @param _address the address to be checked /// @return a boolean value, indicating if _address is on the white list function isWhitelisted(address _address) private view returns (bool) { return (whiteList[_address].person != address(0)); } /// @notice private function to add user directly to the whitelist. Used to process the Genesis Whitelist. function addToWhitelist(address _address, bytes32 _moniker) private { if (! isWhitelisted(_address)) // prevent duplicate whitelist entries { whiteList[_address] = WhitelistPerson(_address, 0); whiteListCount++; whiteListArray.push(_address); monikerList[_address] = _moniker; emit MonikerAnnounce(_address,_moniker); emit NomineeDecision(_address, 0, 0, true); // zero vote counts because there was no vote } else { emit POA_Error(_address, "Dup Whitelist"); } } /// @notice Add a new entry to the nominee list /// @param _nomineeAddress the address of the nominee /// @param _moniker the moniker of the new nominee as displayed during the voting process function submitNominee (address _nomineeAddress, bytes32 _moniker) public payable // checkAuthorisedModifier(msg.sender) { if ((! isWhitelisted(_nomineeAddress)) && (! isNominee(_nomineeAddress)) ) { nomineeList[_nomineeAddress] = NomineeElection({nominee: _nomineeAddress, proposer: msg.sender, yesVotes: 0, noVotes: 0, yesArray: new address[](0),noArray: new address[](0) }); nomineeArray.push(_nomineeAddress); monikerList[_nomineeAddress] = _moniker; emit NomineeProposed(_nomineeAddress, msg.sender); emit MonikerAnnounce(_nomineeAddress, _moniker); } else { if (isWhitelisted(_nomineeAddress)) { emit POA_Error(_nomineeAddress, "On Whitelist"); } else { emit POA_Error(_nomineeAddress, "On Nominee list"); } } } /// @notice Add a new entry to the eviction list /// @param _nomineeAddress the address of the evictee function submitEviction (address _nomineeAddress) public payable checkAuthorisedModifier(msg.sender) { if ((isWhitelisted(_nomineeAddress)) && (! isEvictee(_nomineeAddress)) ) { evictionList[_nomineeAddress] = NomineeElection({nominee: _nomineeAddress, proposer: msg.sender, yesVotes: 0, noVotes: 0, yesArray: new address[](0),noArray: new address[](0) }); evictionArray.push(_nomineeAddress); // monikerList[_nomineeAddress] = _moniker; emit EvictionProposed(_nomineeAddress, msg.sender); // emit MonikerAnnounce(_nomineeAddress, _moniker); } else { if (!isWhitelisted(_nomineeAddress)) { emit POA_Error(_nomineeAddress, "Not on Whitelist"); } else { emit POA_Error(_nomineeAddress, "On Evictee list"); } } } ///@notice Cast a vote for a nominator. Can only be run by people on the whitelist. ///@param _nomineeAddress The address of the nominee ///@param _accepted Whether the vote is to accept (true) or reject (false) them. ///@return returns true if the vote has reached a decision, false if not ///@return only meaningful if the other return value is true, returns true if the nominee is now on the whitelist. false otherwise. function castNomineeVote(address _nomineeAddress, bool _accepted) public payable checkAuthorisedModifier(msg.sender) returns (bool decided, bool voteresult){ decided = false; voteresult = false; // Check if open nominee, other checks redundant if (isNominee(_nomineeAddress)) { // Check that this sender has not voted before. Initial config is no redos - so just reject if (nomineeList[_nomineeAddress].vote[msg.sender].voter == address(0)) { // Vote is valid. So lets cast the Vote nomineeList[_nomineeAddress].vote[msg.sender] = NomineeVote({voter: msg.sender, accept: _accepted }); // Amend Totals if (_accepted) { nomineeList[_nomineeAddress].yesVotes++; nomineeList[_nomineeAddress].yesArray.push(msg.sender); } else { nomineeList[_nomineeAddress].noVotes++; nomineeList[_nomineeAddress].noArray.push(msg.sender); } emit NomineeVoteCast(_nomineeAddress, msg.sender,nomineeList[_nomineeAddress].yesVotes, nomineeList[_nomineeAddress].noVotes, _accepted); // Check to see if enough votes have been cast for a decision (decided, voteresult) = checkForNomineeVoteDecision(_nomineeAddress); } } else { // Not a nominee, so set decided to true emit POA_Error(_nomineeAddress,"Not nominee"); decided = true; } // If decided, check if on whitelist if (decided) { voteresult = isWhitelisted(_nomineeAddress); } return (decided, voteresult); } ///@notice Cast a vote for an eviction. Can only be run by people on the whitelist. ///@param _nomineeAddress The address of the potential evictee ///@param _accepted Whether the vote is to evict (true) or remain (false) them. ///@return returns true if the vote has reached a decision, false if not ///@return only meaningful if the other return value is true, returns true if the nominee is now evicted. false otherwise. function castEvictionVote(address _nomineeAddress, bool _accepted) public payable checkAuthorisedModifier(msg.sender) returns (bool decided, bool voteresult){ decided = false; voteresult = false; // Check if open nominee, other checks redundant if (isEvictee(_nomineeAddress)) { // Check that this sender has not voted before. Initial config is no redos - so just reject if (evictionList[_nomineeAddress].vote[msg.sender].voter == address(0)) { // Vote is valid. So lets cast the Vote evictionList[_nomineeAddress].vote[msg.sender] = NomineeVote({voter: msg.sender, accept: _accepted }); // Amend Totals if (_accepted) { evictionList[_nomineeAddress].yesVotes++; evictionList[_nomineeAddress].yesArray.push(msg.sender); } else { evictionList[_nomineeAddress].noVotes++; evictionList[_nomineeAddress].noArray.push(msg.sender); } emit EvictionVoteCast(_nomineeAddress, msg.sender,evictionList[_nomineeAddress].yesVotes, nomineeList[_nomineeAddress].noVotes, _accepted); // Check to see if enough votes have been cast for a decision (decided, voteresult) = checkForEvictionVoteDecision(_nomineeAddress); } } else { // Not a nominee, so set decided to true emit POA_Error(_nomineeAddress,"Not nominee"); decided = true; } // If decided, check if on whitelist if (decided) { voteresult = ! isWhitelisted(_nomineeAddress); } return (decided, voteresult); } ///@notice This function encapsulates the logic for determining if there are enough votes for a definitive decision ///@param _nomineeAddress The address of the NomineeElection ///@return returns true if the vote has reached a decision, false if not ///@return only meaningful if the other return value is true, returns true if the nominee is now on the whitelist. false otherwise. function checkForNomineeVoteDecision(address _nomineeAddress) private returns (bool decided, bool voteresult) { NomineeElection memory election = nomineeList[_nomineeAddress]; decided = false; voteresult = false; if (election.noVotes > 0) // Someone Voted No { declineNominee(election.nominee); decided = true; voteresult = false; } else { // Requires unanimous approval if(election.yesVotes >= whiteListCount) { acceptNominee(election.nominee); decided = true; voteresult = true; } } if (decided) { emit NomineeDecision(_nomineeAddress, election.yesVotes, election.noVotes, voteresult); } return (decided, voteresult); } ///@notice This function encapsulates the logic for determining if there are enough votes for a definitive decision ///@param _nomineeAddress The address of the EvictionElection ///@return returns true if the vote has reached a decision, false if not ///@return only meaningful if the other return value is true, returns true if the nominee is not now on the whitelist. false otherwise. function checkForEvictionVoteDecision(address _nomineeAddress) private returns (bool decided, bool voteresult) { NomineeElection memory election = evictionList[_nomineeAddress]; decided = false; voteresult = false; if (election.noVotes > 0) // Someone Voted No { declineEviction(election.nominee); decided = true; voteresult = false; } else { // Requires unanimous approval if(election.yesVotes >= (whiteListCount - 1 )) { acceptEviction(election.nominee); decided = true; voteresult = true; } } if (decided) { emit EvictionDecision(_nomineeAddress, election.yesVotes, election.noVotes, voteresult); } return (decided, voteresult); } ///@notice This private function adds the accepted nominee to the whitelist. ///@param _nomineeAddress The address of the nominee being added to the whitelist function acceptNominee(address _nomineeAddress) private { if (! isWhitelisted(_nomineeAddress)) // avoid re-adding and corrupting the whiteListCount { whiteList[_nomineeAddress] = WhitelistPerson(_nomineeAddress, 0); whiteListArray.push(_nomineeAddress); whiteListCount++; } else { emit POA_Error(_nomineeAddress,"Already Whitelisted"); } // Remove from nominee list removeNominee(_nomineeAddress); } ///@notice This private function removes the accepted evictee from the whitelist. ///@param _nomineeAddress The address of the nominee being added to the whitelist function acceptEviction(address _nomineeAddress) private { deWhiteList(_nomineeAddress); // Remove from nominee list removeEviction(_nomineeAddress); } ///@notice This private function adds the removes a user from the whitelist. Not currently used. ///@param _address The address of the nominee being removed to the whitelist function deWhiteList(address _address) private { if(isWhitelisted(_address)) { delete(whiteList[_address]); whiteListCount--; for (uint i = 0; i<whiteListArray.length; i++) { if (whiteListArray[i] == _address) { // Replace item to be removed with the last item. Then remove last item. whiteListArray[i] = whiteListArray[whiteListArray.length - 1]; delete whiteListArray[whiteListArray.length - 1]; whiteListArray.length--; break; } } } } // Decline nominee from the nomineeList ///@notice This private function removes the declined nominee from the nominee list. ///@param _nomineeAddress The address of the nominee being removed from the nominee list function declineNominee(address _nomineeAddress) private { removeNominee(_nomineeAddress); } ///@notice This private function removes the declined nominee from the nominee list. ///@param _nomineeAddress The address of the nominee being removed from the nominee list function removeNominee(address _nomineeAddress) private { removeNomineeVote(_nomineeAddress); // Remove from Mapping delete(nomineeList[_nomineeAddress]); for (uint i = 0; i<nomineeArray.length; i++) { if (nomineeArray[i] == _nomineeAddress) { // Replace item to be removed with the last item. Then remove last item. nomineeArray[i] = nomineeArray[nomineeArray.length - 1]; delete nomineeArray[nomineeArray.length - 1]; nomineeArray.length--; break; } } } ///@notice This private function clears the vote mapping in a Nominee Election record. ///@param _nomineeAddress The nomineeElection record to be cleansed function removeNomineeVote(address _nomineeAddress) private { // Iterate through yes and no array and set the addresses in the // records held in the vote mapping to zero address // THis means it is treated as unset by out validity checks. for (uint j = 0 ; j < nomineeList[_nomineeAddress].yesArray.length; j++) { nomineeList[_nomineeAddress].vote[nomineeList[_nomineeAddress].yesArray[j]].voter = address(0); } for (uint j = 0 ; j < nomineeList[_nomineeAddress].noArray.length; j++) { nomineeList[_nomineeAddress].vote[nomineeList[_nomineeAddress].noArray[j]].voter = address(0); } } ///@notice This private function clears the vote mapping in a Eviction Election record. ///@param _nomineeAddress The nomineeElection record to be cleansed function removeEvicteeVote(address _nomineeAddress) private { // Iterate through yes and no array and set the addresses in the // records held in the vote mapping to zero address // THis means it is treated as unset by out validity checks. for (uint j = 0 ; j < evictionList[_nomineeAddress].yesArray.length; j++) { evictionList[_nomineeAddress].vote[evictionList[_nomineeAddress].yesArray[j]].voter = address(0); } for (uint j = 0 ; j < evictionList[_nomineeAddress].noArray.length; j++) { evictionList[_nomineeAddress].vote[evictionList[_nomineeAddress].noArray[j]].voter = address(0); } } // Deline evictee from the evictionList ///@notice This private function removes the declined nominee from the nominee list. ///@param _nomineeAddress The address of the nominee being removed from the nominee list function declineEviction(address _nomineeAddress) private { removeEviction(_nomineeAddress); } ///@notice This private function removes the declined evictee from the Eviction list. ///@param _nomineeAddress The address of the nominee being removed from the eviction list function removeEviction(address _nomineeAddress) private { removeEvicteeVote(_nomineeAddress); // Remove from Mapping delete(evictionList[_nomineeAddress]); for (uint i = 0; i<evictionArray.length; i++) { if (evictionArray[i] == _nomineeAddress) { // Replace item to be removed with the last item. Then remove last item. evictionArray[i] = evictionArray[evictionArray.length - 1]; delete evictionArray[evictionArray.length - 1]; evictionArray.length--; break; } } } // Information Section. function getNomineeElection(address _address) public view returns (address nominee, address proposer, uint yesVotes, uint noVotes) { return (nomineeList[_address].nominee, nomineeList[_address].proposer, nomineeList[_address].yesVotes, nomineeList[_address].noVotes); } function getEvictionElection(address _address) public view returns (address nominee, address proposer, uint yesVotes, uint noVotes) { return (evictionList[_address].nominee, evictionList[_address].proposer, evictionList[_address].yesVotes, evictionList[_address].noVotes); } // Array Section. Functions to support Arrays. function getNomineeCount() public view returns (uint count) { return (nomineeArray.length); } function getEvictionCount() public view returns (uint count) { return (evictionArray.length); } function getNomineeAddressFromIdx(uint idx) public view returns (address NomineeAddress) { require (idx < nomineeArray.length, "Requested address is out of range."); return (nomineeArray[idx]); } function getNomineeElectionFromIdx(uint idx) public view returns (address nominee, address proposer, uint yesVotes, uint noVotes) { return (getNomineeElection(getNomineeAddressFromIdx(idx))) ; } function getEvictionAddressFromIdx(uint idx) public view returns (address NomineeAddress) { require (idx < evictionArray.length, "Requested address is out of range."); return (evictionArray[idx]); } function getEvictionElectionFromIdx(uint idx) public view returns (address nominee, address proposer, uint yesVotes, uint noVotes) { return (getEvictionElection(getEvictionAddressFromIdx(idx))) ; } function getWhiteListCount() public view returns (uint count) { return (whiteListArray.length); } function getWhiteListAddressFromIdx(uint idx) public view returns (address WhiteListAddress) { require (idx < whiteListArray.length, "Requested address is out of range."); return (whiteListArray[idx]); } function getYesVoteCount(address _nomineeAddress) public view returns (uint count) { return (nomineeList[_nomineeAddress].yesArray.length); } function getYesVoterFromIdx(address _nomineeAddress, uint _idx) public view returns (address voter) { require (_idx < nomineeList[_nomineeAddress].yesArray.length, "Requested address is out of range."); return (nomineeList[_nomineeAddress].yesArray[_idx]); } function getNoVoteCount(address _nomineeAddress) public view returns (uint count) { return (nomineeList[_nomineeAddress].noArray.length); } function getNoVoterFromIdx(address _nomineeAddress, uint _idx) public view returns (address voter) { require (_idx < nomineeList[_nomineeAddress].noArray.length, "Requested address is out of range."); return (nomineeList[_nomineeAddress].noArray[_idx]); } function getEvictionYesVoteCount(address _nomineeAddress) public view returns (uint count) { return (evictionList[_nomineeAddress].yesArray.length); } function getEvictionYesVoterFromIdx(address _nomineeAddress, uint _idx) public view returns (address voter) { require (_idx < evictionList[_nomineeAddress].yesArray.length, "Requested address is out of range."); return (evictionList[_nomineeAddress].yesArray[_idx]); } function getEvictionNoVoteCount(address _nomineeAddress) public view returns (uint count) { return (evictionList[_nomineeAddress].noArray.length); } function getEvictionNoVoterFromIdx(address _nomineeAddress, uint _idx) public view returns (address voter) { require (_idx < evictionList[_nomineeAddress].noArray.length, "Requested address is out of range."); return (evictionList[_nomineeAddress].noArray[_idx]); } function getMoniker(address _address) public view returns (bytes32 moniker) { return (monikerList[_address]); } function getCurrentNomineeVotes(address _address) public view returns (uint yes, uint no) { if (! isNominee(_address)) {return (yes, no);} return (nomineeList[_address].yesVotes,nomineeList[_address].noVotes); } function getCurrentEvictionVotes(address _address) public view returns (uint yes, uint no) { if (! isEvictee(_address)) {return (yes, no);} return (evictionList[_address].yesVotes,evictionList[_address].noVotes); } }
Check that this sender has not voted before. Initial config is no redos - so just reject Vote is valid. So lets cast the Vote Amend Totals
function castNomineeVote(address _nomineeAddress, bool _accepted) if (isNominee(_nomineeAddress)) { if (nomineeList[_nomineeAddress].vote[msg.sender].voter == address(0)) { if (_accepted) { nomineeList[_nomineeAddress].yesVotes++; nomineeList[_nomineeAddress].yesArray.push(msg.sender); nomineeList[_nomineeAddress].noVotes++; nomineeList[_nomineeAddress].noArray.push(msg.sender); } emit NomineeVoteCast(_nomineeAddress, msg.sender,nomineeList[_nomineeAddress].yesVotes, nomineeList[_nomineeAddress].noVotes, _accepted); } } else emit POA_Error(_nomineeAddress,"Not nominee"); decided = true;
12,688,634
[ 1, 1564, 716, 333, 5793, 711, 486, 331, 16474, 1865, 18, 10188, 642, 353, 1158, 1755, 538, 300, 1427, 2537, 4925, 27540, 353, 923, 18, 6155, 14557, 4812, 326, 27540, 3986, 409, 399, 352, 1031, 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, 445, 4812, 26685, 558, 73, 19338, 12, 2867, 389, 12306, 558, 73, 1887, 16, 1426, 389, 23847, 13, 203, 377, 309, 261, 291, 26685, 558, 73, 24899, 12306, 558, 73, 1887, 3719, 288, 203, 203, 203, 540, 309, 261, 12306, 558, 73, 682, 63, 67, 12306, 558, 73, 1887, 8009, 25911, 63, 3576, 18, 15330, 8009, 90, 20005, 422, 1758, 12, 20, 3719, 288, 203, 203, 2398, 309, 261, 67, 23847, 13, 203, 2398, 288, 203, 1171, 12457, 558, 73, 682, 63, 67, 12306, 558, 73, 1887, 8009, 9707, 29637, 9904, 31, 203, 1171, 12457, 558, 73, 682, 63, 67, 12306, 558, 73, 1887, 8009, 9707, 1076, 18, 6206, 12, 3576, 18, 15330, 1769, 203, 1171, 12457, 558, 73, 682, 63, 67, 12306, 558, 73, 1887, 8009, 2135, 29637, 9904, 31, 203, 1171, 12457, 558, 73, 682, 63, 67, 12306, 558, 73, 1887, 8009, 2135, 1076, 18, 6206, 12, 3576, 18, 15330, 1769, 203, 2398, 289, 203, 203, 2398, 3626, 423, 362, 558, 73, 19338, 9735, 24899, 12306, 558, 73, 1887, 16, 1234, 18, 15330, 16, 12306, 558, 73, 682, 63, 67, 12306, 558, 73, 1887, 8009, 9707, 29637, 16, 203, 10402, 12457, 558, 73, 682, 63, 67, 12306, 558, 73, 1887, 8009, 2135, 29637, 16, 389, 23847, 1769, 203, 203, 540, 289, 203, 377, 289, 203, 377, 469, 203, 540, 3626, 13803, 37, 67, 668, 24899, 12306, 558, 73, 1887, 10837, 1248, 12457, 558, 73, 8863, 203, 540, 2109, 13898, 273, 638, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.11; import "./interfaces/IStrategy.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "hardhat/console.sol"; /** * @dev Implementation of a vault to deposit funds for yield optimizing. * This is the contract that receives funds and that users interface with. * The yield optimizing strategy itself is implemented in a separate 'Strategy.sol' contract. */ contract ReaperVaultv1_3 is ERC20, Ownable, ReentrancyGuard { using SafeERC20 for IERC20; using SafeMath for uint256; address public strategy; uint256 public depositFee; uint256 public constant PERCENT_DIVISOR = 10000; uint256 public tvlCap; /** * @dev The stretegy's initialization status. Gives deployer 20 minutes after contract * construction (constructionTime) to set the strategy implementation. */ bool public initialized = false; uint256 public constructionTime; // The token the vault accepts and looks to maximize. IERC20 public token; /** * + WEBSITE DISCLAIMER + * While we have taken precautionary measures to protect our users, * it is imperative that you read, understand and agree to the disclaimer below: * * Using our platform may involve financial risk of loss. * Never invest more than what you can afford to lose. * Never invest in a Reaper Vault with tokens you don't trust. * Never invest in a Reaper Vault with tokens whose rules for minting you don’t agree with. * Ensure the accuracy of the contracts for the tokens in the Reaper Vault. * Ensure the accuracy of the contracts for the Reaper Vault and Strategy you are depositing in. * Check our documentation regularly for additional disclaimers and security assessments. * ...and of course: DO YOUR OWN RESEARCH!!! * * By accepting these terms, you agree that Byte Masons, Fantom.Farm, or any parties * affiliated with the deployment and management of these vaults or their attached strategies * are not liable for any financial losses you might incur as a direct or indirect * result of investing in any of the pools on the platform. */ mapping(address => bool) public hasReadAndAcceptedTerms; /** * @dev simple mappings used to determine PnL denominated in LP tokens, * as well as keep a generalized history of a user's protocol usage. */ mapping(address => uint256) public cumulativeDeposits; mapping(address => uint256) public cumulativeWithdrawals; event TermsAccepted(address user); event TvlCapUpdated(uint256 newTvlCap); event DepositsIncremented(address user, uint256 amount, uint256 total); event WithdrawalsIncremented(address user, uint256 amount, uint256 total); /** * @dev Sets the value of {token} to the token that the vault will * hold as underlying value. It initializes the vault's own 'moo' token. * This token is minted when someone does a deposit. It is burned in order * to withdraw the corresponding portion of the underlying assets. * @param _token the token to maximize. * @param _name the name of the vault token. * @param _symbol the symbol of the vault token. * @param _depositFee one-time fee taken from deposits to this vault (in basis points) * @param _tvlCap initial deposit cap for scaling TVL safely */ constructor( address _token, string memory _name, string memory _symbol, uint256 _depositFee, uint256 _tvlCap ) ERC20(string(_name), string(_symbol)) { token = IERC20(_token); constructionTime = block.timestamp; depositFee = _depositFee; tvlCap = _tvlCap; } /** * @dev Connects the vault to its initial strategy. One use only. * @notice deployer has only 20 minutes after construction to connect the initial strategy. * @param _strategy the vault's initial strategy */ function initialize(address _strategy) public onlyOwner returns (bool) { require(!initialized, "Contract is already initialized."); require( block.timestamp <= (constructionTime + 1200), "initialization period over, use timelock" ); strategy = _strategy; initialized = true; return true; } /** * @dev Gives user access to the client * @notice this does not affect vault permissions, and is read from client-side */ function agreeToTerms() public returns (bool) { require( !hasReadAndAcceptedTerms[msg.sender], "you have already accepted the terms" ); hasReadAndAcceptedTerms[msg.sender] = true; emit TermsAccepted(msg.sender); return true; } /** * @dev It calculates the total underlying value of {token} held by the system. * It takes into account the vault contract balance, the strategy contract balance * and the balance deployed in other contracts as part of the strategy. */ function balance() public view returns (uint256) { return token.balanceOf(address(this)).add(IStrategy(strategy).balanceOf()); } /** * @dev Custom logic in here for how much the vault allows to be borrowed. * We return 100% of tokens for now. Under certain conditions we might * want to keep some of the system funds at hand in the vault, instead * of putting them to work. */ function available() public view returns (uint256) { return token.balanceOf(address(this)); } /** * @dev Function for various UIs to display the current value of one of our yield tokens. * Returns an uint256 with 18 decimals of how much underlying asset one vault share represents. */ function getPricePerFullShare() public view returns (uint256) { return totalSupply() == 0 ? 1e18 : balance().mul(1e18).div(totalSupply()); } /** * @dev A helper function to call deposit() with all the sender's funds. */ function depositAll() external { deposit(token.balanceOf(msg.sender)); } /** * @dev The entrypoint of funds into the system. People deposit with this function * into the vault. The vault is then in charge of sending funds into the strategy. * @notice the _before and _after variables are used to account properly for * 'burn-on-transaction' tokens. * @notice to ensure 'owner' can't sneak an implementation past the timelock, * it's set to true */ function deposit(uint256 _amount) public nonReentrant { require(_amount != 0, "please provide amount"); uint256 _pool = balance(); require(_pool.add(_amount) <= tvlCap, "vault is full!"); uint256 _before = token.balanceOf(address(this)); token.safeTransferFrom(msg.sender, address(this), _amount); uint256 _after = token.balanceOf(address(this)); _amount = _after.sub(_before); uint256 _amountAfterDeposit = ( _amount.mul(PERCENT_DIVISOR.sub(depositFee)) ).div(PERCENT_DIVISOR); uint256 shares = 0; if (totalSupply() == 0) { shares = _amountAfterDeposit; } else { shares = (_amountAfterDeposit.mul(totalSupply())).div(_pool); } _mint(msg.sender, shares); earn(); incrementDeposits(_amount); } /** * @dev Function to send funds into the strategy and put them to work. It's primarily called * by the vault's deposit() function. */ function earn() public { uint256 _bal = available(); token.safeTransfer(strategy, _bal); IStrategy(strategy).deposit(); } /** * @dev A helper function to call withdraw() with all the sender's funds. */ function withdrawAll() external { withdraw(balanceOf(msg.sender)); } /** * @dev Function to exit the system. The vault will withdraw the required tokens * from the strategy and pay up the token holder. A proportional number of IOU * tokens are burned in the process. */ function withdraw(uint256 _shares) public nonReentrant { require(_shares > 0, "please provide amount"); uint256 r = (balance().mul(_shares)).div(totalSupply()); _burn(msg.sender, _shares); uint256 b = token.balanceOf(address(this)); if (b < r) { uint256 _withdraw = r.sub(b); IStrategy(strategy).withdraw(_withdraw); uint256 _after = token.balanceOf(address(this)); uint256 _diff = _after.sub(b); if (_diff < _withdraw) { r = b.add(_diff); } } token.safeTransfer(msg.sender, r); incrementWithdrawals(r); } function updateDepositFee(uint256 fee) public onlyOwner { depositFee = fee; } /** * @dev pass in max value of uint to effectively remove TVL cap */ function updateTvlCap(uint256 _newTvlCap) public onlyOwner { tvlCap = _newTvlCap; emit TvlCapUpdated(tvlCap); } /** * @dev helper function to remove TVL cap */ function removeTvlCap() external onlyOwner { updateTvlCap(type(uint256).max); } /* * @dev functions to increase user's cumulative deposits and withdrawals * @param _amount number of LP tokens being deposited/withdrawn */ function incrementDeposits(uint256 _amount) internal returns (bool) { uint256 initial = cumulativeDeposits[tx.origin]; uint256 newTotal = initial + _amount; cumulativeDeposits[tx.origin] = newTotal; emit DepositsIncremented(tx.origin, _amount, newTotal); return true; } function incrementWithdrawals(uint256 _amount) internal returns (bool) { uint256 initial = cumulativeWithdrawals[tx.origin]; uint256 newTotal = initial + _amount; cumulativeWithdrawals[tx.origin] = newTotal; emit WithdrawalsIncremented(tx.origin, _amount, newTotal); return true; } /** * @dev Rescues random funds stuck that the strat can't handle. * @param _token address of the token to rescue. */ function inCaseTokensGetStuck(address _token) external onlyOwner { require(_token != address(token), "!token"); uint256 amount = IERC20(_token).balanceOf(address(this)); IERC20(_token).safeTransfer(msg.sender, amount); } }
* @dev Implementation of a vault to deposit funds for yield optimizing. This is the contract that receives funds and that users interface with. The yield optimizing strategy itself is implemented in a separate 'Strategy.sol' contract./ The token the vault accepts and looks to maximize.
contract ReaperVaultv1_3 is ERC20, Ownable, ReentrancyGuard { using SafeERC20 for IERC20; using SafeMath for uint256; address public strategy; uint256 public depositFee; uint256 public constant PERCENT_DIVISOR = 10000; uint256 public tvlCap; bool public initialized = false; uint256 public constructionTime; IERC20 public token; mapping(address => bool) public hasReadAndAcceptedTerms; mapping(address => uint256) public cumulativeDeposits; mapping(address => uint256) public cumulativeWithdrawals; event TermsAccepted(address user); event TvlCapUpdated(uint256 newTvlCap); event DepositsIncremented(address user, uint256 amount, uint256 total); event WithdrawalsIncremented(address user, uint256 amount, uint256 total); constructor( address _token, string memory _name, string memory _symbol, uint256 _depositFee, uint256 _tvlCap ) ERC20(string(_name), string(_symbol)) { token = IERC20(_token); constructionTime = block.timestamp; depositFee = _depositFee; tvlCap = _tvlCap; } function initialize(address _strategy) public onlyOwner returns (bool) { require(!initialized, "Contract is already initialized."); require( block.timestamp <= (constructionTime + 1200), "initialization period over, use timelock" ); strategy = _strategy; initialized = true; return true; } function agreeToTerms() public returns (bool) { require( !hasReadAndAcceptedTerms[msg.sender], "you have already accepted the terms" ); hasReadAndAcceptedTerms[msg.sender] = true; emit TermsAccepted(msg.sender); return true; } function balance() public view returns (uint256) { return token.balanceOf(address(this)).add(IStrategy(strategy).balanceOf()); } function available() public view returns (uint256) { return token.balanceOf(address(this)); } function getPricePerFullShare() public view returns (uint256) { return totalSupply() == 0 ? 1e18 : balance().mul(1e18).div(totalSupply()); } function depositAll() external { deposit(token.balanceOf(msg.sender)); } function deposit(uint256 _amount) public nonReentrant { require(_amount != 0, "please provide amount"); uint256 _pool = balance(); require(_pool.add(_amount) <= tvlCap, "vault is full!"); uint256 _before = token.balanceOf(address(this)); token.safeTransferFrom(msg.sender, address(this), _amount); uint256 _after = token.balanceOf(address(this)); _amount = _after.sub(_before); uint256 _amountAfterDeposit = ( _amount.mul(PERCENT_DIVISOR.sub(depositFee)) ).div(PERCENT_DIVISOR); uint256 shares = 0; if (totalSupply() == 0) { shares = _amountAfterDeposit; shares = (_amountAfterDeposit.mul(totalSupply())).div(_pool); } _mint(msg.sender, shares); earn(); incrementDeposits(_amount); } function deposit(uint256 _amount) public nonReentrant { require(_amount != 0, "please provide amount"); uint256 _pool = balance(); require(_pool.add(_amount) <= tvlCap, "vault is full!"); uint256 _before = token.balanceOf(address(this)); token.safeTransferFrom(msg.sender, address(this), _amount); uint256 _after = token.balanceOf(address(this)); _amount = _after.sub(_before); uint256 _amountAfterDeposit = ( _amount.mul(PERCENT_DIVISOR.sub(depositFee)) ).div(PERCENT_DIVISOR); uint256 shares = 0; if (totalSupply() == 0) { shares = _amountAfterDeposit; shares = (_amountAfterDeposit.mul(totalSupply())).div(_pool); } _mint(msg.sender, shares); earn(); incrementDeposits(_amount); } } else { function earn() public { uint256 _bal = available(); token.safeTransfer(strategy, _bal); IStrategy(strategy).deposit(); } function withdrawAll() external { withdraw(balanceOf(msg.sender)); } function withdraw(uint256 _shares) public nonReentrant { require(_shares > 0, "please provide amount"); uint256 r = (balance().mul(_shares)).div(totalSupply()); _burn(msg.sender, _shares); uint256 b = token.balanceOf(address(this)); if (b < r) { uint256 _withdraw = r.sub(b); IStrategy(strategy).withdraw(_withdraw); uint256 _after = token.balanceOf(address(this)); uint256 _diff = _after.sub(b); if (_diff < _withdraw) { r = b.add(_diff); } } token.safeTransfer(msg.sender, r); incrementWithdrawals(r); } function withdraw(uint256 _shares) public nonReentrant { require(_shares > 0, "please provide amount"); uint256 r = (balance().mul(_shares)).div(totalSupply()); _burn(msg.sender, _shares); uint256 b = token.balanceOf(address(this)); if (b < r) { uint256 _withdraw = r.sub(b); IStrategy(strategy).withdraw(_withdraw); uint256 _after = token.balanceOf(address(this)); uint256 _diff = _after.sub(b); if (_diff < _withdraw) { r = b.add(_diff); } } token.safeTransfer(msg.sender, r); incrementWithdrawals(r); } function withdraw(uint256 _shares) public nonReentrant { require(_shares > 0, "please provide amount"); uint256 r = (balance().mul(_shares)).div(totalSupply()); _burn(msg.sender, _shares); uint256 b = token.balanceOf(address(this)); if (b < r) { uint256 _withdraw = r.sub(b); IStrategy(strategy).withdraw(_withdraw); uint256 _after = token.balanceOf(address(this)); uint256 _diff = _after.sub(b); if (_diff < _withdraw) { r = b.add(_diff); } } token.safeTransfer(msg.sender, r); incrementWithdrawals(r); } function updateDepositFee(uint256 fee) public onlyOwner { depositFee = fee; } function updateTvlCap(uint256 _newTvlCap) public onlyOwner { tvlCap = _newTvlCap; emit TvlCapUpdated(tvlCap); } function removeTvlCap() external onlyOwner { updateTvlCap(type(uint256).max); } function incrementDeposits(uint256 _amount) internal returns (bool) { uint256 initial = cumulativeDeposits[tx.origin]; uint256 newTotal = initial + _amount; cumulativeDeposits[tx.origin] = newTotal; emit DepositsIncremented(tx.origin, _amount, newTotal); return true; } function incrementWithdrawals(uint256 _amount) internal returns (bool) { uint256 initial = cumulativeWithdrawals[tx.origin]; uint256 newTotal = initial + _amount; cumulativeWithdrawals[tx.origin] = newTotal; emit WithdrawalsIncremented(tx.origin, _amount, newTotal); return true; } function inCaseTokensGetStuck(address _token) external onlyOwner { require(_token != address(token), "!token"); uint256 amount = IERC20(_token).balanceOf(address(this)); IERC20(_token).safeTransfer(msg.sender, amount); } }
12,756,774
[ 1, 13621, 434, 279, 9229, 358, 443, 1724, 284, 19156, 364, 2824, 5213, 6894, 18, 1220, 353, 326, 6835, 716, 17024, 284, 19156, 471, 716, 3677, 1560, 598, 18, 1021, 2824, 5213, 6894, 6252, 6174, 353, 8249, 316, 279, 9004, 296, 4525, 18, 18281, 11, 6835, 18, 19, 1021, 1147, 326, 9229, 8104, 471, 10192, 358, 943, 10153, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 16351, 868, 7294, 12003, 90, 21, 67, 23, 353, 4232, 39, 3462, 16, 14223, 6914, 16, 868, 8230, 12514, 16709, 288, 203, 565, 1450, 14060, 654, 39, 3462, 364, 467, 654, 39, 3462, 31, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 565, 1758, 1071, 6252, 31, 203, 203, 565, 2254, 5034, 1071, 443, 1724, 14667, 31, 203, 565, 2254, 5034, 1071, 5381, 10950, 19666, 67, 2565, 26780, 916, 273, 12619, 31, 203, 565, 2254, 5034, 1071, 268, 10872, 4664, 31, 203, 203, 565, 1426, 1071, 6454, 273, 629, 31, 203, 565, 2254, 5034, 1071, 16171, 950, 31, 203, 203, 565, 467, 654, 39, 3462, 1071, 1147, 31, 203, 203, 565, 2874, 12, 2867, 516, 1426, 13, 1071, 711, 1994, 1876, 18047, 11673, 31, 203, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 1071, 15582, 758, 917, 1282, 31, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 1071, 15582, 1190, 9446, 1031, 31, 203, 203, 565, 871, 26563, 18047, 12, 2867, 729, 1769, 203, 565, 871, 399, 10872, 4664, 7381, 12, 11890, 5034, 394, 56, 10872, 4664, 1769, 203, 203, 565, 871, 4019, 538, 1282, 10798, 329, 12, 2867, 729, 16, 2254, 5034, 3844, 16, 2254, 5034, 2078, 1769, 203, 565, 871, 3423, 9446, 1031, 10798, 329, 12, 2867, 729, 16, 2254, 5034, 3844, 16, 2254, 5034, 2078, 1769, 203, 203, 565, 3885, 12, 203, 3639, 1758, 389, 2316, 16, 203, 3639, 533, 3778, 389, 529, 16, 203, 3639, 533, 3778, 389, 7175, 16, 203, 3639, 2254, 5034, 389, 2 ]
./partial_match/56/0xd4c89791eF0FAdE72eAAc6475296320b5572b28e/sources/StrategyRamenLP.sol
* @dev Swaps {output} for {lpToken0}, {lpToken1} & {wbnb} using PancakeSwap./
function addLiquidity() internal { uint256 outputHalf = IERC20(output).balanceOf(address(this)).div(2); if (lpToken0 != output) { IUniswapRouterETH(unirouter).swapExactTokensForTokens(outputHalf, 0, outputToLp0Route, address(this), now.add(600)); } if (lpToken1 != output) { IUniswapRouterETH(unirouter).swapExactTokensForTokens(outputHalf, 0, outputToLp1Route, address(this), now.add(600)); } uint256 lp0Bal = IERC20(lpToken0).balanceOf(address(this)); uint256 lp1Bal = IERC20(lpToken1).balanceOf(address(this)); IUniswapRouterETH(unirouter).addLiquidity(lpToken0, lpToken1, lp0Bal, lp1Bal, 1, 1, address(this), now.add(600)); }
11,124,310
[ 1, 6050, 6679, 288, 2844, 97, 364, 288, 9953, 1345, 20, 5779, 288, 9953, 1345, 21, 97, 473, 288, 9464, 6423, 97, 1450, 12913, 23780, 12521, 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, 527, 48, 18988, 24237, 1435, 2713, 288, 203, 3639, 2254, 5034, 876, 16168, 273, 467, 654, 39, 3462, 12, 2844, 2934, 12296, 951, 12, 2867, 12, 2211, 13, 2934, 2892, 12, 22, 1769, 203, 203, 3639, 309, 261, 9953, 1345, 20, 480, 876, 13, 288, 203, 5411, 467, 984, 291, 91, 438, 8259, 1584, 44, 12, 318, 77, 10717, 2934, 22270, 14332, 5157, 1290, 5157, 12, 2844, 16168, 16, 374, 16, 876, 774, 48, 84, 20, 3255, 16, 1758, 12, 2211, 3631, 2037, 18, 1289, 12, 28133, 10019, 203, 3639, 289, 203, 203, 3639, 309, 261, 9953, 1345, 21, 480, 876, 13, 288, 203, 5411, 467, 984, 291, 91, 438, 8259, 1584, 44, 12, 318, 77, 10717, 2934, 22270, 14332, 5157, 1290, 5157, 12, 2844, 16168, 16, 374, 16, 876, 774, 48, 84, 21, 3255, 16, 1758, 12, 2211, 3631, 2037, 18, 1289, 12, 28133, 10019, 203, 3639, 289, 203, 203, 3639, 2254, 5034, 12423, 20, 38, 287, 273, 467, 654, 39, 3462, 12, 9953, 1345, 20, 2934, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 3639, 2254, 5034, 12423, 21, 38, 287, 273, 467, 654, 39, 3462, 12, 9953, 1345, 21, 2934, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 3639, 467, 984, 291, 91, 438, 8259, 1584, 44, 12, 318, 77, 10717, 2934, 1289, 48, 18988, 24237, 12, 9953, 1345, 20, 16, 12423, 1345, 21, 16, 12423, 20, 38, 287, 16, 12423, 21, 38, 287, 16, 404, 16, 404, 16, 1758, 12, 2211, 3631, 2037, 18, 1289, 12, 28133, 10019, 2 ]
./partial_match/3/0x863534bDC6e93d0D0e5a67293CBf1636E1Fc984d/sources/UtilityTokenETHOnly.sol
* Used for donate ETH without receiving token/
function donateETH() public payable validGasPrice nonReentrant() { }
5,247,334
[ 1, 6668, 364, 2727, 340, 512, 2455, 2887, 15847, 1147, 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, 2727, 340, 1584, 44, 1435, 1071, 8843, 429, 923, 27998, 5147, 1661, 426, 8230, 970, 1435, 288, 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, -100, -100, -100, -100, -100, -100 ]
//Address: 0x861825daa0068136a55f6effb3f4a0b9aa17f51f //Contract name: Token //Balance: 0 Ether //Verification Date: 1/17/2018 //Transacion Count: 167 // CODE STARTS HERE // Copyright (c) 2017, 2018 EtherJack.io. All rights reserved. // This code is disclosed only to be used for inspection and audit purposes. // Code modification and use for any purpose other than security audit // is prohibited. Creation of derived works or unauthorized deployment // of the code or any its portion to a blockchain is prohibited. pragma solidity ^0.4.19; contract HouseOwned { address house; modifier onlyHouse { require(msg.sender == house); _; } /// @dev Contract constructor function HouseOwned() public { house = msg.sender; } } // SafeMath is a part of Zeppelin Solidity library // licensed under MIT License // https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/LICENSE /** * @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; } } // ---------------------------------------------------------------------------- // 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 _owner) public constant returns (uint balance); function allowance(address _owner, address _spender) public constant returns (uint remaining); function transfer(address _to, uint _value) public returns (bool success); function approve(address _spender, uint _value) public returns (bool success); function transferFrom(address _from, address _to, uint _value) public returns (bool success); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed tokenOwner, address indexed spender, uint value); } contract Token is HouseOwned, ERC20Interface { using SafeMath for uint; // Public variables of the token string public name; string public symbol; uint8 public constant decimals = 0; uint256 public supply; // Trusted addresses Jackpot public jackpot; address public croupier; // All users' balances mapping (address => uint256) internal balances; // Users' deposits with Croupier mapping (address => uint256) public depositOf; // Total amount of deposits uint256 public totalDeposit; // Total amount of "Frozen Deposit Pool" -- the tokens for sale at Croupier uint256 public frozenPool; // Allowance mapping mapping (address => mapping (address => uint256)) internal allowed; ////// /// @title Modifiers // /// @dev Only Croupier modifier onlyCroupier { require(msg.sender == croupier); _; } /// @dev Only Jackpot modifier onlyJackpot { require(msg.sender == address(jackpot)); _; } /// @dev Protection from short address attack modifier onlyPayloadSize(uint size) { assert(msg.data.length == size + 4); _; } ////// /// @title Events // /// @dev Fired when a token is burned (bet made) event Burn(address indexed from, uint256 value); /// @dev Fired when a deposit is made or withdrawn /// direction == 0: deposit /// direction == 1: withdrawal event Deposit(address indexed from, uint256 value, uint8 direction, uint256 newDeposit); /// @dev Fired when a deposit with Croupier is frozen (set for sale) event DepositFrozen(address indexed from, uint256 value); /// @dev Fired when a deposit with Croupier is unfrozen (removed from sale) // Value is the resulting deposit, NOT the unfrozen amount event DepositUnfrozen(address indexed from, uint256 value); ////// /// @title Constructor and Initialization // /// @dev Initializes contract with initial supply tokens to the creator of the contract function Token() HouseOwned() public { name = "JACK Token"; symbol = "JACK"; supply = 1000000; } /// @dev Function to set address of Jackpot contract once after creation /// @param _jackpot Address of the Jackpot contract function setJackpot(address _jackpot) onlyHouse public { require(address(jackpot) == 0x0); require(_jackpot != address(this)); // Protection from admin's mistake jackpot = Jackpot(_jackpot); uint256 bountyPortion = supply / 40; // 2.5% is the bounty portion for marketing expenses balances[house] = bountyPortion; // House receives the bounty tokens balances[jackpot] = supply - bountyPortion; // Jackpot gets the rest croupier = jackpot.croupier(); } ////// /// @title Public Methods // /// @dev Croupier invokes this method to return deposits to players /// @param _to The address of the recipient /// @param _extra Additional off-chain credit (AirDrop support), so that croupier can return more than the user has actually deposited function returnDeposit(address _to, uint256 _extra) onlyCroupier public { require(depositOf[_to] > 0 || _extra > 0); uint256 amount = depositOf[_to]; depositOf[_to] = 0; totalDeposit = totalDeposit.sub(amount); _transfer(croupier, _to, amount.add(_extra)); Deposit(_to, amount, 1, 0); } /// @dev Gets the balance of the specified address. /// @param _owner The address function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } function totalSupply() public view returns (uint256) { return supply; } /// @dev Send `_value` tokens to `_to` /// @param _to The address of the recipient /// @param _value the amount to send function transfer(address _to, uint256 _value) onlyPayloadSize(2 * 32) public returns (bool) { require(address(jackpot) != 0x0); require(croupier != 0x0); if (_to == address(jackpot)) { // It is a token bet. Ignoring _value, only using 1 token _burnFromAccount(msg.sender, 1); jackpot.betToken(msg.sender); return true; } if (_to == croupier && msg.sender != house) { // It's a deposit to Croupier. In addition to transferring the token, // mark it in the deposits table // House can't make deposits. If House is transferring something to // Croupier, it's just a transfer, nothing more depositOf[msg.sender] += _value; totalDeposit = totalDeposit.add(_value); Deposit(msg.sender, _value, 0, depositOf[msg.sender]); } // In all cases but Jackpot transfer (which is terminated by a return), actually // do perform the transfer return _transfer(msg.sender, _to, _value); } /// @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. /// @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 Increase the amount of tokens that an owner allowed to a spender. /// @param _spender The address which will spend the funds. /// @param _addedValue The amount of tokens to increase the allowance by. function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /// @dev Decrease the amount of tokens that an owner allowed to a spender. /// @param _spender The address which will spend the funds. /// @param _subtractedValue The amount of tokens to decrease the allowance by. function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /// @dev Croupier uses this method to set deposited credits of a player for sale /// @param _user The address of the user /// @param _extra Additional off-chain credit (AirDrop support), so that croupier could have frozen more than the user had invested function freezeDeposit(address _user, uint256 _extra) onlyCroupier public { require(depositOf[_user] > 0 || _extra > 0); uint256 deposit = depositOf[_user]; depositOf[_user] = depositOf[_user].sub(deposit); totalDeposit = totalDeposit.sub(deposit); uint256 depositWithExtra = deposit.add(_extra); frozenPool = frozenPool.add(depositWithExtra); DepositFrozen(_user, depositWithExtra); } /// @dev Croupier uses this method stop selling user's tokens and return them to normal deposit /// @param _user The user whose deposit is being unfrozen /// @param _value The value to unfreeze according to Croupier's records (off-chain sale data) function unfreezeDeposit(address _user, uint256 _value) onlyCroupier public { require(_value > 0); require(frozenPool >= _value); depositOf[_user] = depositOf[_user].add(_value); totalDeposit = totalDeposit.add(_value); frozenPool = frozenPool.sub(_value); DepositUnfrozen(_user, depositOf[_user]); } /// @dev The Jackpot contract invokes this method when selling tokens from Croupier /// @param _to The recipient of the tokens /// @param _value The amount function transferFromCroupier(address _to, uint256 _value) onlyJackpot public { require(_value > 0); require(frozenPool >= _value); frozenPool = frozenPool.sub(_value); _transfer(croupier, _to, _value); } ////// /// @title Internal Methods // /// @dev Internal transfer function /// @param _from From address /// @param _to To address /// @param _value The value to transfer /// @return success function _transfer(address _from, address _to, uint256 _value) internal returns (bool) { require(_to != address(0)); // Prevent transfer to 0x0 address require(balances[_from] >= _value); // Check if the sender has enough balances[_from] = balances[_from].sub(_value); // Subtract from the sender balances[_to] = balances[_to].add(_value); // Add the same to the recipient Transfer(_from, _to, _value); return true; } /// @dev Internal function for burning tokens /// @param _sender The token sender (whose tokens are being burned) /// @param _value The amount of tokens to burn function _burnFromAccount(address _sender, uint256 _value) internal { require(balances[_sender] >= _value); // Check if the sender has enough balances[_sender] = balances[_sender].sub(_value); // Subtract from the sender supply = supply.sub(_value); // Updates totalSupply Burn(_sender, _value); } } contract Jackpot is HouseOwned { using SafeMath for uint; enum Stages { InitialOffer, // ICO stage: forming the jackpot fund GameOn, // The game is running GameOver, // The jackpot is won, paying out the jackpot Aborted // ICO aborted, refunding investments } uint256 constant initialIcoTokenPrice = 4 finney; uint256 constant initialBetAmount = 10 finney; uint constant gameStartJackpotThreshold = 333 ether; uint constant icoTerminationTimeout = 48 hours; // These variables hold the values needed for minor prize checking: // - when they were last won (once the number reaches the corresponding amount, the // minor prize is won, and it should be reset) // - how much ether was bet since it was last won // `etherSince*` variables start with value of 1 and always have +1 in their value // so that the variables never go 0, for gas consumption consistency uint32 public totalBets = 0; uint256 public etherSince20 = 1; uint256 public etherSince50 = 1; uint256 public etherSince100 = 1; uint256 public pendingEtherForCroupier = 0; // ICO status uint32 public icoSoldTokens; uint256 public icoEndTime; // Jackpot status address public lastBetUser; uint256 public terminationTime; address public winner; uint256 public pendingJackpotForHouse; uint256 public pendingJackpotForWinner; // General configuration and stage address public croupier; Token public token; Stages public stage = Stages.InitialOffer; // Price state uint256 public currentIcoTokenPrice = initialIcoTokenPrice; uint256 public currentBetAmount = initialBetAmount; // Investment tracking for emergency ICO termination mapping (address => uint256) public investmentOf; uint256 public abortTime; ////// /// @title Modifiers // /// @dev Only Token modifier onlyToken { require(msg.sender == address(token)); _; } /// @dev Only Croupier modifier onlyCroupier { require(msg.sender == address(croupier)); _; } ////// /// @title Events // /// @dev Fired when tokens are sold for Ether in ICO event EtherIco(address indexed from, uint256 value, uint256 tokens); /// @dev Fired when a bid with Ether is made event EtherBet(address indexed from, uint256 value, uint256 dividends); /// @dev Fired when a bid with a Token is made event TokenBet(address indexed from); /// @dev Fired when a bidder wins a minor prize /// Type: 1: 20, 2: 50, 3: 100 event MinorPrizePayout(address indexed from, uint256 value, uint8 prizeType); /// @dev Fired when as a result of ether bid, tokens are sold from the Croupier's pool /// The parameters are who bought them, how many tokens, and for how much Ether they were sold event SoldTokensFromCroupier(address indexed from, uint256 value, uint256 tokens); /// @dev Fired when the jackpot is won event JackpotWon(address indexed from, uint256 value); ////// /// @title Constructor and Initialization // /// @dev The contract constructor /// @param _croupier The address of the trusted Croupier bot's account function Jackpot(address _croupier) HouseOwned() public { require(_croupier != 0x0); croupier = _croupier; // There are no bets (it even starts in ICO stage), so initialize // lastBetUser, just so that value is not zero and is meaningful // The game can't end until at least one bid is made, and once // a bid is made, this value is permanently overwritten. lastBetUser = _croupier; } /// @dev Function to set address of Token contract once after creation /// @param _token Address of the Token contract (JACK Token) function setToken(address _token) onlyHouse public { require(address(token) == 0x0); require(_token != address(this)); // Protection from admin's mistake token = Token(_token); } ////// /// @title Default Function // /// @dev The fallback function for receiving ether (bets) /// Action depends on stages: /// - ICO: just sell the tokens /// - Game: accept bets, award tokens, award minor (20, 50, 100) prizes /// - Game Over: pay out jackpot /// - Aborted: fail function() payable public { require(croupier != 0x0); require(address(token) != 0x0); require(stage != Stages.Aborted); uint256 tokens; if (stage == Stages.InitialOffer) { // First, check if the ICO is over. If it is, trigger the events and // refund sent ether bool started = checkGameStart(); if (started) { // Refund ether without failing the transaction // (because side-effect is needed) msg.sender.transfer(msg.value); return; } require(msg.value >= currentIcoTokenPrice); // THE PLAN // 1. [CHECK + EFFECT] Calculate how much times price, the investment amount is, // calculate how many tokens the investor is going to get // 2. [EFFECT] Log and count // 3. [EFFECT] Check game start conditions and maybe start the game // 4. [INT] Award the tokens // 5. [INT] Transfer 20% to house // 1. [CHECK + EFFECT] Checking the amount tokens = _icoTokensForEther(msg.value); // 2. [EFFECT] Log // Log the ICO event and count investment EtherIco(msg.sender, msg.value, tokens); investmentOf[msg.sender] = investmentOf[msg.sender].add( msg.value.sub(msg.value / 5) ); // 3. [EFFECT] Game start // Check if we have accumulated the jackpot amount required for game start if (icoEndTime == 0 && this.balance >= gameStartJackpotThreshold) { icoEndTime = now + icoTerminationTimeout; } // 4. [INT] Awarding tokens // Award the deserved tokens (if any) if (tokens > 0) { token.transfer(msg.sender, tokens); } // 5. [INT] House // House gets 20% of ICO according to the rules house.transfer(msg.value / 5); } else if (stage == Stages.GameOn) { // First, check if the game is over. If it is, trigger the events and // refund sent ether bool terminated = checkTermination(); if (terminated) { // Refund ether without failing the transaction // (because side-effect is needed) msg.sender.transfer(msg.value); return; } // Now processing an Ether bid require(msg.value >= currentBetAmount); // THE PLAN // 1. [CHECK] Calculate how much times min-bet, the bet amount is, // calculate how many tokens the player is going to get // 2. [CHECK] Check how much is sold from the Croupier's pool, and how much from Jackpot // 3. [EFFECT] Deposit 25% to the Croupier (for dividends and house's benefit) // 4. [EFFECT] Log and mark bid // 6. [INT] Check and reward (if won) minor (20, 100, 1000) prizes // 7. [EFFECT] Update bet amount // 8. [INT] Award the tokens // 1. [CHECK + EFFECT] Checking the bet amount and token reward tokens = _betTokensForEther(msg.value); // 2. [CHECK] Check how much is sold from the Croupier's pool, and how much from Jackpot // The priority is (1) Croupier, (2) Jackpot uint256 sellingFromJackpot = 0; uint256 sellingFromCroupier = 0; if (tokens > 0) { uint256 croupierPool = token.frozenPool(); uint256 jackpotPool = token.balanceOf(this); if (croupierPool == 0) { // Simple case: only Jackpot is selling sellingFromJackpot = tokens; if (sellingFromJackpot > jackpotPool) { sellingFromJackpot = jackpotPool; } } else if (jackpotPool == 0 || tokens <= croupierPool) { // Simple case: only Croupier is selling // either because Jackpot has 0, or because Croupier takes over // by priority and has enough tokens in its pool sellingFromCroupier = tokens; if (sellingFromCroupier > croupierPool) { sellingFromCroupier = croupierPool; } } else { // Complex case: both are selling now sellingFromCroupier = croupierPool; // (tokens > croupierPool) is guaranteed at this point sellingFromJackpot = tokens.sub(sellingFromCroupier); if (sellingFromJackpot > jackpotPool) { sellingFromJackpot = jackpotPool; } } } // 3. [EFFECT] Croupier deposit // Transfer a portion to the Croupier for dividend payout and house benefit // Dividends are a sum of: // + 25% of bet // + 50% of price of tokens sold from Jackpot (or just anything other than the bet and Croupier payment) // + 0% of price of tokens sold from Croupier // (that goes in SoldTokensFromCroupier instead) uint256 tokenValue = msg.value.sub(currentBetAmount); uint256 croupierSaleRevenue = 0; if (sellingFromCroupier > 0) { croupierSaleRevenue = tokenValue.div( sellingFromJackpot.add(sellingFromCroupier) ).mul(sellingFromCroupier); } uint256 jackpotSaleRevenue = tokenValue.sub(croupierSaleRevenue); uint256 dividends = (currentBetAmount.div(4)).add(jackpotSaleRevenue.div(2)); // 100% of money for selling from Croupier still goes to Croupier // so that it's later paid out to the selling user pendingEtherForCroupier = pendingEtherForCroupier.add(dividends.add(croupierSaleRevenue)); // 4. [EFFECT] Log and mark bid // Log the bet with actual amount charged (value less change) EtherBet(msg.sender, msg.value, dividends); lastBetUser = msg.sender; terminationTime = now + _terminationDuration(); // If anything was sold from Croupier, log it appropriately if (croupierSaleRevenue > 0) { SoldTokensFromCroupier(msg.sender, croupierSaleRevenue, sellingFromCroupier); } // 5. [INT] Minor prizes // Check for winning minor prizes _checkMinorPrizes(msg.sender, currentBetAmount); // 6. [EFFECT] Update bet amount _updateBetAmount(); // 7. [INT] Awarding tokens if (sellingFromJackpot > 0) { token.transfer(msg.sender, sellingFromJackpot); } if (sellingFromCroupier > 0) { token.transferFromCroupier(msg.sender, sellingFromCroupier); } } else if (stage == Stages.GameOver) { require(msg.sender == winner || msg.sender == house); if (msg.sender == winner) { require(pendingJackpotForWinner > 0); uint256 winnersPay = pendingJackpotForWinner; pendingJackpotForWinner = 0; msg.sender.transfer(winnersPay); } else if (msg.sender == house) { require(pendingJackpotForHouse > 0); uint256 housePay = pendingJackpotForHouse; pendingJackpotForHouse = 0; msg.sender.transfer(housePay); } } } // Croupier will call this function when the jackpot is won // If Croupier fails to call the function for any reason, house and winner // still can claim their jackpot portion by sending ether to Jackpot function payOutJackpot() onlyCroupier public { require(winner != 0x0); if (pendingJackpotForHouse > 0) { uint256 housePay = pendingJackpotForHouse; pendingJackpotForHouse = 0; house.transfer(housePay); } if (pendingJackpotForWinner > 0) { uint256 winnersPay = pendingJackpotForWinner; pendingJackpotForWinner = 0; winner.transfer(winnersPay); } } ////// /// @title Public Functions // /// @dev View function to check whether the game should be terminated /// Used as internal function by checkTermination, as well as by the /// Croupier bot, to check whether it should call checkTermination /// @return Whether the game should be terminated by timeout function shouldBeTerminated() public view returns (bool should) { return stage == Stages.GameOn && terminationTime != 0 && now > terminationTime; } /// @dev Check whether the game should be terminated, and if it should, terminate it /// @return Whether the game was terminated as the result function checkTermination() public returns (bool terminated) { if (shouldBeTerminated()) { stage = Stages.GameOver; winner = lastBetUser; // Flush amount due for Croupier immediately _flushEtherToCroupier(); // The rest should be claimed by the winner (except what house gets) JackpotWon(winner, this.balance); uint256 jackpot = this.balance; pendingJackpotForHouse = jackpot.div(5); pendingJackpotForWinner = jackpot.sub(pendingJackpotForHouse); return true; } return false; } /// @dev View function to check whether the game should be started /// Used as internal function by `checkGameStart`, as well as by the /// Croupier bot, to check whether it should call `checkGameStart` /// @return Whether the game should be started function shouldBeStarted() public view returns (bool should) { return stage == Stages.InitialOffer && icoEndTime != 0 && now > icoEndTime; } /// @dev Check whether the game should be started, and if it should, start it /// @return Whether the game was started as the result function checkGameStart() public returns (bool started) { if (shouldBeStarted()) { stage = Stages.GameOn; return true; } return false; } /// @dev Bet 1 token in the game /// The token has already been burned having passed all checks, so /// just process the bet of 1 token function betToken(address _user) onlyToken public { // Token bets can only be accepted in the game stage require(stage == Stages.GameOn); bool terminated = checkTermination(); if (terminated) { return; } TokenBet(_user); lastBetUser = _user; terminationTime = now + _terminationDuration(); // Check for winning minor prizes _checkMinorPrizes(_user, 0); } /// @dev Allows House to terminate ICO as an emergency measure function abort() onlyHouse public { require(stage == Stages.InitialOffer); stage = Stages.Aborted; abortTime = now; } /// @dev In case the ICO is emergency-terminated by House, allows investors /// to pull back the investments function claimRefund() public { require(stage == Stages.Aborted); require(investmentOf[msg.sender] > 0); uint256 payment = investmentOf[msg.sender]; investmentOf[msg.sender] = 0; msg.sender.transfer(payment); } /// @dev In case the ICO was terminated, allows House to kill the contract in 2 months /// after the termination date function killAborted() onlyHouse public { require(stage == Stages.Aborted); require(now > abortTime + 60 days); selfdestruct(house); } ////// /// @title Internal Functions // /// @dev Get current bid timer duration /// @return duration The duration function _terminationDuration() internal view returns (uint256 duration) { return (5 + 19200 / (100 + totalBets)) * 1 minutes; } /// @dev Updates the current ICO price according to the rules function _updateIcoPrice() internal { uint256 newIcoTokenPrice = currentIcoTokenPrice; if (icoSoldTokens < 10000) { newIcoTokenPrice = 4 finney; } else if (icoSoldTokens < 20000) { newIcoTokenPrice = 5 finney; } else if (icoSoldTokens < 30000) { newIcoTokenPrice = 5.3 finney; } else if (icoSoldTokens < 40000) { newIcoTokenPrice = 5.7 finney; } else { newIcoTokenPrice = 6 finney; } if (newIcoTokenPrice != currentIcoTokenPrice) { currentIcoTokenPrice = newIcoTokenPrice; } } /// @dev Updates the current bid price according to the rules function _updateBetAmount() internal { uint256 newBetAmount = 10 finney + (totalBets / 100) * 6 finney; if (newBetAmount != currentBetAmount) { currentBetAmount = newBetAmount; } } /// @dev Calculates how many tokens a user should get with a given Ether bid /// @param value The bid amount /// @return tokens The number of tokens function _betTokensForEther(uint256 value) internal view returns (uint256 tokens) { // One bet amount is for the bet itself, for the rest we will sell // tokens tokens = (value / currentBetAmount) - 1; if (tokens >= 1000) { tokens = tokens + tokens / 4; // +25% } else if (tokens >= 300) { tokens = tokens + tokens / 5; // +20% } else if (tokens >= 100) { tokens = tokens + tokens / 7; // ~ +14.3% } else if (tokens >= 50) { tokens = tokens + tokens / 10; // +10% } else if (tokens >= 20) { tokens = tokens + tokens / 20; // +5% } } /// @dev Calculates how many tokens a user should get with a given ICO transfer /// @param value The transfer amount /// @return tokens The number of tokens function _icoTokensForEther(uint256 value) internal returns (uint256 tokens) { // How many times the input is greater than current token price tokens = value / currentIcoTokenPrice; if (tokens >= 10000) { tokens = tokens + tokens / 4; // +25% } else if (tokens >= 5000) { tokens = tokens + tokens / 5; // +20% } else if (tokens >= 1000) { tokens = tokens + tokens / 7; // ~ +14.3% } else if (tokens >= 500) { tokens = tokens + tokens / 10; // +10% } else if (tokens >= 200) { tokens = tokens + tokens / 20; // +5% } // Checking if Jackpot has the tokens in reserve if (tokens > token.balanceOf(this)) { tokens = token.balanceOf(this); } icoSoldTokens += (uint32)(tokens); _updateIcoPrice(); } /// @dev Flush the currently pending Ether to Croupier function _flushEtherToCroupier() internal { if (pendingEtherForCroupier > 0) { uint256 willTransfer = pendingEtherForCroupier; pendingEtherForCroupier = 0; croupier.transfer(willTransfer); } } /// @dev Count the bid towards minor prize fund, check if the user /// wins a minor prize, and if they did, transfer the prize to them /// @param user The user in question /// @param value The bid value function _checkMinorPrizes(address user, uint256 value) internal { // First and foremost, increment the counters and ether counters totalBets ++; if (value > 0) { etherSince20 = etherSince20.add(value); etherSince50 = etherSince50.add(value); etherSince100 = etherSince100.add(value); } // Now actually check if the bets won uint256 etherPayout; if ((totalBets + 30) % 100 == 0) { // Won 100th etherPayout = (etherSince100 - 1) / 10; etherSince100 = 1; MinorPrizePayout(user, etherPayout, 3); user.transfer(etherPayout); return; } if ((totalBets + 5) % 50 == 0) { // Won 100th etherPayout = (etherSince50 - 1) / 10; etherSince50 = 1; MinorPrizePayout(user, etherPayout, 2); user.transfer(etherPayout); return; } if (totalBets % 20 == 0) { // Won 20th etherPayout = (etherSince20 - 1) / 10; etherSince20 = 1; _flushEtherToCroupier(); MinorPrizePayout(user, etherPayout, 1); user.transfer(etherPayout); return; } return; } }
Updates totalSupply
supply = supply.sub(_value);
15,810,021
[ 1, 5121, 2078, 3088, 1283, 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, 3639, 14467, 273, 14467, 18, 1717, 24899, 1132, 1769, 7682, 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 ]
/* SPDX-License-Identifier: MIT */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import { console } from "@nomiclabs/buidler/console.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@chainlink/contracts/src/v0.6/ChainlinkClient.sol"; //https://github.com/smartcontractkit/chainlink/issues/3153#issuecomment-655241638 import "@chainlink/contracts/src/v0.6/vendor/SafeMath.sol"; /// @title CommitPool single-player mode contract /// @notice Enables staking and validating performance. No social/pool functionality. contract SinglePlayerCommit is ChainlinkClient, Ownable { using SafeMath for uint256; /****************** GLOBAL CONSTANTS ******************/ IERC20 public token; uint256 BIGGEST_NUMBER = uint256(-1); uint256 constant private ORACLE_PAYMENT = 0.01 * 10 ** 18; //0.01 LINK /*************** DATA TYPES ***************/ /// @notice Activity as part of commitment with oracle address. E.g. "cycling" with ChainLink Strava node struct Activity { string name; address oracle; bool allowed; bool exists; } struct Commitment { address committer; // user bytes32 activityKey; uint256 goalValue; uint256 startTime; uint256 endTime; uint256 stake; // amount of token staked, scaled by token decimals uint256 reportedValue; // as reported by oracle uint256 lastActivityUpdate; // when updated by oracle bool met; // whether the commitment has been met string userId; bool exists; // flag to help check if commitment exists } /*************** EVENTS ***************/ event NewCommitment( address committer, string activityName, uint256 goalValue, uint256 startTime, uint256 endTime, uint256 stake ); event CommitmentEnded(address committer, bool met, uint256 amountPenalized); event Deposit(address committer, uint256 amount); event Withdrawal(address committer, uint256 amount); event RequestActivityDistanceFulfilled( bytes32 indexed requestId, uint256 indexed distance, address indexed committer ); event ActivityUpdated( string name, bytes32 activityKey, address oracle, bool allowed, bool exists); /****************** INTERNAL ACCOUNTING ******************/ mapping(bytes32 => Activity) public activities; // get Activity object based on activity key bytes32[] public activityKeyList; // List of activityKeys, used for indexing allowed activities mapping(address => Commitment) public commitments; // active commitments // address[] public userCommitments; // addresses with active commitments mapping(address => uint256) public committerBalances; // current token balances per user uint256 public totalCommitterBalance; // sum of current token balances uint256 public slashedBalance; //sum of all slashed balances mapping(bytes32 => address) public jobAddresses; // holds the address that ran the job /******** FUNCTIONS ********/ /// @notice Contract constructor used during deployment /// @param _activityList String list of activities reported by oracle /// @param _oracleAddress Address of oracle for activity data /// @param _daiToken Address of <dai token> contract /// @param _linkToken Address of <link token> contract /// @dev Configure token address, add activities to activities mapping by calling _addActivities method constructor( string[] memory _activityList, address _oracleAddress, address _daiToken, address _linkToken ) public { console.log("Constructor called for SinglePlayerCommit contract"); require(_activityList.length >= 1, "SPC::constructor - activityList empty"); token = IERC20(_daiToken); setChainlinkToken(_linkToken); _addActivities(_activityList, _oracleAddress); } // view functions /// @notice Get name string of activity based on key /// @param _activityKey Keccak256 hashed, encoded name of activity /// @dev Lookup in mapping and get name field function getActivityName(bytes32 _activityKey) public view returns (string memory activityName) { return activities[_activityKey].name; } // other public functions /// @notice Deposit amount of <token> into contract /// @param amount Size of deposit /// @dev Transfer amount to <token> contract, update balance, emit event function deposit(uint256 amount) public returns (bool success) { console.log("Received call for depositing amount %s from sender %s", amount, msg.sender); require( token.transferFrom(msg.sender, address(this), amount), "SPC::deposit - token transfer failed" ); _changeCommitterBalance(msg.sender, amount, true); emit Deposit(msg.sender, amount); return true; } /// @notice Public function to withdraw unstaked balance of user /// @param amount Amount of <token> to withdraw /// @dev Check balances and active stake, withdraw from balances, emit event function withdraw(uint256 amount) public returns (bool success) { console.log("Received call for withdrawing amount %s from sender %s", amount, msg.sender); uint256 available = committerBalances[msg.sender]; Commitment storage commitment = commitments[msg.sender]; if(commitment.exists == true){ available = available.sub(commitment.stake); } require(amount <= available, "SPC::withdraw - not enough (unstaked) balance available"); _changeCommitterBalance(msg.sender, amount, false); require(token.transfer(msg.sender, amount), "SPC::withdraw - token transfer failed"); emit Withdrawal(msg.sender, amount); return true; } /// @notice Create commitment, store on-chain and emit event /// @param _activityKey Keccak256 hashed, encoded name of activity /// @param _goalValue Distance of activity as goal /// @param _startTime Unix timestamp in seconds to set commitment starting time /// @param _endTime Unix timestamp in seconds to set commitment deadline /// @param _stake Amount of <token> to stake againt achieving goal /// @param _userId ??? /// @dev Check parameters, create commitment, store on-chain and emit event function makeCommitment( bytes32 _activityKey, uint256 _goalValue, uint256 _startTime, uint256 _endTime, uint256 _stake, string memory _userId ) public returns (bool success) { console.log("makeCommitment called by %s", msg.sender); require(!commitments[msg.sender].exists, "SPC::makeCommitment - msg.sender already has a commitment"); require(activities[_activityKey].allowed, "SPC::makeCommitment - activity doesn't exist or isn't allowed"); require(_endTime > _startTime, "SPC::makeCommitment - endTime before startTime"); require(_goalValue > 1, "SPC::makeCommitment - goal is too low"); require(committerBalances[msg.sender] >= _stake, "SPC::makeCommitment - insufficient token balance"); Commitment memory commitment = Commitment({ committer: msg.sender, activityKey: _activityKey, goalValue: _goalValue, startTime: _startTime, endTime: _endTime, stake: _stake, reportedValue: 0, lastActivityUpdate: 0, met: false, userId: _userId, exists: true }); commitments[msg.sender] = commitment; emit NewCommitment(msg.sender, activities[_activityKey].name, _goalValue, _startTime, _endTime, _stake); return true; } /// @notice Wrapper function to deposit <token> and create commitment in one call /// @param _activityKey Keccak256 hashed, encoded name of activity /// @param _goalValue Distance of activity as goal /// @param _startTime Unix timestamp in seconds to set commitment starting time /// @param _endTime Unix timestamp in seconds to set commitment deadline /// @param _stake Amount of <token> to stake againt achieving goale /// @param _depositAmount Size of deposit /// @param _userId ??? /// @dev Call deposit and makeCommitment method function depositAndCommit( bytes32 _activityKey, uint256 _goalValue, uint256 _startTime, uint256 _endTime, uint256 _stake, uint256 _depositAmount, string memory _userId ) public returns (bool success) { require(deposit(_depositAmount), "SPC::depositAndCommit - deposit failed"); require( makeCommitment(_activityKey, _goalValue, _startTime, _endTime, _stake, _userId), "SPC::depositAndCommit - commitment creation failed" ); return true; } // /// @notice Enables processing of open commitments after endDate that have not been processed by creator // /// @param committer address of the creator of the committer to process // /// @dev Process commitment by lookup based on address, checking metrics, state and updating balances // function processCommitment(address committer) public { // console.log("Processing commitment"); // require(commitments[committer].exists, "SPC::processCommitment - commitment does not exist"); // Commitment storage commitment = commitments[committer]; // require(commitment.endTime < block.timestamp, "SPC::processCommitment - commitment is still active"); // require(commitment.endTime < commitment.lastActivityUpdate, "SPC::processCommitment - update activity"); // require(_settleCommitment(commitment), "SPC::processCommitmentUser - settlement failed"); // emit CommitmentEnded(committer, commitment.met, commitment.stake); // } /// @notice Enables control of processing own commitment. For instance when completed. /// @dev Process commitment by lookup msg.sender, checking metrics, state and updating balances function processCommitmentUser() public { console.log("Processing commitment"); require(commitments[msg.sender].exists, "SPC::processCommitmentUser - commitment does not exist"); Commitment storage commitment = commitments[msg.sender]; require(_settleCommitment(commitment), "SPC::processCommitmentUser - settlement failed"); emit CommitmentEnded(msg.sender, commitment.met, commitment.stake); } /// @notice Internal function for evaluating commitment and slashing funds if needed /// @dev Receive call with commitment object from storage function _settleCommitment(Commitment storage commitment) internal returns (bool success) { console.log("Settling commitment"); commitment.met = commitment.reportedValue >= commitment.goalValue; commitment.exists = false; commitment.met ? withdraw(commitment.stake) : _slashFunds(commitment.stake, msg.sender); return true; } /// @notice Contract owner can withdraw funds not owned by committers. E.g. slashed from failed commitments /// @param amount Amount of <token> to withdraw /// @dev Check amount against slashedBalance, transfer amount and update slashedBalance function ownerWithdraw(uint256 amount) public onlyOwner returns (bool success) { console.log("Received call for owner withdrawal for amount %s", amount); require(amount <= slashedBalance, "SPC::ownerWithdraw - not enough available balance"); slashedBalance = slashedBalance.sub(amount); require(token.transfer(msg.sender, amount), "SPC::ownerWithdraw - token transfer failed"); return true; } /// @notice Internal function to update balance of caller and total balance /// @param amount Amount of <token> to deposit/withdraw /// @param add Boolean toggle to deposit or withdraw /// @dev Based on add param add or substract amount from msg.sender balance and total committerBalance function _changeCommitterBalance(address committer, uint256 amount, bool add) internal returns (bool success) { console.log("Changing committer balance"); if (add) { committerBalances[committer] = committerBalances[committer].add(amount); totalCommitterBalance = totalCommitterBalance.add(amount); } else { committerBalances[committer] = committerBalances[committer].sub(amount); totalCommitterBalance = totalCommitterBalance.sub(amount); } return true; } /// @notice Internal function to slash funds from user /// @param amount Amount of <token> to slash /// @param committer Address of committer /// @dev Substract amount from committer balance and add to slashedBalance function _slashFunds(uint256 amount, address committer) internal returns (bool success) { console.log("Slashing funds commitment"); require(committerBalances[committer] >= amount, "SPC::_slashFunds - funds not available"); _changeCommitterBalance(committer, amount, false); slashedBalance = slashedBalance.add(amount); return true; } // internal functions /// @notice Adds list of activities with oracle (i.e. datasource) to contract /// @param _activityList String list of activities reported by oracle /// @param oracleAddress Address of oracle for activity data /// @dev Basically just loops over _addActivity for list function _addActivities(string[] memory _activityList, address oracleAddress) internal { require(_activityList.length > 0, "SPC::_addActivities - list appears to be empty"); for (uint256 i = 0; i < _activityList.length; i++) { _addActivity(_activityList[i], oracleAddress); } console.log("All provided activities added"); } /// @notice Add activity to contract's activityKeyList /// @param _activityName String name of activity /// @param _oracleAddress Contract address of oracle /// @dev Create key from name, create activity, push to activityKeyList, return key function _addActivity(string memory _activityName, address _oracleAddress) internal returns (bytes32 activityKey) { bytes memory activityNameBytes = bytes(_activityName); require(activityNameBytes.length > 0, "SPC::_addActivity - _activityName empty"); bytes32 _activityKey = keccak256(abi.encode(_activityName)); Activity memory activity = Activity({ name: _activityName, oracle: _oracleAddress, allowed: true, exists: true }); console.log( "Registered activity %s", _activityName ); activities[_activityKey] = activity; activityKeyList.push(_activityKey); emit ActivityUpdated( activity.name, _activityKey, activity.oracle, activity.allowed, activity.exists); return _activityKey; } /// @notice Function to update oracle address of existing activity /// @param _activityKey Keccak256 hashed, encoded name of activity /// @param _oracleAddress Address of oracle for activity data /// @dev Check activity exists, update state, emit event function updateActivityOracle(bytes32 _activityKey, address _oracleAddress) public onlyOwner returns (bool success) { require(activities[_activityKey].exists, "SPC::_updateActivityOracle - activity does not exist"); Activity storage activity = activities[_activityKey]; activity.oracle = _oracleAddress; emit ActivityUpdated( activity.name, _activityKey, activity.oracle, activity.allowed, activity.exists ); return true; } /// @notice Function to update availability of activity of existing activity /// @param _activityKey Keccak256 hashed, encoded name of activity /// @param _allowed Toggle for allowing new commitments with activity /// @dev Check activity exists, update state, emit event function updateActivityAllowed(bytes32 _activityKey, bool _allowed) public onlyOwner returns (bool success) { require(activities[_activityKey].exists, "SPC::_updateActivityOracle - activity does not exist"); Activity storage activity = activities[_activityKey]; activity.allowed = _allowed; emit ActivityUpdated( activity.name, _activityKey, activity.oracle, activity.allowed, activity.exists ); return true; } /// @notice Function to 'delete' an existing activity. One way function, cannot be reversed. /// @param _activityKey Keccak256 hashed, encoded name of activity /// @dev Check activity exists, update state, emit event function disableActivity(bytes32 _activityKey) public onlyOwner returns (bool success) { require(activities[_activityKey].exists, "SPC::_updateActivityOracle - activity does not exist"); Activity storage activity = activities[_activityKey]; activity.exists = false; emit ActivityUpdated( activity.name, _activityKey, activity.oracle, activity.allowed, activity.exists ); return true; } //Chainlink functions /// @notice Call ChainLink node to report distance measured based on Strava data /// @param _committer Address of creator of commitment /// @param _oracle ChainLink oracle address /// @param _jobId ??? /// @dev Async function sending request to ChainLink node function requestActivityDistance(address _committer, address _oracle, string memory _jobId) public { Commitment memory commitment = commitments[_committer]; Chainlink.Request memory req = buildChainlinkRequest( stringToBytes32(_jobId), address(this), this.fulfillActivityDistance.selector ); req.add("type", activities[commitment.activityKey].name); req.add("startTime", uint2str(commitment.startTime)); req.add("endTime", uint2str(commitment.endTime)); req.add("userId", commitment.userId); bytes32 requestId = sendChainlinkRequestTo(_oracle, req, ORACLE_PAYMENT); jobAddresses[requestId] = _committer; } /// @notice Register distance reported by ChainLink node /// @param _requestId ID or request triggering the method call /// @param _distance Distance to register /// @dev Follow-up function to requestActivityDistance function fulfillActivityDistance(bytes32 _requestId, uint256 _distance) public recordChainlinkFulfillment(_requestId) { address userAddress = jobAddresses[_requestId]; emit RequestActivityDistanceFulfilled(_requestId, _distance, userAddress); commitments[userAddress].reportedValue = _distance; commitments[userAddress].lastActivityUpdate = block.timestamp; } /// @notice Get address for ChainLink token contract /// @dev ChainLink contract method function getChainlinkToken() public view returns (address tokenAddress) { return chainlinkTokenAddress(); } /// @notice Withdraw ChainLink token from contract to contract owner function withdrawLink() public onlyOwner { LinkTokenInterface link = LinkTokenInterface(chainlinkTokenAddress()); require(link.transfer(msg.sender, link.balanceOf(address(this))), "Unable to transfer"); } function cancelRequest( bytes32 _requestId, uint256 _payment, bytes4 _callbackFunctionId, uint256 _expiration ) public onlyOwner { cancelChainlinkRequest(_requestId, _payment, _callbackFunctionId, _expiration); } function stringToBytes32(string memory source) private pure returns (bytes32 result) { bytes memory tempEmptyStringTest = bytes(source); if (tempEmptyStringTest.length == 0) { return 0x0; } assembly { // solhint-disable-line no-inline-assembly result := mload(add(source, 32)) } } function uint2str(uint i) internal pure returns (string memory str){ if (i == 0) return "0"; uint j = i; uint length; while (j != 0){ length++; j /= 10; } bytes memory bstr = new bytes(length); uint k = length - 1; while (i != 0){ bstr[k--] = byte(uint8(48 + i % 10)); i /= 10; } return string(bstr); } function addDays(uint256 amountOfDays, uint256 startDate) internal pure returns (uint256 updatedDate) { return (startDate + amountOfDays * 1 days); } }
as reported by oracle
uint256 reportedValue;
1,060,780
[ 1, 345, 14010, 635, 20865, 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, 3639, 2254, 5034, 14010, 620, 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 ]
// 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; import "../../utils/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: 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: 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: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IIntegrationManager interface /// @author Enzyme Council <[email protected]> /// @notice Interface for the IntegrationManager interface IIntegrationManager { enum SpendAssetsHandleType {None, Approve, Transfer, Remove} } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../IIntegrationManager.sol"; /// @title Integration Adapter interface /// @author Enzyme Council <[email protected]> /// @notice Interface for all integration adapters interface IIntegrationAdapter { function identifier() external pure returns (string memory identifier_); function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ); } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.6.12; import "../utils/actions/CurveGaugeV2RewardsHandlerBase.sol"; import "../utils/actions/CurveSethLiquidityActionsMixin.sol"; import "../utils/actions/UniswapV2ActionsMixin.sol"; import "../utils/AdapterBase2.sol"; /// @title CurveLiquiditySethAdapter Contract /// @author Enzyme Council <[email protected]> /// @notice Adapter for liquidity provision in Curve's seth pool (https://www.curve.fi/seth) /// @dev Rewards tokens are not included as spend assets or incoming assets for claimRewards() /// or claimRewardsAndReinvest(). Rationale: /// - rewards tokens can be claimed to the vault outside of the IntegrationManager, so no need /// to enforce policy management or emit an event /// - rewards tokens can be outside of the asset universe, in which case they cannot be tracked /// This adapter will need to be re-deployed if UniswapV2 low liquidity becomes /// a concern for rewards tokens when using claimRewardsAndReinvest(). contract CurveLiquiditySethAdapter is AdapterBase2, CurveGaugeV2RewardsHandlerBase, CurveSethLiquidityActionsMixin, UniswapV2ActionsMixin { address private immutable LIQUIDITY_GAUGE_TOKEN; address private immutable LP_TOKEN; address private immutable SETH_TOKEN; constructor( address _integrationManager, address _liquidityGaugeToken, address _lpToken, address _minter, address _pool, address _crvToken, address _sethToken, address _wethToken, address _uniswapV2Router2 ) public AdapterBase2(_integrationManager) CurveGaugeV2RewardsHandlerBase(_minter, _crvToken) CurveSethLiquidityActionsMixin(_pool, _sethToken, _wethToken) UniswapV2ActionsMixin(_uniswapV2Router2) { LIQUIDITY_GAUGE_TOKEN = _liquidityGaugeToken; LP_TOKEN = _lpToken; SETH_TOKEN = _sethToken; // Max approve contracts to spend relevant tokens ERC20(_lpToken).safeApprove(_liquidityGaugeToken, type(uint256).max); } /// @dev Needed to receive ETH from redemption and to unwrap WETH receive() external payable {} // EXTERNAL FUNCTIONS /// @notice Provides a constant string identifier for an adapter /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "CURVE_LIQUIDITY_SETH"; } /// @notice Approves assets from the vault to be used by this contract. /// @dev No logic necessary. Exists only to grant adapter with necessary approvals from the vault, /// which takes place in the IntegrationManager. function approveAssets( address, bytes calldata, bytes calldata ) external {} /// @notice Claims rewards from the Curve Minter as well as pool-specific rewards /// @param _vaultProxy The VaultProxy of the calling fund function claimRewards( address _vaultProxy, bytes calldata, bytes calldata ) external onlyIntegrationManager { __curveGaugeV2ClaimAllRewards(LIQUIDITY_GAUGE_TOKEN, _vaultProxy); } /// @notice Claims rewards and then compounds the rewards tokens back into the staked LP token /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @dev Requires the adapter to be granted an allowance of each reward token by the vault. /// For supported assets (e.g., CRV), this must be done via the `approveAssets()` function in this adapter. /// For unsupported assets, this must be done via `ComptrollerProxy.vaultCallOnContract()`. /// The `useFullBalances` option indicates whether to use only the newly claimed balances of /// rewards tokens, or whether to use the full balances of these assets in the vault. function claimRewardsAndReinvest( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager postActionIncomingAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { ( bool useFullBalances, uint256 minIncomingLiquidityGaugeTokenAmount ) = __decodeClaimRewardsAndReinvestCallArgs(_encodedCallArgs); ( address[] memory rewardsTokens, uint256[] memory rewardsTokenAmountsToUse ) = __curveGaugeV2ClaimRewardsAndPullBalances( LIQUIDITY_GAUGE_TOKEN, _vaultProxy, useFullBalances ); // Swap all reward tokens to WETH via UniswapV2. // Note that if a reward token takes a fee on transfer, // we could not use these memory balances. __uniswapV2SwapManyToOne( address(this), rewardsTokens, rewardsTokenAmountsToUse, getCurveSethLiquidityWethToken(), address(0) ); // Lend all received WETH for staked LP tokens uint256 wethBalance = ERC20(getCurveSethLiquidityWethToken()).balanceOf(address(this)); if (wethBalance > 0) { __curveSethLend(wethBalance, 0, minIncomingLiquidityGaugeTokenAmount); __curveGaugeV2Stake( LIQUIDITY_GAUGE_TOKEN, LP_TOKEN, ERC20(LP_TOKEN).balanceOf(address(this)) ); } } /// @notice Claims rewards and then swaps the rewards tokens to the specified asset via UniswapV2 /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @dev Requires the adapter to be granted an allowance of each reward token by the vault. /// For supported assets (e.g., CRV), this must be done via the `approveAssets()` function in this adapter. /// For unsupported assets, this must be done via `ComptrollerProxy.vaultCallOnContract()`. /// The `useFullBalances` option indicates whether to use only the newly claimed balances of /// rewards tokens, or whether to use the full balances of these assets in the vault. function claimRewardsAndSwap( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata ) external onlyIntegrationManager { (bool useFullBalances, address incomingAsset, ) = __decodeClaimRewardsAndSwapCallArgs( _encodedCallArgs ); ( address[] memory rewardsTokens, uint256[] memory rewardsTokenAmountsToUse ) = __curveGaugeV2ClaimRewardsAndPullBalances( LIQUIDITY_GAUGE_TOKEN, _vaultProxy, useFullBalances ); // Swap all reward tokens to the designated incomingAsset via UniswapV2. // Note that if a reward token takes a fee on transfer, // we could not use these memory balances. __uniswapV2SwapManyToOne( _vaultProxy, rewardsTokens, rewardsTokenAmountsToUse, incomingAsset, getCurveSethLiquidityWethToken() ); } /// @notice Lends assets for seth LP tokens /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function lend( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager postActionIncomingAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { ( uint256 outgoingWethAmount, uint256 outgoingSethAmount, uint256 minIncomingLiquidityGaugeTokenAmount ) = __decodeLendCallArgs(_encodedCallArgs); __curveSethLend( outgoingWethAmount, outgoingSethAmount, minIncomingLiquidityGaugeTokenAmount ); } /// @notice Lends assets for seth LP tokens, then stakes the received LP tokens /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function lendAndStake( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager postActionIncomingAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { ( uint256 outgoingWethAmount, uint256 outgoingSethAmount, uint256 minIncomingLiquidityGaugeTokenAmount ) = __decodeLendCallArgs(_encodedCallArgs); __curveSethLend( outgoingWethAmount, outgoingSethAmount, minIncomingLiquidityGaugeTokenAmount ); __curveGaugeV2Stake( LIQUIDITY_GAUGE_TOKEN, LP_TOKEN, ERC20(LP_TOKEN).balanceOf(address(this)) ); } /// @notice Redeems seth LP tokens /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function redeem( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager postActionIncomingAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { ( uint256 outgoingLpTokenAmount, uint256 minIncomingWethAmount, uint256 minIncomingSethAmount, bool redeemSingleAsset ) = __decodeRedeemCallArgs(_encodedCallArgs); __curveSethRedeem( outgoingLpTokenAmount, minIncomingWethAmount, minIncomingSethAmount, redeemSingleAsset ); } /// @notice Stakes seth LP tokens /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function stake( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager postActionIncomingAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { __curveGaugeV2Stake( LIQUIDITY_GAUGE_TOKEN, LP_TOKEN, __decodeStakeCallArgs(_encodedCallArgs) ); } /// @notice Unstakes seth LP tokens /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function unstake( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager postActionIncomingAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { __curveGaugeV2Unstake(LIQUIDITY_GAUGE_TOKEN, __decodeUnstakeCallArgs(_encodedCallArgs)); } /// @notice Unstakes seth LP tokens, then redeems them /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function unstakeAndRedeem( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager postActionIncomingAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { ( uint256 outgoingLiquidityGaugeTokenAmount, uint256 minIncomingWethAmount, uint256 minIncomingSethAmount, bool redeemSingleAsset ) = __decodeRedeemCallArgs(_encodedCallArgs); __curveGaugeV2Unstake(LIQUIDITY_GAUGE_TOKEN, outgoingLiquidityGaugeTokenAmount); __curveSethRedeem( outgoingLiquidityGaugeTokenAmount, minIncomingWethAmount, minIncomingSethAmount, redeemSingleAsset ); } ///////////////////////////// // PARSE ASSETS FOR METHOD // ///////////////////////////// /// @notice Parses the expected assets to receive from a call on integration /// @param _selector The function selector for the callOnIntegration /// @param _encodedCallArgs The encoded parameters for the callOnIntegration /// @return spendAssetsHandleType_ A type that dictates how to handle granting /// the adapter access to spend assets (`None` by default) /// @return spendAssets_ The assets to spend in the call /// @return spendAssetAmounts_ The max asset amounts to spend in the call /// @return incomingAssets_ The assets to receive in the call /// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { if (_selector == APPROVE_ASSETS_SELECTOR) { return __parseAssetsForApproveAssets(_encodedCallArgs); } else if (_selector == CLAIM_REWARDS_SELECTOR) { return __parseAssetsForClaimRewards(); } else if (_selector == CLAIM_REWARDS_AND_REINVEST_SELECTOR) { return __parseAssetsForClaimRewardsAndReinvest(_encodedCallArgs); } else if (_selector == CLAIM_REWARDS_AND_SWAP_SELECTOR) { return __parseAssetsForClaimRewardsAndSwap(_encodedCallArgs); } else if (_selector == LEND_SELECTOR) { return __parseAssetsForLend(_encodedCallArgs); } else if (_selector == LEND_AND_STAKE_SELECTOR) { return __parseAssetsForLendAndStake(_encodedCallArgs); } else if (_selector == REDEEM_SELECTOR) { return __parseAssetsForRedeem(_encodedCallArgs); } else if (_selector == STAKE_SELECTOR) { return __parseAssetsForStake(_encodedCallArgs); } else if (_selector == UNSTAKE_SELECTOR) { return __parseAssetsForUnstake(_encodedCallArgs); } else if (_selector == UNSTAKE_AND_REDEEM_SELECTOR) { return __parseAssetsForUnstakeAndRedeem(_encodedCallArgs); } revert("parseAssetsForMethod: _selector invalid"); } /// @dev Helper function to parse spend and incoming assets from encoded call args /// during approveAssets() calls function __parseAssetsForApproveAssets(bytes calldata _encodedCallArgs) private view returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { (spendAssets_, spendAssetAmounts_) = __decodeApproveAssetsCallArgs(_encodedCallArgs); require( spendAssets_.length == spendAssetAmounts_.length, "__parseAssetsForApproveAssets: Unequal arrays" ); // Validate that only rewards tokens are given allowances address[] memory rewardsTokens = __curveGaugeV2GetRewardsTokensWithCrv( LIQUIDITY_GAUGE_TOKEN ); for (uint256 i; i < spendAssets_.length; i++) { // Allow revoking approval for any asset if (spendAssetAmounts_[i] > 0) { require( rewardsTokens.contains(spendAssets_[i]), "__parseAssetsForApproveAssets: Invalid reward token" ); } } return ( IIntegrationManager.SpendAssetsHandleType.Approve, spendAssets_, spendAssetAmounts_, new address[](0), new uint256[](0) ); } /// @dev Helper function to parse spend and incoming assets from encoded call args /// during claimRewards() calls. /// No action required, all values empty. function __parseAssetsForClaimRewards() private pure returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { return ( IIntegrationManager.SpendAssetsHandleType.None, new address[](0), new uint256[](0), new address[](0), new uint256[](0) ); } /// @dev Helper function to parse spend and incoming assets from encoded call args /// during claimRewardsAndReinvest() calls. function __parseAssetsForClaimRewardsAndReinvest(bytes calldata _encodedCallArgs) private view returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { (, uint256 minIncomingLiquidityGaugeTokenAmount) = __decodeClaimRewardsAndReinvestCallArgs( _encodedCallArgs ); incomingAssets_ = new address[](1); incomingAssets_[0] = LIQUIDITY_GAUGE_TOKEN; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minIncomingLiquidityGaugeTokenAmount; return ( IIntegrationManager.SpendAssetsHandleType.None, new address[](0), new uint256[](0), incomingAssets_, minIncomingAssetAmounts_ ); } /// @dev Helper function to parse spend and incoming assets from encoded call args /// during claimRewardsAndSwap() calls. function __parseAssetsForClaimRewardsAndSwap(bytes calldata _encodedCallArgs) private pure returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { ( , address incomingAsset, uint256 minIncomingAssetAmount ) = __decodeClaimRewardsAndSwapCallArgs(_encodedCallArgs); incomingAssets_ = new address[](1); incomingAssets_[0] = incomingAsset; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minIncomingAssetAmount; return ( IIntegrationManager.SpendAssetsHandleType.None, new address[](0), new uint256[](0), incomingAssets_, minIncomingAssetAmounts_ ); } /// @dev Helper function to parse spend and incoming assets from encoded call args /// during lend() calls function __parseAssetsForLend(bytes calldata _encodedCallArgs) private view returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { ( uint256 outgoingWethAmount, uint256 outgoingSethAmount, uint256 minIncomingLpTokenAmount ) = __decodeLendCallArgs(_encodedCallArgs); (spendAssets_, spendAssetAmounts_) = __parseSpendAssetsForLendingCalls( outgoingWethAmount, outgoingSethAmount ); incomingAssets_ = new address[](1); incomingAssets_[0] = LP_TOKEN; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minIncomingLpTokenAmount; return ( IIntegrationManager.SpendAssetsHandleType.Transfer, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @dev Helper function to parse spend and incoming assets from encoded call args /// during lendAndStake() calls function __parseAssetsForLendAndStake(bytes calldata _encodedCallArgs) private view returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { ( uint256 outgoingWethAmount, uint256 outgoingSethAmount, uint256 minIncomingLiquidityGaugeTokenAmount ) = __decodeLendCallArgs(_encodedCallArgs); (spendAssets_, spendAssetAmounts_) = __parseSpendAssetsForLendingCalls( outgoingWethAmount, outgoingSethAmount ); incomingAssets_ = new address[](1); incomingAssets_[0] = LIQUIDITY_GAUGE_TOKEN; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minIncomingLiquidityGaugeTokenAmount; return ( IIntegrationManager.SpendAssetsHandleType.Transfer, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @dev Helper function to parse spend and incoming assets from encoded call args /// during redeem() calls function __parseAssetsForRedeem(bytes calldata _encodedCallArgs) private view returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { ( uint256 outgoingLpTokenAmount, uint256 minIncomingWethAmount, uint256 minIncomingSethAmount, bool receiveSingleAsset ) = __decodeRedeemCallArgs(_encodedCallArgs); spendAssets_ = new address[](1); spendAssets_[0] = LP_TOKEN; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingLpTokenAmount; (incomingAssets_, minIncomingAssetAmounts_) = __parseIncomingAssetsForRedemptionCalls( minIncomingWethAmount, minIncomingSethAmount, receiveSingleAsset ); return ( IIntegrationManager.SpendAssetsHandleType.Transfer, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @dev Helper function to parse spend and incoming assets from encoded call args /// during stake() calls function __parseAssetsForStake(bytes calldata _encodedCallArgs) private view returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { uint256 outgoingLpTokenAmount = __decodeStakeCallArgs(_encodedCallArgs); spendAssets_ = new address[](1); spendAssets_[0] = LP_TOKEN; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingLpTokenAmount; incomingAssets_ = new address[](1); incomingAssets_[0] = LIQUIDITY_GAUGE_TOKEN; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = outgoingLpTokenAmount; return ( IIntegrationManager.SpendAssetsHandleType.Transfer, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @dev Helper function to parse spend and incoming assets from encoded call args /// during unstake() calls function __parseAssetsForUnstake(bytes calldata _encodedCallArgs) private view returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { uint256 outgoingLiquidityGaugeTokenAmount = __decodeUnstakeCallArgs(_encodedCallArgs); spendAssets_ = new address[](1); spendAssets_[0] = LIQUIDITY_GAUGE_TOKEN; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingLiquidityGaugeTokenAmount; incomingAssets_ = new address[](1); incomingAssets_[0] = LP_TOKEN; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = outgoingLiquidityGaugeTokenAmount; return ( IIntegrationManager.SpendAssetsHandleType.Transfer, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @dev Helper function to parse spend and incoming assets from encoded call args /// during unstakeAndRedeem() calls function __parseAssetsForUnstakeAndRedeem(bytes calldata _encodedCallArgs) private view returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { ( uint256 outgoingLiquidityGaugeTokenAmount, uint256 minIncomingWethAmount, uint256 minIncomingSethAmount, bool receiveSingleAsset ) = __decodeRedeemCallArgs(_encodedCallArgs); spendAssets_ = new address[](1); spendAssets_[0] = LIQUIDITY_GAUGE_TOKEN; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingLiquidityGaugeTokenAmount; (incomingAssets_, minIncomingAssetAmounts_) = __parseIncomingAssetsForRedemptionCalls( minIncomingWethAmount, minIncomingSethAmount, receiveSingleAsset ); return ( IIntegrationManager.SpendAssetsHandleType.Transfer, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @dev Helper function to parse spend assets for redeem() and unstakeAndRedeem() calls function __parseIncomingAssetsForRedemptionCalls( uint256 _minIncomingWethAmount, uint256 _minIncomingSethAmount, bool _receiveSingleAsset ) private view returns (address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_) { if (_receiveSingleAsset) { incomingAssets_ = new address[](1); minIncomingAssetAmounts_ = new uint256[](1); if (_minIncomingWethAmount == 0) { require( _minIncomingSethAmount > 0, "__parseIncomingAssetsForRedemptionCalls: No min asset amount specified" ); incomingAssets_[0] = SETH_TOKEN; minIncomingAssetAmounts_[0] = _minIncomingSethAmount; } else { require( _minIncomingSethAmount == 0, "__parseIncomingAssetsForRedemptionCalls: Too many min asset amounts specified" ); incomingAssets_[0] = getCurveSethLiquidityWethToken(); minIncomingAssetAmounts_[0] = _minIncomingWethAmount; } } else { incomingAssets_ = new address[](2); incomingAssets_[0] = getCurveSethLiquidityWethToken(); incomingAssets_[1] = SETH_TOKEN; minIncomingAssetAmounts_ = new uint256[](2); minIncomingAssetAmounts_[0] = _minIncomingWethAmount; minIncomingAssetAmounts_[1] = _minIncomingSethAmount; } return (incomingAssets_, minIncomingAssetAmounts_); } /// @dev Helper function to parse spend assets for lend() and lendAndStake() calls function __parseSpendAssetsForLendingCalls( uint256 _outgoingWethAmount, uint256 _outgoingSethAmount ) private view returns (address[] memory spendAssets_, uint256[] memory spendAssetAmounts_) { if (_outgoingWethAmount > 0 && _outgoingSethAmount > 0) { spendAssets_ = new address[](2); spendAssets_[0] = getCurveSethLiquidityWethToken(); spendAssets_[1] = SETH_TOKEN; spendAssetAmounts_ = new uint256[](2); spendAssetAmounts_[0] = _outgoingWethAmount; spendAssetAmounts_[1] = _outgoingSethAmount; } else if (_outgoingWethAmount > 0) { spendAssets_ = new address[](1); spendAssets_[0] = getCurveSethLiquidityWethToken(); spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = _outgoingWethAmount; } else { spendAssets_ = new address[](1); spendAssets_[0] = SETH_TOKEN; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = _outgoingSethAmount; } return (spendAssets_, spendAssetAmounts_); } /////////////////////// // ENCODED CALL ARGS // /////////////////////// /// @dev Helper to decode the encoded call arguments for approving asset allowances function __decodeApproveAssetsCallArgs(bytes memory _encodedCallArgs) private pure returns (address[] memory assets_, uint256[] memory amounts_) { return abi.decode(_encodedCallArgs, (address[], uint256[])); } /// @dev Helper to decode the encoded call arguments for claiming rewards function __decodeClaimRewardsAndReinvestCallArgs(bytes memory _encodedCallArgs) private pure returns (bool useFullBalances_, uint256 minIncomingLiquidityGaugeTokenAmount_) { return abi.decode(_encodedCallArgs, (bool, uint256)); } /// @dev Helper to decode the encoded call arguments for claiming rewards and swapping function __decodeClaimRewardsAndSwapCallArgs(bytes memory _encodedCallArgs) private pure returns ( bool useFullBalances_, address incomingAsset_, uint256 minIncomingAssetAmount_ ) { return abi.decode(_encodedCallArgs, (bool, address, uint256)); } /// @dev Helper to decode the encoded call arguments for lending function __decodeLendCallArgs(bytes memory _encodedCallArgs) private pure returns ( uint256 outgoingWethAmount_, uint256 outgoingSethAmount_, uint256 minIncomingAssetAmount_ ) { return abi.decode(_encodedCallArgs, (uint256, uint256, uint256)); } /// @dev Helper to decode the encoded call arguments for redeeming. /// If `receiveSingleAsset_` is `true`, then one (and only one) of /// `minIncomingWethAmount_` and `minIncomingSethAmount_` must be >0 /// to indicate which asset is to be received. function __decodeRedeemCallArgs(bytes memory _encodedCallArgs) private pure returns ( uint256 outgoingAssetAmount_, uint256 minIncomingWethAmount_, uint256 minIncomingSethAmount_, bool receiveSingleAsset_ ) { return abi.decode(_encodedCallArgs, (uint256, uint256, uint256, bool)); } /// @dev Helper to decode the encoded call arguments for staking function __decodeStakeCallArgs(bytes memory _encodedCallArgs) private pure returns (uint256 outgoingLpTokenAmount_) { return abi.decode(_encodedCallArgs, (uint256)); } /// @dev Helper to decode the encoded call arguments for unstaking function __decodeUnstakeCallArgs(bytes memory _encodedCallArgs) private pure returns (uint256 outgoingLiquidityGaugeTokenAmount_) { return abi.decode(_encodedCallArgs, (uint256)); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `LIQUIDITY_GAUGE_TOKEN` variable /// @return liquidityGaugeToken_ The `LIQUIDITY_GAUGE_TOKEN` variable value function getLiquidityGaugeToken() external view returns (address liquidityGaugeToken_) { return LIQUIDITY_GAUGE_TOKEN; } /// @notice Gets the `LP_TOKEN` variable /// @return lpToken_ The `LP_TOKEN` variable value function getLpToken() external view returns (address lpToken_) { return LP_TOKEN; } /// @notice Gets the `SETH_TOKEN` variable /// @return sethToken_ The `SETH_TOKEN` variable value function getSethToken() external view returns (address sethToken_) { return SETH_TOKEN; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../IIntegrationAdapter.sol"; import "./IntegrationSelectors.sol"; /// @title AdapterBase Contract /// @author Enzyme Council <[email protected]> /// @notice A base contract for integration adapters abstract contract AdapterBase is IIntegrationAdapter, IntegrationSelectors { using SafeERC20 for ERC20; address internal immutable INTEGRATION_MANAGER; /// @dev Provides a standard implementation for transferring assets between /// the fund's VaultProxy and the adapter, by wrapping the adapter action. /// This modifier should be implemented in almost all adapter actions, unless they /// do not move assets or can spend and receive assets directly with the VaultProxy modifier fundAssetsTransferHandler( address _vaultProxy, bytes memory _encodedAssetTransferArgs ) { ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType, address[] memory spendAssets, uint256[] memory spendAssetAmounts, address[] memory incomingAssets ) = __decodeEncodedAssetTransferArgs(_encodedAssetTransferArgs); // Take custody of spend assets (if necessary) if (spendAssetsHandleType == IIntegrationManager.SpendAssetsHandleType.Approve) { for (uint256 i = 0; i < spendAssets.length; i++) { ERC20(spendAssets[i]).safeTransferFrom( _vaultProxy, address(this), spendAssetAmounts[i] ); } } // Execute call _; // Transfer remaining assets back to the fund's VaultProxy __transferContractAssetBalancesToFund(_vaultProxy, incomingAssets); __transferContractAssetBalancesToFund(_vaultProxy, spendAssets); } modifier onlyIntegrationManager { require( msg.sender == INTEGRATION_MANAGER, "Only the IntegrationManager can call this function" ); _; } constructor(address _integrationManager) public { INTEGRATION_MANAGER = _integrationManager; } // INTERNAL FUNCTIONS /// @dev Helper for adapters to approve their integratees with the max amount of an asset. /// Since everything is done atomically, and only the balances to-be-used are sent to adapters, /// there is no need to approve exact amounts on every call. function __approveMaxAsNeeded( address _asset, address _target, uint256 _neededAmount ) internal { if (ERC20(_asset).allowance(address(this), _target) < _neededAmount) { ERC20(_asset).safeApprove(_target, type(uint256).max); } } /// @dev Helper to decode the _encodedAssetTransferArgs param passed to adapter call function __decodeEncodedAssetTransferArgs(bytes memory _encodedAssetTransferArgs) internal pure returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_ ) { return abi.decode( _encodedAssetTransferArgs, (IIntegrationManager.SpendAssetsHandleType, address[], uint256[], address[]) ); } /// @dev Helper to transfer full contract balances of assets to the specified VaultProxy function __transferContractAssetBalancesToFund(address _vaultProxy, address[] memory _assets) private { for (uint256 i = 0; i < _assets.length; i++) { uint256 postCallAmount = ERC20(_assets[i]).balanceOf(address(this)); if (postCallAmount > 0) { ERC20(_assets[i]).safeTransfer(_vaultProxy, postCallAmount); } } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `INTEGRATION_MANAGER` variable /// @return integrationManager_ The `INTEGRATION_MANAGER` variable value function getIntegrationManager() external view returns (address integrationManager_) { return INTEGRATION_MANAGER; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./AdapterBase.sol"; /// @title AdapterBase2 Contract /// @author Enzyme Council <[email protected]> /// @notice A base contract for integration adapters that extends AdapterBase /// @dev This is a temporary contract that will be merged into AdapterBase with the next release abstract contract AdapterBase2 is AdapterBase { /// @dev Provides a standard implementation for transferring incoming assets and /// unspent spend assets from an adapter to a VaultProxy at the end of an adapter action modifier postActionAssetsTransferHandler( address _vaultProxy, bytes memory _encodedAssetTransferArgs ) { _; ( , address[] memory spendAssets, , address[] memory incomingAssets ) = __decodeEncodedAssetTransferArgs(_encodedAssetTransferArgs); __transferFullAssetBalances(_vaultProxy, incomingAssets); __transferFullAssetBalances(_vaultProxy, spendAssets); } /// @dev Provides a standard implementation for transferring incoming assets /// from an adapter to a VaultProxy at the end of an adapter action modifier postActionIncomingAssetsTransferHandler( address _vaultProxy, bytes memory _encodedAssetTransferArgs ) { _; (, , , address[] memory incomingAssets) = __decodeEncodedAssetTransferArgs( _encodedAssetTransferArgs ); __transferFullAssetBalances(_vaultProxy, incomingAssets); } /// @dev Provides a standard implementation for transferring unspent spend assets /// from an adapter to a VaultProxy at the end of an adapter action modifier postActionSpendAssetsTransferHandler( address _vaultProxy, bytes memory _encodedAssetTransferArgs ) { _; (, address[] memory spendAssets, , ) = __decodeEncodedAssetTransferArgs( _encodedAssetTransferArgs ); __transferFullAssetBalances(_vaultProxy, spendAssets); } constructor(address _integrationManager) public AdapterBase(_integrationManager) {} /// @dev Helper to transfer full asset balances of current contract to the specified target function __transferFullAssetBalances(address _target, address[] memory _assets) internal { for (uint256 i = 0; i < _assets.length; i++) { uint256 balance = ERC20(_assets[i]).balanceOf(address(this)); if (balance > 0) { ERC20(_assets[i]).safeTransfer(_target, balance); } } } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IntegrationSelectors Contract /// @author Enzyme Council <[email protected]> /// @notice Selectors for integration actions /// @dev Selectors are created from their signatures rather than hardcoded for easy verification abstract contract IntegrationSelectors { bytes4 public constant ADD_TRACKED_ASSETS_SELECTOR = bytes4( keccak256("addTrackedAssets(address,bytes,bytes)") ); // Asset approval bytes4 public constant APPROVE_ASSETS_SELECTOR = bytes4( keccak256("approveAssets(address,bytes,bytes)") ); // Trading bytes4 public constant TAKE_ORDER_SELECTOR = bytes4( keccak256("takeOrder(address,bytes,bytes)") ); // Lending bytes4 public constant LEND_SELECTOR = bytes4(keccak256("lend(address,bytes,bytes)")); bytes4 public constant REDEEM_SELECTOR = bytes4(keccak256("redeem(address,bytes,bytes)")); // Staking bytes4 public constant STAKE_SELECTOR = bytes4(keccak256("stake(address,bytes,bytes)")); bytes4 public constant UNSTAKE_SELECTOR = bytes4(keccak256("unstake(address,bytes,bytes)")); // Rewards bytes4 public constant CLAIM_REWARDS_SELECTOR = bytes4( keccak256("claimRewards(address,bytes,bytes)") ); // Combined bytes4 public constant CLAIM_REWARDS_AND_REINVEST_SELECTOR = bytes4( keccak256("claimRewardsAndReinvest(address,bytes,bytes)") ); bytes4 public constant CLAIM_REWARDS_AND_SWAP_SELECTOR = bytes4( keccak256("claimRewardsAndSwap(address,bytes,bytes)") ); bytes4 public constant LEND_AND_STAKE_SELECTOR = bytes4( keccak256("lendAndStake(address,bytes,bytes)") ); bytes4 public constant UNSTAKE_AND_REDEEM_SELECTOR = bytes4( keccak256("unstakeAndRedeem(address,bytes,bytes)") ); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../../interfaces/ICurveLiquidityGaugeV2.sol"; import "../../../../../utils/AssetHelpers.sol"; /// @title CurveGaugeV2ActionsMixin Contract /// @author Enzyme Council <[email protected]> /// @notice Mixin contract for interacting with any Curve LiquidityGaugeV2 contract abstract contract CurveGaugeV2ActionsMixin is AssetHelpers { uint256 private constant CURVE_GAUGE_V2_MAX_REWARDS = 8; /// @dev Helper to claim pool-specific rewards function __curveGaugeV2ClaimRewards(address _gauge, address _target) internal { ICurveLiquidityGaugeV2(_gauge).claim_rewards(_target); } /// @dev Helper to get list of pool-specific rewards tokens function __curveGaugeV2GetRewardsTokens(address _gauge) internal view returns (address[] memory rewardsTokens_) { address[] memory lpRewardsTokensWithEmpties = new address[](CURVE_GAUGE_V2_MAX_REWARDS); uint256 rewardsTokensCount; for (uint256 i; i < CURVE_GAUGE_V2_MAX_REWARDS; i++) { address rewardToken = ICurveLiquidityGaugeV2(_gauge).reward_tokens(i); if (rewardToken != address(0)) { lpRewardsTokensWithEmpties[i] = rewardToken; rewardsTokensCount++; } else { break; } } rewardsTokens_ = new address[](rewardsTokensCount); for (uint256 i; i < rewardsTokensCount; i++) { rewardsTokens_[i] = lpRewardsTokensWithEmpties[i]; } return rewardsTokens_; } /// @dev Helper to stake LP tokens function __curveGaugeV2Stake( address _gauge, address _lpToken, uint256 _amount ) internal { __approveAssetMaxAsNeeded(_lpToken, _gauge, _amount); ICurveLiquidityGaugeV2(_gauge).deposit(_amount, address(this)); } /// @dev Helper to unstake LP tokens function __curveGaugeV2Unstake(address _gauge, uint256 _amount) internal { ICurveLiquidityGaugeV2(_gauge).withdraw(_amount); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../../interfaces/ICurveMinter.sol"; import "../../../../../utils/AddressArrayLib.sol"; import "./CurveGaugeV2ActionsMixin.sol"; /// @title CurveGaugeV2RewardsHandlerBase Contract /// @author Enzyme Council <[email protected]> /// @notice Base contract for handling claiming and reinvesting rewards for a Curve pool /// that uses the LiquidityGaugeV2 contract abstract contract CurveGaugeV2RewardsHandlerBase is CurveGaugeV2ActionsMixin { using AddressArrayLib for address[]; address private immutable CURVE_GAUGE_V2_REWARDS_HANDLER_CRV_TOKEN; address private immutable CURVE_GAUGE_V2_REWARDS_HANDLER_MINTER; constructor(address _minter, address _crvToken) public { CURVE_GAUGE_V2_REWARDS_HANDLER_CRV_TOKEN = _crvToken; CURVE_GAUGE_V2_REWARDS_HANDLER_MINTER = _minter; } /// @dev Helper to claim all rewards (CRV and pool-specific). /// Requires contract to be approved to use mint_for(). function __curveGaugeV2ClaimAllRewards(address _gauge, address _target) internal { // Claim owed $CRV ICurveMinter(CURVE_GAUGE_V2_REWARDS_HANDLER_MINTER).mint_for(_gauge, _target); // Claim owed pool-specific rewards __curveGaugeV2ClaimRewards(_gauge, _target); } /// @dev Helper to claim all rewards, then pull either the newly claimed balances only, /// or full vault balances into the current contract function __curveGaugeV2ClaimRewardsAndPullBalances( address _gauge, address _target, bool _useFullBalances ) internal returns (address[] memory rewardsTokens_, uint256[] memory rewardsTokenAmountsPulled_) { if (_useFullBalances) { return __curveGaugeV2ClaimRewardsAndPullFullBalances(_gauge, _target); } return __curveGaugeV2ClaimRewardsAndPullClaimedBalances(_gauge, _target); } /// @dev Helper to claim all rewards, then pull only the newly claimed balances /// of all rewards tokens into the current contract function __curveGaugeV2ClaimRewardsAndPullClaimedBalances(address _gauge, address _target) internal returns (address[] memory rewardsTokens_, uint256[] memory rewardsTokenAmountsPulled_) { rewardsTokens_ = __curveGaugeV2GetRewardsTokensWithCrv(_gauge); uint256[] memory rewardsTokenPreClaimBalances = new uint256[](rewardsTokens_.length); for (uint256 i; i < rewardsTokens_.length; i++) { rewardsTokenPreClaimBalances[i] = ERC20(rewardsTokens_[i]).balanceOf(_target); } __curveGaugeV2ClaimAllRewards(_gauge, _target); rewardsTokenAmountsPulled_ = __pullPartialAssetBalances( _target, rewardsTokens_, rewardsTokenPreClaimBalances ); return (rewardsTokens_, rewardsTokenAmountsPulled_); } /// @dev Helper to claim all rewards, then pull the full balances of all rewards tokens /// in the target into the current contract function __curveGaugeV2ClaimRewardsAndPullFullBalances(address _gauge, address _target) internal returns (address[] memory rewardsTokens_, uint256[] memory rewardsTokenAmountsPulled_) { __curveGaugeV2ClaimAllRewards(_gauge, _target); rewardsTokens_ = __curveGaugeV2GetRewardsTokensWithCrv(_gauge); rewardsTokenAmountsPulled_ = __pullFullAssetBalances(_target, rewardsTokens_); return (rewardsTokens_, rewardsTokenAmountsPulled_); } /// @dev Helper to get all rewards tokens for staking LP tokens function __curveGaugeV2GetRewardsTokensWithCrv(address _gauge) internal view returns (address[] memory rewardsTokens_) { return __curveGaugeV2GetRewardsTokens(_gauge).addUniqueItem( CURVE_GAUGE_V2_REWARDS_HANDLER_CRV_TOKEN ); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `CURVE_GAUGE_V2_REWARDS_HANDLER_CRV_TOKEN` variable /// @return crvToken_ The `CURVE_GAUGE_V2_REWARDS_HANDLER_CRV_TOKEN` variable value function getCurveGaugeV2RewardsHandlerCrvToken() public view returns (address crvToken_) { return CURVE_GAUGE_V2_REWARDS_HANDLER_CRV_TOKEN; } /// @notice Gets the `CURVE_GAUGE_V2_REWARDS_HANDLER_MINTER` variable /// @return minter_ The `CURVE_GAUGE_V2_REWARDS_HANDLER_MINTER` variable value function getCurveGaugeV2RewardsHandlerMinter() public view returns (address minter_) { return CURVE_GAUGE_V2_REWARDS_HANDLER_MINTER; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../../../../../interfaces/ICurveStableSwapSeth.sol"; import "../../../../../interfaces/IWETH.sol"; /// @title CurveSethLiquidityActionsMixin Contract /// @author Enzyme Council <[email protected]> /// @notice Mixin contract for interacting with the Curve seth pool's liquidity functions /// @dev Inheriting contract must have a receive() function abstract contract CurveSethLiquidityActionsMixin { using SafeERC20 for ERC20; int128 private constant CURVE_SETH_POOL_INDEX_ETH = 0; int128 private constant CURVE_SETH_POOL_INDEX_SETH = 1; address private immutable CURVE_SETH_LIQUIDITY_POOL; address private immutable CURVE_SETH_LIQUIDITY_WETH_TOKEN; constructor( address _pool, address _sethToken, address _wethToken ) public { CURVE_SETH_LIQUIDITY_POOL = _pool; CURVE_SETH_LIQUIDITY_WETH_TOKEN = _wethToken; // Pre-approve pool to use max of seth token ERC20(_sethToken).safeApprove(_pool, type(uint256).max); } /// @dev Helper to add liquidity to the pool function __curveSethLend( uint256 _outgoingWethAmount, uint256 _outgoingSethAmount, uint256 _minIncomingLPTokenAmount ) internal { if (_outgoingWethAmount > 0) { IWETH((CURVE_SETH_LIQUIDITY_WETH_TOKEN)).withdraw(_outgoingWethAmount); } ICurveStableSwapSeth(CURVE_SETH_LIQUIDITY_POOL).add_liquidity{value: _outgoingWethAmount}( [_outgoingWethAmount, _outgoingSethAmount], _minIncomingLPTokenAmount ); } /// @dev Helper to remove liquidity from the pool. // Assumes that if _redeemSingleAsset is true, then // "_minIncomingWethAmount > 0 XOR _minIncomingSethAmount > 0" has already been validated. function __curveSethRedeem( uint256 _outgoingLPTokenAmount, uint256 _minIncomingWethAmount, uint256 _minIncomingSethAmount, bool _redeemSingleAsset ) internal { if (_redeemSingleAsset) { if (_minIncomingWethAmount > 0) { ICurveStableSwapSeth(CURVE_SETH_LIQUIDITY_POOL).remove_liquidity_one_coin( _outgoingLPTokenAmount, CURVE_SETH_POOL_INDEX_ETH, _minIncomingWethAmount ); IWETH(payable(CURVE_SETH_LIQUIDITY_WETH_TOKEN)).deposit{ value: payable(address(this)).balance }(); } else { ICurveStableSwapSeth(CURVE_SETH_LIQUIDITY_POOL).remove_liquidity_one_coin( _outgoingLPTokenAmount, CURVE_SETH_POOL_INDEX_SETH, _minIncomingSethAmount ); } } else { ICurveStableSwapSeth(CURVE_SETH_LIQUIDITY_POOL).remove_liquidity( _outgoingLPTokenAmount, [_minIncomingWethAmount, _minIncomingSethAmount] ); IWETH(payable(CURVE_SETH_LIQUIDITY_WETH_TOKEN)).deposit{ value: payable(address(this)).balance }(); } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `CURVE_SETH_LIQUIDITY_POOL` variable /// @return pool_ The `CURVE_SETH_LIQUIDITY_POOL` variable value function getCurveSethLiquidityPool() public view returns (address pool_) { return CURVE_SETH_LIQUIDITY_POOL; } /// @notice Gets the `CURVE_SETH_LIQUIDITY_WETH_TOKEN` variable /// @return wethToken_ The `CURVE_SETH_LIQUIDITY_WETH_TOKEN` variable value function getCurveSethLiquidityWethToken() public view returns (address wethToken_) { return CURVE_SETH_LIQUIDITY_WETH_TOKEN; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../../interfaces/IUniswapV2Router2.sol"; import "../../../../../utils/AssetHelpers.sol"; /// @title UniswapV2ActionsMixin Contract /// @author Enzyme Council <[email protected]> /// @notice Mixin contract for interacting with Uniswap v2 abstract contract UniswapV2ActionsMixin is AssetHelpers { address private immutable UNISWAP_V2_ROUTER2; constructor(address _router) public { UNISWAP_V2_ROUTER2 = _router; } // EXTERNAL FUNCTIONS /// @dev Helper to add liquidity function __uniswapV2Lend( address _recipient, address _tokenA, address _tokenB, uint256 _amountADesired, uint256 _amountBDesired, uint256 _amountAMin, uint256 _amountBMin ) internal { __approveAssetMaxAsNeeded(_tokenA, UNISWAP_V2_ROUTER2, _amountADesired); __approveAssetMaxAsNeeded(_tokenB, UNISWAP_V2_ROUTER2, _amountBDesired); // Execute lend on Uniswap IUniswapV2Router2(UNISWAP_V2_ROUTER2).addLiquidity( _tokenA, _tokenB, _amountADesired, _amountBDesired, _amountAMin, _amountBMin, _recipient, __uniswapV2GetActionDeadline() ); } /// @dev Helper to remove liquidity function __uniswapV2Redeem( address _recipient, address _poolToken, uint256 _poolTokenAmount, address _tokenA, address _tokenB, uint256 _amountAMin, uint256 _amountBMin ) internal { __approveAssetMaxAsNeeded(_poolToken, UNISWAP_V2_ROUTER2, _poolTokenAmount); // Execute redeem on Uniswap IUniswapV2Router2(UNISWAP_V2_ROUTER2).removeLiquidity( _tokenA, _tokenB, _poolTokenAmount, _amountAMin, _amountBMin, _recipient, __uniswapV2GetActionDeadline() ); } /// @dev Helper to execute a swap function __uniswapV2Swap( address _recipient, uint256 _outgoingAssetAmount, uint256 _minIncomingAssetAmount, address[] memory _path ) internal { __approveAssetMaxAsNeeded(_path[0], UNISWAP_V2_ROUTER2, _outgoingAssetAmount); // Execute fill IUniswapV2Router2(UNISWAP_V2_ROUTER2).swapExactTokensForTokens( _outgoingAssetAmount, _minIncomingAssetAmount, _path, _recipient, __uniswapV2GetActionDeadline() ); } /// @dev Helper to swap many assets to a single target asset. /// The intermediary asset will generally be WETH, and though we could make it // per-outgoing asset, seems like overkill until there is a need. function __uniswapV2SwapManyToOne( address _recipient, address[] memory _outgoingAssets, uint256[] memory _outgoingAssetAmounts, address _incomingAsset, address _intermediaryAsset ) internal { bool noIntermediary = _intermediaryAsset == address(0) || _intermediaryAsset == _incomingAsset; for (uint256 i; i < _outgoingAssets.length; i++) { // Skip cases where outgoing and incoming assets are the same, or // there is no specified outgoing asset or amount if ( _outgoingAssetAmounts[i] == 0 || _outgoingAssets[i] == address(0) || _outgoingAssets[i] == _incomingAsset ) { continue; } address[] memory uniswapPath; if (noIntermediary || _outgoingAssets[i] == _intermediaryAsset) { uniswapPath = new address[](2); uniswapPath[0] = _outgoingAssets[i]; uniswapPath[1] = _incomingAsset; } else { uniswapPath = new address[](3); uniswapPath[0] = _outgoingAssets[i]; uniswapPath[1] = _intermediaryAsset; uniswapPath[2] = _incomingAsset; } __uniswapV2Swap(_recipient, _outgoingAssetAmounts[i], 1, uniswapPath); } } /// @dev Helper to get the deadline for a Uniswap V2 action in a standardized way function __uniswapV2GetActionDeadline() private view returns (uint256 deadline_) { return block.timestamp + 1; } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `UNISWAP_V2_ROUTER2` variable /// @return router_ The `UNISWAP_V2_ROUTER2` variable value function getUniswapV2Router2() public view returns (address router_) { return UNISWAP_V2_ROUTER2; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ICurveLiquidityGaugeV2 interface /// @author Enzyme Council <[email protected]> interface ICurveLiquidityGaugeV2 { function claim_rewards(address) external; function deposit(uint256, address) external; function reward_tokens(uint256) external view returns (address); function withdraw(uint256) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ICurveMinter interface /// @author Enzyme Council <[email protected]> interface ICurveMinter { function mint_for(address, address) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ICurveStableSwapSeth interface /// @author Enzyme Council <[email protected]> interface ICurveStableSwapSeth { function add_liquidity(uint256[2] calldata, uint256) external payable returns (uint256); function remove_liquidity(uint256, uint256[2] calldata) external returns (uint256[2] memory); function remove_liquidity_one_coin( uint256, int128, uint256 ) external returns (uint256); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title UniswapV2Router2 Interface /// @author Enzyme Council <[email protected]> /// @dev Minimal interface for our interactions with Uniswap V2's Router2 interface IUniswapV2Router2 { function addLiquidity( address, address, uint256, uint256, uint256, uint256, address, uint256 ) external returns ( uint256, uint256, uint256 ); function removeLiquidity( address, address, uint256, uint256, uint256, address, uint256 ) external returns (uint256, uint256); function swapExactTokensForTokens( uint256, uint256, address[] calldata, address, uint256 ) external returns (uint256[] memory); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title WETH Interface /// @author Enzyme Council <[email protected]> interface IWETH { function deposit() external payable; function withdraw(uint256) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title AddressArray Library /// @author Enzyme Council <[email protected]> /// @notice A library to extend the address array data type library AddressArrayLib { /// @dev Helper to add an item to an array. Does not assert uniqueness of the new item. function addItem(address[] memory _self, address _itemToAdd) internal pure returns (address[] memory nextArray_) { nextArray_ = new address[](_self.length + 1); for (uint256 i; i < _self.length; i++) { nextArray_[i] = _self[i]; } nextArray_[_self.length] = _itemToAdd; return nextArray_; } /// @dev Helper to add an item to an array, only if it is not already in the array. function addUniqueItem(address[] memory _self, address _itemToAdd) internal pure returns (address[] memory nextArray_) { if (contains(_self, _itemToAdd)) { return _self; } return addItem(_self, _itemToAdd); } /// @dev Helper to verify if an array contains a particular value function contains(address[] memory _self, address _target) internal pure returns (bool doesContain_) { for (uint256 i; i < _self.length; i++) { if (_target == _self[i]) { return true; } } return false; } /// @dev Helper to reassign all items in an array with a specified value function fill(address[] memory _self, address _value) internal pure returns (address[] memory nextArray_) { nextArray_ = new address[](_self.length); for (uint256 i; i < nextArray_.length; i++) { nextArray_[i] = _value; } return nextArray_; } /// @dev Helper to verify if array is a set of unique values. /// Does not assert length > 0. function isUniqueSet(address[] memory _self) internal pure returns (bool isUnique_) { if (_self.length <= 1) { return true; } uint256 arrayLength = _self.length; for (uint256 i; i < arrayLength; i++) { for (uint256 j = i + 1; j < arrayLength; j++) { if (_self[i] == _self[j]) { return false; } } } return true; } /// @dev Helper to remove items from an array. Removes all matching occurrences of each item. /// Does not assert uniqueness of either array. function removeItems(address[] memory _self, address[] memory _itemsToRemove) internal pure returns (address[] memory nextArray_) { if (_itemsToRemove.length == 0) { return _self; } bool[] memory indexesToRemove = new bool[](_self.length); uint256 remainingItemsCount = _self.length; for (uint256 i; i < _self.length; i++) { if (contains(_itemsToRemove, _self[i])) { indexesToRemove[i] = true; remainingItemsCount--; } } if (remainingItemsCount == _self.length) { nextArray_ = _self; } else if (remainingItemsCount > 0) { nextArray_ = new address[](remainingItemsCount); uint256 nextArrayIndex; for (uint256 i; i < _self.length; i++) { if (!indexesToRemove[i]) { nextArray_[nextArrayIndex] = _self[i]; nextArrayIndex++; } } } return nextArray_; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; /// @title AssetHelpers Contract /// @author Enzyme Council <[email protected]> /// @notice A util contract for common token actions abstract contract AssetHelpers { using SafeERC20 for ERC20; using SafeMath for uint256; /// @dev Helper to approve a target account with the max amount of an asset. /// This is helpful for fully trusted contracts, such as adapters that /// interact with external protocol like Uniswap, Compound, etc. function __approveAssetMaxAsNeeded( address _asset, address _target, uint256 _neededAmount ) internal { if (ERC20(_asset).allowance(address(this), _target) < _neededAmount) { ERC20(_asset).safeApprove(_target, type(uint256).max); } } /// @dev Helper to get the balances of specified assets for a target function __getAssetBalances(address _target, address[] memory _assets) internal view returns (uint256[] memory balances_) { balances_ = new uint256[](_assets.length); for (uint256 i; i < _assets.length; i++) { balances_[i] = ERC20(_assets[i]).balanceOf(_target); } return balances_; } /// @dev Helper to transfer full asset balances from a target to the current contract. /// Requires an adequate allowance for each asset granted to the current contract for the target. function __pullFullAssetBalances(address _target, address[] memory _assets) internal returns (uint256[] memory amountsTransferred_) { amountsTransferred_ = new uint256[](_assets.length); for (uint256 i; i < _assets.length; i++) { ERC20 assetContract = ERC20(_assets[i]); amountsTransferred_[i] = assetContract.balanceOf(_target); if (amountsTransferred_[i] > 0) { assetContract.safeTransferFrom(_target, address(this), amountsTransferred_[i]); } } return amountsTransferred_; } /// @dev Helper to transfer partial asset balances from a target to the current contract. /// Requires an adequate allowance for each asset granted to the current contract for the target. function __pullPartialAssetBalances( address _target, address[] memory _assets, uint256[] memory _amountsToExclude ) internal returns (uint256[] memory amountsTransferred_) { amountsTransferred_ = new uint256[](_assets.length); for (uint256 i; i < _assets.length; i++) { ERC20 assetContract = ERC20(_assets[i]); amountsTransferred_[i] = assetContract.balanceOf(_target).sub(_amountsToExclude[i]); if (amountsTransferred_[i] > 0) { assetContract.safeTransferFrom(_target, address(this), amountsTransferred_[i]); } } return amountsTransferred_; } /// @dev Helper to transfer full asset balances from the current contract to a target function __pushFullAssetBalances(address _target, address[] memory _assets) internal returns (uint256[] memory amountsTransferred_) { amountsTransferred_ = new uint256[](_assets.length); for (uint256 i; i < _assets.length; i++) { ERC20 assetContract = ERC20(_assets[i]); amountsTransferred_[i] = assetContract.balanceOf(address(this)); if (amountsTransferred_[i] > 0) { assetContract.safeTransfer(_target, amountsTransferred_[i]); } } return amountsTransferred_; } }
@notice Lends assets for seth LP tokens, then stakes the received LP tokens @param _vaultProxy The VaultProxy of the calling fund @param _encodedCallArgs Encoded order parameters @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive
function lendAndStake( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager postActionIncomingAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { ( uint256 outgoingWethAmount, uint256 outgoingSethAmount, uint256 minIncomingLiquidityGaugeTokenAmount ) = __decodeLendCallArgs(_encodedCallArgs); __curveSethLend( outgoingWethAmount, outgoingSethAmount, minIncomingLiquidityGaugeTokenAmount ); __curveGaugeV2Stake( LIQUIDITY_GAUGE_TOKEN, LP_TOKEN, ERC20(LP_TOKEN).balanceOf(address(this)) ); }
5,831,032
[ 1, 48, 5839, 7176, 364, 444, 76, 511, 52, 2430, 16, 1508, 384, 3223, 326, 5079, 511, 52, 2430, 225, 389, 26983, 3886, 1021, 17329, 3886, 434, 326, 4440, 284, 1074, 225, 389, 10787, 1477, 2615, 23306, 1353, 1472, 225, 389, 10787, 6672, 5912, 2615, 23306, 833, 364, 2665, 7176, 358, 17571, 471, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 328, 409, 1876, 510, 911, 12, 203, 3639, 1758, 389, 26983, 3886, 16, 203, 3639, 1731, 745, 892, 389, 10787, 1477, 2615, 16, 203, 3639, 1731, 745, 892, 389, 10787, 6672, 5912, 2615, 203, 565, 262, 203, 3639, 3903, 203, 3639, 1338, 15372, 1318, 203, 3639, 1603, 1803, 20370, 10726, 5912, 1503, 24899, 26983, 3886, 16, 389, 10787, 6672, 5912, 2615, 13, 203, 565, 288, 203, 3639, 261, 203, 5411, 2254, 5034, 12902, 59, 546, 6275, 16, 203, 5411, 2254, 5034, 12902, 55, 546, 6275, 16, 203, 5411, 2254, 5034, 1131, 20370, 48, 18988, 24237, 18941, 1345, 6275, 203, 3639, 262, 273, 1001, 3922, 48, 409, 1477, 2615, 24899, 10787, 1477, 2615, 1769, 203, 203, 3639, 1001, 16683, 55, 546, 48, 409, 12, 203, 5411, 12902, 59, 546, 6275, 16, 203, 5411, 12902, 55, 546, 6275, 16, 203, 5411, 1131, 20370, 48, 18988, 24237, 18941, 1345, 6275, 203, 3639, 11272, 203, 3639, 1001, 16683, 18941, 58, 22, 510, 911, 12, 203, 5411, 8961, 53, 3060, 4107, 67, 43, 27738, 67, 8412, 16, 203, 5411, 511, 52, 67, 8412, 16, 203, 5411, 4232, 39, 3462, 12, 14461, 67, 8412, 2934, 12296, 951, 12, 2867, 12, 2211, 3719, 203, 3639, 11272, 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 ]
./partial_match/1/0xF13e21653AEB763595D5E4baA1dC115689Da49b9/sources/contracts/lib/ERC20Token.sol
* @dev Decrease the amount of tokens that an owner allowed to a spender. approve should be called when allowed[_spender] == 0. To decrement allowed value is better to use this function to avoid 2 calls (and wait until the first transaction is mined) From MonolithDAO Token.sol @param _spender The address which will spend the funds. @param _subtractedValue The amount of tokens to decrease the allowance by./
function decreaseApproval( address _spender, uint _subtractedValue ) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; }
4,025,461
[ 1, 23326, 448, 326, 3844, 434, 2430, 716, 392, 3410, 2935, 358, 279, 17571, 264, 18, 6617, 537, 1410, 506, 2566, 1347, 2935, 63, 67, 87, 1302, 264, 65, 422, 374, 18, 2974, 15267, 2935, 460, 353, 7844, 358, 999, 333, 445, 358, 4543, 576, 4097, 261, 464, 2529, 3180, 326, 1122, 2492, 353, 1131, 329, 13, 6338, 9041, 355, 483, 18485, 3155, 18, 18281, 225, 389, 87, 1302, 264, 1021, 1758, 1492, 903, 17571, 326, 284, 19156, 18, 225, 389, 1717, 1575, 329, 620, 1021, 3844, 434, 2430, 358, 20467, 326, 1699, 1359, 635, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 20467, 23461, 12, 203, 3639, 1758, 389, 87, 1302, 264, 16, 203, 3639, 2254, 565, 389, 1717, 1575, 329, 620, 203, 3639, 262, 203, 3639, 1071, 203, 3639, 1135, 261, 6430, 13, 203, 565, 288, 203, 3639, 2254, 11144, 273, 2935, 63, 3576, 18, 15330, 6362, 67, 87, 1302, 264, 15533, 203, 3639, 309, 261, 67, 1717, 1575, 329, 620, 405, 11144, 13, 288, 203, 5411, 2935, 63, 3576, 18, 15330, 6362, 67, 87, 1302, 264, 65, 273, 374, 31, 203, 5411, 2935, 63, 3576, 18, 15330, 6362, 67, 87, 1302, 264, 65, 273, 11144, 18, 1717, 24899, 1717, 1575, 329, 620, 1769, 203, 3639, 289, 203, 3639, 3626, 1716, 685, 1125, 12, 3576, 18, 15330, 16, 389, 87, 1302, 264, 16, 2935, 63, 3576, 18, 15330, 6362, 67, 87, 1302, 264, 19226, 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 ]
./partial_match/42/0xce75428062389938C67b1B29bddb4d2AB51172c4/sources/Dollar.sol
* @dev Storage slot with the address of the current implementation. This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is validated in the constructor./* @dev Emitted when the implementation is upgraded. @param implementation Address of the new implementation./
function initialize() public { require(!_state.isInitialized, "already initialized"); }
3,409,361
[ 1, 3245, 4694, 598, 326, 1758, 434, 326, 783, 4471, 18, 1220, 353, 326, 417, 24410, 581, 17, 5034, 1651, 434, 315, 73, 625, 3657, 9599, 18, 5656, 18, 30810, 6, 10418, 329, 635, 404, 16, 471, 353, 10266, 316, 326, 3885, 18, 19, 225, 512, 7948, 1347, 326, 4471, 353, 31049, 18, 225, 4471, 5267, 434, 326, 394, 4471, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 4046, 1435, 1071, 288, 203, 3639, 2583, 12, 5, 67, 2019, 18, 291, 11459, 16, 315, 17583, 6454, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.24; contract RSEvents { // fired whenever a player registers a name event onNewName ( uint256 indexed playerID, address indexed playerAddress, bytes32 indexed playerName, bool isNewPlayer, uint256 affiliateID, address affiliateAddress, bytes32 affiliateName, uint256 amountPaid, uint256 timeStamp ); // fired at end of buy or reload event onEndTx ( uint256 compressedData, uint256 compressedIDs, bytes32 playerName, address playerAddress, uint256 ethIn, uint256 keysBought, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 genAmount, uint256 potAmount, uint256 airDropPot ); // fired whenever theres a withdraw event onWithdraw ( uint256 indexed playerID, address playerAddress, bytes32 playerName, uint256 ethOut, uint256 timeStamp ); // fired whenever a withdraw forces end round to be ran event onWithdrawAndDistribute ( address playerAddress, bytes32 playerName, uint256 ethOut, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 genAmount ); // fired whenever a player tries a buy after round timer // hit zero, and causes end round to be ran. event onBuyAndDistribute ( address playerAddress, bytes32 playerName, uint256 ethIn, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 genAmount ); // fired whenever a player tries a reload after round timer // hit zero, and causes end round to be ran. event onReLoadAndDistribute ( address playerAddress, bytes32 playerName, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 genAmount ); // fired whenever an affiliate is paid event onAffiliatePayout ( uint256 indexed affiliateID, address affiliateAddress, bytes32 affiliateName, uint256 indexed buyerID, uint256 amount, uint256 timeStamp ); } contract modularRatScam is RSEvents {} contract RatScam is modularRatScam { using SafeMath for *; using NameFilter for string; using RSKeysCalc for uint256; RatBookInterface constant private RatBook = RatBookInterface(0x3257d637B8977781B4f8178365858A474b2A6195); string constant public name = "RatScam In One Hour"; string constant public symbol = "RS"; uint256 private rndGap_ = 0; uint256 private rndInit_ = 1 hours; // round timer starts at this uint256 private rndInc_ = 30 seconds; // every full key purchased adds this much to the timer uint256 private rndMax_ = 1 hours; // max length a round timer can be //============================================================================== // _| _ _|_ _ _ _ _|_ _ . // (_|(_| | (_| _\(/_ | |_||_) . (data used to store game info that changes) //=============================|================================================ uint256 public airDropPot_; // person who gets the airdrop wins part of this pot uint256 public airDropTracker_ = 0; // incremented each time a "qualified" tx occurs. used to determine winning air drop uint256 public rID_; // round id number / total rounds that have happened //**************** // PLAYER DATA //**************** address private adminAddress; mapping (address => uint256) public pIDxAddr_; // (addr => pID) returns player id by address mapping (bytes32 => uint256) public pIDxName_; // (name => pID) returns player id by name mapping (uint256 => RSdatasets.Player) public plyr_; // (pID => data) player data mapping (uint256 => mapping (uint256 => RSdatasets.PlayerRounds)) public plyrRnds_; // (pID => rID => data) player round data by player id & round id mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_; // (pID => name => bool) list of names a player owns. (used so you can change your display name amongst any name you own) //**************** // ROUND DATA //**************** //RSdatasets.Round public round_; // round data mapping (uint256 => RSdatasets.Round) public round_; // (rID => data) round data //**************** // TEAM FEE DATA //**************** uint256 public fees_ = 60; // fee distribution uint256 public potSplit_ = 45; // pot split distribution //============================================================================== // _ _ _ __|_ _ __|_ _ _ . // (_(_)| |_\ | | |_|(_ | (_)| . (initial data setup upon contract deploy) //============================================================================== constructor() public { adminAddress = msg.sender; } //============================================================================== // _ _ _ _|. |`. _ _ _ . // | | |(_)(_||~|~|(/_| _\ . (these are safety checks) //============================================================================== /** * @dev used to make sure no one can interact with contract until it has * been activated. */ modifier isActivated() { require(activated_ == true, "its not ready yet"); _; } /** * @dev prevents contracts from interacting with ratscam */ modifier isHuman() { address _addr = msg.sender; uint256 _codeLength; assembly {_codeLength := extcodesize(_addr)} require(_codeLength == 0, "non smart contract address only"); _; } /** * @dev sets boundaries for incoming tx */ modifier isWithinLimits(uint256 _eth) { require(_eth >= 1000000000, "too little money"); require(_eth <= 100000000000000000000000, "too much money"); _; } //============================================================================== // _ |_ |. _ |` _ __|_. _ _ _ . // |_)|_||_)||(_ ~|~|_|| |(_ | |(_)| |_\ . (use these to interact with contract) //====|========================================================================= /** * @dev emergency buy uses last stored affiliate ID and team snek */ function() isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not RSdatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // buy core buyCore(_pID, plyr_[_pID].laff, _eventData_); } /** * @dev converts all incoming ethereum to keys. * -functionhash- 0x8f38f309 (using ID for affiliate) * -functionhash- 0x98a0871d (using address for affiliate) * -functionhash- 0xa65b37a1 (using name for affiliate) * @param _affCode the ID/address/name of the player who gets the affiliate fee */ function buyXid(uint256 _affCode) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not RSdatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz if (_affCode == 0 || _affCode == _pID) { // use last stored affiliate code _affCode = plyr_[_pID].laff; // if affiliate code was given & its not the same as previously stored } else if (_affCode != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affCode; } // buy core buyCore(_pID, _affCode, _eventData_); } function buyXaddr(address _affCode) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not RSdatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == address(0) || _affCode == msg.sender) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxAddr_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // buy core buyCore(_pID, _affID, _eventData_); } function buyXname(bytes32 _affCode) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not RSdatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == '' || _affCode == plyr_[_pID].name) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxName_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // buy core buyCore(_pID, _affID, _eventData_); } /** * @dev essentially the same as buy, but instead of you sending ether * from your wallet, it uses your unwithdrawn earnings. * -functionhash- 0x349cdcac (using ID for affiliate) * -functionhash- 0x82bfc739 (using address for affiliate) * -functionhash- 0x079ce327 (using name for affiliate) * @param _affCode the ID/address/name of the player who gets the affiliate fee * @param _eth amount of earnings to use (remainder returned to gen vault) */ function reLoadXid(uint256 _affCode, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data RSdatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz if (_affCode == 0 || _affCode == _pID) { // use last stored affiliate code _affCode = plyr_[_pID].laff; // if affiliate code was given & its not the same as previously stored } else if (_affCode != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affCode; } // reload core reLoadCore(_pID, _affCode, _eth, _eventData_); } function reLoadXaddr(address _affCode, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data RSdatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == address(0) || _affCode == msg.sender) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxAddr_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // reload core reLoadCore(_pID, _affID, _eth, _eventData_); } function reLoadXname(bytes32 _affCode, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data RSdatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == '' || _affCode == plyr_[_pID].name) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxName_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // reload core reLoadCore(_pID, _affID, _eth, _eventData_); } /** * @dev withdraws all of your earnings. * -functionhash- 0x3ccfd60b */ function withdraw() isActivated() isHuman() public { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // setup temp var for player eth uint256 _eth; // check to see if round has ended and no one has run round end yet if (_now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) { // set up our tx event data RSdatasets.EventReturns memory _eventData_; // end the round (distributes pot) round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // get their earnings _eth = withdrawEarnings(_pID); // gib moni if (_eth > 0) plyr_[_pID].addr.transfer(_eth); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire withdraw and distribute event emit RSEvents.onWithdrawAndDistribute ( msg.sender, plyr_[_pID].name, _eth, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.genAmount ); // in any other situation } else { // get their earnings _eth = withdrawEarnings(_pID); // gib moni if (_eth > 0) plyr_[_pID].addr.transfer(_eth); // fire withdraw event emit RSEvents.onWithdraw(_pID, msg.sender, plyr_[_pID].name, _eth, _now); } } /** * @dev use these to register names. they are just wrappers that will send the * registration requests to the PlayerBook contract. So registering here is the * same as registering there. UI will always display the last name you registered. * but you will still own all previously registered names to use as affiliate * links. * - must pay a registration fee. * - name must be unique * - names will be converted to lowercase * - name cannot start or end with a space * - cannot have more than 1 space in a row * - cannot be only numbers * - cannot start with 0x * - name must be at least 1 char * - max length of 32 characters long * - allowed characters: a-z, 0-9, and space * -functionhash- 0x921dec21 (using ID for affiliate) * -functionhash- 0x3ddd4698 (using address for affiliate) * -functionhash- 0x685ffd83 (using name for affiliate) * @param _nameString players desired name * @param _affCode affiliate ID, address, or name of who referred you * @param _all set to true if you want this to push your info to all games * (this might cost a lot of gas) */ function registerNameXID(string _nameString, uint256 _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = RatBook.registerNameXIDFromDapp.value(_paid)(_addr, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit RSEvents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } function registerNameXaddr(string _nameString, address _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = RatBook.registerNameXaddrFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit RSEvents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } function registerNameXname(string _nameString, bytes32 _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = RatBook.registerNameXnameFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit RSEvents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } //============================================================================== // _ _ _|__|_ _ _ _ . // (_|(/_ | | (/_| _\ . (for UI & viewing things on etherscan) //=====_|======================================================================= /** * @dev return the price buyer will pay for next 1 individual key. * -functionhash- 0x018a25e8 * @return price for next key bought (in wei format) */ function getBuyPrice() public view returns(uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // are we in a round? if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( (round_[_rID].keys.add(1000000000000000000)).ethRec(1000000000000000000) ); else // rounds over. need price for new round return ( 75000000000000 ); // init } /** * @dev returns time left. dont spam this, you'll ddos yourself from your node * provider * -functionhash- 0xc7e284b8 * @return time left in seconds */ function getTimeLeft() public view returns(uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; if (_now < round_[_rID].end) if (_now > round_[_rID].strt + rndGap_) return( (round_[_rID].end).sub(_now) ); else return( (round_[_rID].strt + rndGap_).sub(_now)); else return(0); } /** * @dev returns player earnings per vaults * -functionhash- 0x63066434 * @return winnings vault * @return general vault * @return affiliate vault */ function getPlayerVaults(uint256 _pID) public view returns(uint256 ,uint256, uint256) { // setup local rID uint256 _rID = rID_; // if round has ended. but round end has not been run (so contract has not distributed winnings) if (now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) { // if player is winner if (round_[_rID].plyr == _pID) { return ( (plyr_[_pID].win).add( ((round_[_rID].pot).mul(48)) / 100 ), (plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ), plyr_[_pID].aff ); // if player is not the winner } else { return ( plyr_[_pID].win, (plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ), plyr_[_pID].aff ); } // if round is still going on, or round has ended and round end has been ran } else { return ( plyr_[_pID].win, (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), plyr_[_pID].aff ); } } /** * solidity hates stack limits. this lets us avoid that hate */ function getPlayerVaultsHelper(uint256 _pID, uint256 _rID) private view returns(uint256) { return( ((((round_[_rID].mask).add(((((round_[_rID].pot).mul(potSplit_)) / 100).mul(1000000000000000000)) / (round_[_rID].keys))).mul(plyrRnds_[_pID][_rID].keys)) / 1000000000000000000) ); } /** * @dev returns all current round info needed for front end * -functionhash- 0x747dff42 * @return total keys * @return time ends * @return time started * @return current pot * @return current player ID in lead * @return current player in leads address * @return current player in leads name * @return airdrop tracker # & airdrop pot */ function getCurrentRoundInfo() public view returns(uint256, uint256, uint256, uint256, uint256, address, bytes32, uint256) { // setup local rID uint256 _rID = rID_; return ( round_[rID_].keys, //0 round_[rID_].end, //1 round_[rID_].strt, //2 round_[rID_].pot, //3 round_[rID_].plyr, //4 plyr_[round_[rID_].plyr].addr, //5 plyr_[round_[rID_].plyr].name, //6 airDropTracker_ + (airDropPot_ * 1000) //7 ); } /** * @dev returns player info based on address. if no address is given, it will * use msg.sender * -functionhash- 0xee0b5d8b * @param _addr address of the player you want to lookup * @return player ID * @return player name * @return keys owned (current round) * @return winnings vault * @return general vault * @return affiliate vault * @return player round eth */ function getPlayerInfoByAddress(address _addr) public view returns(uint256, bytes32, uint256, uint256, uint256, uint256, uint256) { // setup local rID uint256 _rID = rID_; if (_addr == address(0)) { _addr == msg.sender; } uint256 _pID = pIDxAddr_[_addr]; return ( _pID, //0 plyr_[_pID].name, //1 plyrRnds_[_pID][_rID].keys, //2 plyr_[_pID].win, //3 (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), //4 plyr_[_pID].aff, //5 plyrRnds_[_pID][_rID].eth //6 ); } //============================================================================== // _ _ _ _ | _ _ . _ . // (_(_)| (/_ |(_)(_||(_ . (this + tools + calcs + modules = our softwares engine) //=====================_|======================================================= /** * @dev logic runs whenever a buy order is executed. determines how to handle * incoming eth depending on if we are in an active round or not */ function buyCore(uint256 _pID, uint256 _affID, RSdatasets.EventReturns memory _eventData_) private { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // if round is end, fire endRound if (_now > round_[_rID].end && round_[_rID].ended == false) { // end the round (distributes pot) & start new round round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire buy and distribute event emit RSEvents.onBuyAndDistribute ( msg.sender, plyr_[_pID].name, msg.value, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.genAmount ); } _rID = rID_; core(_rID, _pID, msg.value, _affID, _eventData_); } /** * @dev logic runs whenever a reload order is executed. determines how to handle * incoming eth depending on if we are in an active round or not */ function reLoadCore(uint256 _pID, uint256 _affID, uint256 _eth, RSdatasets.EventReturns memory _eventData_) private { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // if round is end, fire endRound if (_now > round_[_rID].end && round_[_rID].ended == false) { // end the round (distributes pot) & start new round round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire buy and distribute event emit RSEvents.onBuyAndDistribute ( msg.sender, plyr_[_pID].name, msg.value, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.genAmount ); } // get earnings from all vaults and return unused to gen vault // because we use a custom safemath library. this will throw if player // tried to spend more eth than they have. plyr_[_pID].gen = withdrawEarnings(_pID).sub(_eth); // call core core( _rID, _pID, _eth, _affID, _eventData_); } /** * @dev this is the core logic for any buy/reload that happens while a round * is live. */ function core(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, RSdatasets.EventReturns memory _eventData_) private { // if player is new to round if (plyrRnds_[_pID][_rID].keys == 0) _eventData_ = managePlayer(_pID, _eventData_); // early round eth limiter if (round_[_rID].eth < 100000000000000000000 && plyrRnds_[_pID][_rID].eth.add(_eth) > 10000000000000000000) { uint256 _availableLimit = (10000000000000000000).sub(plyrRnds_[_pID][_rID].eth); uint256 _refund = _eth.sub(_availableLimit); plyr_[_pID].gen = plyr_[_pID].gen.add(_refund); _eth = _availableLimit; } // if eth left is greater than min eth allowed (sorry no pocket lint) if (_eth > 1000000000) { // mint the new keys uint256 _keys = (round_[_rID].eth).keysRec(_eth); // if they bought at least 1 whole key if (_keys >= 1000000000000000000) { updateTimer(_keys, _rID); // set new leaders if (round_[_rID].plyr != _pID) round_[_rID].plyr = _pID; // set the new leader bool to true _eventData_.compressedData = _eventData_.compressedData + 100; } // manage airdrops if (_eth >= 100000000000000000) { airDropTracker_++; if (airdrop() == true) { // gib muni uint256 _prize; if (_eth >= 10000000000000000000) { // calculate prize and give it to winner _prize = ((airDropPot_).mul(75)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); // adjust airDropPot airDropPot_ = (airDropPot_).sub(_prize); // let event know a tier 3 prize was won _eventData_.compressedData += 300000000000000000000000000000000; } else if (_eth >= 1000000000000000000 && _eth < 10000000000000000000) { // calculate prize and give it to winner _prize = ((airDropPot_).mul(50)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); // adjust airDropPot airDropPot_ = (airDropPot_).sub(_prize); // let event know a tier 2 prize was won _eventData_.compressedData += 200000000000000000000000000000000; } else if (_eth >= 100000000000000000 && _eth < 1000000000000000000) { // calculate prize and give it to winner _prize = ((airDropPot_).mul(25)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); // adjust airDropPot airDropPot_ = (airDropPot_).sub(_prize); // let event know a tier 1 prize was won _eventData_.compressedData += 100000000000000000000000000000000; } // set airdrop happened bool to true _eventData_.compressedData += 10000000000000000000000000000000; // let event know how much was won _eventData_.compressedData += _prize * 1000000000000000000000000000000000; // reset air drop tracker airDropTracker_ = 0; } } // store the air drop tracker number (number of buys since last airdrop) _eventData_.compressedData = _eventData_.compressedData + (airDropTracker_ * 1000); // update player plyrRnds_[_pID][_rID].keys = _keys.add(plyrRnds_[_pID][_rID].keys); plyrRnds_[_pID][_rID].eth = _eth.add(plyrRnds_[_pID][_rID].eth); // update round round_[_rID].keys = _keys.add(round_[_rID].keys); round_[_rID].eth = _eth.add(round_[_rID].eth); // distribute eth _eventData_ = distributeExternal(_rID, _pID, _eth, _affID, _eventData_); _eventData_ = distributeInternal(_rID, _pID, _eth, _keys, _eventData_); // call end tx function to fire end tx event. endTx(_pID, _eth, _keys, _eventData_); } } //============================================================================== // _ _ | _ | _ _|_ _ _ _ . // (_(_||(_|_||(_| | (_)| _\ . //============================================================================== /** * @dev calculates unmasked earnings (just calculates, does not update mask) * @return earnings in wei format */ function calcUnMaskedEarnings(uint256 _pID, uint256 _rID) private view returns(uint256) { return((((round_[_rID].mask).mul(plyrRnds_[_pID][_rID].keys)) / (1000000000000000000)).sub(plyrRnds_[_pID][_rID].mask)); } /** * @dev returns the amount of keys you would get given an amount of eth. * -functionhash- 0xce89c80c * @param _eth amount of eth sent in * @return keys received */ function calcKeysReceived(uint256 _eth) public view returns(uint256) { uint256 _rID = rID_; // grab time uint256 _now = now; // are we in a round? if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( (round_[_rID].eth).keysRec(_eth) ); else // rounds over. need keys for new round return ( (_eth).keys() ); } /** * @dev returns current eth price for X keys. * -functionhash- 0xcf808000 * @param _keys number of keys desired (in 18 decimal format) * @return amount of eth needed to send */ function iWantXKeys(uint256 _keys) public view returns(uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // are we in a round? if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( (round_[_rID].keys.add(_keys)).ethRec(_keys) ); else // rounds over. need price for new round return ( (_keys).eth() ); } //============================================================================== // _|_ _ _ | _ . // | (_)(_)|_\ . //============================================================================== /** * @dev receives name/player info from names contract */ function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff) external { require (msg.sender == address(RatBook), "only RatBook can call this function"); if (pIDxAddr_[_addr] != _pID) pIDxAddr_[_addr] = _pID; if (pIDxName_[_name] != _pID) pIDxName_[_name] = _pID; if (plyr_[_pID].addr != _addr) plyr_[_pID].addr = _addr; if (plyr_[_pID].name != _name) plyr_[_pID].name = _name; if (plyr_[_pID].laff != _laff) plyr_[_pID].laff = _laff; if (plyrNames_[_pID][_name] == false) plyrNames_[_pID][_name] = true; } /** * @dev receives entire player name list */ function receivePlayerNameList(uint256 _pID, bytes32 _name) external { require (msg.sender == address(RatBook), "only RatBook can call this function"); if(plyrNames_[_pID][_name] == false) plyrNames_[_pID][_name] = true; } /** * @dev gets existing or registers new pID. use this when a player may be new * @return pID */ function determinePID(RSdatasets.EventReturns memory _eventData_) private returns (RSdatasets.EventReturns) { uint256 _pID = pIDxAddr_[msg.sender]; // if player is new to this version of ratscam if (_pID == 0) { // grab their player ID, name and last aff ID, from player names contract _pID = RatBook.getPlayerID(msg.sender); bytes32 _name = RatBook.getPlayerName(_pID); uint256 _laff = RatBook.getPlayerLAff(_pID); // set up player account pIDxAddr_[msg.sender] = _pID; plyr_[_pID].addr = msg.sender; if (_name != "") { pIDxName_[_name] = _pID; plyr_[_pID].name = _name; plyrNames_[_pID][_name] = true; } if (_laff != 0 && _laff != _pID) plyr_[_pID].laff = _laff; // set the new player bool to true _eventData_.compressedData = _eventData_.compressedData + 1; } return (_eventData_); } /** * @dev decides if round end needs to be run & new round started. and if * player unmasked earnings from previously played rounds need to be moved. */ function managePlayer(uint256 _pID, RSdatasets.EventReturns memory _eventData_) private returns (RSdatasets.EventReturns) { // if player has played a previous round, move their unmasked earnings // from that round to gen vault. if (plyr_[_pID].lrnd != 0) updateGenVault(_pID, plyr_[_pID].lrnd); // update player's last round played plyr_[_pID].lrnd = rID_; // set the joined round bool to true _eventData_.compressedData = _eventData_.compressedData + 10; return(_eventData_); } /** * @dev ends the round. manages paying out winner/splitting up pot */ function endRound(RSdatasets.EventReturns memory _eventData_) private returns (RSdatasets.EventReturns) { // setup local rID uint256 _rID = rID_; // grab our winning player and team id's uint256 _winPID = round_[_rID].plyr; // grab our pot amount // add airdrop pot into the final pot uint256 _pot = round_[_rID].pot; // calculate our winner share, community rewards, gen share, // p3d share, and amount reserved for next pot uint256 _win = (_pot.mul(45)) / 100; uint256 _com = (_pot / 10); uint256 _gen = (_pot.mul(potSplit_)) / 100; // calculate ppt for round mask uint256 _ppt = 0; if(round_[_rID].keys > 0) { _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys); } uint256 _dust = _gen.sub((_ppt.mul(round_[_rID].keys)) / 1000000000000000000); if (_dust > 0) { _gen = _gen.sub(_dust); _com = _com.add(_dust); } // pay our winner plyr_[_winPID].win = _win.add(plyr_[_winPID].win); // community rewards adminAddress.transfer(_com); // distribute gen portion to key holders round_[_rID].mask = _ppt.add(round_[_rID].mask); // prepare event data _eventData_.compressedData = _eventData_.compressedData + (round_[_rID].end * 1000000); _eventData_.compressedIDs = _eventData_.compressedIDs + (_winPID * 100000000000000000000000000); _eventData_.winnerAddr = plyr_[_winPID].addr; _eventData_.winnerName = plyr_[_winPID].name; _eventData_.amountWon = _win; _eventData_.genAmount = _gen; _eventData_.newPot = 0; // start next round rID_++; _rID++; round_[_rID].strt = now; round_[_rID].end = now.add(rndInit_).add(rndGap_); round_[_rID].pot = 0; return(_eventData_); } /** * @dev moves any unmasked earnings to gen vault. updates earnings mask */ function updateGenVault(uint256 _pID, uint256 _rID) private { uint256 _earnings = calcUnMaskedEarnings(_pID, _rID); if (_earnings > 0) { // put in gen vault plyr_[_pID].gen = _earnings.add(plyr_[_pID].gen); // zero out their earnings by updating mask plyrRnds_[_pID][_rID].mask = _earnings.add(plyrRnds_[_pID][_rID].mask); } } /** * @dev updates round timer based on number of whole keys bought. */ function updateTimer(uint256 _keys, uint256 _rID) private { // grab time uint256 _now = now; // calculate time based on number of keys bought uint256 _newTime; if (_now > round_[_rID].end && round_[_rID].plyr == 0) _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(_now); else _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(round_[_rID].end); // compare to max and set new end time if (_newTime < (rndMax_).add(_now)) round_[_rID].end = _newTime; else round_[_rID].end = rndMax_.add(_now); } /** * @dev generates a random number between 0-99 and checks to see if thats * resulted in an airdrop win * @return do we have a winner? */ function airdrop() private view returns(bool) { uint256 seed = uint256(keccak256(abi.encodePacked( (block.timestamp).add (block.difficulty).add ((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (now)).add (block.gaslimit).add ((uint256(keccak256(abi.encodePacked(msg.sender)))) / (now)).add (block.number) ))); if((seed - ((seed / 1000) * 1000)) < airDropTracker_) return(true); else return(false); } /** * @dev distributes eth based on fees to com, aff, and p3d */ function distributeExternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, RSdatasets.EventReturns memory _eventData_) private returns(RSdatasets.EventReturns) { // pay 5% out to community rewards uint256 _com = _eth * 5 / 100; // distribute share to affiliate uint256 _aff = _eth / 10; // decide what to do with affiliate share of fees // affiliate must not be self, and must have a name registered if (_affID != _pID && plyr_[_affID].name != '') { plyr_[_affID].aff = _aff.add(plyr_[_affID].aff); emit RSEvents.onAffiliatePayout(_affID, plyr_[_affID].addr, plyr_[_affID].name, _pID, _aff, now); } else { // no affiliates, add to community _com += _aff; } // pay out team adminAddress.transfer(_com); return(_eventData_); } /** * @dev distributes eth based on fees to gen and pot */ function distributeInternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _keys, RSdatasets.EventReturns memory _eventData_) private returns(RSdatasets.EventReturns) { // calculate gen share uint256 _gen = (_eth.mul(fees_)) / 100; // toss 5% into airdrop pot uint256 _air = (_eth / 20); airDropPot_ = airDropPot_.add(_air); // calculate pot (20%) uint256 _pot = (_eth.mul(20) / 100); // distribute gen share (thats what updateMasks() does) and adjust // balances for dust. uint256 _dust = updateMasks(_rID, _pID, _gen, _keys); if (_dust > 0) _gen = _gen.sub(_dust); // add eth to pot round_[_rID].pot = _pot.add(_dust).add(round_[_rID].pot); // set up event data _eventData_.genAmount = _gen.add(_eventData_.genAmount); _eventData_.potAmount = _pot; return(_eventData_); } /** * @dev updates masks for round and player when keys are bought * @return dust left over */ function updateMasks(uint256 _rID, uint256 _pID, uint256 _gen, uint256 _keys) private returns(uint256) { /* MASKING NOTES earnings masks are a tricky thing for people to wrap their minds around. the basic thing to understand here. is were going to have a global tracker based on profit per share for each round, that increases in relevant proportion to the increase in share supply. the player will have an additional mask that basically says "based on the rounds mask, my shares, and how much i've already withdrawn, how much is still owed to me?" */ // calc profit per key & round mask based on this buy: (dust goes to pot) uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys); round_[_rID].mask = _ppt.add(round_[_rID].mask); // calculate player earning from their own buy (only based on the keys // they just bought). & update player earnings mask uint256 _pearn = (_ppt.mul(_keys)) / (1000000000000000000); plyrRnds_[_pID][_rID].mask = (((round_[_rID].mask.mul(_keys)) / (1000000000000000000)).sub(_pearn)).add(plyrRnds_[_pID][_rID].mask); // calculate & return dust return(_gen.sub((_ppt.mul(round_[_rID].keys)) / (1000000000000000000))); } /** * @dev adds up unmasked earnings, & vault earnings, sets them all to 0 * @return earnings in wei format */ function withdrawEarnings(uint256 _pID) private returns(uint256) { // update gen vault updateGenVault(_pID, plyr_[_pID].lrnd); // from vaults uint256 _earnings = (plyr_[_pID].win).add(plyr_[_pID].gen).add(plyr_[_pID].aff); if (_earnings > 0) { plyr_[_pID].win = 0; plyr_[_pID].gen = 0; plyr_[_pID].aff = 0; } return(_earnings); } /** * @dev prepares compression data and fires event for buy or reload tx's */ function endTx(uint256 _pID, uint256 _eth, uint256 _keys, RSdatasets.EventReturns memory _eventData_) private { _eventData_.compressedData = _eventData_.compressedData + (now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID + (rID_ * 10000000000000000000000000000000000000000000000000000); emit RSEvents.onEndTx ( _eventData_.compressedData, _eventData_.compressedIDs, plyr_[_pID].name, msg.sender, _eth, _keys, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.genAmount, _eventData_.potAmount, airDropPot_ ); } /** upon contract deploy, it will be deactivated. this is a one time * use function that will activate the contract. we do this so devs * have time to set things up on the web end **/ bool public activated_ = false; function activate() public { // only owner can activate require( msg.sender == adminAddress, "only owner can activate" ); // can only be ran once require(activated_ == false, "ratscam already activated"); // activate the contract activated_ = true; // lets start first round rID_ = 1; round_[1].strt = now - rndGap_; round_[1].end = now + rndInit_; } function setNextRndTime(uint32 rndInit, uint32 rndInc, uint32 rndMax) public { // only owner require(msg.sender == adminAddress, "only owner can setNextRndTime"); rndInit_ = rndInit * 1 hours; rndInc_ = rndInc * 1 seconds; rndMax_ = rndMax * 1 hours; } } //============================================================================== // __|_ _ __|_ _ . // _\ | | |_|(_ | _\ . //============================================================================== library RSdatasets { //compressedData key // [76-33][32][31][30][29][28-18][17][16-6][5-3][2][1][0] // 0 - new player (bool) // 1 - joined round (bool) // 2 - new leader (bool) // 3-5 - air drop tracker (uint 0-999) // 6-16 - round end time // 17 - winnerTeam // 18 - 28 timestamp // 29 - team // 30 - 0 = reinvest (round), 1 = buy (round), 2 = buy (ico), 3 = reinvest (ico) // 31 - airdrop happened bool // 32 - airdrop tier // 33 - airdrop amount won //compressedIDs key // [77-52][51-26][25-0] // 0-25 - pID // 26-51 - winPID // 52-77 - rID struct EventReturns { uint256 compressedData; uint256 compressedIDs; address winnerAddr; // winner address bytes32 winnerName; // winner name uint256 amountWon; // amount won uint256 newPot; // amount in new pot uint256 genAmount; // amount distributed to gen uint256 potAmount; // amount added to pot } struct Player { address addr; // player address bytes32 name; // player name uint256 win; // winnings vault uint256 gen; // general vault uint256 aff; // affiliate vault uint256 laff; // last affiliate id used uint256 lrnd; // last round played } struct PlayerRounds { uint256 eth; // eth player has added to round (used for eth limiter) uint256 keys; // keys uint256 mask; // player mask } struct Round { uint256 plyr; // pID of player in lead uint256 end; // time ends/ended bool ended; // has round end function been ran uint256 strt; // time round started uint256 keys; // keys uint256 eth; // total eth in uint256 pot; // eth to pot (during round) / final amount paid to winner (after round ends) uint256 mask; // global mask } } //============================================================================== // | _ _ _ | _ . // |<(/_\/ (_(_||(_ . //=======/====================================================================== library RSKeysCalc { using SafeMath for *; /** * @dev calculates number of keys received given X eth * @param _curEth current amount of eth in contract * @param _newEth eth being spent * @return amount of ticket purchased */ function keysRec(uint256 _curEth, uint256 _newEth) internal pure returns (uint256) { return(keys((_curEth).add(_newEth)).sub(keys(_curEth))); } /** * @dev calculates amount of eth received if you sold X keys * @param _curKeys current amount of keys that exist * @param _sellKeys amount of keys you wish to sell * @return amount of eth received */ function ethRec(uint256 _curKeys, uint256 _sellKeys) internal pure returns (uint256) { return((eth(_curKeys)).sub(eth(_curKeys.sub(_sellKeys)))); } /** * @dev calculates how many keys would exist with given an amount of eth * @param _eth eth "in contract" * @return number of keys that would exist */ function keys(uint256 _eth) internal pure returns(uint256) { return ((((((_eth).mul(1000000000000000000)).mul(312500000000000000000000000)).add(5624988281256103515625000000000000000000000000000000000000000000)).sqrt()).sub(74999921875000000000000000000000)) / (156250000); } /** * @dev calculates how much eth would be in contract given a number of keys * @param _keys number of keys "in contract" * @return eth that would exists */ function eth(uint256 _keys) internal pure returns(uint256) { return ((78125000).mul(_keys.sq()).add(((149999843750000).mul(_keys.mul(1000000000000000000))) / (2))) / ((1000000000000000000).sq()); } } //interface RatInterfaceForForwarder { // function deposit() external payable returns(bool); //} interface RatBookInterface { function getPlayerID(address _addr) external returns (uint256); function getPlayerName(uint256 _pID) external view returns (bytes32); function getPlayerLAff(uint256 _pID) external view returns (uint256); function getPlayerAddr(uint256 _pID) external view returns (address); function getNameFee() external view returns (uint256); function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all) external payable returns(bool, uint256); function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all) external payable returns(bool, uint256); function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all) external payable returns(bool, uint256); } library NameFilter { /** * @dev filters name strings * -converts uppercase to lower case. * -makes sure it does not start/end with a space * -makes sure it does not contain multiple spaces in a row * -cannot be only numbers * -cannot start with 0x * -restricts characters to A-Z, a-z, 0-9, and space. * @return reprocessed string in bytes32 format */ function nameFilter(string _input) internal pure returns(bytes32) { bytes memory _temp = bytes(_input); uint256 _length = _temp.length; //sorry limited to 32 characters require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters"); // make sure it doesnt start with or end with space require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space"); // make sure first two characters are not 0x if (_temp[0] == 0x30) { require(_temp[1] != 0x78, "string cannot start with 0x"); require(_temp[1] != 0x58, "string cannot start with 0X"); } // create a bool to track if we have a non number character bool _hasNonNumber; // convert & check for (uint256 i = 0; i < _length; i++) { // if its uppercase A-Z if (_temp[i] > 0x40 && _temp[i] < 0x5b) { // convert to lower case a-z _temp[i] = byte(uint(_temp[i]) + 32); // we have a non number if (_hasNonNumber == false) _hasNonNumber = true; } else { require ( // require character is a space _temp[i] == 0x20 || // OR lowercase a-z (_temp[i] > 0x60 && _temp[i] < 0x7b) || // or 0-9 (_temp[i] > 0x2f && _temp[i] < 0x3a), "string contains invalid characters" ); // make sure theres not 2x spaces in a row if (_temp[i] == 0x20) require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces"); // see if we have a character other than a number if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39)) _hasNonNumber = true; } } require(_hasNonNumber == true, "string cannot be only numbers"); bytes32 _ret; assembly { _ret := mload(add(_temp, 32)) } return (_ret); } } /** * @title SafeMath v0.1.9 * @dev Math operations with safety checks that throw on error * change notes: original SafeMath library from OpenZeppelin modified by Inventor * - added sqrt * - added sq * - changed asserts to requires with error log outputs * - removed div, its useless */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; require(c / a == b, "SafeMath mul failed"); 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) { require(b <= a, "SafeMath sub failed"); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; require(c >= a, "SafeMath add failed"); return c; } /** * @dev gives square root of given x. */ function sqrt(uint256 x) internal pure returns (uint256 y) { uint256 z = ((add(x,1)) / 2); y = x; while (z < y) { y = z; z = ((add((x / z),z)) / 2); } } /** * @dev gives square. multiplies x by x */ function sq(uint256 x) internal pure returns (uint256) { return (mul(x,x)); } }
set up our tx event data fetch player ID manage affiliate residuals if no affiliate code was given or player tried to use their own, lolz use last stored affiliate code if affiliate code was given get affiliate ID from aff Code if affID is not the same as previously stored update last affiliate
function reLoadXname(bytes32 _affCode, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { RSdatasets.EventReturns memory _eventData_; uint256 _pID = pIDxAddr_[msg.sender]; uint256 _affID; if (_affCode == '' || _affCode == plyr_[_pID].name) { _affID = plyr_[_pID].laff; _affID = pIDxName_[_affCode]; if (_affID != plyr_[_pID].laff) { plyr_[_pID].laff = _affID; } } }
429,683
[ 1, 542, 731, 3134, 2229, 871, 501, 2158, 7291, 1599, 10680, 7103, 330, 3840, 29252, 309, 1158, 7103, 330, 3840, 981, 1703, 864, 578, 7291, 12928, 358, 999, 3675, 4953, 16, 328, 355, 94, 999, 1142, 4041, 7103, 330, 3840, 981, 309, 7103, 330, 3840, 981, 1703, 864, 336, 7103, 330, 3840, 1599, 628, 7103, 3356, 309, 7103, 734, 353, 486, 326, 1967, 487, 7243, 4041, 1089, 1142, 7103, 330, 3840, 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, 283, 2563, 60, 529, 12, 3890, 1578, 389, 7329, 1085, 16, 2254, 5034, 389, 546, 13, 203, 565, 353, 28724, 1435, 203, 565, 27803, 6925, 1435, 203, 565, 353, 18949, 12768, 24899, 546, 13, 203, 565, 1071, 203, 565, 288, 203, 3639, 14746, 21125, 18, 1133, 1356, 3778, 389, 2575, 751, 67, 31, 203, 203, 3639, 2254, 5034, 389, 84, 734, 273, 293, 734, 92, 3178, 67, 63, 3576, 18, 15330, 15533, 203, 203, 3639, 2254, 5034, 389, 7329, 734, 31, 203, 3639, 309, 261, 67, 7329, 1085, 422, 875, 747, 389, 7329, 1085, 422, 293, 715, 86, 67, 63, 67, 84, 734, 8009, 529, 13, 203, 3639, 288, 203, 5411, 389, 7329, 734, 273, 293, 715, 86, 67, 63, 67, 84, 734, 8009, 80, 7329, 31, 203, 203, 5411, 389, 7329, 734, 273, 293, 734, 92, 461, 67, 63, 67, 7329, 1085, 15533, 203, 203, 5411, 309, 261, 67, 7329, 734, 480, 293, 715, 86, 67, 63, 67, 84, 734, 8009, 80, 7329, 13, 203, 5411, 288, 203, 7734, 293, 715, 86, 67, 63, 67, 84, 734, 8009, 80, 7329, 273, 389, 7329, 734, 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 ]
./full_match/43114/0x443F8af9f96d0746dD8047a1AaEe7d11CD70fECB/sources/contracts/royalties.sol
@title Royalties for Non-Fungible Tokens @dev Contract for the split between community royalties and dev royalties
contract Royalties is Ownable { uint256 public communityClaimed = 0; uint256 public creatorClaimed = 0; uint256 public collectionSize = 10000; address public tokenFeesAddress; address public creatorAddress; address public collectionAddress; mapping(uint256 => uint256) private communityClaims; mapping(address => uint256) private addressClaims; event CommunityClaimed(address owner, uint256 amount, uint256 tokenID); event CreatorClaimed(uint256 amount); event RoyaltiesCreated(address collectionAddress); constructor( address _tokenFeesAddress, address _creatorAddress, address _collectionAddress, uint256 _collectionSize ) { tokenFeesAddress = _tokenFeesAddress; creatorAddress = _creatorAddress; collectionAddress = _collectionAddress; collectionSize = _collectionSize; emit RoyaltiesCreated(collectionAddress); } function setTokenFeesAddress(address _tokenFeesAddress) external onlyOwner { tokenFeesAddress = _tokenFeesAddress; } function setCreatorAddress(address _creatorAddress) external onlyOwner { creatorAddress = _creatorAddress; } function setCollectionSize(uint256 _collectionSize) external onlyOwner { require(_collectionSize < collectionSize, 'Cannot increase collection size'); collectionSize = _collectionSize; } function setCreatorRoyalties(uint256 _creatorRoyalties) external onlyOwner { creatorRoyalties = _creatorRoyalties; } function setCommunityRoyalties(uint256 _communityRoyalties) external onlyOwner { communityRoyalties = _communityRoyalties; } function getTotalRoyalties() public view returns (uint256) { return creatorRoyalties + communityRoyalties; } function getRoyalties() public view returns (uint256, uint256) { return (creatorRoyalties, communityRoyalties); } function getTotalCollected() public view returns (uint256) { uint256 balance = ERC20(tokenFeesAddress).balanceOf(address(this)); return balance + creatorClaimed + communityClaimed; } function getCreatorBalance() public view returns (uint256) { uint256 _creatorRoyalties = (creatorRoyalties * 100) / getTotalRoyalties(); return (getTotalCollected() * _creatorRoyalties) / 100 - creatorClaimed; } function getTokenTotalRoyalties() public view returns (uint256) { uint256 _communityRoyalties = (communityRoyalties * 100) / getTotalRoyalties(); return ((getTotalCollected() * _communityRoyalties) / 100) / collectionSize; } function getTokenBalance(uint256 tokenID) public view returns (uint256) { return getTokenTotalRoyalties() - communityClaims[tokenID]; } function getTokensBalance(uint256[] memory tokenIDs) public view returns (uint256) { uint256 totalBalance = 0; for (uint256 i = 0; i<tokenIDs.length; i++) { uint256 balance = getTokenBalance(tokenIDs[i]); totalBalance = (totalBalance + balance); } return totalBalance; } function getTokensBalance(uint256[] memory tokenIDs) public view returns (uint256) { uint256 totalBalance = 0; for (uint256 i = 0; i<tokenIDs.length; i++) { uint256 balance = getTokenBalance(tokenIDs[i]); totalBalance = (totalBalance + balance); } return totalBalance; } function getAddressClaims(address account) public view returns (uint256) { return addressClaims[account]; } function claimCommunity(uint256 tokenID) public { uint256 balance = getTokenBalance(tokenID); if (balance > 0) { address owner = ERC721(collectionAddress).ownerOf(tokenID); if (owner != address(0)) { ERC20(tokenFeesAddress).transfer(owner, balance); communityClaims[tokenID] = communityClaims[tokenID] + balance; addressClaims[owner] = addressClaims[owner] + balance; communityClaimed = communityClaimed + balance; emit CommunityClaimed(owner, balance, tokenID); } } } function claimCommunity(uint256 tokenID) public { uint256 balance = getTokenBalance(tokenID); if (balance > 0) { address owner = ERC721(collectionAddress).ownerOf(tokenID); if (owner != address(0)) { ERC20(tokenFeesAddress).transfer(owner, balance); communityClaims[tokenID] = communityClaims[tokenID] + balance; addressClaims[owner] = addressClaims[owner] + balance; communityClaimed = communityClaimed + balance; emit CommunityClaimed(owner, balance, tokenID); } } } function claimCommunity(uint256 tokenID) public { uint256 balance = getTokenBalance(tokenID); if (balance > 0) { address owner = ERC721(collectionAddress).ownerOf(tokenID); if (owner != address(0)) { ERC20(tokenFeesAddress).transfer(owner, balance); communityClaims[tokenID] = communityClaims[tokenID] + balance; addressClaims[owner] = addressClaims[owner] + balance; communityClaimed = communityClaimed + balance; emit CommunityClaimed(owner, balance, tokenID); } } } function claimCommunityBatch(uint256[] calldata tokenIDs) external { for (uint256 i=0; i<tokenIDs.length; i++) { claimCommunity(tokenIDs[i]); } } function claimCommunityBatch(uint256[] calldata tokenIDs) external { for (uint256 i=0; i<tokenIDs.length; i++) { claimCommunity(tokenIDs[i]); } } function claimCreator() external { require(msg.sender == creatorAddress, "Only creator can claim"); uint256 balance = getCreatorBalance(); require(balance > 0, "No balance to claim"); ERC20(tokenFeesAddress).transfer(creatorAddress, balance); creatorClaimed = creatorClaimed + balance; emit CreatorClaimed(balance); } }
4,626,154
[ 1, 54, 13372, 2390, 606, 364, 3858, 17, 42, 20651, 1523, 13899, 225, 13456, 364, 326, 1416, 3086, 19833, 721, 93, 2390, 606, 471, 4461, 721, 93, 2390, 606, 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, 534, 13372, 2390, 606, 353, 14223, 6914, 288, 203, 565, 2254, 5034, 1071, 19833, 9762, 329, 273, 374, 31, 203, 565, 2254, 5034, 1071, 11784, 9762, 329, 273, 374, 31, 203, 203, 203, 565, 2254, 5034, 1071, 1849, 1225, 273, 12619, 31, 203, 203, 565, 1758, 1071, 1147, 2954, 281, 1887, 31, 203, 565, 1758, 1071, 11784, 1887, 31, 203, 565, 1758, 1071, 1849, 1887, 31, 203, 203, 565, 2874, 12, 11890, 5034, 516, 2254, 5034, 13, 3238, 19833, 15925, 31, 203, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 3238, 1758, 15925, 31, 203, 203, 565, 871, 16854, 13352, 9762, 329, 12, 2867, 3410, 16, 2254, 5034, 3844, 16, 2254, 5034, 1147, 734, 1769, 203, 565, 871, 29525, 9762, 329, 12, 11890, 5034, 3844, 1769, 203, 565, 871, 534, 13372, 2390, 606, 6119, 12, 2867, 1849, 1887, 1769, 203, 203, 565, 3885, 12, 203, 3639, 1758, 389, 2316, 2954, 281, 1887, 16, 203, 3639, 1758, 389, 20394, 1887, 16, 203, 3639, 1758, 389, 5548, 1887, 16, 203, 3639, 2254, 5034, 389, 5548, 1225, 203, 565, 262, 288, 203, 3639, 1147, 2954, 281, 1887, 273, 389, 2316, 2954, 281, 1887, 31, 203, 3639, 11784, 1887, 273, 389, 20394, 1887, 31, 203, 3639, 1849, 1887, 273, 389, 5548, 1887, 31, 203, 3639, 1849, 1225, 273, 389, 5548, 1225, 31, 203, 3639, 3626, 534, 13372, 2390, 606, 6119, 12, 5548, 1887, 1769, 203, 565, 289, 203, 203, 565, 445, 22629, 2954, 281, 1887, 12, 2867, 389, 2316, 2954, 281, 1887, 13, 3903, 1338, 5541, 2 ]
pragma solidity 0.5.11; // Syntropy By Solange Gueiros // versao 0.3.2 contract Token { using SafeMath for uint256; //By OpenZeppelin mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; uint256 private _totalSupply; 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; } function totalSupply() public view returns (uint256) { return _totalSupply; } function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } function allowance(address owner, address spender) public view returns (uint256) { return _allowed[owner][spender]; } function transfer(address to, uint256 value) public returns (bool) { _transfer(msg.sender, to, value); return true; } function approve(address spender, uint256 value) public returns (bool) { _approve(msg.sender, spender, value); return true; } function transferFrom(address from, address to, uint256 value) public returns (bool) { _transfer(from, to, value); _approve(from, msg.sender, _allowed[from][msg.sender].sub(value)); return true; } function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(msg.sender, spender, _allowed[msg.sender][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue)); return true; } //function mint(address to, uint256 value) public onlyMinter returns (bool) { function mint(address to, uint256 value) public returns (bool) { _mint(to, value); return true; } event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); function _transfer(address from, address to, uint256 value) internal { require(to != address(0)); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); } function _mint(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.add(value); _balances[account] = _balances[account].add(value); emit Transfer(address(0), account, value); } function _approve(address owner, address spender, uint256 value) internal { require(spender != address(0)); require(owner != address(0)); _allowed[owner][spender] = value; emit Approval(owner, spender, value); } } contract UsdS is Token { // Syntropy By Solange Gueiros uint8 private constant decimals_ = 2; uint256 private constant initialSupply_ = 1000000 * (10 ** uint256(decimals_)); constructor () public Token("Syntropy USD", "USDS", decimals_) { _mint(msg.sender, initialSupply_); } } contract Border { using SafeMath for uint256; // Syntropy By Solange Gueiros string public name; address public creator; address public usdAddress; uint256 internal constant decimalpercent = 10000; //100.00 = precisão da porcentagem (2) + 2 casas para 100% uint8 public constant MaxAccount = 49; //Número máximo de transferencias / depósitos em batch mapping (address => uint256) public ratioOwner; address[] private owners; mapping (address => uint256) private indexOwner; //posicao no array uint256 public totalRatio; //totalSupply do token uint256 private _valueDeposited; //Valor que será dividido de acordo com o shareRatio mapping (address => uint256) private _balances; //Saldo disponivel em USD que cada pessoa pode retirar constructor(string memory _name, address _usdAddress, address _ownerAddress) public { creator = _ownerAddress; name = _name; usdAddress = _usdAddress; totalRatio = 0; _valueDeposited = 0; owners.push(address(0x0)); //posicao 0 zerada } function listOwners() public view returns (address[] memory) { return owners; } function isOwner(address _address) public view returns (bool) { if (ratioOwner[_address] > 0) return true; else return false; } function countOwners() public view returns (uint256) { return owners.length-1; } function _addOwner(address account, uint256 shareRatio) internal returns (bool) { require(account != address(0), "zero address"); require(shareRatio > 0, "shares are 0"); if (indexOwner[account] == 0) { indexOwner[account] = owners.push(account)-1; ratioOwner[account] = shareRatio; emit AddOwner(account, shareRatio); } else { ratioOwner[account] = ratioOwner[account].add(shareRatio); } totalRatio = totalRatio.add(shareRatio); return true; } function _removeOwner(address _address) internal returns (bool) { //Retirar do array Owner uint256 indexToDelete = indexOwner[_address]; address addressToMove = owners[owners.length-1]; indexOwner[addressToMove] = indexToDelete; owners[indexToDelete] = addressToMove; owners.length--; emit RemoveOwner(_address); return true; } event AddOwner (address indexed _address, uint256 shareRatio); event RemoveOwner (address indexed _address); event DepositUSD(uint256 _totalValue, address[] indexed _froms, uint256[] _values); function depositUSD(uint256 _totalValue, address[] calldata _froms, uint256[] calldata _values) external { //function depositUSD(uint256 _totalValue, address[] memory _froms, uint256[] memory _values) public { require(_froms.length == _values.length, "number froms and values don't match"); require(_froms.length < MaxAccount, "too many recipients"); UsdS usdS = UsdS(usdAddress); //A soma dos valores não pode ser maior que o allowance require(usdS.allowance(msg.sender, address(this)) >= _totalValue, "ammount not approved"); require(usdS.transferFrom(msg.sender, address(this), _totalValue), "Can't transfer to border"); emit DepositUSD(_totalValue, _froms, _values); if (owners.length == 1) { //Só tem a primeira posicao zerada, for (uint256 i = 0; i < _froms.length; i++) { _balances[_froms[i]] = _balances[_froms[i]].add(_values[i]); } } else { _valueDeposited = _totalValue; for (uint256 i = 1; i < owners.length; i++) { _receiveUSD(owners[i]); } _valueDeposited = 0; } for (uint256 i = 0; i < _froms.length; i++) { _addOwner(_froms[i], _values[i]); } } event ReceiveUSD(address indexed to, uint256 value); function _receiveUSD(address account) internal { require(ratioOwner[account] > 0, "no shares"); uint256 payment = _valueDeposited.mul(ratioOwner[account]).div(totalRatio); _balances[account] = _balances[account].add(payment); emit ReceiveUSD(account, payment); } //Balance USD in the contract in behalf of account function balanceOf(address account) public view returns (uint256) { return _balances[account]; } //Withdrawal USD in the contract in behalf of msg.sender function withdrawalUSD() public { require(_balances[msg.sender] > 0, "balance is zero"); uint256 value = _balances[msg.sender]; _balances[msg.sender] = 0; UsdS usdS = UsdS(usdAddress); require(usdS.transfer(msg.sender, value), "usdS transfer error"); delete value; } //Token Border equivalent - % da conta em relação ao total da borda function percOf(address account) public view returns (uint256) { uint256 value = decimalpercent.mul(ratioOwner[account]).div(totalRatio); return value; } event TransferRatio(address indexed from, address indexed to, uint256 value); //Transfer a perc (based in total) in Border to another account function transferRatio(address account, uint256 perc) public { require(account != address(0), "zero address"); require((perc > 0 && perc <= percOf(msg.sender) ), "invalid perc"); //Calcular o ratio em relacao a perc uint256 ratio = ratioOwner[msg.sender].mul(perc).div(percOf(msg.sender)); uint256 newRatio = ratioOwner[msg.sender].sub(ratio); //Se ratioOwner[msg.sender] = 0, retiro do array para não passar por ele sem necessidade if (newRatio == 0) { require(_removeOwner(msg.sender), "removeOwner error"); } ratioOwner[msg.sender] = newRatio; totalRatio = totalRatio.sub(ratio); _addOwner(account, ratio); emit TransferRatio (msg.sender, account, perc); } } contract BorderFactory { // Syntropy By Solange Gueiros address[] public borders; mapping (address => bool) public isBorder; address public usdAddress; constructor(address _usdAddress) public { usdAddress = _usdAddress; } function inBorderFactory (address _borderAddress) public view returns (bool) { return (isBorder[_borderAddress]); } function listBorders() public view returns (address[] memory) { return borders; } function lastBorderCreated () public view returns (address) { return borders[borders.length-1]; } event CreateBorder (address indexed _address, string _name); function createBorder (string memory _name) public returns (Border) { Border border = new Border (_name, usdAddress, msg.sender); borders.push(address(border)); isBorder[address(border)] = true; emit CreateBorder (address(border), _name); return border; } } library SyntropyStruct { //enum TypeShare {Out = 0, In = 1, Border = 2} enum TypeShare {Out, In, Border} struct ShareStruct { address accountFrom; address accountTo; uint256 ratio; uint256 indexFrom; uint256 indexTo; TypeShare accountType; } struct PaymentStruct { uint256 total; uint256 borderTotal; uint256 accountInTotal; bool payed; bool borderPayed; bool accountInPayed; } // function decimalpercent() external pure returns (uint256) { // //uint256 constant decimalpercent = 10000; //100.00 = precisão da porcentagem (2) + 2 casas para 100% // return 10000; // } } contract Moviment { using SafeMath for uint256; // Syntropy By Solange Gueiros string public name; address public creator; uint256 internal constant decimalpercent = 10000; //100.00 = precisão da porcentagem (2) + 2 casas para 100% uint32 public constant MaxAccountIn = 277; //Número máximo de transferencias / depósitos em batch BorderFactory public borderFactory; //From BorderFactory address public usdAddress; SyntropyStruct.ShareStruct[] public ownerShare; mapping (address => mapping (address => uint256)) public shareIndex; //para cada AC1 AC2 guarda o indice da struct onde estao as informacoes mapping (address => uint256[]) public indexFrom; //Guarda os indices da struct onde o endereço envia o share mapping (address => uint256[]) public indexTo; //Guarda os indices da struct onde o endereço recebe o share address[] public borders; //Bordas que recebem deste movimento mapping (address => uint256) public indexBorder; //borda que recebe deste movimento - posicao no array address[] public accountsIn; //Accounts que recebem deste movimento - por dentro - o movimento faz o pagamento mapping (address => uint256) internal indexAccountIn; //AccountsIn - posicao no array mapping (address => uint256) internal countAccountIn; //AccountsIn - quantos do IndexTo para Account são IN mapping (address => uint256) public _balances; //Saldo disponivel em USD que cada account pode retirar //mapping (address => SyntropyStruct.PaymentStruct) public payments; // out of gas constructor(string memory _name, address _borderFactory, address _usdAddress, address _ownerAddress) public { creator = _ownerAddress; name = _name; usdAddress = _usdAddress; borderFactory = BorderFactory(_borderFactory); borders.push(address(0x0)); //posicao 0 zerada accountsIn.push(address(0x0)); //posicao 0 zerada owners.push(address(0x0)); //posicao 0 zerada indexOwner[_ownerAddress] = owners.push(_ownerAddress)-1; addShareStruct(address(0x0), address(0x0), 0, SyntropyStruct.TypeShare.Out); //posicao 0 zerada addShareStruct(_ownerAddress, _ownerAddress, decimalpercent, SyntropyStruct.TypeShare.Out); } function addShareStruct (address _accountFrom, address _accountTo, uint256 _ratio, SyntropyStruct.TypeShare _accountType) internal returns (uint256 index) { //Verifica se já existe ownerShare para _accountFrom e _accountTo. require (shareIndex[_accountFrom][_accountTo] == 0, "ownerShare exists"); uint256 posIndexFrom = indexFrom[_accountFrom].push(index) - 1; //index = 0 aqui, só descobre qual é a posição no indexFrom uint256 posIndexTo = indexTo[_accountTo].push(index) - 1; SyntropyStruct.ShareStruct memory s1 = SyntropyStruct.ShareStruct({ accountFrom: _accountFrom, accountTo: _accountTo, ratio: _ratio, indexFrom: posIndexFrom, indexTo: posIndexTo, accountType: _accountType }); index = ownerShare.push(s1) - 1; shareIndex[_accountFrom][_accountTo] = index; indexFrom[_accountFrom][posIndexFrom] = index; indexTo[_accountTo][posIndexTo] = index; } function delShareStruct (uint256 _index) internal returns (bool) { address accountFrom = ownerShare[_index].accountFrom; address accountTo = ownerShare[_index].accountTo; //Retira do ownerShare uint256 keyToMove = ownerShare.length - 1; shareIndex[ownerShare[keyToMove].accountFrom][ownerShare[keyToMove].accountTo] = _index; ownerShare[_index].accountFrom = ownerShare[keyToMove].accountFrom; ownerShare[_index].accountTo = ownerShare[keyToMove].accountTo; ownerShare[_index].ratio = ownerShare[keyToMove].ratio; ownerShare[_index].accountType = ownerShare[keyToMove].accountType; //ARRUMAR NAS OUTRAS VERSOES //Atualiza o index do From indexFrom[ownerShare[keyToMove].accountFrom][ownerShare[keyToMove].indexFrom] = _index; //Atualiza o index do To indexTo[ownerShare[keyToMove].accountTo][ownerShare[keyToMove].indexTo] = _index; ownerShare.length--; //Retira do From - VERIFICAR: é o último mesmo que tem que retirar? indexFrom[accountFrom].length--; //Retira do To - VERIFICAR: é o último mesmo que tem que retirar? indexTo[accountTo].length--; shareIndex[accountFrom][accountTo] = 0; return true; } // function countIndexFrom(address _address) public view returns (uint256) { // return indexFrom[_address].length; // } // function countIndexTo(address _address) public view returns (uint256) { // return indexTo[_address].length; // } // function countAccountsIn() public view returns (uint256) { // return accountsIn.length; // } function listAccountsIn() external view returns (address[] memory) { return accountsIn; } function listIndexTo(address _address) external view returns (uint256[] memory) { return indexTo[_address]; } function listIndexFrom(address _address) external view returns (uint256[] memory) { return indexFrom[_address]; } //SHARES function ratioShare (address accountFrom, address accountTo) public view returns (uint256) { uint256 index = shareIndex[accountFrom][accountTo]; if (index == 0) return 0; else return ownerShare[index].ratio; } event ShareIncrease (address indexed _from, address indexed _to, uint256 _ratio); event ShareDecrease (address indexed _from, address indexed _to, uint256 _ratio); function shareIncrease(address _account, uint _ratio) public onlyOwner { SyntropyStruct.TypeShare _accountType; if (isBorder(_account)) { _accountType = SyntropyStruct.TypeShare.Border; } else { _accountType = SyntropyStruct.TypeShare.Out; } _shareIncrease(_account, _ratio, _accountType); delete _accountType; } function _shareIncrease(address _account, uint _ratio, SyntropyStruct.TypeShare _accountType) internal { uint256 from = shareIndex[msg.sender][msg.sender]; uint256 ratio = ownerShare[from].ratio; require(ratio >= _ratio, "greater than owner share"); ownerShare[from].ratio = ownerShare[from].ratio.sub(_ratio); uint256 to = shareIndex[msg.sender][_account]; if (to > 0) { require(ownerShare[to].accountType == _accountType, "accountType mismach"); //Já tem um share, so aumenta o ratio ownerShare[to].ratio = ownerShare[to].ratio.add(_ratio); } else { //Se msg.sender não share com _account ainda, adiciona _account if (_accountType == SyntropyStruct.TypeShare.Border) { //Se a borda não está na lista de bordas que recebe do movimento (array borders), adiciona if (indexTo[_account].length == 0) { addBorder(_account); } to = addShareStruct(msg.sender, _account, _ratio, SyntropyStruct.TypeShare.Border); } else { if (_accountType == SyntropyStruct.TypeShare.In) { //Se account não está na lista de AccountIn que recebe do movimento (array AccountsIn), adiciona if (countAccountIn[_account] == 0) { addAccountIn(_account); } countAccountIn[_account] ++; } to = addShareStruct(msg.sender, _account, _ratio, _accountType); } } if (ownerShare[from].ratio == 0) { //msg.sender não tem mais ratio, retira do array de structs delShareStruct(from); } emit ShareIncrease(msg.sender, _account, _ratio); delete from; delete to; delete ratio; } function shareDecrease(address _account, uint _ratio) public onlyOwner { uint256 to = shareIndex[msg.sender][_account]; uint256 ratio = ownerShare[to].ratio; require(ratio >= _ratio, "greater than account's share"); ownerShare[to].ratio = ownerShare[to].ratio.sub(_ratio); uint256 from = shareIndex[msg.sender][msg.sender]; if (from > 0) { ownerShare[from].ratio = ownerShare[from].ratio.add(_ratio); } else { //Se msg.sender não tinha mais share, adiciona from = addShareStruct(msg.sender, msg.sender, _ratio, SyntropyStruct.TypeShare.Out); } if (ownerShare[to].ratio == 0) { SyntropyStruct.TypeShare accountType = ownerShare[to].accountType; //_account não tem mais share, retira do array de structs delShareStruct(to); //é uma borda e não recebe de mais ninguem if (inBorderList(_account) && indexTo[_account].length == 0 ) { removeBorder(_account); } if (accountType == SyntropyStruct.TypeShare.In) { countAccountIn[_account] --; if (countAccountIn[_account] == 0) { removeAccountIn(_account); } } } emit ShareDecrease(msg.sender, _account, _ratio); delete from; delete to; delete ratio; } //OWNERS address[] public owners; //Donos do movimento mapping (address => uint256) public indexOwner; //posicao no array event AddOwner (address indexed _address); event RemoveOwner (address indexed _address); modifier onlyOwner { _onlyOwner(); _; } function _onlyOwner() internal view { require(indexOwner[msg.sender] > 0, "only owner"); } function inOwnerList (address _address) public view returns (bool) { if (indexOwner[_address] > 0) return true; else return false; } function addOwner (address _address) internal returns (uint256) { require (!inOwnerList(_address), "owner exists"); indexOwner[_address] = owners.push(_address)-1; emit AddOwner(_address); return indexOwner[_address]; } function removeOwner (address _address) internal returns (bool) { require (inOwnerList(_address), "owner not exists"); //Retirar do array Owner uint256 indexToDelete = indexOwner[_address]; address addressToMove = owners[owners.length-1]; indexOwner[addressToMove] = indexToDelete; owners[indexToDelete] = addressToMove; owners.length--; indexOwner[_address] = 0; emit RemoveOwner(_address); delete indexToDelete; delete addressToMove; return true; } event OwnerTransfer (address indexed _from, address indexed _to, uint256 _ratio); function ownerTransfer(address _account, uint _ratio) public onlyOwner { //_account não pode ser uma borda require(!isBorder(_account), "is Border"); uint256 from = shareIndex[msg.sender][msg.sender]; uint256 ratio = ownerShare[from].ratio; require(ratio >= _ratio, "greater than owner share"); ownerShare[from].ratio = ownerShare[from].ratio.sub(_ratio); uint256 to = shareIndex[_account][_account]; if (to > 0) { //Já tem um share, so aumenta o ratio ownerShare[to].ratio = ownerShare[to].ratio.add(_ratio); } else { to = addShareStruct(_account, _account, _ratio, SyntropyStruct.TypeShare.Out); addOwner(_account); } if (ownerShare[from].ratio == 0) { //msg.sender não tem mais ratio, retira do array de structs delShareStruct(from); removeOwner(msg.sender); } emit OwnerTransfer(msg.sender, _account, _ratio); delete from; delete to; delete ratio; } function listOwners() public view returns (address[] memory) { return owners; } //BORDERS function inBorderList (address _address) internal view returns (bool) { if (indexBorder[_address] > 0) return true; else return false; } function isBorder (address _address) public view returns (bool) { return borderFactory.inBorderFactory (_address); } function listBorders() public view returns (address[] memory) { return borders; } event AddBorder (address indexed _address); event RemoveBorder (address indexed _address); function addBorder (address _address) internal returns (uint256) { require (!inBorderList(_address), "border exists"); indexBorder[_address] = borders.push(_address)-1; emit AddBorder(_address); return indexBorder[_address]; } function removeBorder (address _address) internal returns (bool) { require (inBorderList(_address), "border not exists"); //Retirar do array Border uint256 indexToDelete = indexBorder[_address]; address addressToMove = borders[borders.length-1]; indexBorder[addressToMove] = indexToDelete; borders[indexToDelete] = addressToMove; borders.length--; indexBorder[_address] = 0; emit RemoveBorder(_address); delete indexToDelete; delete addressToMove; return true; } //ACCOUNTINs event AddAccountIn (address indexed _address); event RemoveAccountIn (address indexed _address); function isAccountIn (address _address) public view returns (bool) { if (indexAccountIn[_address] > 0) return true; else return false; } function addAccountIn (address _address) internal returns (uint256) { require (!isAccountIn(_address), "accountIn exists"); require(accountsIn.length < MaxAccountIn, "max number of accountIN"); indexAccountIn[_address] = accountsIn.push(_address)-1; emit AddAccountIn(_address); return indexAccountIn[_address]; } function removeAccountIn (address _address) internal returns (bool) { require (isAccountIn(_address), "accountIn not exists"); //Retirar do array accountIn uint256 indexToDelete = indexAccountIn[_address]; address addressToMove = accountsIn[accountsIn.length-1]; indexAccountIn[addressToMove] = indexToDelete; accountsIn[indexToDelete] = addressToMove; accountsIn.length--; indexAccountIn[_address] = 0; emit RemoveAccountIn(_address); delete indexToDelete; delete addressToMove; return true; } function shareIncreaseIn(address _account, uint _ratio) public onlyOwner { require (!isBorder(_account), "is border"); SyntropyStruct.TypeShare _accountType; _accountType = SyntropyStruct.TypeShare.In; _shareIncrease(_account, _ratio, _accountType); } // borderTransfer address[] private borderFroms; uint256[] private borderValues; function borderTransfer (uint256 _total, uint256 _borderAmount) public onlyOwner returns (uint256) { //Fazer o approve do USD, para que seja distribuido aqui UsdS usdS = UsdS(usdAddress); Border border; require(usdS.transferFrom(msg.sender, address(this), _borderAmount), "can not transfer to moviment"); //E se o _borderAmount não é suficiente? uint256 totalTransfer = 0; for (uint256 b = 1; b < borders.length; b++) { uint256 totalBorder = 0; //Structs de quem a borda recebe for (uint256 t = 0; t < indexTo[borders[b]].length; t++) { uint256 index = indexTo[borders[b]][t]; uint256 value = ownerShare[index].ratio.mul(_total).div(decimalpercent); totalBorder = totalBorder.add(value); borderFroms.push(ownerShare[index].accountFrom); borderValues.push(value); } if (totalBorder > 0) { totalTransfer = totalTransfer.add(totalBorder); usdS.approve(borders[b], totalBorder); border = Border(borders[b]); border.depositUSD (totalBorder, borderFroms, borderValues); } delete borderFroms; delete borderValues; } //Sobrou troco? devolve para o sender if (_borderAmount.sub(totalTransfer) > 0) { usdS.transfer(msg.sender, _borderAmount.sub(totalTransfer)); } return totalTransfer; } event Transfer(address indexed from, address indexed to, uint256 value); //AccountIN PROCESSAR as entradas - como o depositUSD do Border function accountInTransfer (uint256 _total, uint256 _accountAmount) public onlyOwner returns (uint256) { //Fazer o approve do USD, para que seja distribuido aqui UsdS usdS = UsdS(usdAddress); require(usdS.transferFrom(msg.sender, address(this), _accountAmount), "Can not transfer to moviment"); //USD agora está armazenado no moviment //E se o _accountAmount não é suficiente? uint256 totalTransfer = 0; for (uint256 a = 1; a < accountsIn.length; a++) { uint256 totalAmount = 0; //Structs de quem accountIN recebe for (uint256 t = 0; t < indexTo[accountsIn[a]].length; t++) { uint256 index = indexTo[accountsIn[a]][t]; uint256 amount = ownerShare[index].ratio.mul(_total).div(decimalpercent); totalAmount = totalAmount.add(amount); emit Transfer (ownerShare[index].accountFrom, ownerShare[index].accountTo, amount); } _balances[accountsIn[a]] = _balances[accountsIn[a]].add(totalAmount); totalTransfer = totalTransfer.add(totalAmount); } //Sobrou troco? devolve para o sender if (_accountAmount.sub(totalTransfer) > 0) { usdS.transfer(msg.sender, _accountAmount.sub(totalTransfer)); } return totalTransfer; } //Balance USD in the contract in behalf of account function balanceOf(address account) public view returns (uint256) { return _balances[account]; } //Withdrawal USD in the contract in behalf of msg.sender function withdrawalUSD() public { require(_balances[msg.sender] > 0, "balance is zero"); uint256 value = _balances[msg.sender]; _balances[msg.sender] = 0; UsdS usdS = UsdS(usdAddress); require(usdS.transfer(msg.sender, value), "usdS transfer error"); delete value; } } contract MovimentView { using SafeMath for uint256; // Syntropy By Solange Gueiros uint256 constant decimalpercent = 10000; //100.00 = precisão da porcentagem (2) + 2 casas para 100% /* function test (address _movAddress) public view returns (uint256) { Moviment moviment = Moviment (_movAddress); address[] memory borders; borders = moviment.listBorders(); uint256[] memory indexTo; indexTo = moviment.listIndexTo(borders[1]); //uint256 value = moviment.ratioShare() //ShareStruct memory share = moviment.ownerShare(indexTo[0]); //ShareStruct memory share = moviment.getStructOwnerShare(2); //returns (address accountFrom, address accountTo, uint256 ratio, uint256 indexFrom, uint256 indexTo, TypeShare accountType) //return (ownerShare[_index].accountFrom, ownerShare[_index].accountTo, // ownerShare[_index].ratio, ownerShare[_index].indexFrom, ownerShare[_index].indexTo, ownerShare[_index].accountType); //uint256 total = 0; //return share.ratio; return indexTo[0]; } */ function listIndexFrom (address _movAddress, address _indexAddress) public view returns (uint256[] memory) { Moviment moviment = Moviment (_movAddress); uint256[] memory indexFrom; indexFrom = moviment.listIndexTo(_indexAddress); return indexFrom; } function listIndexTo (address _movAddress, address _indexAddress) public view returns (uint256[] memory) { Moviment moviment = Moviment (_movAddress); uint256[] memory indexTo; indexTo = moviment.listIndexTo(_indexAddress); return indexTo; } function listBorders (address _movAddress) public view returns (address[] memory) { Moviment moviment = Moviment (_movAddress); address[] memory borders; borders = moviment.listBorders(); return borders; } function inBorderList (address _movAddress, address _borderAddress) public view returns (bool) { Moviment moviment = Moviment (_movAddress); if (moviment.indexBorder(_borderAddress) > 0) return true; else return false; } function getStructOwnerShare (address _movAddress, uint256 _index) public view returns (address accountFrom, address accountTo, uint256 ratio, uint256 indexFrom, uint256 indexTo, SyntropyStruct.TypeShare accountType) { Moviment moviment = Moviment (_movAddress); (accountFrom, accountTo, ratio, indexFrom, indexTo, accountType) = moviment.ownerShare(_index); return (accountFrom, accountTo, ratio, indexFrom, indexTo, accountType); } function getBorderAmount (address _movAddress, uint256 _total) public view returns (uint256) { Moviment moviment = Moviment (_movAddress); uint256 total = 0; //Borders address[] memory borders; borders = moviment.listBorders(); for (uint256 b = 1; b < borders.length; b++) { //Structs de quem a borda recebe uint256[] memory indexTo; indexTo = moviment.listIndexTo(borders[b]); for (uint256 t = 0; t < indexTo.length; t++) { (, , uint256 ratio, , , ) = moviment.ownerShare(indexTo[t]); //uint256 ratio = moviment.ratioShareByIndex(indexTo[t]); uint256 value = ratio.mul(_total).div(decimalpercent); total = total.add(value); } } return total; } function getAccountInAmount (address _movAddress, uint256 _total) public view returns (uint256) { Moviment moviment = Moviment (_movAddress); uint256 total = 0; //AccountIns address[] memory accountIns; accountIns = moviment.listAccountsIn(); for (uint256 b = 1; b < accountIns.length; b++) { uint256[] memory indexTo; indexTo = moviment.listIndexTo(accountIns[b]); for (uint256 t = 0; t < indexTo.length; t++) { //uint256 ratio = moviment.ratioShareByIndex(indexTo[t]); (, ,uint256 ratio, , , ) = moviment.ownerShare(indexTo[t]); uint256 value = ratio.mul(_total).div(decimalpercent); total = total.add(value); } } return total; } //Se eu receber XXX, quanto tenho que enviar para as bordas e accountIns, seja em meu nome ou em nome dos outros? function getTransferAmount (address _movAddress, uint256 _total) public view returns (uint256 totalBorders, uint256 totalAccountIns) { totalBorders = getBorderAmount(_movAddress, _total); totalAccountIns = getAccountInAmount(_movAddress, _total); return (totalBorders, totalAccountIns) ; } modifier onlyOwner (address _movAddress) { _onlyOwner(_movAddress); _; } function _onlyOwner (address _movAddress) internal view { Moviment moviment = Moviment (_movAddress); require(moviment.indexOwner(msg.sender) > 0, "only owner"); } event Incoming(address indexed moviment, address indexed from, uint256 value, string description); event AnnounceBorderIncoming(address indexed moviment, address indexed from, address indexed to, uint256 value, string description); event AnnounceShareIncoming(address indexed moviment, address indexed from, address indexed to, uint256 value, SyntropyStruct.TypeShare accountType, string description); //function reportIncoming (address _movAddress, uint256 _value, string memory _description) public onlyOwner { function reportIncoming (address _movAddress, uint256 _total, string memory _description) public onlyOwner(_movAddress) { Moviment moviment = Moviment (_movAddress); emit Incoming(_movAddress, msg.sender, _total, _description); address to; uint256 value; SyntropyStruct.TypeShare accountType; address[] memory owners = moviment.listOwners(); for (uint256 o = 1; o < owners.length; o++) { //Structs para quem o owner envia uint256[] memory indexFrom = moviment.listIndexFrom(owners[o]); for (uint256 f = 0; f < indexFrom.length; f++) { (, to, value, , , accountType) = moviment.ownerShare(indexFrom[f]); value = value.mul(_total).div(decimalpercent); if (accountType == SyntropyStruct.TypeShare.Border) emit AnnounceBorderIncoming (_movAddress, owners[o], to, value, _description); else emit AnnounceShareIncoming (_movAddress, owners[o], to, value, accountType, _description); } } } } contract MovimentFactory { // Syntropy By Solange Gueiros address public usdAddress; address public borderFactory; constructor(address _usdAddress, address _borderFactory) public { usdAddress = _usdAddress; borderFactory = _borderFactory; } event CreateMoviment (address indexed _address, string _name); function createMoviment (string memory _name) public returns (address) { Moviment moviment = new Moviment (_name, borderFactory, usdAddress, msg.sender); emit CreateMoviment (address(moviment), _name); return address(moviment); } } library SafeMath { //By OpenZeppelin 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; } function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } }
Retira do ownerShareAtualiza o index do FromAtualiza o index do ToRetira do From - VERIFICAR: é o último mesmo que tem que retirar?Retira do To - VERIFICAR: é o último mesmo que tem que retirar?
function delShareStruct (uint256 _index) internal returns (bool) { address accountFrom = ownerShare[_index].accountFrom; address accountTo = ownerShare[_index].accountTo; uint256 keyToMove = ownerShare.length - 1; shareIndex[ownerShare[keyToMove].accountFrom][ownerShare[keyToMove].accountTo] = _index; ownerShare[_index].accountFrom = ownerShare[keyToMove].accountFrom; ownerShare[_index].accountTo = ownerShare[keyToMove].accountTo; ownerShare[_index].ratio = ownerShare[keyToMove].ratio; indexFrom[ownerShare[keyToMove].accountFrom][ownerShare[keyToMove].indexFrom] = _index; indexTo[ownerShare[keyToMove].accountTo][ownerShare[keyToMove].indexTo] = _index; ownerShare.length--; indexFrom[accountFrom].length--; indexTo[accountTo].length--; shareIndex[accountFrom][accountTo] = 0; return true; }
12,637,450
[ 1, 7055, 11547, 741, 3410, 9535, 861, 1462, 452, 69, 320, 770, 741, 6338, 861, 1462, 452, 69, 320, 770, 741, 2974, 7055, 11547, 741, 6338, 300, 6422, 22183, 985, 30, 225, 132, 107, 320, 225, 132, 123, 5618, 381, 83, 15216, 8683, 6597, 1022, 6597, 325, 481, 297, 35, 7055, 11547, 741, 2974, 300, 6422, 22183, 985, 30, 225, 132, 107, 320, 225, 132, 123, 5618, 381, 83, 15216, 8683, 6597, 1022, 6597, 325, 481, 297, 35, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 1464, 9535, 3823, 261, 11890, 5034, 389, 1615, 13, 2713, 1135, 261, 6430, 13, 288, 203, 3639, 1758, 2236, 1265, 273, 3410, 9535, 63, 67, 1615, 8009, 4631, 1265, 31, 203, 3639, 1758, 2236, 774, 273, 3410, 9535, 63, 67, 1615, 8009, 4631, 774, 31, 203, 203, 3639, 2254, 5034, 498, 774, 7607, 273, 3410, 9535, 18, 2469, 300, 404, 31, 203, 3639, 7433, 1016, 63, 8443, 9535, 63, 856, 774, 7607, 8009, 4631, 1265, 6362, 8443, 9535, 63, 856, 774, 7607, 8009, 4631, 774, 65, 273, 389, 1615, 31, 203, 3639, 3410, 9535, 63, 67, 1615, 8009, 4631, 1265, 273, 3410, 9535, 63, 856, 774, 7607, 8009, 4631, 1265, 31, 203, 3639, 3410, 9535, 63, 67, 1615, 8009, 4631, 774, 273, 3410, 9535, 63, 856, 774, 7607, 8009, 4631, 774, 31, 203, 3639, 3410, 9535, 63, 67, 1615, 8009, 9847, 273, 3410, 9535, 63, 856, 774, 7607, 8009, 9847, 31, 203, 203, 3639, 770, 1265, 63, 8443, 9535, 63, 856, 774, 7607, 8009, 4631, 1265, 6362, 8443, 9535, 63, 856, 774, 7607, 8009, 1615, 1265, 65, 273, 389, 1615, 31, 203, 203, 3639, 770, 774, 63, 8443, 9535, 63, 856, 774, 7607, 8009, 4631, 774, 6362, 8443, 9535, 63, 856, 774, 7607, 8009, 1615, 774, 65, 273, 389, 1615, 31, 203, 203, 3639, 3410, 9535, 18, 2469, 413, 31, 203, 203, 3639, 770, 1265, 63, 4631, 1265, 8009, 2469, 413, 31, 203, 540, 203, 3639, 770, 774, 63, 4631, 774, 8009, 2469, 413, 31, 203, 203, 3639, 7433, 1016, 63, 4631, 2 ]
./partial_match/42/0x631FFD1AA2A854736727b02379a147cBE0E98F9f/sources/UBXGStaking.sol
notice The status of updated pool info by owner
mapping (uint256 => bool) ownerPoolInfoUpdate;
3,328,076
[ 1, 20392, 1021, 1267, 434, 3526, 2845, 1123, 635, 3410, 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, 2874, 261, 11890, 5034, 516, 1426, 13, 3410, 2864, 966, 1891, 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 ]
pragma solidity 0.4.21; import '../contracts/misc/SafeMath.sol'; import '../contracts/misc/Ownable.sol'; interface Dgvc { function balanceOf(address _owner) external constant returns (uint256 balance); } interface Reputation { function getGroupRate (uint _rep) external returns (uint8); function calculateRep(uint fullPlatformReputation, uint curatorReputation, bool _activation, bool _quorum, bool _uptick, bool _downtick, bool _flag) external returns (uint, uint8, uint); } interface Limit { function setLimits(uint8 _repGroup, uint dgvcBalance) external returns (uint, uint, uint, uint); function checkUpdateLimits(uint _limit) external returns (bool, uint); } interface CuratorPoolContract { function getTransit() external returns(uint, uint); } contract Curator is Ownable { using SafeMath for *; Dgvc public dgvcToken; Reputation public reputation; Limit public limit; CuratorPoolContract public curatorPoolContract; address public proposalContractAddress; address[] curatorAddresses; struct CuratorInstance { bool exist; //to check if curator exists uint reputation; // reputation that accumulating during his work on the platform and impacts on the limits uint rewarding; //accumulated rewarding which should be paid to curator uint8 reputationGroup; uint limitLike; //limits uint limitFlag; uint limitComment; uint limitLikeComment; uint timestampLimits; // when limits was done uint totalAssessed; // number of accessed ICOs uint totalRated; // number of rated ICOs } uint fullPlatformReputation; // rate of reputation, depends on was proposal activated or not, reached quorum or not and curator's reaction uint activationQuorumUptick; //if proposal was activated, reached the quorum and curator uptick this proposal uint noActivationNoQuorumDowntick; //if proposal was not activated, not reached the quorum and curator downtick this proposal uint activationNoQuorumDowntick; //if proposal was activated, not reached the quorum and curator downtick this proposal uint activationNoQuorumUptick; //if proposal was activated, not reached the quorum and curator uptick this proposal uint noActivationNoQuorumUptick; //if proposal was not activated,not reached the quorum and curator uptick this proposal uint activationQuorumDowntick; //if proposal was activated, reached the quorum and curator downtick this proposal mapping(address => CuratorInstance) curators; //mapping(address => uint) balances; //Transit public transition; //address public proposalController; //ProposalController contract address function Curator() public { owner = msg.sender; // sum of reputation from all curators on the fullPlatformReputation //fullPlatformReputation = 0; //reputation rates activationQuorumUptick = 7; noActivationNoQuorumDowntick = 2; activationNoQuorumDowntick = 7; activationNoQuorumUptick = 5; noActivationNoQuorumUptick = 2; activationQuorumDowntick = 5; } function setCuratorPool(address _curatorPool) public { require(_curatorPool != address(0)); curatorPoolContract = CuratorPoolContract(_curatorPool); } function setReputationGroupAddress(address _reputationAddress) public onlyOwner { require(_reputationAddress != address(0)); reputation = Reputation(_reputationAddress); } function setDgvcContractAddress(address _dgvcTokenAddress) public onlyOwner { require(_dgvcTokenAddress != address(0)); dgvcToken = Dgvc(_dgvcTokenAddress); } function setLimitContractAddress(address _limitAddress) public onlyOwner { require(_limitAddress != address(0)); limit = Limit(_limitAddress); } function setProposalContractAddress(address _proposalContractAddress) public onlyOwner { require(_proposalContractAddress != address(0)); proposalContractAddress = _proposalContractAddress; } modifier onlyProposal() { require(msg.sender == proposalContractAddress); _; } function getBalance() public view returns (uint256) { return dgvcToken.balanceOf(msg.sender); } //create curator with 0 reputation, 0 rewarding and 1 reputation group function createCurator() public { require(!curators[msg.sender].exist); uint256 dgvcBalance = dgvcToken.balanceOf(msg.sender); require(dgvcBalance >= 5*1e4); if (dgvcBalance >= 5*1e4 && dgvcBalance < 1000*1e4 ) { curators[msg.sender] = CuratorInstance(true, 0, 0, 1, 30, 0, 0, 5, now, 0, 0); } if (dgvcBalance >= 1000*1e4 && dgvcBalance < 2000*1e4) { curators[msg.sender] = CuratorInstance(true, 0, 0, 1, 20, 1, 1, 10, now, 0, 0); } if (dgvcBalance >= 2000*1e4 && dgvcBalance < 10000*1e4) { curators[msg.sender] = CuratorInstance(true, 0, 0, 1, 20, 3, 4, 10, now, 0, 0); } if (dgvcBalance >= 10000*1e4) { curators[msg.sender] = CuratorInstance(true, 0, 0, 1, 30, 5, 5, 10000, now, 0, 0); } curatorAddresses.push(msg.sender); } //getter for ReputationGroup contract to divide curators for different reputation group function getFullReputation() public view returns (uint) { return fullPlatformReputation; } //get curator's reputation from proposal contract in order to store data about reputation of those curators who uptick comment function getReputation(address _curator) public view returns (uint) { return curators[_curator].reputation; } //get curator's reputation group from proposal contract in order to store data about reputation of those curators who uptick comment function getReputationGroup(address _curator) public view returns (uint) { return curators[_curator].reputationGroup; } //ProposalController call these two functions (calcPos, calcNeg - positive and negative reputation) //one by one to calculate reputation and rates of group //according to curator's reputation. Also here we calculate 'fullPlatformReputation' //groupA = 1 //groupB = 2 //groupC = 3 //groupD = 4 function calculateReputation(address _curator, bool _activation, bool _quorum, bool _uptick, bool _downtick, bool _flag) external onlyProposal { uint256 dgvcBalance = dgvcToken.balanceOf(_curator); require(curators[_curator].exist && dgvcBalance >= 5); (curators[_curator].reputation, curators[_curator].reputationGroup, fullPlatformReputation) = reputation.calculateRep(fullPlatformReputation, curators[_curator].reputation, _activation, _quorum, _uptick, _downtick, _flag); //reputation.calculateRates curators[_curator].reputationGroup = reputation.getGroupRate(curators[_curator].reputation); } //proposal contract checks curator's limits for 24 hours once he made some action with proposal //1 == uptick proposal, 2 == downtick proposal, 3 == flag proposal, 4 == comment, 5 == commentLike function limits(address _curator, uint8 _action) external onlyProposal returns (bool) { uint256 dgvcBalance = dgvcToken.balanceOf(_curator); require(curators[_curator].exist && dgvcBalance >= 5); if (now < (curators[_curator].timestampLimits + 24 hours)) { return subtractLimits(_curator, _action); } if (now >= (curators[_curator].timestampLimits + 24 hours)) { curators[_curator].timestampLimits = now; //if timestamp is more then + 24 hours we set timestamp 'now' (curators[_curator].limitLike, curators[_curator].limitFlag, curators[_curator].limitComment, curators[_curator].limitLikeComment) = limit.setLimits(curators[_curator].reputationGroup, dgvcBalance); //and call function to refresh limits return subtractLimits(_curator, _action); } } function subtractLimits(address _curator, uint8 _action) internal returns (bool){ bool hasLimit; uint newLimit; if (_action == 1 || _action == 2) { //then we need to subtract of limits exact action (hasLimit, newLimit) = limit.checkUpdateLimits(curators[_curator].limitLike); curators[_curator].limitLike = newLimit; return hasLimit; } if (_action == 3) { (hasLimit, newLimit) = limit.checkUpdateLimits(curators[_curator].limitFlag); curators[_curator].limitFlag = newLimit; return hasLimit; } if (_action == 4) { (hasLimit, newLimit) = limit.checkUpdateLimits(curators[_curator].limitComment); curators[_curator].limitComment = newLimit; return hasLimit; } if (_action == 5) { (hasLimit, newLimit) = limit.checkUpdateLimits(curators[_curator].limitLikeComment); curators[_curator].limitLikeComment = newLimit; return hasLimit; } } // get limits to place in ui by curator's address function getLimits(address _curator) public view returns (uint, uint, uint, uint) { require(curators[_curator].exist); return ( curators[_curator].limitLike, curators[_curator].limitFlag, curators[_curator].limitComment, curators[_curator].limitLikeComment ); } // check if curator is existed function checkExistence(address _curator) external view returns(bool) { uint256 dgvcBalance = dgvcToken.balanceOf(_curator); if (curators[_curator].exist && dgvcBalance >= 5) { return true; } else { return false; } } function getCurators() public view returns(address[]) { return curatorAddresses; } // 1 == rated, 2 == accessed function addRateAccessCount(uint8 _type, address _curator) external onlyProposal { if (_type == 1) { curators[_curator].totalRated += 1; } else if (_type == 2) { curators[_curator].totalAssessed += 1; } else { revert(); } } function getRatedAccessedAmount(address _curator) public view returns(uint, uint) { return( curators[_curator].totalRated, curators[_curator].totalAssessed ); } }
create curator with 0 reputation, 0 rewarding and 1 reputation group
function createCurator() public { require(!curators[msg.sender].exist); uint256 dgvcBalance = dgvcToken.balanceOf(msg.sender); require(dgvcBalance >= 5*1e4); if (dgvcBalance >= 5*1e4 && dgvcBalance < 1000*1e4 ) { curators[msg.sender] = CuratorInstance(true, 0, 0, 1, 30, 0, 0, 5, now, 0, 0); } if (dgvcBalance >= 1000*1e4 && dgvcBalance < 2000*1e4) { curators[msg.sender] = CuratorInstance(true, 0, 0, 1, 20, 1, 1, 10, now, 0, 0); } if (dgvcBalance >= 2000*1e4 && dgvcBalance < 10000*1e4) { curators[msg.sender] = CuratorInstance(true, 0, 0, 1, 20, 3, 4, 10, now, 0, 0); } if (dgvcBalance >= 10000*1e4) { curators[msg.sender] = CuratorInstance(true, 0, 0, 1, 30, 5, 5, 10000, now, 0, 0); } curatorAddresses.push(msg.sender); }
919,873
[ 1, 2640, 662, 639, 598, 374, 283, 458, 367, 16, 374, 19890, 310, 471, 404, 283, 458, 367, 1041, 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, 445, 752, 2408, 639, 1435, 1071, 288, 203, 3639, 2583, 12, 5, 1397, 3062, 63, 3576, 18, 15330, 8009, 7398, 1769, 203, 3639, 2254, 5034, 14938, 4227, 13937, 273, 14938, 4227, 1345, 18, 12296, 951, 12, 3576, 18, 15330, 1769, 203, 3639, 2583, 12, 72, 75, 4227, 13937, 1545, 1381, 14, 21, 73, 24, 1769, 203, 3639, 309, 261, 72, 75, 4227, 13937, 1545, 1381, 14, 21, 73, 24, 597, 14938, 4227, 13937, 411, 4336, 14, 21, 73, 24, 262, 288, 203, 5411, 662, 3062, 63, 3576, 18, 15330, 65, 273, 7251, 639, 1442, 12, 3767, 16, 374, 16, 374, 16, 404, 16, 225, 5196, 16, 374, 16, 374, 16, 1381, 16, 2037, 16, 374, 16, 374, 1769, 203, 3639, 289, 203, 3639, 309, 261, 72, 75, 4227, 13937, 1545, 4336, 14, 21, 73, 24, 597, 14938, 4227, 13937, 411, 16291, 14, 21, 73, 24, 13, 288, 203, 5411, 662, 3062, 63, 3576, 18, 15330, 65, 273, 7251, 639, 1442, 12, 3767, 16, 374, 16, 374, 16, 404, 16, 225, 4200, 16, 404, 16, 404, 16, 1728, 16, 2037, 16, 374, 16, 374, 1769, 203, 3639, 289, 203, 3639, 309, 261, 72, 75, 4227, 13937, 1545, 16291, 14, 21, 73, 24, 597, 14938, 4227, 13937, 411, 12619, 14, 21, 73, 24, 13, 288, 203, 5411, 662, 3062, 63, 3576, 18, 15330, 65, 273, 7251, 639, 1442, 12, 3767, 16, 374, 16, 374, 16, 404, 16, 225, 4200, 16, 890, 16, 1059, 16, 1728, 16, 2037, 16, 374, 16, 374, 1769, 203, 3639, 289, 2 ]
./full_match/43113/0x1f8a61267136BB9511ac51bdd96379038526391C/sources/Multisig.sol
@dev Allows to add a new owner. Transaction has to be sent by wallet. @param owner Address of new owner.
function addOwner(address owner) public onlyWallet ownerDoesNotExist(owner) notNull(owner) validRequirement(owners.length + 1, confirmationsRequired) { owners.push(owner); _isOwner[owner] = owners.length; emit OwnerAddition(owner); }
7,136,561
[ 1, 19132, 358, 527, 279, 394, 3410, 18, 5947, 711, 358, 506, 3271, 635, 9230, 18, 225, 3410, 5267, 434, 394, 3410, 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 ]
[ 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, 0, 0 ]
[ 1, 565, 445, 527, 5541, 12, 2867, 3410, 13, 203, 3639, 1071, 203, 3639, 1338, 16936, 203, 3639, 3410, 15264, 12, 8443, 13, 203, 3639, 7713, 12, 8443, 13, 203, 3639, 923, 18599, 12, 995, 414, 18, 2469, 397, 404, 16, 6932, 1012, 3705, 13, 203, 565, 288, 203, 3639, 25937, 18, 6206, 12, 8443, 1769, 203, 3639, 389, 291, 5541, 63, 8443, 65, 273, 25937, 18, 2469, 31, 203, 540, 203, 3639, 3626, 16837, 30296, 12, 8443, 1769, 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 ]
./full_match/42/0xe9c33878b0a99C3Ac75890ecA5499A9290988171/sources/atomicSwap.sol
Second address of path
path[1] = tokenToSwapAddress;
16,208,052
[ 1, 8211, 1758, 434, 589, 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, 3639, 589, 63, 21, 65, 273, 1147, 774, 12521, 1887, 31, 28524, 5411, 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.17; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20Detailed.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20Mintable.sol"; import "../interfaces/TTokenInterface.sol"; /** * @notice This contract represents a wrapped token within the Teller protocol * * @author [email protected] */ contract TToken is TTokenInterface, ERC20Detailed, ERC20Mintable { /* Constructor */ /** * @param name The name of the token * @param symbol The symbol of the token * @param decimals The amount of decimals for the token */ constructor( string memory name, string memory symbol, uint8 decimals ) public { ERC20Detailed.initialize(name, symbol, decimals); ERC20Mintable.initialize(msg.sender); } /* Public Functions */ /** * @notice Reduce account supply of specified token amount * @param account The account to burn tokens from * @param amount The amount of tokens to burn * @return true if successful */ function burn(address account, uint256 amount) public onlyMinter returns (bool) { _burn(account, amount); return true; } }
Public Functions */* @notice Reduce account supply of specified token amount @param account The account to burn tokens from @param amount The amount of tokens to burn @return true if successful/
function burn(address account, uint256 amount) public onlyMinter returns (bool) { _burn(account, amount); return true; }
5,358,381
[ 1, 4782, 15486, 342, 225, 24614, 2236, 14467, 434, 1269, 1147, 3844, 225, 2236, 1021, 2236, 358, 18305, 2430, 628, 225, 3844, 1021, 3844, 434, 2430, 358, 18305, 327, 638, 309, 6873, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 445, 18305, 12, 2867, 2236, 16, 2254, 5034, 3844, 13, 1071, 1338, 49, 2761, 1135, 261, 6430, 13, 288, 203, 3639, 389, 70, 321, 12, 4631, 16, 3844, 1769, 203, 3639, 327, 638, 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 ]
//SPDX-License-Identifier: MIT pragma solidity ^0.8.6; import { ITreasury, IUniswapV2Factory, IUniswapV2Router01 } from "./ERC20.sol"; /// @dev The TaxToken is responsible for supporting generic ERC20 functionality including ERC20Pausable functionality. /// The TaxToken will generate taxes on transfer() and transferFrom() calls for non-whitelisted addresses. /// The Admin can specify the tax fee in basis points for buys, sells, and transfers. /// The TaxToken will forward all taxes generated to a Treasury contract TaxToken { // --------------- // State Variables // --------------- // ERC20 Basic uint256 _totalSupply; uint8 private _decimals; string private _name; string private _symbol; // ERC20 Pausable bool private _paused; // ERC20 Pausable state // Extras address public owner; address public treasury; address public UNIV2_ROUTER = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; bool public taxesRemoved; /// @dev Once true, taxes are permanently set to 0 and CAN NOT be increased in the future. uint256 public maxWalletSize; uint256 public maxTxAmount; // ERC20 Mappings mapping(address => uint256) balances; // Track balances. mapping(address => mapping(address => uint256)) allowed; // Track allowances. // Extras Mappings mapping(address => bool) public blacklist; /// @dev If an address is blacklisted, they cannot perform transfer() or transferFrom(). mapping(address => bool) public whitelist; /// @dev Any transfer that involves a whitelisted address, will not incur a tax. mapping(address => uint) public senderTaxType; /// @dev Identifies tax type for msg.sender of transfer() call. mapping(address => uint) public receiverTaxType; /// @dev Identifies tax type for _to of transfer() call. mapping(uint => uint) public basisPointsTax; /// @dev Mapping between taxType and basisPoints (taxed). // ----------- // Constructor // ----------- /// @notice Initializes the TaxToken. /// @param totalSupplyInput The total supply of this token (this value is multipled by 10**decimals in constructor). /// @param nameInput The name of this token. /// @param symbolInput The symbol of this token. /// @param decimalsInput The decimal precision of this token. /// @param maxWalletSizeInput The maximum wallet size (this value is multipled by 10**decimals in constructor). /// @param maxTxAmountInput The maximum tx size (this value is multipled by 10**decimals in constructor). constructor( uint totalSupplyInput, string memory nameInput, string memory symbolInput, uint8 decimalsInput, uint256 maxWalletSizeInput, uint256 maxTxAmountInput ) { _paused = false; // ERC20 Pausable global state variable, initial state is not paused ("unpaused"). _name = nameInput; _symbol = symbolInput; _decimals = decimalsInput; _totalSupply = totalSupplyInput * 10**_decimals; // Create a uniswap pair for this new token address UNISWAP_V2_PAIR = IUniswapV2Factory( IUniswapV2Router01(UNIV2_ROUTER).factory() ).createPair(address(this), IUniswapV2Router01(UNIV2_ROUTER).WETH()); senderTaxType[UNISWAP_V2_PAIR] = 1; receiverTaxType[UNISWAP_V2_PAIR] = 2; owner = msg.sender; // The "owner" is the "admin" of this contract. balances[msg.sender] = totalSupplyInput * 10**_decimals; // Initial liquidity, allocated entirely to "owner". maxWalletSize = maxWalletSizeInput * 10**_decimals; maxTxAmount = maxTxAmountInput * 10**_decimals; } // --------- // Modifiers // --------- /// @dev whenNotPausedUni() is used if the contract MUST be paused ("paused"). modifier whenNotPausedUni(address a) { require(!paused() || whitelist[a], "ERR: Contract is currently paused."); _; } /// @dev whenNotPausedDual() is used if the contract MUST be paused ("paused"). modifier whenNotPausedDual(address from, address to) { require(!paused() || whitelist[from] || whitelist[to], "ERR: Contract is currently paused."); _; } /// @dev whenNotPausedTri() is used if the contract MUST be paused ("paused"). modifier whenNotPausedTri(address from, address to, address sender) { require(!paused() || whitelist[from] || whitelist[to] || whitelist[sender], "ERR: Contract is currently paused."); _; } /// @dev whenPaused() is used if the contract MUST NOT be paused ("unpaused"). modifier whenPaused() { require(paused(), "ERR: Contract is not currently paused."); _; } /// @dev onlyOwner() is used if msg.sender MUST be owner. modifier onlyOwner { require(msg.sender == owner, "ERR: TaxToken.sol, onlyOwner()"); _; } // ------ // Events // ------ event Paused(address account); /// @dev Emitted when the pause is triggered by `account`. event Unpaused(address account); /// @dev Emitted when the pause is lifted by `account`. /// @dev Emitted when approve() is called. event Approval(address indexed _owner, address indexed _spender, uint256 _value); /// @dev Emitted during transfer() or transferFrom(). event Transfer(address indexed _from, address indexed _to, uint256 _value); event TransferTax(address indexed _from, address indexed _to, uint256 _value, uint256 _taxType); // --------- // Functions // --------- // ~ ERC20 View ~ 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; } function totalSupply() public view returns (uint256) { return _totalSupply; } function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } // ~ ERC20 transfer(), transferFrom(), approve() ~ function approve(address _spender, uint256 _amount) public returns (bool success) { allowed[msg.sender][_spender] = _amount; emit Approval(msg.sender, _spender, _amount); return true; } function transfer(address _to, uint256 _amount) public whenNotPausedDual(msg.sender, _to) returns (bool success) { // taxType 0 => Xfer Tax // taxType 1 => Buy Tax // taxType 2 => Sell Tax uint _taxType; if (balances[msg.sender] >= _amount && (!blacklist[msg.sender] && !blacklist[_to])) { // Take a tax from them if neither party is whitelisted. if (!whitelist[_to] && !whitelist[msg.sender] && _amount <= maxTxAmount) { // Determine, if not the default 0, tax type of transfer. if (senderTaxType[msg.sender] != 0) { _taxType = senderTaxType[msg.sender]; } if (receiverTaxType[_to] != 0) { _taxType = receiverTaxType[_to]; } // Calculate taxAmt and sendAmt. uint _taxAmt = _amount * basisPointsTax[_taxType] / 10000; uint _sendAmt = _amount * (10000 - basisPointsTax[_taxType]) / 10000; if (balances[_to] + _sendAmt <= maxWalletSize) { balances[msg.sender] -= _amount; balances[_to] += _sendAmt; balances[treasury] += _taxAmt; require(_taxAmt + _sendAmt >= _amount * 999999999 / 1000000000, "Critical error, math."); // Update accounting in Treasury. ITreasury(treasury).updateTaxesAccrued( _taxType, _taxAmt ); emit Transfer(msg.sender, _to, _sendAmt); emit TransferTax(msg.sender, treasury, _taxAmt, _taxType); return true; } else { return false; } } else if (!whitelist[_to] && !whitelist[msg.sender] && _amount > maxTxAmount) { return false; } else { balances[msg.sender] -= _amount; balances[_to] += _amount; emit Transfer(msg.sender, _to, _amount); return true; } } else { return false; } } function transferFrom(address _from, address _to, uint256 _amount) public whenNotPausedTri(_from, _to, msg.sender) returns (bool success) { // taxType 0 => Xfer Tax // taxType 1 => Buy Tax // taxType 2 => Sell Tax uint _taxType; if ( balances[_from] >= _amount && allowed[_from][msg.sender] >= _amount && _amount > 0 && balances[_to] + _amount > balances[_to] && _amount <= maxTxAmount && (!blacklist[_from] && !blacklist[_to]) ) { // Reduce allowance. allowed[_from][msg.sender] -= _amount; // Take a tax from them if neither party is whitelisted. if (!whitelist[_to] && !whitelist[_from] && _amount <= maxTxAmount) { // Determine, if not the default 0, tax type of transfer. if (senderTaxType[_from] != 0) { _taxType = senderTaxType[_from]; } if (receiverTaxType[_to] != 0) { _taxType = receiverTaxType[_to]; } // Calculate taxAmt and sendAmt. uint _taxAmt = _amount * basisPointsTax[_taxType] / 10000; uint _sendAmt = _amount * (10000 - basisPointsTax[_taxType]) / 10000; if (balances[_to] + _sendAmt <= maxWalletSize || _taxType == 2) { balances[_from] -= _amount; balances[_to] += _sendAmt; balances[treasury] += _taxAmt; require(_taxAmt + _sendAmt == _amount, "Critical error, math."); // Update accounting in Treasury. ITreasury(treasury).updateTaxesAccrued( _taxType, _taxAmt ); emit Transfer(_from, _to, _sendAmt); emit TransferTax(_from, treasury, _taxAmt, _taxType); return true; } else { return false; } } else if (!whitelist[_to] && !whitelist[_from] && _amount > maxTxAmount) { return false; } // Skip taxation if either party is whitelisted (_from or _to). else { balances[_from] -= _amount; balances[_to] += _amount; emit Transfer(_from, _to, _amount); return true; } } else { return false; } } function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return allowed[_owner][_spender]; } // ~ ERC20 Pausable ~ /// @notice Pause the contract, blocks transfer() and transferFrom(). /// @dev Contract MUST NOT be paused to call this, caller must be "owner". function pause() public onlyOwner whenNotPausedUni(msg.sender) { _paused = true; emit Paused(msg.sender); } /// @notice Unpause the contract. /// @dev Contract MUST be puased to call this, caller must be "owner". function unpause() public onlyOwner whenPaused { _paused = false; emit Unpaused(msg.sender); } /// @return _paused Indicates whether the contract is paused (true) or not paused (false). function paused() public view virtual returns (bool) { return _paused; } // ~ TaxType & Fee Management ~ /// @notice Used to store the LP Pair to differ type of transaction. Will be used to mark a BUY. /// @dev _taxType must be lower than 3 because there can only be 3 tax types; buy, sell, & send. /// @param _sender This value is the PAIR address. /// @param _taxType This value must be be 0, 1, or 2. Best to correspond value with the BUY tax type. function updateSenderTaxType(address _sender, uint _taxType) public onlyOwner { require(_taxType < 3, "err _taxType must be less than 3"); senderTaxType[_sender] = _taxType; } /// @notice Used to store the LP Pair to differ type of transaction. Will be used to mark a SELL. /// @dev _taxType must be lower than 3 because there can only be 3 tax types; buy, sell, & send. /// @param _receiver This value is the PAIR address. /// @param _taxType This value must be be 0, 1, or 2. Best to correspond value with the SELL tax type. function updateReceiverTaxType(address _receiver, uint _taxType) public onlyOwner { require(_taxType < 3, "err _taxType must be less than 3"); receiverTaxType[_receiver] = _taxType; } /// @notice Used to map the tax type 0, 1 or 2 with it's corresponding tax percentage. /// @dev Must be lower than 2000 which is equivalent to 20%. /// @param _taxType This value is the tax type. Has to be 0, 1, or 2. /// @param _bpt This is the corresponding percentage that is taken for royalties. 1200 = 12%. function adjustBasisPointsTax(uint _taxType, uint _bpt) public onlyOwner { require(_bpt <= 2000, "err TaxToken.sol _bpt > 2000 (20%)"); require(!taxesRemoved, "err TaxToken.sol taxation has been removed"); basisPointsTax[_taxType] = _bpt; } /// @notice Permanently remove taxes from this contract. /// @dev An input is required here for sanity-check, given importance of this function call (and irreversible nature). /// @param _key This value MUST equal 42 for function to execute. function permanentlyRemoveTaxes(uint _key) public onlyOwner { require(_key == 42, "err TaxToken.sol _key != 42"); basisPointsTax[0] = 0; basisPointsTax[1] = 0; basisPointsTax[2] = 0; taxesRemoved = true; } // ~ Admin ~ /// @notice This is used to change the owner's wallet address. Used to give ownership to another wallet. /// @param _owner is the new owner address. function transferOwnership(address _owner) public onlyOwner { owner = _owner; } /// @notice Set the treasury (contract)) which receives taxes generated through transfer() and transferFrom(). /// @param _treasury is the contract address of the treasury. function setTreasury(address _treasury) public onlyOwner { treasury = _treasury; } /// @notice Adjust maxTxAmount value (maximum amount transferrable in a single transaction). /// @dev Does not affect whitelisted wallets. /// @param _maxTxAmount is the max amount of tokens that can be transacted at one time for a non-whitelisted wallet. function updateMaxTxAmount(uint256 _maxTxAmount) public onlyOwner { maxTxAmount = (_maxTxAmount * 10**_decimals); } /// @notice This function is used to set the max amount of tokens a wallet can hold. /// @dev Does not affect whitelisted wallets. /// @param _maxWalletSize is the max amount of tokens that can be held on a non-whitelisted wallet. function updateMaxWalletSize(uint256 _maxWalletSize) public onlyOwner { maxWalletSize = (_maxWalletSize * 10**_decimals); } /// @notice This function is used to add wallets to the whitelist mapping. /// @dev Whitelisted wallets are not affected by maxWalletSize, maxTxAmount, and taxes. /// @param _wallet is the wallet address that will have their whitelist status modified. /// @param _whitelist use True to whitelist a wallet, otherwise use False to remove wallet from whitelist. function modifyWhitelist(address _wallet, bool _whitelist) public onlyOwner { whitelist[_wallet] = _whitelist; } /// @notice This function is used to add or remove wallets from the blacklist. /// @dev Blacklisted wallets cannot perform transfer() or transferFrom(). /// @param _wallet is the wallet address that will have their blacklist status modified. /// @param _blacklist use True to blacklist a wallet, otherwise use False to remove wallet from blacklist. function modifyBlacklist(address _wallet, bool _blacklist) public onlyOwner { blacklist[_wallet] = _blacklist; } }
ERC20 Pausable global state variable, initial state is not paused ("unpaused").
_paused = false;
13,595,657
[ 1, 654, 39, 3462, 21800, 16665, 2552, 919, 2190, 16, 2172, 919, 353, 486, 17781, 7566, 318, 8774, 3668, 20387, 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 ]
[ 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, 0 ]
[ 1, 3639, 389, 8774, 3668, 273, 629, 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, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/80001/0xc34B52F78985DaeFcEea47A4a76E68D34717b074/sources/contracts/prebuilts/marketplace/IMarketplace.sol
* @notice The parameters a seller sets when creating or updating a listing. @param assetContract The address of the smart contract of the NFTs being listed. @param tokenId The tokenId of the NFTs being listed. @param quantity The quantity of NFTs being listed. This must be non-zero, and is expected to be `1` for ERC-721 NFTs. @param currency The currency in which the price must be paid when buying the listed NFTs. @param pricePerToken The price to pay per unit of NFTs listed. @param startTimestamp The UNIX timestamp at and after which NFTs can be bought from the listing. @param endTimestamp The UNIX timestamp at and after which NFTs cannot be bought from the listing. @param reserved Whether the listing is reserved to be bought from a specific set of buyers./
struct ListingParameters { address assetContract; uint256 tokenId; uint256 quantity; address currency; uint256 pricePerToken; uint128 startTimestamp; uint128 endTimestamp; bool reserved; }
5,602,929
[ 1, 1986, 1472, 279, 29804, 1678, 1347, 4979, 578, 9702, 279, 11591, 18, 282, 3310, 8924, 1021, 1758, 434, 326, 13706, 6835, 434, 326, 423, 4464, 87, 3832, 12889, 18, 282, 1147, 548, 1021, 1147, 548, 434, 326, 423, 4464, 87, 3832, 12889, 18, 282, 10457, 1021, 10457, 434, 423, 4464, 87, 3832, 12889, 18, 1220, 1297, 506, 1661, 17, 7124, 16, 471, 353, 2665, 358, 5375, 506, 1375, 21, 68, 364, 4232, 39, 17, 27, 5340, 423, 4464, 87, 18, 282, 5462, 1021, 5462, 316, 1492, 326, 6205, 1297, 506, 30591, 1347, 30143, 310, 326, 12889, 423, 4464, 87, 18, 282, 6205, 2173, 1345, 1021, 6205, 358, 8843, 1534, 2836, 434, 423, 4464, 87, 12889, 18, 282, 787, 4921, 1021, 23160, 2858, 622, 471, 1839, 1492, 423, 4464, 87, 848, 506, 800, 9540, 628, 326, 11591, 18, 282, 679, 4921, 1021, 23160, 2858, 622, 471, 1839, 1492, 423, 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, 1958, 987, 310, 2402, 288, 203, 3639, 1758, 3310, 8924, 31, 203, 3639, 2254, 5034, 1147, 548, 31, 203, 3639, 2254, 5034, 10457, 31, 203, 3639, 1758, 5462, 31, 203, 3639, 2254, 5034, 6205, 2173, 1345, 31, 203, 3639, 2254, 10392, 787, 4921, 31, 203, 3639, 2254, 10392, 679, 4921, 31, 203, 3639, 1426, 8735, 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 ]
/** * @file LibJson.sol * @author liaoyan * @time 2017-07-01 * @desc The definition of LibJson library. * All functions in this library are extension functions, * call eth functionalities through assembler commands. * * @funcs * isJson(string _json) internal constant returns(bool _ret) * jsonRead(string _json, string _keyPath) internal constant returns(string _ret) * jsonKeyExists(string _json, string _keyPath) internal constant returns(bool _ret) * jsonUpdate(string _json, string _key, string _value) internal constant returns (string _ret) * * @usage * 1) import "LibJson.sol"; * 2) using LibJson for *; */ pragma solidity ^0.4.19; import "./LibInt.sol"; import "./LibString.sol"; import "./LibLog.sol"; library LibJson { using LibInt for *; using LibString for *; using LibJson for *; function isJson(string _json) internal constant returns(bool _ret) { string memory arg = "[69d98d6a04c41b4605aacb7bd2f74bee][09JsonParse]"; uint argptr; uint arglen = bytes(arg).length; bytes32 b32; assembly { argptr := add(arg, 0x20) b32 := sha3(argptr, arglen) } if (uint(b32) != 0) return true; else return false; } /* function jsonRead(string _json, string _keyPath) internal constant returns(string _ret) { uint i = 0; while (true) { string memory arg = "[69d98d6a04c41b4605aacb7bd2f74bee][08JsonRead]"; arg = arg.concat(_keyPath, "|$%&@*^#!|"); arg = arg.concat(uint(i*32).toString(), "|$%&@*^#!|", uint(32).toString()); uint argptr; uint arglen = bytes(arg).length; bytes32 b32; assembly { argptr := add(arg, 0x20) b32 := sha3(argptr, arglen) } string memory r = uint(b32).recoveryToString(); _ret = _ret.concat(r); if (bytes(r).length < 32) break; ++i; } } */ function jsonRead(string _json, string _keyPath) internal constant returns(string _ret) { _ret = ""; uint len = jsonKeyExistsEx(_json, _keyPath); if (len > 0) { _ret = new string(len); uint strptr; assembly { strptr := add(_ret, 0x20) } string memory arg = "[69d98d6a04c41b4605aacb7bd2f74bee][10JsonReadEx]"; arg = arg.concat(_keyPath); arg = arg.concat("|$%&@*^#!|", strptr.toString()); uint argptr; uint arglen = bytes(arg).length; bytes32 b32; assembly { argptr := add(arg, 0x20) b32 := sha3(argptr, arglen) } string memory errRet = ""; uint ret = uint(b32); if (ret != 0) { return errRet; } } } function jsonKeyExists(string _json, string _keyPath) internal constant returns(bool _ret) { string memory arg = "[69d98d6a04c41b4605aacb7bd2f74bee][13JsonKeyExists]"; arg = arg.concat(_keyPath); uint argptr; uint arglen = bytes(arg).length; bytes32 b32; assembly { argptr := add(arg, 0x20) b32 := sha3(argptr, arglen) } if (uint(b32) != 0) return true; else return false; } function jsonKeyExistsEx(string _json, string _keyPath) internal constant returns(uint _len) { string memory arg = "[69d98d6a04c41b4605aacb7bd2f74bee][15JsonKeyExistsEx]"; arg = arg.concat(_keyPath); uint argptr; uint arglen = bytes(arg).length; bytes32 b32; assembly { argptr := add(arg, 0x20) b32 := sha3(argptr, arglen) } _len = uint(b32); } function jsonArrayLength(string _json, string _keyPath) internal constant returns(uint _ret) { string memory arg = "[69d98d6a04c41b4605aacb7bd2f74bee][15jsonArrayLength]"; arg = arg.concat(_keyPath); uint argptr; uint arglen = bytes(arg).length; bytes32 b32; assembly { argptr := add(arg, 0x20) b32 := sha3(argptr, arglen) } return uint(b32); } function jsonUpdate(string _json, string _keyPath, string _value) internal constant returns (string _ret) { string memory arg = "[69d98d6a04c41b4605aacb7bd2f74bee][10JsonUpdate]"; arg = arg.concat(_keyPath, "|$%&@*^#!|", _value); uint argptr; uint arglen = bytes(arg).length; bytes32 b32; assembly { argptr := add(arg, 0x20) b32 := sha3(argptr, arglen) } if (uint(b32) != 0) //return lastJson(); return lastJsonEx(); else return ""; } function lastJson() internal constant returns(string _ret) { uint i = 0; while (true) { string memory arg = "[69d98d6a04c41b4605aacb7bd2f74bee][08LastJson]"; arg = arg.concat(uint(i*32).toString(), "|$%&@*^#!|", uint(32).toString()); uint argptr; uint arglen = bytes(arg).length; bytes32 b32; assembly { argptr := add(arg, 0x20) b32 := sha3(argptr, arglen) } string memory r = uint(b32).recoveryToString(); _ret = _ret.concat(r); if (bytes(r).length < 32) break; ++i; } } function lastJsonEx() internal constant returns(string _ret) { _ret = ""; uint len = lastJsonLength(); if (len > 0) { _ret = new string(len); uint strptr; assembly { strptr := add(_ret, 0x20) } string memory arg = "[69d98d6a04c41b4605aacb7bd2f74bee][10LastJsonEx]"; arg = arg.concat(strptr.toString()); uint argptr; uint arglen = bytes(arg).length; bytes32 b32; assembly { argptr := add(arg, 0x20) b32 := sha3(argptr, arglen) } string memory errRet = ""; uint ret = uint(b32); if (ret != 0) { return errRet; } } } function lastJsonLength() internal constant returns(uint _len) { string memory arg = "[69d98d6a04c41b4605aacb7bd2f74bee][14LastJsonLength]"; arg = arg.concat(""); //don't delete this line uint argptr; uint arglen = bytes(arg).length; bytes32 b32; assembly { argptr := add(arg, 0x20) b32 := sha3(argptr, arglen) } _len = uint(b32); } function jsonCat(string _self, string _str) internal constant returns (string _ret) { _ret = _self.trim().concat(_str.trim()); } function jsonCat(string _self, string _key, string _val) internal constant returns (string _ret) { _ret = _self.trim(); if (bytes(_ret).length > 0 && (bytes(_ret)[bytes(_ret).length-1] != '{' && bytes(_ret)[bytes(_ret).length-1] != '[')) { _ret = _ret.concat(","); } bool _isJson = false; if (bytes(_val).length > 0 && bytes(_val)[0] == '{' && bytes(_val)[bytes(_val).length-1] == '}') { _isJson = true; } if (bytes(_val).length > 0 && bytes(_val)[0] == '[' && bytes(_val)[bytes(_val).length-1] == ']') { _isJson = true; } if (_isJson) { _ret = _ret.concat("\"", _key, "\":"); _ret = _ret.concat(_val); } else { _ret = _ret.concat("\"", _key, "\":"); _ret = _ret.concat("\"", _val, "\""); } "}"; //compiler bug } function jsonCat(string _self, string _key, uint _val) internal constant returns (string _ret) { _ret = _self.trim(); if (bytes(_ret).length > 0 && (bytes(_ret)[bytes(_ret).length-1] != '{' && bytes(_ret)[bytes(_ret).length-1] != '[')) { _ret = _ret.concat(","); } _ret = _ret.concat("\"", _key, "\":"); _ret = _ret.concat(_val.toString()); "}"; //compiler bug } function jsonCat(string _self, string _key, int _val) internal constant returns (string _ret) { _ret = _self.trim(); if (bytes(_ret).length > 0 && (bytes(_ret)[bytes(_ret).length-1] != '{' && bytes(_ret)[bytes(_ret).length-1] != '[')) { _ret = _ret.concat(","); } _ret = _ret.concat("\"", _key, "\":"); _ret = _ret.concat(_val.toString()); "}"; //compiler bug } function jsonCat(string _self, string _key, address _val) internal constant returns (string _ret) { _ret = _self.trim(); if (bytes(_ret).length > 0 && (bytes(_ret)[bytes(_ret).length-1] != '{' && bytes(_ret)[bytes(_ret).length-1] != '[')) { _ret = _ret.concat(","); } _ret = _ret.concat("\"", _key, "\":"); _ret = _ret.concat("\"", uint(_val).toAddrString(), "\""); "}"; //compiler bug } function toJsonArray(uint[] storage _self) internal constant returns(string _json) { _json = _json.concat("["); for (uint i=0; i<_self.length; ++i) { if (i == 0) _json = _json.concat(_self[i].toString()); else _json = _json.concat(",", _self[i].toString()); } _json = _json.concat("]"); } function toJsonArray(string[] storage _self) internal constant returns(string _json) { _json = _json.concat("["); for (uint i=0; i<_self.length; ++i) { if (i == 0) _json = _json.concat("\"", _self[i], "\""); else _json = _json.concat(",\"", _self[i], "\""); } _json = _json.concat("]"); } function fromJsonArray(uint[] storage _self, string _json) internal returns(bool succ) { LibLog.log("/////////////////////////////////////////",_json); if(bytes(_json).length == 0){ return false; } push(_json); _self.length = 0; if (!isJson(_json)) { pop(); return false; } while (true) { string memory key = "[".concat(_self.length.toString(), "]"); if (!jsonKeyExists(_json, key)) break; _self.length++; //_self[_self.length-1] = jsonRead(_json, key).toUint(); _self[_self.length-1] = jsonRead(_json, key).toUint(); } pop(); return true; } function fromJsonArray(string[] storage _self, string _json) internal returns(bool succ) { LibLog.log("**************************************",_json); if(bytes(_json).length == 0){ return false; } push(_json); _self.length = 0; if (!isJson(_json)) { pop(); return false; } while (true) { string memory key = "[".concat(_self.length.toString(), "]"); if (!jsonKeyExists(_json, key)) break; _self.length++; //_self[_self.length-1] = jsonRead(_json, key); _self[_self.length-1] = jsonRead(_json, key); } pop(); return true; } //old libJSON // ???JSON function getObjectValueByKey(string _self, string _key) internal returns (string _ret) { int pos = -1; uint searchStart = 0; while (true) { pos = _self.indexOf("\"".concat(_key, "\""), searchStart); if (pos == -1) { pos = _self.indexOf("'".concat(_key, "'"), searchStart); if (pos == -1) { return; } } pos += int(bytes(_key).length+2); // pos ??????{ bool colon = false; while (uint(pos) < bytes(_self).length) { if (bytes(_self)[uint(pos)] == ' ' || bytes(_self)[uint(pos)] == '\t' || bytes(_self)[uint(pos)] == '\r' || bytes(_self)[uint(pos)] == '\n') { pos++; } else if (bytes(_self)[uint(pos)] == ':') { pos++; colon = true; break; } else { break; } } if(uint(pos) == bytes(_self).length) { return; } if (colon) { break; } else { searchStart = uint(pos); } } int start = _self.indexOf("{", uint(pos)); if (start == -1) { return; } //start += 1; int end = _self.indexOf("}", uint(pos)); if (end == -1) { return; } end +=1 ; _ret = _self.substr(uint(start), uint(end-start)); } function getIntArrayValueByKey(string _self, string _key, uint[] storage _array) internal { for (uint i=0; i<10; ++i) { //delete _array[i]; _array[i] = i; } //_array.length = 0; /* int pos = -1; uint searchStart = 0; while (true) { pos = _self.indexOf("\"".concat(_key, "\""), searchStart); if (pos == -1) { pos = _self.indexOf("'".concat(_key, "'"), searchStart); if (pos == -1) { return; } } pos += int(bytes(_key).length+2); bool colon = false; while (uint(pos) < bytes(_self).length) { if (bytes(_self)[uint(pos)] == ' ' || bytes(_self)[uint(pos)] == '\t' || bytes(_self)[uint(pos)] == '\r' || bytes(_self)[uint(pos)] == '\n') { pos++; } else if (bytes(_self)[uint(pos)] == ':') { pos++; colon = true; break; } else { break; } } if(uint(pos) == bytes(_self).length) { return; } if (colon) { break; } else { searchStart = uint(pos); } } int start = _self.indexOf("[", uint(pos)); if (start == -1) { return; } start += 1; int end = _self.indexOf("]", uint(pos)); if (end == -1) { return; } string memory vals = _self.substr(uint(start), uint(end-start)).trim(" \t\r\n"); if (bytes(vals).length == 0) { return; } */ // string[] memory _strArray ; // vals.split(",", _strArray); // for (uint i=0; i<_strArray.length; ++i) { // _array[i] = _strArray[i].trim(" \t\r\n"); // _array[i] = _strArray[i].trim("'\""); // } } function push(string _json) internal constant returns(uint _len) { if (bytes(_json).length == 0) { LibLog.log("ERROR: LibJson.push an empty json!!!"); return 0; } string memory arg = "[69d98d6a04c41b4605aacb7bd2f74bee][08JsonPush]"; arg = arg.concat(_json); uint argptr; uint arglen = bytes(arg).length; bytes32 b32; assembly { argptr := add(arg, 0x20) b32 := sha3(argptr, arglen) } _len = uint(b32); } function pop() internal constant { string memory arg = "[69d98d6a04c41b4605aacb7bd2f74bee][07JsonPop]"; if (bytes(arg).length == 0) { LibLog.log("ERROR: LibJson.pop an args invalid!!!"); } uint argptr; uint arglen = bytes(arg).length; bytes32 b32; assembly { argptr := add(arg, 0x20) b32 := sha3(argptr, arglen) } } function size() internal constant returns(uint _ret) { string memory arg = "[69d98d6a04c41b4605aacb7bd2f74bee][13JsonStackSize]"; if (bytes(arg).length == 0) { LibLog.log("ERROR: LibJson.size an args invalid!!!"); } uint argptr; uint arglen = bytes(arg).length; bytes32 b32; assembly { argptr := add(arg, 0x20) b32 := sha3(argptr, arglen) } return uint(b32); } function clear() internal constant { string memory arg = "[69d98d6a04c41b4605aacb7bd2f74bee][14JsonStackClear]"; if (bytes(arg).length == 0) { LibLog.log("ERROR: LibJson.clear an args invalid!!!"); } uint argptr; uint arglen = bytes(arg).length; bytes32 b32; assembly { argptr := add(arg, 0x20) b32 := sha3(argptr, arglen) } } }
_self[_self.length-1] = jsonRead(_json, key);
while (true) { string memory key = "[".concat(_self.length.toString(), "]"); if (!jsonKeyExists(_json, key)) break; _self.length++; _self[_self.length-1] = jsonRead(_json, key); } pop(); return true;
906,136
[ 1, 67, 2890, 63, 67, 2890, 18, 2469, 17, 21, 65, 273, 1163, 1994, 24899, 1977, 16, 498, 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 ]
[ 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, 1323, 261, 3767, 13, 288, 203, 5411, 533, 3778, 498, 273, 5158, 9654, 16426, 24899, 2890, 18, 2469, 18, 10492, 9334, 9870, 1769, 203, 5411, 309, 16051, 1977, 653, 4002, 24899, 1977, 16, 498, 3719, 203, 7734, 898, 31, 203, 203, 5411, 389, 2890, 18, 2469, 9904, 31, 203, 5411, 389, 2890, 63, 67, 2890, 18, 2469, 17, 21, 65, 273, 1163, 1994, 24899, 1977, 16, 498, 1769, 203, 3639, 289, 203, 203, 3639, 1843, 5621, 203, 3639, 327, 638, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol"; import {TransferData} from "../IToken.sol"; import {ExtensionStorage} from "../../extensions/ExtensionStorage.sol"; library ExtensionLib { bytes32 constant ERC20_EXTENSION_LIST_LOCATION = keccak256("erc20.core.storage.address"); /** * @dev A state of all possible registered extension states * A registered extension can either not exist, be enabled or disabled */ enum ExtensionState { EXTENSION_NOT_EXISTS, EXTENSION_ENABLED, EXTENSION_DISABLED } /** * @dev Registered extension data * @param state The current state of this registered extension * @param index The current index of this registered extension in registeredExtensions array * @param context The current context address this extension should be executed in * @param ignoreReverts Whether reverts when executing this extension should be ignored */ struct ExtensionData { ExtensionState state; uint256 index; address context; } struct MappedExtensions { address[] registeredExtensions; mapping(bytes4 => address) funcToExtension; mapping(address => ExtensionData) extensions; mapping(address => bool) contextCache; } function extensionStorage() private pure returns (MappedExtensions storage ds) { bytes32 position = ERC20_EXTENSION_LIST_LOCATION; assembly { ds.slot := position } } function _isActiveExtension(address extension) internal view returns (bool) { MappedExtensions storage extLibStorage = extensionStorage(); return extLibStorage.extensions[extension].state == ExtensionState.EXTENSION_ENABLED; } function _registerExtension(address extension) internal { MappedExtensions storage extLibStorage = extensionStorage(); require(extLibStorage.extensions[extension].state == ExtensionState.EXTENSION_NOT_EXISTS, "The extension must not already exist"); //TODO Register with 1820 //Interfaces has been validated, lets begin setup //Next we need to deploy the ExtensionStorage contract //To sandbox our extension's storage ExtensionStorage context = new ExtensionStorage(address(this), extension); //Next lets figure out what external functions to register in the Diamond bytes4[] memory externalFunctions = context.externalFunctions(); //If we have external functions to register, then lets register them if (externalFunctions.length > 0) { for (uint i = 0; i < externalFunctions.length; i++) { bytes4 func = externalFunctions[i]; require(extLibStorage.funcToExtension[func] == address(0), "Function signature conflict"); extLibStorage.funcToExtension[func] = extension; } } //Initalize the new extension context context.initalize(); //Finally, add it to storage extLibStorage.extensions[extension] = ExtensionData( ExtensionState.EXTENSION_ENABLED, extLibStorage.registeredExtensions.length, address(context) ); extLibStorage.registeredExtensions.push(extension); extLibStorage.contextCache[address(context)] = true; } function _functionToExtensionContextAddress(bytes4 funcSig) internal view returns (address) { MappedExtensions storage extLibStorage = extensionStorage(); return extLibStorage.extensions[extLibStorage.funcToExtension[funcSig]].context; } function _functionToExtensionData(bytes4 funcSig) internal view returns (ExtensionData storage) { MappedExtensions storage extLibStorage = extensionStorage(); require(extLibStorage.funcToExtension[funcSig] != address(0), "Unknown function"); return extLibStorage.extensions[extLibStorage.funcToExtension[funcSig]]; } function _disableExtension(address extension) internal { MappedExtensions storage extLibStorage = extensionStorage(); ExtensionData storage extData = extLibStorage.extensions[extension]; require(extData.state == ExtensionState.EXTENSION_ENABLED, "The extension must be enabled"); extData.state = ExtensionState.EXTENSION_DISABLED; extLibStorage.contextCache[extData.context] = false; } function _enableExtension(address extension) internal { MappedExtensions storage extLibStorage = extensionStorage(); ExtensionData storage extData = extLibStorage.extensions[extension]; require(extData.state == ExtensionState.EXTENSION_DISABLED, "The extension must be enabled"); extData.state = ExtensionState.EXTENSION_ENABLED; extLibStorage.contextCache[extData.context] = true; } function _isContextAddress(address callsite) internal view returns (bool) { MappedExtensions storage extLibStorage = extensionStorage(); return extLibStorage.contextCache[callsite]; } function _allExtensions() internal view returns (address[] memory) { MappedExtensions storage extLibStorage = extensionStorage(); return extLibStorage.registeredExtensions; } function _contextAddressForExtension(address extension) internal view returns (address) { MappedExtensions storage extLibStorage = extensionStorage(); ExtensionData storage extData = extLibStorage.extensions[extension]; require(extData.state != ExtensionState.EXTENSION_NOT_EXISTS, "The extension must exist (either enabled or disabled)"); return extData.context; } function _removeExtension(address extension) internal { MappedExtensions storage extLibStorage = extensionStorage(); ExtensionData storage extData = extLibStorage.extensions[extension]; require(extData.state != ExtensionState.EXTENSION_NOT_EXISTS, "The extension must exist (either enabled or disabled)"); // To prevent a gap in the extensions array, we store the last extension in the index of the extension to delete, and // then delete the last slot (swap and pop). uint256 lastExtensionIndex = extLibStorage.registeredExtensions.length - 1; uint256 extensionIndex = extData.index; // When the extension to delete is the last extension, the swap operation is unnecessary. However, since this occurs so // rarely that we still do the swap here to avoid the gas cost of adding // an 'if' statement address lastExtension = extLibStorage.registeredExtensions[lastExtensionIndex]; extLibStorage.registeredExtensions[extensionIndex] = lastExtension; extLibStorage.extensions[lastExtension].index = extensionIndex; extLibStorage.contextCache[extData.context] = false; delete extLibStorage.extensions[extension]; extLibStorage.registeredExtensions.pop(); } /** * @dev Go through each extension, if it's enabled execute the implemented function and pass the extension * If any invokation of the implemented function given an extension returns false, halt and return false * If they all return true (or there are no extensions), then return true * @param toInvoke The function that should be invoked with each enabled extension * @param data The current data that will be passed to the implemented function along with the enabled extension address * @return bool True if all extensions were executed successfully, false if any extension returned false */ function _executeOnAllExtensions(function (address, TransferData memory) internal returns (bool) toInvoke, TransferData memory data) internal returns (bool) { MappedExtensions storage extLibData = extensionStorage(); for (uint i = 0; i < extLibData.registeredExtensions.length; i++) { address extension = extLibData.registeredExtensions[i]; ExtensionData memory extData = extLibData.extensions[extension]; if (extData.state == ExtensionState.EXTENSION_DISABLED) { continue; //Skip if the extension is disabled } //Execute the implemented function using the enabled extension //however, execute the call at the ExtensionStorage contract address //The ExtensionStorage contract will delegatecall the extension logic //and manage storage/api address context = extData.context; bool result = toInvoke(context, data); if (!result) { return false; } } return true; } }
* @dev Go through each extension, if it's enabled execute the implemented function and pass the extension If any invokation of the implemented function given an extension returns false, halt and return false If they all return true (or there are no extensions), then return true @param toInvoke The function that should be invoked with each enabled extension @param data The current data that will be passed to the implemented function along with the enabled extension address @return bool True if all extensions were executed successfully, false if any extension returned false/
function _executeOnAllExtensions(function (address, TransferData memory) internal returns (bool) toInvoke, TransferData memory data) internal returns (bool) { MappedExtensions storage extLibData = extensionStorage(); for (uint i = 0; i < extLibData.registeredExtensions.length; i++) { address extension = extLibData.registeredExtensions[i]; ExtensionData memory extData = extLibData.extensions[extension]; if (extData.state == ExtensionState.EXTENSION_DISABLED) { } bool result = toInvoke(context, data); if (!result) { return false; } } return true; }
12,721,352
[ 1, 5741, 3059, 1517, 2710, 16, 309, 518, 1807, 3696, 1836, 326, 8249, 445, 471, 1342, 326, 2710, 971, 1281, 5770, 367, 434, 326, 8249, 445, 864, 392, 2710, 1135, 629, 16, 18389, 471, 327, 629, 971, 2898, 777, 327, 638, 261, 280, 1915, 854, 1158, 4418, 3631, 1508, 327, 638, 225, 358, 10969, 1021, 445, 716, 1410, 506, 8187, 598, 1517, 3696, 2710, 225, 501, 1021, 783, 501, 716, 903, 506, 2275, 358, 326, 8249, 445, 7563, 598, 326, 3696, 2710, 1758, 327, 1426, 1053, 309, 777, 4418, 4591, 7120, 4985, 16, 629, 309, 1281, 2710, 2106, 629, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 389, 8837, 1398, 1595, 7513, 12, 915, 261, 2867, 16, 12279, 751, 3778, 13, 2713, 1135, 261, 6430, 13, 358, 10969, 16, 12279, 751, 3778, 501, 13, 2713, 1135, 261, 6430, 13, 288, 203, 3639, 22806, 7513, 2502, 1110, 5664, 751, 273, 2710, 3245, 5621, 203, 203, 3639, 364, 261, 11890, 277, 273, 374, 31, 277, 411, 1110, 5664, 751, 18, 14327, 7513, 18, 2469, 31, 277, 27245, 288, 203, 5411, 1758, 2710, 273, 1110, 5664, 751, 18, 14327, 7513, 63, 77, 15533, 203, 203, 5411, 10021, 751, 3778, 1110, 751, 273, 1110, 5664, 751, 18, 9489, 63, 6447, 15533, 7010, 203, 5411, 309, 261, 408, 751, 18, 2019, 422, 10021, 1119, 18, 12796, 67, 24493, 13, 288, 203, 5411, 289, 203, 203, 5411, 1426, 563, 273, 358, 10969, 12, 2472, 16, 501, 1769, 203, 5411, 309, 16051, 2088, 13, 288, 203, 7734, 327, 629, 31, 203, 5411, 289, 203, 3639, 289, 203, 203, 3639, 327, 638, 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 ]
./full_match/80001/0x210Ca0087D51BF14408afe404caE8D8EEe2CE3f7/sources/_openzeppelin/contracts-upgradeable/token/ERC20/extensions/ERC20VotesUpgradeable.sol
* @dev Extension of ERC20 to support Compound-like voting and delegation. This version is more generic than Compound's, and supports token supply up to 2^224^ - 1, while COMP is limited to 2^96^ - 1. NOTE: If exact COMP compatibility is required, use the {ERC20VotesComp} variant of this module. This extension keeps a history (checkpoints) of each account's vote power. Vote power can be delegated either by calling the {delegate} function directly, or by providing a signature to be used with {delegateBySig}. Voting power can be queried through the public accessors {getVotes} and {getPastVotes}. By default, token balance does not account for voting power. This makes transfers cheaper. The downside is that it requires users to delegate to themselves in order to activate checkpoints and have their voting power tracked. _Available since v4.2._/
abstract contract ERC20VotesUpgradeable is Initializable, ERC20PermitUpgradeable, IERC5805Upgradeable { function __ERC20Votes_init() internal onlyInitializing { } function __ERC20Votes_init_unchained() internal onlyInitializing { } struct Checkpoint { uint32 fromBlock; uint224 votes; } bytes32 private constant _DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); mapping(address => address) private _delegates; mapping(address => Checkpoint[]) private _checkpoints; Checkpoint[] private _totalSupplyCheckpoints; function clock() public view virtual override returns (uint48) { return SafeCastUpgradeable.toUint48(block.number); } function CLOCK_MODE() public view virtual override returns (string memory) { require(clock() == block.number, "ERC20Votes: broken clock mode"); return "mode=blocknumber&from=default"; } function checkpoints(address account, uint32 pos) public view virtual returns (Checkpoint memory) { return _checkpoints[account][pos]; } function numCheckpoints(address account) public view virtual returns (uint32) { return SafeCastUpgradeable.toUint32(_checkpoints[account].length); } function delegates(address account) public view virtual override returns (address) { return _delegates[account]; } function getVotes(address account) public view virtual override returns (uint256) { uint256 pos = _checkpoints[account].length; unchecked { return pos == 0 ? 0 : _checkpoints[account][pos - 1].votes; } } function getVotes(address account) public view virtual override returns (uint256) { uint256 pos = _checkpoints[account].length; unchecked { return pos == 0 ? 0 : _checkpoints[account][pos - 1].votes; } } function getPastVotes(address account, uint256 timepoint) public view virtual override returns (uint256) { require(timepoint < clock(), "ERC20Votes: future lookup"); return _checkpointsLookup(_checkpoints[account], timepoint); } function getPastTotalSupply(uint256 timepoint) public view virtual override returns (uint256) { require(timepoint < clock(), "ERC20Votes: future lookup"); return _checkpointsLookup(_totalSupplyCheckpoints, timepoint); } function _checkpointsLookup(Checkpoint[] storage ckpts, uint256 timepoint) private view returns (uint256) { uint256 length = ckpts.length; uint256 low = 0; uint256 high = length; if (length > 5) { uint256 mid = length - MathUpgradeable.sqrt(length); if (_unsafeAccess(ckpts, mid).fromBlock > timepoint) { high = mid; low = mid + 1; } } while (low < high) { uint256 mid = MathUpgradeable.average(low, high); if (_unsafeAccess(ckpts, mid).fromBlock > timepoint) { high = mid; low = mid + 1; } } unchecked { return high == 0 ? 0 : _unsafeAccess(ckpts, high - 1).votes; } } function _checkpointsLookup(Checkpoint[] storage ckpts, uint256 timepoint) private view returns (uint256) { uint256 length = ckpts.length; uint256 low = 0; uint256 high = length; if (length > 5) { uint256 mid = length - MathUpgradeable.sqrt(length); if (_unsafeAccess(ckpts, mid).fromBlock > timepoint) { high = mid; low = mid + 1; } } while (low < high) { uint256 mid = MathUpgradeable.average(low, high); if (_unsafeAccess(ckpts, mid).fromBlock > timepoint) { high = mid; low = mid + 1; } } unchecked { return high == 0 ? 0 : _unsafeAccess(ckpts, high - 1).votes; } } function _checkpointsLookup(Checkpoint[] storage ckpts, uint256 timepoint) private view returns (uint256) { uint256 length = ckpts.length; uint256 low = 0; uint256 high = length; if (length > 5) { uint256 mid = length - MathUpgradeable.sqrt(length); if (_unsafeAccess(ckpts, mid).fromBlock > timepoint) { high = mid; low = mid + 1; } } while (low < high) { uint256 mid = MathUpgradeable.average(low, high); if (_unsafeAccess(ckpts, mid).fromBlock > timepoint) { high = mid; low = mid + 1; } } unchecked { return high == 0 ? 0 : _unsafeAccess(ckpts, high - 1).votes; } } } else { function _checkpointsLookup(Checkpoint[] storage ckpts, uint256 timepoint) private view returns (uint256) { uint256 length = ckpts.length; uint256 low = 0; uint256 high = length; if (length > 5) { uint256 mid = length - MathUpgradeable.sqrt(length); if (_unsafeAccess(ckpts, mid).fromBlock > timepoint) { high = mid; low = mid + 1; } } while (low < high) { uint256 mid = MathUpgradeable.average(low, high); if (_unsafeAccess(ckpts, mid).fromBlock > timepoint) { high = mid; low = mid + 1; } } unchecked { return high == 0 ? 0 : _unsafeAccess(ckpts, high - 1).votes; } } function _checkpointsLookup(Checkpoint[] storage ckpts, uint256 timepoint) private view returns (uint256) { uint256 length = ckpts.length; uint256 low = 0; uint256 high = length; if (length > 5) { uint256 mid = length - MathUpgradeable.sqrt(length); if (_unsafeAccess(ckpts, mid).fromBlock > timepoint) { high = mid; low = mid + 1; } } while (low < high) { uint256 mid = MathUpgradeable.average(low, high); if (_unsafeAccess(ckpts, mid).fromBlock > timepoint) { high = mid; low = mid + 1; } } unchecked { return high == 0 ? 0 : _unsafeAccess(ckpts, high - 1).votes; } } } else { function _checkpointsLookup(Checkpoint[] storage ckpts, uint256 timepoint) private view returns (uint256) { uint256 length = ckpts.length; uint256 low = 0; uint256 high = length; if (length > 5) { uint256 mid = length - MathUpgradeable.sqrt(length); if (_unsafeAccess(ckpts, mid).fromBlock > timepoint) { high = mid; low = mid + 1; } } while (low < high) { uint256 mid = MathUpgradeable.average(low, high); if (_unsafeAccess(ckpts, mid).fromBlock > timepoint) { high = mid; low = mid + 1; } } unchecked { return high == 0 ? 0 : _unsafeAccess(ckpts, high - 1).votes; } } function delegate(address delegatee) public virtual override { _delegate(_msgSender(), delegatee); } function delegateBySig( address delegatee, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) public virtual override { require(block.timestamp <= expiry, "ERC20Votes: signature expired"); address signer = ECDSAUpgradeable.recover( _hashTypedDataV4(keccak256(abi.encode(_DELEGATION_TYPEHASH, delegatee, nonce, expiry))), v, r, s ); require(nonce == _useNonce(signer), "ERC20Votes: invalid nonce"); _delegate(signer, delegatee); } function _maxSupply() internal view virtual returns (uint224) { return type(uint224).max; } function _mint(address account, uint256 amount) internal virtual override { super._mint(account, amount); require(totalSupply() <= _maxSupply(), "ERC20Votes: total supply risks overflowing votes"); _writeCheckpoint(_totalSupplyCheckpoints, _add, amount); } function _burn(address account, uint256 amount) internal virtual override { super._burn(account, amount); _writeCheckpoint(_totalSupplyCheckpoints, _subtract, amount); } function _afterTokenTransfer(address from, address to, uint256 amount) internal virtual override { super._afterTokenTransfer(from, to, amount); _moveVotingPower(delegates(from), delegates(to), amount); } function _delegate(address delegator, address delegatee) internal virtual { address currentDelegate = delegates(delegator); uint256 delegatorBalance = balanceOf(delegator); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveVotingPower(currentDelegate, delegatee, delegatorBalance); } function _moveVotingPower(address src, address dst, uint256 amount) private { if (src != dst && amount > 0) { if (src != address(0)) { (uint256 oldWeight, uint256 newWeight) = _writeCheckpoint(_checkpoints[src], _subtract, amount); emit DelegateVotesChanged(src, oldWeight, newWeight); } if (dst != address(0)) { (uint256 oldWeight, uint256 newWeight) = _writeCheckpoint(_checkpoints[dst], _add, amount); emit DelegateVotesChanged(dst, oldWeight, newWeight); } } } function _moveVotingPower(address src, address dst, uint256 amount) private { if (src != dst && amount > 0) { if (src != address(0)) { (uint256 oldWeight, uint256 newWeight) = _writeCheckpoint(_checkpoints[src], _subtract, amount); emit DelegateVotesChanged(src, oldWeight, newWeight); } if (dst != address(0)) { (uint256 oldWeight, uint256 newWeight) = _writeCheckpoint(_checkpoints[dst], _add, amount); emit DelegateVotesChanged(dst, oldWeight, newWeight); } } } function _moveVotingPower(address src, address dst, uint256 amount) private { if (src != dst && amount > 0) { if (src != address(0)) { (uint256 oldWeight, uint256 newWeight) = _writeCheckpoint(_checkpoints[src], _subtract, amount); emit DelegateVotesChanged(src, oldWeight, newWeight); } if (dst != address(0)) { (uint256 oldWeight, uint256 newWeight) = _writeCheckpoint(_checkpoints[dst], _add, amount); emit DelegateVotesChanged(dst, oldWeight, newWeight); } } } function _moveVotingPower(address src, address dst, uint256 amount) private { if (src != dst && amount > 0) { if (src != address(0)) { (uint256 oldWeight, uint256 newWeight) = _writeCheckpoint(_checkpoints[src], _subtract, amount); emit DelegateVotesChanged(src, oldWeight, newWeight); } if (dst != address(0)) { (uint256 oldWeight, uint256 newWeight) = _writeCheckpoint(_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; unchecked { Checkpoint memory oldCkpt = pos == 0 ? Checkpoint(0, 0) : _unsafeAccess(ckpts, pos - 1); oldWeight = oldCkpt.votes; newWeight = op(oldWeight, delta); if (pos > 0 && oldCkpt.fromBlock == clock()) { _unsafeAccess(ckpts, pos - 1).votes = SafeCastUpgradeable.toUint224(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; unchecked { Checkpoint memory oldCkpt = pos == 0 ? Checkpoint(0, 0) : _unsafeAccess(ckpts, pos - 1); oldWeight = oldCkpt.votes; newWeight = op(oldWeight, delta); if (pos > 0 && oldCkpt.fromBlock == clock()) { _unsafeAccess(ckpts, pos - 1).votes = SafeCastUpgradeable.toUint224(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; unchecked { Checkpoint memory oldCkpt = pos == 0 ? Checkpoint(0, 0) : _unsafeAccess(ckpts, pos - 1); oldWeight = oldCkpt.votes; newWeight = op(oldWeight, delta); if (pos > 0 && oldCkpt.fromBlock == clock()) { _unsafeAccess(ckpts, pos - 1).votes = SafeCastUpgradeable.toUint224(newWeight); } } } } else { ckpts.push(Checkpoint({fromBlock: SafeCastUpgradeable.toUint32(clock()), votes: SafeCastUpgradeable.toUint224(newWeight)})); 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; } function _unsafeAccess(Checkpoint[] storage ckpts, uint256 pos) private pure returns (Checkpoint storage result) { assembly { mstore(0, ckpts.slot) result.slot := add(keccak256(0, 0x20), pos) } } function _unsafeAccess(Checkpoint[] storage ckpts, uint256 pos) private pure returns (Checkpoint storage result) { assembly { mstore(0, ckpts.slot) result.slot := add(keccak256(0, 0x20), pos) } } uint256[47] private __gap; }
5,634,260
[ 1, 3625, 434, 4232, 39, 3462, 358, 2865, 21327, 17, 5625, 331, 17128, 471, 23595, 18, 1220, 1177, 353, 1898, 5210, 2353, 21327, 1807, 16, 471, 6146, 1147, 14467, 731, 358, 576, 66, 23622, 66, 300, 404, 16, 1323, 13846, 353, 13594, 358, 576, 66, 10525, 66, 300, 404, 18, 5219, 30, 971, 5565, 13846, 8926, 353, 1931, 16, 999, 326, 288, 654, 39, 3462, 29637, 2945, 97, 5437, 434, 333, 1605, 18, 1220, 2710, 20948, 279, 4927, 261, 1893, 4139, 13, 434, 1517, 2236, 1807, 12501, 7212, 18, 27540, 7212, 848, 506, 30055, 3344, 635, 4440, 326, 288, 22216, 97, 445, 5122, 16, 578, 635, 17721, 279, 3372, 358, 506, 1399, 598, 288, 22216, 858, 8267, 5496, 776, 17128, 7212, 848, 506, 23264, 3059, 326, 1071, 28088, 288, 588, 29637, 97, 471, 288, 588, 52, 689, 29637, 5496, 2525, 805, 16, 1147, 11013, 1552, 486, 2236, 364, 331, 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, 17801, 6835, 4232, 39, 3462, 29637, 10784, 429, 353, 10188, 6934, 16, 4232, 39, 3462, 9123, 305, 10784, 429, 16, 467, 654, 39, 25, 3672, 25, 10784, 429, 288, 203, 203, 565, 445, 1001, 654, 39, 3462, 29637, 67, 2738, 1435, 2713, 1338, 29782, 288, 203, 565, 289, 203, 203, 565, 445, 1001, 654, 39, 3462, 29637, 67, 2738, 67, 4384, 8707, 1435, 2713, 1338, 29782, 288, 203, 565, 289, 203, 565, 1958, 25569, 288, 203, 3639, 2254, 1578, 628, 1768, 31, 203, 3639, 2254, 23622, 19588, 31, 203, 565, 289, 203, 203, 565, 1731, 1578, 3238, 5381, 389, 1639, 19384, 2689, 67, 2399, 15920, 273, 203, 3639, 417, 24410, 581, 5034, 2932, 26945, 12, 2867, 7152, 73, 16, 11890, 5034, 7448, 16, 11890, 5034, 10839, 2225, 1769, 203, 203, 565, 2874, 12, 2867, 516, 1758, 13, 3238, 389, 3771, 1332, 815, 31, 203, 565, 2874, 12, 2867, 516, 25569, 63, 5717, 3238, 389, 1893, 4139, 31, 203, 565, 25569, 8526, 3238, 389, 4963, 3088, 1283, 1564, 4139, 31, 203, 203, 565, 445, 7268, 1435, 1071, 1476, 5024, 3849, 1135, 261, 11890, 8875, 13, 288, 203, 3639, 327, 14060, 9735, 10784, 429, 18, 869, 5487, 8875, 12, 2629, 18, 2696, 1769, 203, 565, 289, 203, 203, 565, 445, 385, 6589, 67, 7038, 1435, 1071, 1476, 5024, 3849, 1135, 261, 1080, 3778, 13, 288, 203, 3639, 2583, 12, 18517, 1435, 422, 1203, 18, 2696, 16, 315, 654, 39, 3462, 29637, 30, 12933, 7268, 1965, 8863, 203, 3639, 327, 315, 3188, 33, 2629, 2696, 10, 2080, 2 ]
./full_match/3/0xa0826607DBc6345EC7757C25cdd946965e97Ad7A/sources/contracts/elections.sol
* @dev this function sets the state to Created. @notice this function indicates the start of the election./
function startVote() public inState(State.Created) onlyOwner { state = State.Voting; } the owner cannot vote. Specifies the address the voter voted for, and sets the flag to indicate that the voter has now voted. It increments the candidate's vote count and the total vote count.
8,182,857
[ 1, 2211, 445, 1678, 326, 919, 358, 12953, 18, 225, 333, 445, 8527, 326, 787, 434, 326, 25526, 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 ]
[ 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, 0 ]
[ 1, 565, 445, 787, 19338, 1435, 1071, 316, 1119, 12, 1119, 18, 6119, 13, 1338, 5541, 288, 203, 3639, 919, 273, 3287, 18, 58, 17128, 31, 203, 565, 289, 203, 203, 3639, 326, 3410, 2780, 12501, 18, 4185, 5032, 326, 1758, 326, 331, 20005, 331, 16474, 364, 16, 471, 1678, 7010, 3639, 326, 2982, 358, 10768, 716, 326, 331, 20005, 711, 2037, 331, 16474, 18, 2597, 17071, 326, 7010, 3639, 5500, 1807, 12501, 1056, 471, 326, 2078, 12501, 1056, 18, 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 ]
// File: hardhat/console.sol pragma solidity >= 0.4.22 <0.9.0; library console { address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67); function _sendLogPayload(bytes memory payload) private view { uint256 payloadLength = payload.length; address consoleAddress = CONSOLE_ADDRESS; assembly { let payloadStart := add(payload, 32) let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0) } } function log() internal view { _sendLogPayload(abi.encodeWithSignature("log()")); } function logInt(int p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(int)", p0)); } function logUint(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function logString(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function logBool(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function logAddress(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function logBytes(bytes memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes)", p0)); } function logBytes1(bytes1 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0)); } function logBytes2(bytes2 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0)); } function logBytes3(bytes3 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0)); } function logBytes4(bytes4 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0)); } function logBytes5(bytes5 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0)); } function logBytes6(bytes6 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0)); } function logBytes7(bytes7 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0)); } function logBytes8(bytes8 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0)); } function logBytes9(bytes9 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0)); } function logBytes10(bytes10 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0)); } function logBytes11(bytes11 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0)); } function logBytes12(bytes12 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0)); } function logBytes13(bytes13 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0)); } function logBytes14(bytes14 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0)); } function logBytes15(bytes15 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0)); } function logBytes16(bytes16 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0)); } function logBytes17(bytes17 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0)); } function logBytes18(bytes18 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0)); } function logBytes19(bytes19 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0)); } function logBytes20(bytes20 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0)); } function logBytes21(bytes21 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0)); } function logBytes22(bytes22 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0)); } function logBytes23(bytes23 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0)); } function logBytes24(bytes24 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0)); } function logBytes25(bytes25 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0)); } function logBytes26(bytes26 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0)); } function logBytes27(bytes27 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0)); } function logBytes28(bytes28 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0)); } function logBytes29(bytes29 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0)); } function logBytes30(bytes30 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0)); } function logBytes31(bytes31 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0)); } function logBytes32(bytes32 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0)); } function log(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function log(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function log(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function log(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function log(uint p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1)); } function log(uint p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1)); } function log(uint p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1)); } function log(uint p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1)); } function log(string memory p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1)); } function log(string memory p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1)); } function log(string memory p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1)); } function log(string memory p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1)); } function log(bool p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1)); } function log(bool p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1)); } function log(bool p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1)); } function log(bool p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1)); } function log(address p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1)); } function log(address p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1)); } function log(address p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1)); } function log(address p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1)); } function log(uint p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2)); } function log(uint p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2)); } function log(uint p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2)); } function log(uint p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2)); } function log(uint p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2)); } function log(uint p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2)); } function log(uint p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2)); } function log(uint p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2)); } function log(uint p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2)); } function log(uint p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2)); } function log(uint p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2)); } function log(uint p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2)); } function log(uint p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2)); } function log(uint p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2)); } function log(uint p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2)); } function log(uint p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2)); } function log(string memory p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2)); } function log(string memory p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2)); } function log(string memory p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2)); } function log(string memory p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2)); } function log(string memory p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2)); } function log(string memory p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2)); } function log(string memory p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2)); } function log(string memory p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2)); } function log(string memory p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2)); } function log(string memory p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2)); } function log(string memory p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2)); } function log(string memory p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2)); } function log(string memory p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2)); } function log(string memory p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2)); } function log(string memory p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2)); } function log(string memory p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2)); } function log(bool p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2)); } function log(bool p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2)); } function log(bool p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2)); } function log(bool p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2)); } function log(bool p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2)); } function log(bool p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2)); } function log(bool p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2)); } function log(bool p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2)); } function log(bool p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2)); } function log(bool p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2)); } function log(bool p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2)); } function log(bool p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2)); } function log(bool p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2)); } function log(bool p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2)); } function log(bool p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2)); } function log(bool p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2)); } function log(address p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2)); } function log(address p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2)); } function log(address p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2)); } function log(address p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2)); } function log(address p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2)); } function log(address p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2)); } function log(address p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2)); } function log(address p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2)); } function log(address p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2)); } function log(address p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2)); } function log(address p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2)); } function log(address p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2)); } function log(address p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2)); } function log(address p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2)); } function log(address p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2)); } function log(address p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2)); } function log(uint p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3)); } } // File: @openzeppelin/contracts/utils/math/SafeMath.sol // OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol) pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // File: @openzeppelin/contracts/utils/Counters.sol // OpenZeppelin Contracts v4.4.1 (utils/Counters.sol) pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // File: @openzeppelin/contracts/utils/cryptography/MerkleProof.sol // OpenZeppelin Contracts (last updated v4.5.0) (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 = _efficientHash(computedHash, proofElement); } else { // Hash(current element of the proof + current computed hash) computedHash = _efficientHash(proofElement, computedHash); } } return computedHash; } function _efficientHash(bytes32 a, bytes32 b) private pure returns (bytes32 value) { assembly { mstore(0x00, a) mstore(0x20, b) value := keccak256(0x00, 0x40) } } } // File: @openzeppelin/contracts/utils/Strings.sol // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts/utils/Context.sol // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: @openzeppelin/contracts/utils/Address.sol // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts/utils/introspection/IERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Enumerable.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts/token/ERC721/ERC721.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // File: @openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Enumerable.sol) pragma solidity ^0.8.0; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // File: contracts/MonaiUniverse.sol //SPDX-License-Identifier: MIT /* * * * ███╗░░░███╗░█████╗░███╗░░██╗░█████╗░██╗  ██╗░░░██╗███╗░░██╗██╗██╗░░░██╗███████╗██████╗░░██████╗███████╗ * ████╗░████║██╔══██╗████╗░██║██╔══██╗██║  ██║░░░██║████╗░██║██║██║░░░██║██╔════╝██╔══██╗██╔════╝██╔════╝ * ██╔████╔██║██║░░██║██╔██╗██║███████║██║  ██║░░░██║██╔██╗██║██║╚██╗░██╔╝█████╗░░██████╔╝╚█████╗░█████╗░░ * ██║╚██╔╝██║██║░░██║██║╚████║██╔══██║██║  ██║░░░██║██║╚████║██║░╚████╔╝░██╔══╝░░██╔══██╗░╚═══██╗██╔══╝░░ * ██║░╚═╝░██║╚█████╔╝██║░╚███║██║░░██║██║  ╚██████╔╝██║░╚███║██║░░╚██╔╝░░███████╗██║░░██║██████╔╝███████╗ * ╚═╝░░░░░╚═╝░╚════╝░╚═╝░░╚══╝╚═╝░░╚═╝╚═╝  ░╚═════╝░╚═╝░░╚══╝╚═╝░░░╚═╝░░░╚══════╝╚═╝░░╚═╝╚═════╝░╚══════╝ * */ pragma solidity ^0.8.4; struct MintAllowance{ uint8 allowed; uint8 minted; } contract MonaiUniverse is ERC721Enumerable, Ownable { using Strings for uint256; string public baseURI; string public notRevealedUri; bool public whiteListSaleIsActive = false; bool public holderSaleIsActive = false; bool public publicsaleIsActive = false; bool public revealed = false; bytes32 public whiteListMerkleRoot; // WhiteList Merkle root uint256 public constant PER_TX_MINT_QTY = 2; // Max number of mints per transaction uint256 public constant Max_Monai_Supply = 1000; // Max Monai Universe's that can exist uint256 public PUBLICE_SALE_PRICE = 0.07 ether; // Monai Mint Cost uint256 public constant MONAI_HOLDER_SALE_PRICE = 0.0 ether; // Monai World Holder Free Mint address[2] private _admins; bool private _adminsSet = false; mapping(address => MintAllowance) private _addressMintAllowance; mapping(address => uint256) private _whitelistMints; event Mint(address indexed recipient, uint256 indexed tokenId); constructor( string memory _name, string memory _symbol, string memory _setMintedBaseURI, string memory _setNotRevealedUri ) ERC721(_name, _symbol){ setBaseURI(_setMintedBaseURI); setNotRevealedUri(_setNotRevealedUri); } // Modifiers modifier publicSale() { require(publicsaleIsActive, "Public sale is not open right now"); _; } modifier holderSale() { require(holderSaleIsActive, "Monai World Holders sale is not active right now"); _; } modifier whiteListSale() { require(whiteListSaleIsActive, "White list sale is not open"); _; } modifier onlyOwnerOrAdmin() { require( _msgSender() == owner() || (_adminsSet && (_msgSender() == _admins[0] || _msgSender() == _admins[1])), "Caller is not the owner or an admin" ); _; } modifier validProof(bytes32[] calldata merkleProof, bytes32 root) { require( MerkleProof.verify( merkleProof, root, keccak256(abi.encodePacked(msg.sender)) ), "Address not listed" ); _; } /* * * Public Mint Monai Universe */ function mintMonai(uint256 numberOfTokens) external payable publicSale { require(totalSupply() + numberOfTokens <= Max_Monai_Supply, "Monai Universe is sold out!"); require(numberOfTokens <= PER_TX_MINT_QTY, "Mint amount exceeds the maximum."); require(PUBLICE_SALE_PRICE * numberOfTokens <= msg.value , "Wrong Eth value sent"); for (uint256 i = 0; i < numberOfTokens; i++) { uint256 tokenId = totalSupply() + 1; _safeMint(msg.sender, tokenId); emit Mint(msg.sender, tokenId); } } /* * Whitelist mint for merkleProof */ function mintWhiteList(uint256 numberOfTokens, bytes32[] calldata merkleProof) external payable whiteListSale validProof(merkleProof, whiteListMerkleRoot) { require(totalSupply() + numberOfTokens <= Max_Monai_Supply, "Monai Universe is sold out!"); require(numberOfTokens <= PER_TX_MINT_QTY, "Mint amount exceeds the maximum."); require(PUBLICE_SALE_PRICE * numberOfTokens <= msg.value , "Wrong Eth value sent"); require(_whitelistMints[msg.sender] + numberOfTokens <= 2, "Exceeds maximum whitelist mint quantity"); for (uint256 i = 0; i < numberOfTokens; i++) { uint256 tokenId = totalSupply() + 1; _safeMint(msg.sender, tokenId); emit Mint(msg.sender, tokenId); _whitelistMints[msg.sender]++; } } function holderMint(uint256 numberOfTokens) external payable holderSale { require(totalSupply() + numberOfTokens <= Max_Monai_Supply, "Monai Universe is sold out!"); require(_addressMintAllowance[msg.sender].allowed != 0, "Sender address is not included in holder snapshot"); require(_addressMintAllowance[msg.sender].minted + numberOfTokens <= _addressMintAllowance[msg.sender].allowed, "Exceeds maximum allowed mint quantity"); for (uint256 i = 0; i < numberOfTokens; i++) { uint256 tokenId = totalSupply() + 1; _safeMint(msg.sender, tokenId); emit Mint(msg.sender, tokenId); _addressMintAllowance[msg.sender].minted++; } } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "Nonexistent token"); if(revealed == false) { return notRevealedUri; } return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, "/", tokenId.toString(), ".json")) : ""; } function getBaseURI() external view returns (string memory) { return baseURI; } function tokensOfOwner(address owner) external view returns (uint256[] memory) { uint256 tokenCount = balanceOf(owner); if (tokenCount == 0) { return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); uint256 index; for (index = 0; index < tokenCount; index++) { result[index] = tokenOfOwnerByIndex(owner, index); } return result; } } // ----- Only Owner Functions ---- function addHolderMintAllowance(address[] calldata addresses, uint8[] calldata allowedMintQty) external onlyOwnerOrAdmin { require(addresses.length == allowedMintQty.length, "Address allowance mismatch"); for (uint256 i = 0; i < addresses.length; i++) { _addressMintAllowance[addresses[i]] = MintAllowance(allowedMintQty[i], 0); } } function setAdmins(address[2] calldata adminAddresses) external onlyOwner { for (uint256 i = 0; i < adminAddresses.length; i++) { address admin = adminAddresses[i]; require(admin != address(0), "Nope, that's not a good idea"); _admins[i] = admin; } _adminsSet = true; } function reveal() public onlyOwnerOrAdmin { revealed = true; } // Sets new price if needed for some reason function setPrice(uint256 _newPrice) public onlyOwner() { PUBLICE_SALE_PRICE = _newPrice; } function setNotRevealedUri(string memory _notRevealedURI) public onlyOwnerOrAdmin { notRevealedUri = _notRevealedURI; } function setBaseURI(string memory _newBaseURI) public onlyOwnerOrAdmin() { baseURI = _newBaseURI; } function setSaleToActive(bool _saleIsActive) public onlyOwnerOrAdmin { publicsaleIsActive = _saleIsActive; } function setWhitelistSaleToActive(bool _saleIsActive) public onlyOwnerOrAdmin { whiteListSaleIsActive = _saleIsActive; } function setHolderSaleToActive(bool _saleIsActive) public onlyOwnerOrAdmin { holderSaleIsActive = _saleIsActive; } // ----- Enables to set merkle for Whitelist ----- function setWhiteListMerkleRoot(bytes32 merkleRoot) external onlyOwnerOrAdmin { whiteListMerkleRoot = merkleRoot; } function widthdraw() public onlyOwner { uint256 balance = address(this).balance; payable(msg.sender).transfer(balance); } }
Sets new price if needed for some reason
function setPrice(uint256 _newPrice) public onlyOwner() { PUBLICE_SALE_PRICE = _newPrice; }
6,959,141
[ 1, 2785, 394, 6205, 309, 3577, 364, 2690, 3971, 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, 445, 444, 5147, 12, 11890, 5034, 389, 2704, 5147, 13, 1071, 1338, 5541, 1435, 288, 203, 3639, 23295, 2053, 1441, 67, 5233, 900, 67, 7698, 1441, 273, 389, 2704, 5147, 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 ]
//SPDX-License-Identifier: MIT pragma solidity 0.8.10; /* Library Imports */ import { Ownable } from "../../lib/openzeppelin-contracts/contracts/access/Ownable.sol"; /** * @title L2OutputOracle * @notice */ // The payable keyword is used on appendL2Output to save gas on the msg.value check. // slither-disable-next-line locked-ether contract L2OutputOracle is Ownable { /********** * Events * **********/ /// @notice Emitted when an output is appended. event l2OutputAppended(bytes32 indexed _l2Output, uint256 indexed _l2timestamp); /********************** * Contract Variables * **********************/ /// @notice The interval in seconds at which checkpoints must be submitted. uint256 public immutable SUBMISSION_INTERVAL; /// @notice The time between blocks on L2. uint256 public immutable L2_BLOCK_TIME; /// @notice The number of blocks in the chain before the first block in this contract. uint256 public immutable HISTORICAL_TOTAL_BLOCKS; /// @notice The timestamp of the first L2 block recorded in this contract. uint256 public immutable STARTING_BLOCK_TIMESTAMP; /// @notice The timestamp of the most recent L2 block recorded in this contract. uint256 public latestBlockTimestamp; /// @notice A mapping from L2 timestamps to the output root for the block with that timestamp. mapping(uint256 => bytes32) internal l2Outputs; /*************** * Constructor * ***************/ /** * @notice Initialize the L2OutputOracle contract. * @param _submissionInterval The desired interval in seconds at which * checkpoints must be submitted. * @param _l2BlockTime The desired L2 inter-block time in seconds. * @param _genesisL2Output The initial L2 output of the L2 chain. * @param _historicalTotalBlocks The number of blocks that preceding the * initialization of the L2 chain. * @param _startingBlockTimestamp The timestamp to start L2 block at. */ constructor( uint256 _submissionInterval, uint256 _l2BlockTime, bytes32 _genesisL2Output, uint256 _historicalTotalBlocks, uint256 _startingBlockTimestamp, address sequencer ) { require( _submissionInterval % _l2BlockTime == 0, "Submission Interval must be a multiple of L2 Block Time" ); SUBMISSION_INTERVAL = _submissionInterval; L2_BLOCK_TIME = _l2BlockTime; l2Outputs[_startingBlockTimestamp] = _genesisL2Output; // solhint-disable not-rely-on-time HISTORICAL_TOTAL_BLOCKS = _historicalTotalBlocks; latestBlockTimestamp = _startingBlockTimestamp; // solhint-disable not-rely-on-time STARTING_BLOCK_TIMESTAMP = _startingBlockTimestamp; // solhint-disable not-rely-on-time _transferOwnership(sequencer); } /********************************* * External and Public Functions * *********************************/ /** * @notice Accepts an L2 outputRoot and the timestamp of the corresponding L2 block. The * timestamp must be equal to the current value returned by `nextTimestamp()` in order to be * accepted. * This function may only be called by the Sequencer. * @param _l2Output The L2 output of the checkpoint block. * @param _l2timestamp The L2 block timestamp that resulted in _l2Output. * @param _l1Blockhash A block hash which must be included in the current chain. * @param _l1Blocknumber The block number with the specified block hash. */ function appendL2Output( bytes32 _l2Output, uint256 _l2timestamp, bytes32 _l1Blockhash, uint256 _l1Blocknumber ) external payable onlyOwner { require(_l2timestamp < block.timestamp, "Cannot append L2 output in future"); require(_l2timestamp == nextTimestamp(), "Timestamp not equal to next expected timestamp"); require(_l2Output != bytes32(0), "Cannot submit empty L2 output"); if (_l1Blockhash != bytes32(0)) { // This check allows the sequencer to append an output based on a given L1 block, // without fear that it will be reorged out. // It will also revert if the blockheight provided is more than 256 blocks behind the // chain tip (as the hash will return as zero). This does open the door to a griefing // attack in which the sequencer's submission is censored until the block is no longer // retrievable, if the sequencer is experiencing this attack it can simply leave out the // blockhash value, and delay submission until it is confident that the L1 block is // finalized. require( blockhash(_l1Blocknumber) == _l1Blockhash, "Blockhash does not match the hash at the expected height." ); } l2Outputs[_l2timestamp] = _l2Output; latestBlockTimestamp = _l2timestamp; emit l2OutputAppended(_l2Output, _l2timestamp); } /** * @notice Computes the timestamp of the next L2 block that needs to be checkpointed. */ function nextTimestamp() public view returns (uint256) { return latestBlockTimestamp + SUBMISSION_INTERVAL; } /** * @notice Returns the L2 output root given a target L2 block timestamp. Returns 0 if none is * found. * @param _l2Timestamp The L2 block timestamp of the target block. */ function getL2Output(uint256 _l2Timestamp) external view returns (bytes32) { return l2Outputs[_l2Timestamp]; } /** * @notice Computes the L2 block number given a target L2 block timestamp. * @param _l2timestamp The L2 block timestamp of the target block. */ function computeL2BlockNumber(uint256 _l2timestamp) external view returns (uint256) { require( _l2timestamp >= STARTING_BLOCK_TIMESTAMP, "Timestamp prior to startingBlockTimestamp" ); // For the first block recorded (ie. _l2timestamp = STARTING_BLOCK_TIMESTAMP), the // L2BlockNumber should be HISTORICAL_TOTAL_BLOCKS + 1. unchecked { return HISTORICAL_TOTAL_BLOCKS + 1 + ((_l2timestamp - STARTING_BLOCK_TIMESTAMP) / L2_BLOCK_TIME); } } }
* @notice Accepts an L2 outputRoot and the timestamp of the corresponding L2 block. The timestamp must be equal to the current value returned by `nextTimestamp()` in order to be accepted. This function may only be called by the Sequencer. @param _l2Output The L2 output of the checkpoint block. @param _l2timestamp The L2 block timestamp that resulted in _l2Output. @param _l1Blockhash A block hash which must be included in the current chain. @param _l1Blocknumber The block number with the specified block hash./ This check allows the sequencer to append an output based on a given L1 block, without fear that it will be reorged out. It will also revert if the blockheight provided is more than 256 blocks behind the chain tip (as the hash will return as zero). This does open the door to a griefing attack in which the sequencer's submission is censored until the block is no longer retrievable, if the sequencer is experiencing this attack it can simply leave out the blockhash value, and delay submission until it is confident that the L1 block is finalized.
function appendL2Output( bytes32 _l2Output, uint256 _l2timestamp, bytes32 _l1Blockhash, uint256 _l1Blocknumber ) external payable onlyOwner { require(_l2timestamp < block.timestamp, "Cannot append L2 output in future"); require(_l2timestamp == nextTimestamp(), "Timestamp not equal to next expected timestamp"); require(_l2Output != bytes32(0), "Cannot submit empty L2 output"); if (_l1Blockhash != bytes32(0)) { require( blockhash(_l1Blocknumber) == _l1Blockhash, "Blockhash does not match the hash at the expected height." ); } l2Outputs[_l2timestamp] = _l2Output; latestBlockTimestamp = _l2timestamp; emit l2OutputAppended(_l2Output, _l2timestamp); }
5,420,406
[ 1, 26391, 392, 511, 22, 876, 2375, 471, 326, 2858, 434, 326, 4656, 511, 22, 1203, 18, 1021, 2858, 1297, 506, 3959, 358, 326, 783, 460, 2106, 635, 1375, 4285, 4921, 20338, 316, 1353, 358, 506, 8494, 18, 1220, 445, 2026, 1338, 506, 2566, 635, 326, 3265, 372, 23568, 18, 225, 389, 80, 22, 1447, 1021, 511, 22, 876, 434, 326, 9776, 1203, 18, 225, 389, 80, 22, 5508, 1021, 511, 22, 1203, 2858, 716, 563, 329, 316, 389, 80, 22, 1447, 18, 225, 389, 80, 21, 1768, 2816, 432, 1203, 1651, 1492, 1297, 506, 5849, 316, 326, 783, 2687, 18, 225, 389, 80, 21, 1768, 2696, 1021, 1203, 1300, 598, 326, 1269, 1203, 1651, 18, 19, 1220, 866, 5360, 326, 26401, 23568, 358, 714, 392, 876, 2511, 603, 279, 864, 511, 21, 1203, 16, 2887, 1656, 297, 716, 518, 903, 506, 283, 280, 2423, 596, 18, 2597, 903, 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, 714, 48, 22, 1447, 12, 203, 3639, 1731, 1578, 389, 80, 22, 1447, 16, 203, 3639, 2254, 5034, 389, 80, 22, 5508, 16, 203, 3639, 1731, 1578, 389, 80, 21, 1768, 2816, 16, 203, 3639, 2254, 5034, 389, 80, 21, 1768, 2696, 203, 565, 262, 3903, 8843, 429, 1338, 5541, 288, 203, 3639, 2583, 24899, 80, 22, 5508, 411, 1203, 18, 5508, 16, 315, 4515, 714, 511, 22, 876, 316, 3563, 8863, 203, 3639, 2583, 24899, 80, 22, 5508, 422, 1024, 4921, 9334, 315, 4921, 486, 3959, 358, 1024, 2665, 2858, 8863, 203, 3639, 2583, 24899, 80, 22, 1447, 480, 1731, 1578, 12, 20, 3631, 315, 4515, 4879, 1008, 511, 22, 876, 8863, 203, 203, 3639, 309, 261, 67, 80, 21, 1768, 2816, 480, 1731, 1578, 12, 20, 3719, 288, 203, 5411, 2583, 12, 203, 7734, 1203, 2816, 24899, 80, 21, 1768, 2696, 13, 422, 389, 80, 21, 1768, 2816, 16, 203, 7734, 315, 1768, 2816, 1552, 486, 845, 326, 1651, 622, 326, 2665, 2072, 1199, 203, 5411, 11272, 203, 3639, 289, 203, 203, 3639, 328, 22, 13856, 63, 67, 80, 22, 5508, 65, 273, 389, 80, 22, 1447, 31, 203, 3639, 4891, 1768, 4921, 273, 389, 80, 22, 5508, 31, 203, 203, 3639, 3626, 328, 22, 1447, 1294, 11275, 24899, 80, 22, 1447, 16, 389, 80, 22, 5508, 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 ]
pragma solidity ^0.4.24; /** * Libraries **/ library ExtendedMath { function limitLessThan(uint a, uint b) internal pure returns(uint c) { if (a > b) return b; return a; } } 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; } } 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. * @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 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 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 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 ); } contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) internal balances; uint256 internal 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(_value <= balances[msg.sender]); require(_to != address(0)); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns(uint256) { return balances[_owner]; } } 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(_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); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns(bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address _owner, address _spender ) public view returns(uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval( address _spender, uint256 _addedValue ) public returns(bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval( address _spender, 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); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } interface IRemoteFunctions { function _externalAddMasternode(address) external; function _externalStopMasternode(address) external; } interface IcaelumVoting { function getTokenProposalDetails() external view returns(address, uint, uint, uint); function getExpiry() external view returns (uint); function getContractType () external view returns (uint); } interface EIP918Interface { /* * Externally facing mint function that is called by miners to validate challenge digests, calculate reward, * populate statistics, mutate epoch variables and adjust the solution difficulty as required. Once complete, * a Mint event is emitted before returning a success indicator. **/ function mint(uint256 nonce, bytes32 challenge_digest) external returns (bool success); /* * Returns the challenge number **/ function getChallengeNumber() external constant returns (bytes32); /* * Returns the mining difficulty. The number of digits that the digest of the PoW solution requires which * typically auto adjusts during reward generation. **/ function getMiningDifficulty() external constant returns (uint); /* * Returns the mining target **/ function getMiningTarget() external constant returns (uint); /* * Return the current reward amount. Depending on the algorithm, typically rewards are divided every reward era * as tokens are mined to provide scarcity **/ function getMiningReward() external constant returns (uint); /* * Upon successful verification and reward the mint method dispatches a Mint Event indicating the reward address, * the reward amount, the epoch count and newest challenge number. **/ event Mint(address indexed from, uint reward_amount, uint epochCount, bytes32 newChallengeNumber); } contract NewMinerProposal is IcaelumVoting { enum VOTE_TYPE {MINER, MASTER, TOKEN} VOTE_TYPE public contractType = VOTE_TYPE.TOKEN; address contractAddress; uint validUntil; uint votingDurationInDays; /** * @dev Create a new vote proposal for an ERC20 token. * @param _contract ERC20 contract * @param _valid How long do we accept these tokens on the contract (UNIX timestamp) * @param _voteDuration How many days is this vote available */ constructor(address _contract, uint _valid, uint _voteDuration) public { require(_voteDuration >= 14 && _voteDuration <= 50, "Proposed voting duration does not meet requirements"); contractAddress = _contract; validUntil = _valid; votingDurationInDays = _voteDuration; } /** * @dev Returns all details about this proposal */ function getTokenProposalDetails() public view returns(address, uint, uint, uint) { return (contractAddress, 0, validUntil, uint(contractType)); } /** * @dev Displays the expiry date of contract * @return uint Days valid */ function getExpiry() external view returns (uint) { return votingDurationInDays; } /** * @dev Displays the type of contract * @return uint Enum value {TOKEN, TEAM} */ function getContractType () external view returns (uint){ return uint(contractType); } } contract CaelumVotings is Ownable { using SafeMath for uint; enum VOTE_TYPE {MINER, MASTER, TOKEN} struct Proposals { address tokenContract; uint totalVotes; uint proposedOn; uint acceptedOn; VOTE_TYPE proposalType; } struct Voters { bool isVoter; address owner; uint[] votedFor; } uint MAJORITY_PERCENTAGE_NEEDED = 60; uint MINIMUM_VOTERS_NEEDED = 1; bool public proposalPending; mapping(uint => Proposals) public proposalList; mapping (address => Voters) public voterMap; mapping(uint => address) public voterProposals; uint public proposalCounter; uint public votersCount; uint public votersCountTeam; function setMasternodeContractFromVote(address _t) internal ; function setTokenContractFromVote(address _t) internal; function setMiningContractFromVote (address _t) internal; event NewProposal(uint ProposalID); event ProposalAccepted(uint ProposalID); address _CaelumMasternodeContract; CaelumMasternode public MasternodeContract; function setMasternodeContractForData(address _t) onlyOwner public { MasternodeContract = CaelumMasternode(_t); _CaelumMasternodeContract = (_t); } function setVotingMinority(uint _total) onlyOwner public { require(_total > MINIMUM_VOTERS_NEEDED); MINIMUM_VOTERS_NEEDED = _total; } /** * @dev Create a new proposal. * @param _contract Proposal contract address * @return uint ProposalID */ function pushProposal(address _contract) onlyOwner public returns (uint) { if(proposalCounter != 0) require (pastProposalTimeRules (), "You need to wait 90 days before submitting a new proposal."); require (!proposalPending, "Another proposal is pending."); uint _contractType = IcaelumVoting(_contract).getContractType(); proposalList[proposalCounter] = Proposals(_contract, 0, now, 0, VOTE_TYPE(_contractType)); emit NewProposal(proposalCounter); proposalCounter++; proposalPending = true; return proposalCounter.sub(1); } /** * @dev Internal function that handles the proposal after it got accepted. * This function determines if the proposal is a token or team member proposal and executes the corresponding functions. * @return uint Returns the proposal ID. */ function handleLastProposal () internal returns (uint) { uint _ID = proposalCounter.sub(1); proposalList[_ID].acceptedOn = now; proposalPending = false; address _address; uint _required; uint _valid; uint _type; (_address, _required, _valid, _type) = getTokenProposalDetails(_ID); if(_type == uint(VOTE_TYPE.MINER)) { setMiningContractFromVote(_address); } if(_type == uint(VOTE_TYPE.MASTER)) { setMasternodeContractFromVote(_address); } if(_type == uint(VOTE_TYPE.TOKEN)) { setTokenContractFromVote(_address); } emit ProposalAccepted(_ID); return _ID; } /** * @dev Rejects the last proposal after the allowed voting time has expired and it's not accepted. */ function discardRejectedProposal() onlyOwner public returns (bool) { require(proposalPending); require (LastProposalCanDiscard()); proposalPending = false; return (true); } /** * @dev Checks if the last proposal allowed voting time has expired and it's not accepted. * @return bool */ function LastProposalCanDiscard () public view returns (bool) { uint daysBeforeDiscard = IcaelumVoting(proposalList[proposalCounter - 1].tokenContract).getExpiry(); uint entryDate = proposalList[proposalCounter - 1].proposedOn; uint expiryDate = entryDate + (daysBeforeDiscard * 1 days); if (now >= expiryDate) return true; } /** * @dev Returns all details about a proposal */ function getTokenProposalDetails(uint proposalID) public view returns(address, uint, uint, uint) { return IcaelumVoting(proposalList[proposalID].tokenContract).getTokenProposalDetails(); } /** * @dev Returns if our 90 day cooldown has passed * @return bool */ function pastProposalTimeRules() public view returns (bool) { uint lastProposal = proposalList[proposalCounter - 1].proposedOn; if (now >= lastProposal + 90 days) return true; } /** * @dev Allow any masternode user to become a voter. */ function becomeVoter() public { require (MasternodeContract.isMasternodeOwner(msg.sender), "User has no masternodes"); require (!voterMap[msg.sender].isVoter, "User Already voted for this proposal"); voterMap[msg.sender].owner = msg.sender; voterMap[msg.sender].isVoter = true; votersCount = votersCount + 1; if (MasternodeContract.isTeamMember(msg.sender)) votersCountTeam = votersCountTeam + 1; } /** * @dev Allow voters to submit their vote on a proposal. Voters can only cast 1 vote per proposal. * If the proposed vote is about adding Team members, only Team members are able to vote. * A proposal can only be published if the total of votes is greater then MINIMUM_VOTERS_NEEDED. * @param proposalID proposalID */ function voteProposal(uint proposalID) public returns (bool success) { require(voterMap[msg.sender].isVoter, "Sender not listed as voter"); require(proposalID >= 0, "No proposal was selected."); require(proposalID <= proposalCounter, "Proposal out of limits."); require(voterProposals[proposalID] != msg.sender, "Already voted."); require(votersCount >= MINIMUM_VOTERS_NEEDED, "Not enough voters in existence to push a proposal"); voterProposals[proposalID] = msg.sender; proposalList[proposalID].totalVotes++; if(reachedMajority(proposalID)) { // This is the prefered way of handling vote results. It costs more gas but prevents tampering. // If gas is an issue, you can comment handleLastProposal out and call it manually as onlyOwner. handleLastProposal(); return true; } } /** * @dev Check if a proposal has reached the majority vote * @param proposalID Token ID * @return bool */ function reachedMajority (uint proposalID) public view returns (bool) { uint getProposalVotes = proposalList[proposalID].totalVotes; if (getProposalVotes >= majority()) return true; } /** * @dev Internal function that calculates the majority * @return uint Total of votes needed for majority */ function majority () internal view returns (uint) { uint a = (votersCount * MAJORITY_PERCENTAGE_NEEDED ); return a / 100; } /** * @dev Check if a proposal has reached the majority vote for a team member * @param proposalID Token ID * @return bool */ function reachedMajorityForTeam (uint proposalID) public view returns (bool) { uint getProposalVotes = proposalList[proposalID].totalVotes; if (getProposalVotes >= majorityForTeam()) return true; } /** * @dev Internal function that calculates the majority * @return uint Total of votes needed for majority */ function majorityForTeam () internal view returns (uint) { uint a = (votersCountTeam * MAJORITY_PERCENTAGE_NEEDED ); return a / 100; } } contract CaelumAcceptERC20 is Ownable { using SafeMath for uint; IRemoteFunctions public DataVault; address[] public tokensList; bool setOwnContract = true; struct _whitelistTokens { address tokenAddress; bool active; uint requiredAmount; uint validUntil; uint timestamp; } mapping(address => mapping(address => uint)) public tokens; mapping(address => _whitelistTokens) acceptedTokens; event Deposit(address token, address user, uint amount, uint balance); event Withdraw(address token, address user, uint amount, uint balance); /** * @notice Allow the dev to set it's own token as accepted payment. * @dev Can be hardcoded in the constructor. Given the contract size, we decided to separate it. * @return bool */ function addOwnToken() onlyOwner public returns (bool) { require(setOwnContract); addToWhitelist(this, 5000 * 1e8, 36500); setOwnContract = false; return true; } /** * @notice Add a new token as accepted payment method. * @param _token Token contract address. * @param _amount Required amount of this Token as collateral * @param daysAllowed How many days will we accept this token? */ function addToWhitelist(address _token, uint _amount, uint daysAllowed) internal { _whitelistTokens storage newToken = acceptedTokens[_token]; newToken.tokenAddress = _token; newToken.requiredAmount = _amount; newToken.timestamp = now; newToken.validUntil = now + (daysAllowed * 1 days); newToken.active = true; tokensList.push(_token); } /** * @dev internal function to determine if we accept this token. * @param _ad Token contract address * @return bool */ function isAcceptedToken(address _ad) internal view returns(bool) { return acceptedTokens[_ad].active; } /** * @dev internal function to determine the requiredAmount for a specific token. * @param _ad Token contract address * @return bool */ function getAcceptedTokenAmount(address _ad) internal view returns(uint) { return acceptedTokens[_ad].requiredAmount; } /** * @dev internal function to determine if the token is still accepted timewise. * @param _ad Token contract address * @return bool */ function isValid(address _ad) internal view returns(bool) { uint endTime = acceptedTokens[_ad].validUntil; if (block.timestamp < endTime) return true; return false; } /** * @notice Returns an array of all accepted token. You can get more details by calling getTokenDetails function with this address. * @return array Address */ function listAcceptedTokens() public view returns(address[]) { return tokensList; } /** * @notice Returns a full list of the token details * @param token Token contract address */ function getTokenDetails(address token) public view returns(address ad,uint required, bool active, uint valid) { return (acceptedTokens[token].tokenAddress, acceptedTokens[token].requiredAmount,acceptedTokens[token].active, acceptedTokens[token].validUntil); } /** * @notice Public function that allows any user to deposit accepted tokens as collateral to become a masternode. * @param token Token contract address * @param amount Amount to deposit */ function depositCollateral(address token, uint amount) public { require(isAcceptedToken(token), "ERC20 not authorised"); // Should be a token from our list require(amount == getAcceptedTokenAmount(token)); // The amount needs to match our set amount require(isValid(token)); // It should be called within the setup timeframe tokens[token][msg.sender] = tokens[token][msg.sender].add(amount); require(StandardToken(token).transferFrom(msg.sender, this, amount), "error with token"); emit Deposit(token, msg.sender, amount, tokens[token][msg.sender]); DataVault._externalAddMasternode(msg.sender); } /** * @notice Public function that allows any user to withdraw deposited tokens and stop as masternode * @param token Token contract address * @param amount Amount to withdraw */ function withdrawCollateral(address token, uint amount) public { require(token != 0); // token should be an actual address require(isAcceptedToken(token), "ERC20 not authorised"); // Should be a token from our list require(amount == getAcceptedTokenAmount(token)); // The amount needs to match our set amount, allow only one withdrawal at a time. require(tokens[token][msg.sender] >= amount); // The owner must own at least this amount of tokens. uint amountToWithdraw = tokens[token][msg.sender]; tokens[token][msg.sender] = 0; DataVault._externalStopMasternode(msg.sender); if (!StandardToken(token).transfer(msg.sender, amountToWithdraw)) revert(); emit Withdraw(token, msg.sender, amountToWithdraw, amountToWithdraw); } function setDataStorage (address _masternodeContract) onlyOwner public { DataVault = IRemoteFunctions(_masternodeContract); } } contract CaelumAbstractMasternode is Ownable{ using SafeMath for uint; bool onTestnet = false; bool genesisAdded = false; uint public masternodeRound; uint public masternodeCandidate; uint public masternodeCounter; uint public masternodeEpoch; uint public miningEpoch; uint public rewardsProofOfWork; uint public rewardsMasternode; uint rewardsGlobal = 50 * 1e8; uint public MINING_PHASE_DURATION_BLOCKS = 4500; struct MasterNode { address accountOwner; bool isActive; bool isTeamMember; uint storedIndex; uint startingRound; uint[] indexcounter; } uint[] userArray; address[] userAddressArray; mapping(uint => MasterNode) userByIndex; // UINT masterMapping mapping(address => MasterNode) userByAddress; //masterMapping mapping(address => uint) userAddressIndex; event Deposit(address token, address user, uint amount, uint balance); event Withdraw(address token, address user, uint amount, uint balance); event NewMasternode(address candidateAddress, uint timeStamp); event RemovedMasternode(address candidateAddress, uint timeStamp); /** * @dev Add the genesis accounts */ function addGenesis(address _genesis, bool _team) onlyOwner public { require(!genesisAdded); addMasternode(_genesis); if (_team) { updateMasternodeAsTeamMember(msg.sender); } } /** * @dev Close the genesis accounts */ function closeGenesis() onlyOwner public { genesisAdded = true; // Forever lock this. } /** * @dev Add a user as masternode. Called as internal since we only add masternodes by depositing collateral or by voting. * @param _candidate Candidate address * @return uint Masternode index */ function addMasternode(address _candidate) internal returns(uint) { userByIndex[masternodeCounter].accountOwner = _candidate; userByIndex[masternodeCounter].isActive = true; userByIndex[masternodeCounter].startingRound = masternodeRound + 1; userByIndex[masternodeCounter].storedIndex = masternodeCounter; userByAddress[_candidate].accountOwner = _candidate; userByAddress[_candidate].indexcounter.push(masternodeCounter); userArray.push(userArray.length); masternodeCounter++; emit NewMasternode(_candidate, now); return masternodeCounter - 1; // } /** * @dev Allow us to update a masternode's round to keep progress * @param _candidate ID of masternode */ function updateMasternode(uint _candidate) internal returns(bool) { userByIndex[_candidate].startingRound++; return true; } /** * @dev Allow us to update a masternode to team member status * @param _member address */ function updateMasternodeAsTeamMember(address _member) internal returns (bool) { userByAddress[_member].isTeamMember = true; return (true); } /** * @dev Let us know if an address is part of the team. * @param _member address */ function isTeamMember (address _member) public view returns (bool) { if (userByAddress[_member].isTeamMember) return true; } /** * @dev Remove a specific masternode * @param _masternodeID ID of the masternode to remove */ function deleteMasternode(uint _masternodeID) internal returns(bool success) { uint rowToDelete = userByIndex[_masternodeID].storedIndex; uint keyToMove = userArray[userArray.length - 1]; userByIndex[_masternodeID].isActive = userByIndex[_masternodeID].isActive = (false); userArray[rowToDelete] = keyToMove; userByIndex[keyToMove].storedIndex = rowToDelete; userArray.length = userArray.length - 1; removeFromUserCounter(_masternodeID); emit RemovedMasternode(userByIndex[_masternodeID].accountOwner, now); return true; } /** * @dev returns what account belongs to a masternode */ function isPartOf(uint mnid) public view returns (address) { return userByIndex[mnid].accountOwner; } /** * @dev Internal function to remove a masternode from a user address if this address holds multpile masternodes * @param index MasternodeID */ function removeFromUserCounter(uint index) internal returns(uint[]) { address belong = isPartOf(index); if (index >= userByAddress[belong].indexcounter.length) return; for (uint i = index; i<userByAddress[belong].indexcounter.length-1; i++){ userByAddress[belong].indexcounter[i] = userByAddress[belong].indexcounter[i+1]; } delete userByAddress[belong].indexcounter[userByAddress[belong].indexcounter.length-1]; userByAddress[belong].indexcounter.length--; return userByAddress[belong].indexcounter; } /** * @dev Primary contract function to update the current user and prepare the next one. * A number of steps have been token to ensure the contract can never run out of gas when looping over our masternodes. */ 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 == masternodeCounter - 1) { masternodeRound = masternodeRound + 1; masternodeCandidate = 0; } for (uint i = masternodeCandidate; i < masternodeCounter; i++) { if (userByIndex[i].isActive) { if (userByIndex[i].startingRound == masternodeRound) { updateMasternode(i); masternodeCandidate = i; return (userByIndex[i].accountOwner); } } } masternodeRound = masternodeRound + 1; return (0); } /** * @dev Helper function to loop through our masternodes at start and return the correct round */ function getFollowingCandidate() internal view returns(address _address) { uint tmpRound = masternodeRound; uint tmpCandidate = masternodeCandidate; if (tmpCandidate == masternodeCounter - 1) { tmpRound = tmpRound + 1; tmpCandidate = 0; } for (uint i = masternodeCandidate; i < masternodeCounter; i++) { if (userByIndex[i].isActive) { if (userByIndex[i].startingRound == tmpRound) { tmpCandidate = i; return (userByIndex[i].accountOwner); } } } tmpRound = tmpRound + 1; return (0); } /** * @dev Displays all masternodes belonging to a user address. */ function belongsToUser(address userAddress) public view returns(uint[]) { return (userByAddress[userAddress].indexcounter); } /** * @dev Helper function to know if an address owns masternodes */ function isMasternodeOwner(address _candidate) public view returns(bool) { if(userByAddress[_candidate].indexcounter.length <= 0) return false; if (userByAddress[_candidate].accountOwner == _candidate) return true; } /** * @dev Helper function to get the last masternode belonging to a user */ function getLastPerUser(address _candidate) public view returns (uint) { return userByAddress[_candidate].indexcounter[userByAddress[_candidate].indexcounter.length - 1]; } /** * @dev Return the base rewards. This should be overrided by the miner contract. * Return a base value for standalone usage ONLY. */ function getMiningReward() public view returns(uint) { return 50 * 1e8; } /** * @dev Calculate and set the reward schema for Caelum. * Each mining phase is decided by multiplying the MINING_PHASE_DURATION_BLOCKS with factor 10. * Depending on the outcome (solidity always rounds), we can detect the current stage of mining. * First stage we cut the rewards to 5% to prevent instamining. * Last stage we leave 2% for miners to incentivize keeping miners running. */ 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; } /** * @dev Executes the masternode flow. Should be called after mining a block. */ function _arrangeMasternodeFlow() internal { calculateRewardStructures(); setMasternodeCandidate(); miningEpoch++; } /** * @dev Executes the masternode flow. Should be called after mining a block. * This is an emergency manual loop method. */ function _emergencyLoop() onlyOwner public { calculateRewardStructures(); setMasternodeCandidate(); miningEpoch++; } function masternodeInfo(uint index) public view returns ( address, bool, uint, uint ) { return ( userByIndex[index].accountOwner, userByIndex[index].isActive, userByIndex[index].storedIndex, userByIndex[index].startingRound ); } function contractProgress() public view returns ( uint epoch, uint candidate, uint round, uint miningepoch, uint globalreward, uint powreward, uint masternodereward, uint usercounter ) { return ( masternodeEpoch, masternodeCandidate, masternodeRound, miningEpoch, getMiningReward(), rewardsProofOfWork, rewardsMasternode, masternodeCounter ); } } contract CaelumMasternode is CaelumVotings, CaelumAbstractMasternode { /** * @dev Hardcoded token mining address. For trust and safety we do not allow changing this. * Should anything change, a new instance needs to be redeployed. */ address public miningContract; address public tokenContract; bool minerSet = false; bool tokenSet = false; function setMiningContract(address _t) onlyOwner public { require(!minerSet); miningContract = _t; minerSet = true; } function setTokenContract(address _t) onlyOwner public { require(!tokenSet); tokenContract = _t; tokenSet = true; } function setMasternodeContractFromVote(address _t) internal { } function setTokenContractFromVote(address _t) internal{ tokenContract = _t; } function setMiningContractFromVote (address _t) internal { miningContract = _t; } /** * @dev Only allow the token mining contract to call this function when used remotely. * Use the internal function when working within the same contract. */ modifier onlyMiningContract() { require(msg.sender == miningContract); _; } /** * @dev Only allow the token contract to call this function when used remotely. * Use the internal function when working within the same contract. */ modifier onlyTokenContract() { require(msg.sender == tokenContract); _; } /** * @dev Only allow the token contract to call this function when used remotely. * Use the internal function when working within the same contract. */ modifier bothRemoteContracts() { require(msg.sender == tokenContract || msg.sender == miningContract); _; } /** * @dev Use this to externaly call the _arrangeMasternodeFlow function. ALWAYS set a modifier ! */ function _externalArrangeFlow() onlyMiningContract external { _arrangeMasternodeFlow(); } /** * @dev Use this to externaly call the addMasternode function. ALWAYS set a modifier ! */ function _externalAddMasternode(address _received) onlyMiningContract external { addMasternode(_received); } /** * @dev Use this to externaly call the deleteMasternode function. ALWAYS set a modifier ! */ function _externalStopMasternode(address _received) onlyMiningContract external { deleteMasternode(getLastPerUser(_received)); } function getMiningReward() public view returns(uint) { return CaelumMiner(miningContract).getMiningReward(); } address cloneDataFrom = 0x7600bF5112945F9F006c216d5d6db0df2806eDc6; 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(); masternodeEpoch = epoch; masternodeRound = round; miningEpoch = miningepoch; rewardsProofOfWork = powreward; rewardsMasternode = masternodereward; } } contract CaelumToken is Ownable, StandardToken, CaelumVotings, CaelumAcceptERC20 { using SafeMath for uint; ERC20 previousContract; bool contractSet = false; bool public swapClosed = false; uint public swapCounter; string public symbol = "CLM"; string public name = "Caelum Token"; uint8 public decimals = 8; uint256 public totalSupply = 2100000000000000; address public miningContract = 0x0; /** * @dev Only allow the token mining contract to call this function when used remotely. * Use the internal function when working within the same contract. */ modifier onlyMiningContract() { require(msg.sender == miningContract); _; } constructor(address _previousContract) public { previousContract = ERC20(_previousContract); swapClosed = false; swapCounter = 0; } function setMiningContract (address _t) onlyOwner public { require(!contractSet); miningContract = _t; contractSet = true; } function setMasternodeContractFromVote(address _t) internal { return; } function setTokenContractFromVote(address _t) internal{ return; } function setMiningContractFromVote (address _t) internal { miningContract = _t; } function changeSwapState (bool _state) onlyOwner public { require(swapCounter <= 9); swapClosed = _state; swapCounter++; } function rewardExternal(address _receiver, uint _amount) onlyMiningContract external { balances[_receiver] = balances[_receiver].add(_amount); emit Transfer(this, _receiver, _amount); } function upgradeTokens() public{ require(!swapClosed); uint amountToUpgrade = previousContract.balanceOf(msg.sender); require(amountToUpgrade <= previousContract.allowance(msg.sender, this)); if(previousContract.transferFrom(msg.sender, this, amountToUpgrade)){ balances[msg.sender] = balances[msg.sender].add(amountToUpgrade); // 2% Premine as determined by the community meeting. emit Transfer(this, msg.sender, amountToUpgrade); } require(previousContract.balanceOf(msg.sender) == 0); } } contract AbstractERC918 is EIP918Interface { // generate a new challenge number after a new reward is minted bytes32 public challengeNumber; // the current mining difficulty uint public difficulty; // cumulative counter of the total minted tokens uint public tokensMinted; // track read only minting statistics struct Statistics { address lastRewardTo; uint lastRewardAmount; uint lastRewardEthBlockNumber; uint lastRewardTimestamp; } Statistics public statistics; /* * Externally facing mint function that is called by miners to validate challenge digests, calculate reward, * populate statistics, mutate epoch variables and adjust the solution difficulty as required. Once complete, * a Mint event is emitted before returning a success indicator. **/ function mint(uint256 nonce, bytes32 challenge_digest) public returns (bool success); /* * Internal interface function _hash. Overide in implementation to define hashing algorithm and * validation **/ function _hash(uint256 nonce, bytes32 challenge_digest) internal returns (bytes32 digest); /* * Internal interface function _reward. Overide in implementation to calculate and return reward * amount **/ function _reward() internal returns (uint); /* * Internal interface function _newEpoch. Overide in implementation to define a cutpoint for mutating * mining variables in preparation for the next epoch **/ function _newEpoch(uint256 nonce) internal returns (uint); /* * Internal interface function _adjustDifficulty. Overide in implementation to adjust the difficulty * of the mining as required **/ function _adjustDifficulty() internal returns (uint); } contract CaelumAbstractMiner is AbstractERC918 { /** * CaelumMiner contract. * * We need to make sure the contract is 100% compatible when using the EIP918Interface. * This contract is an abstract Caelum miner contract. * * Function 'mint', and '_reward' are overriden in the CaelumMiner contract. * Function '_reward_masternode' is added and needs to be overriden in the CaelumMiner contract. */ using SafeMath for uint; using ExtendedMath for uint; uint256 public totalSupply = 2100000000000000; uint public latestDifficultyPeriodStarted; uint public epochCount; uint public baseMiningReward = 50; uint public blocksPerReadjustment = 512; uint public _MINIMUM_TARGET = 2 ** 16; uint public _MAXIMUM_TARGET = 2 ** 234; uint public rewardEra = 0; uint public maxSupplyForEra; uint public MAX_REWARD_ERA = 39; uint public MINING_RATE_FACTOR = 60; //mint the token 60 times less often than ether uint public MAX_ADJUSTMENT_PERCENT = 100; uint public TARGET_DIVISOR = 2000; uint public QUOTIENT_LIMIT = TARGET_DIVISOR.div(2); mapping(bytes32 => bytes32) solutionForChallenge; mapping(address => mapping(address => uint)) allowed; bytes32 public challengeNumber; uint public difficulty; uint public tokensMinted; Statistics public statistics; event Mint(address indexed from, uint reward_amount, uint epochCount, bytes32 newChallengeNumber); event RewardMasternode(address candidate, uint amount); constructor() public { tokensMinted = 0; maxSupplyForEra = totalSupply.div(2); difficulty = _MAXIMUM_TARGET; latestDifficultyPeriodStarted = block.number; _newEpoch(0); } function _newEpoch(uint256 nonce) internal returns(uint) { if (tokensMinted.add(getMiningReward()) > maxSupplyForEra && rewardEra < MAX_REWARD_ERA) { rewardEra = rewardEra + 1; } maxSupplyForEra = totalSupply - totalSupply.div(2 ** (rewardEra + 1)); epochCount = epochCount.add(1); challengeNumber = blockhash(block.number - 1); return (epochCount); } function mint(uint256 nonce, bytes32 challenge_digest) public returns(bool success); function _hash(uint256 nonce, bytes32 challenge_digest) internal returns(bytes32 digest) { digest = keccak256(challengeNumber, msg.sender, nonce); if (digest != challenge_digest) revert(); if (uint256(digest) > difficulty) revert(); bytes32 solution = solutionForChallenge[challengeNumber]; solutionForChallenge[challengeNumber] = digest; if (solution != 0x0) revert(); //prevent the same answer from awarding twice } function _reward() internal returns(uint); function _reward_masternode() internal returns(uint); function _adjustDifficulty() internal returns(uint) { //every so often, readjust difficulty. Dont readjust when deploying if (epochCount % blocksPerReadjustment != 0) { return difficulty; } uint ethBlocksSinceLastDifficultyPeriod = block.number - latestDifficultyPeriodStarted; //assume 360 ethereum blocks per hour //we want miners to spend 10 minutes to mine each 'block', about 60 ethereum blocks = one 0xbitcoin epoch uint epochsMined = blocksPerReadjustment; uint targetEthBlocksPerDiffPeriod = epochsMined * MINING_RATE_FACTOR; //if there were less eth blocks passed in time than expected if (ethBlocksSinceLastDifficultyPeriod < targetEthBlocksPerDiffPeriod) { uint excess_block_pct = (targetEthBlocksPerDiffPeriod.mul(MAX_ADJUSTMENT_PERCENT)).div(ethBlocksSinceLastDifficultyPeriod); uint excess_block_pct_extra = excess_block_pct.sub(100).limitLessThan(QUOTIENT_LIMIT); // If there were 5% more blocks mined than expected then this is 5. If there were 100% more blocks mined than expected then this is 100. //make it harder difficulty = difficulty.sub(difficulty.div(TARGET_DIVISOR).mul(excess_block_pct_extra)); //by up to 50 % } else { uint shortage_block_pct = (ethBlocksSinceLastDifficultyPeriod.mul(MAX_ADJUSTMENT_PERCENT)).div(targetEthBlocksPerDiffPeriod); uint shortage_block_pct_extra = shortage_block_pct.sub(100).limitLessThan(QUOTIENT_LIMIT); //always between 0 and 1000 //make it easier difficulty = difficulty.add(difficulty.div(TARGET_DIVISOR).mul(shortage_block_pct_extra)); //by up to 50 % } latestDifficultyPeriodStarted = block.number; if (difficulty < _MINIMUM_TARGET) //very difficult { difficulty = _MINIMUM_TARGET; } if (difficulty > _MAXIMUM_TARGET) //very easy { difficulty = _MAXIMUM_TARGET; } } function getChallengeNumber() public view returns(bytes32) { return challengeNumber; } function getMiningDifficulty() public view returns(uint) { return _MAXIMUM_TARGET.div(difficulty); } function getMiningTarget() public view returns(uint) { return difficulty; } function getMiningReward() public view returns(uint) { return (baseMiningReward * 1e8).div(2 ** rewardEra); } function getMintDigest( uint256 nonce, bytes32 challenge_digest, bytes32 challenge_number ) public view returns(bytes32 digesttest) { bytes32 digest = keccak256(challenge_number, msg.sender, nonce); return digest; } function checkMintSolution( uint256 nonce, bytes32 challenge_digest, bytes32 challenge_number, uint testTarget ) public view returns(bool success) { bytes32 digest = keccak256(challenge_number, msg.sender, nonce); if (uint256(digest) > testTarget) revert(); return (digest == challenge_digest); } } contract CaelumMiner is CaelumVotings, CaelumAbstractMiner { /** * CaelumMiner main contract * * Inherit from our abstract CaelumMiner contract and override some functions * of the AbstractERC918 contract to allow masternode rewardings. * * @dev use this contract to make all changes needed for your project. */ address cloneDataFrom = 0x7600bF5112945F9F006c216d5d6db0df2806eDc6; bool ACTIVE_CONTRACT_STATE = true; bool MasternodeSet = false; bool TokenSet = false; address _CaelumMasternodeContract; address _CaelumTokenContract; CaelumMasternode public MasternodeContract; CaelumToken public tokenContract; function setMasternodeContract(address _t) onlyOwner public { require(!MasternodeSet); MasternodeContract = CaelumMasternode(_t); _CaelumMasternodeContract = (_t); MasternodeSet = true; } function setTokenContract(address _t) onlyOwner public { require(!TokenSet); tokenContract = CaelumToken(_t); _CaelumTokenContract = (_t); TokenSet = true; } function setMiningContract (address _t) onlyOwner public { return; } function setMasternodeContractFromVote(address _t) internal { MasternodeContract = CaelumMasternode(_t); _CaelumMasternodeContract = (_t); } function setTokenContractFromVote(address _t) internal{ tokenContract = CaelumToken(_t); _CaelumTokenContract = (_t); } function setMiningContractFromVote (address _t) internal { return; } function lockMiningContract () onlyOwner public { ACTIVE_CONTRACT_STATE = false; } function getDataFromContract () onlyOwner public { require(_CaelumTokenContract != 0); require(_CaelumMasternodeContract != 0); CaelumMiner prev = CaelumMiner(cloneDataFrom); difficulty = prev.difficulty(); rewardEra = prev.rewardEra(); MINING_RATE_FACTOR = prev.MINING_RATE_FACTOR(); maxSupplyForEra = prev.maxSupplyForEra(); tokensMinted = prev.tokensMinted(); epochCount = prev.epochCount(); latestDifficultyPeriodStarted = prev.latestDifficultyPeriodStarted(); ACTIVE_CONTRACT_STATE = true; } /** * @dev override of the original function since we want to call the masternode contract remotely. */ function mint(uint256 nonce, bytes32 challenge_digest) public returns(bool success) { // If contract is no longer active, stop accepting solutions. require(ACTIVE_CONTRACT_STATE); _hash(nonce, challenge_digest); MasternodeContract._externalArrangeFlow(); uint rewardAmount =_reward(); uint rewardMasternode = _reward_masternode(); tokensMinted += rewardAmount.add(rewardMasternode); uint epochCounter = _newEpoch(nonce); _adjustDifficulty(); statistics = Statistics(msg.sender, rewardAmount, block.number, now); emit Mint(msg.sender, rewardAmount, epochCounter, challengeNumber); return true; } /** * @dev override of the original function since we want to call the masternode contract remotely. */ function _reward() internal returns(uint) { uint _pow = MasternodeContract.rewardsProofOfWork(); tokenContract.rewardExternal(msg.sender, _pow); return _pow; } /** * @dev override of the original function since we want to call the masternode contract remotely. */ function _reward_masternode() internal returns(uint) { uint _mnReward = MasternodeContract.rewardsMasternode(); if (MasternodeContract.masternodeCounter() == 0) return 0; uint getCandidate = MasternodeContract.masternodeCandidate(); address _mnCandidate = MasternodeContract.isPartOf(getCandidate); if (_mnCandidate == 0x0) return 0; tokenContract.rewardExternal(_mnCandidate, _mnReward); emit RewardMasternode(_mnCandidate, _mnReward); return _mnReward; } function getMiningReward() public view returns(uint) { return MasternodeContract.rewardsProofOfWork(); } } /** * Burn some gas and create all contracts in a single call :-) */ contract caelumFactory { CaelumMiner public MINER; CaelumMasternode public MASTER; CaelumToken public TOKEN; function newCookie() public { MINER = new CaelumMiner(); MASTER = new CaelumMasternode(); TOKEN = new CaelumToken(0x0); MASTER.setMiningContract(MINER); MASTER.setTokenContract(TOKEN); MINER.setMasternodeContract(MASTER); MINER.setTokenContract(TOKEN); TOKEN.setMiningContract(MINER); TOKEN.setDataStorage(MASTER); MASTER.transferOwnership(msg.sender); TOKEN.transferOwnership(msg.sender); MINER.transferOwnership(msg.sender); } }
* @dev Allow voters to submit their vote on a proposal. Voters can only cast 1 vote per proposal. If the proposed vote is about adding Team members, only Team members are able to vote. A proposal can only be published if the total of votes is greater then MINIMUM_VOTERS_NEEDED. @param proposalID proposalID/ This is the prefered way of handling vote results. It costs more gas but prevents tampering. If gas is an issue, you can comment handleLastProposal out and call it manually as onlyOwner.
function voteProposal(uint proposalID) public returns (bool success) { require(voterMap[msg.sender].isVoter, "Sender not listed as voter"); require(proposalID >= 0, "No proposal was selected."); require(proposalID <= proposalCounter, "Proposal out of limits."); require(voterProposals[proposalID] != msg.sender, "Already voted."); require(votersCount >= MINIMUM_VOTERS_NEEDED, "Not enough voters in existence to push a proposal"); voterProposals[proposalID] = msg.sender; proposalList[proposalID].totalVotes++; if(reachedMajority(proposalID)) { handleLastProposal(); return true; } }
14,043,116
[ 1, 7009, 331, 352, 414, 358, 4879, 3675, 12501, 603, 279, 14708, 18, 776, 352, 414, 848, 1338, 4812, 404, 12501, 1534, 14708, 18, 971, 326, 20084, 12501, 353, 2973, 6534, 10434, 4833, 16, 1338, 10434, 4833, 854, 7752, 358, 12501, 18, 432, 14708, 848, 1338, 506, 9487, 309, 326, 2078, 434, 19588, 353, 6802, 1508, 6989, 18605, 67, 58, 1974, 11367, 67, 5407, 22832, 18, 225, 14708, 734, 14708, 734, 19, 1220, 353, 326, 13256, 329, 4031, 434, 5057, 12501, 1686, 18, 2597, 22793, 1898, 16189, 1496, 17793, 268, 301, 457, 310, 18, 971, 16189, 353, 392, 5672, 16, 1846, 848, 2879, 1640, 3024, 14592, 596, 471, 745, 518, 10036, 487, 1338, 5541, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 12501, 14592, 12, 11890, 14708, 734, 13, 1071, 1135, 261, 6430, 2216, 13, 288, 203, 3639, 2583, 12, 90, 20005, 863, 63, 3576, 18, 15330, 8009, 291, 58, 20005, 16, 315, 12021, 486, 12889, 487, 331, 20005, 8863, 203, 3639, 2583, 12, 685, 8016, 734, 1545, 374, 16, 315, 2279, 14708, 1703, 3170, 1199, 1769, 203, 3639, 2583, 12, 685, 8016, 734, 1648, 14708, 4789, 16, 315, 14592, 596, 434, 8181, 1199, 1769, 203, 3639, 2583, 12, 90, 20005, 626, 22536, 63, 685, 8016, 734, 65, 480, 1234, 18, 15330, 16, 315, 9430, 331, 16474, 1199, 1769, 203, 203, 203, 3639, 2583, 12, 90, 352, 414, 1380, 1545, 6989, 18605, 67, 58, 1974, 11367, 67, 5407, 22832, 16, 315, 1248, 7304, 331, 352, 414, 316, 15782, 358, 1817, 279, 14708, 8863, 203, 3639, 331, 20005, 626, 22536, 63, 685, 8016, 734, 65, 273, 1234, 18, 15330, 31, 203, 3639, 14708, 682, 63, 685, 8016, 734, 8009, 4963, 29637, 9904, 31, 203, 203, 3639, 309, 12, 266, 2004, 17581, 560, 12, 685, 8016, 734, 3719, 288, 203, 5411, 1640, 3024, 14592, 5621, 203, 5411, 327, 638, 31, 203, 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 ]
// SPDX-License-Identifier: AGPL-3.0-only pragma solidity 0.8.10; import {ILensNFTBase} from '../../interfaces/ILensNFTBase.sol'; import {Errors} from '../../libraries/Errors.sol'; import {DataTypes} from '../../libraries/DataTypes.sol'; import {Events} from '../../libraries/Events.sol'; import {ERC721Time} from './ERC721Time.sol'; import {ERC721Enumerable} from './ERC721Enumerable.sol'; abstract contract LensNFTBase is ILensNFTBase, ERC721Enumerable { bytes32 internal constant EIP712_REVISION_HASH = keccak256('1'); bytes32 internal constant PERMIT_TYPEHASH = keccak256('Permit(address spender,uint256 tokenId,uint256 nonce,uint256 deadline)'); bytes32 internal constant PERMIT_FOR_ALL_TYPEHASH = keccak256( 'PermitForAll(address owner,address operator,bool approved,uint256 nonce,uint256 deadline)' ); bytes32 internal constant BURN_WITH_SIG_TYPEHASH = keccak256('BurnWithSig(uint256 tokenId,uint256 nonce,uint256 deadline)'); bytes32 internal constant EIP712_DOMAIN_TYPEHASH = keccak256( 'EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)' ); mapping(address => uint256) public sigNonces; /** * @notice Initializer sets the name, symbol and the cached domain separator. * * NOTE: Inheritor contracts *must* call this function to initialize the name & symbol in the * inherited ERC721 contract. * * @param name The name to set in the ERC721 contract. * @param symbol The symbol to set in the ERC721 contract. */ function _initialize(string calldata name, string calldata symbol) internal { ERC721Time.__ERC721_Init(name, symbol); emit Events.BaseInitialized(name, symbol, block.timestamp); } /// @inheritdoc ILensNFTBase function permit( address spender, uint256 tokenId, DataTypes.EIP712Signature calldata sig ) external override { if (spender == address(0)) revert Errors.ZeroSpender(); address owner = ownerOf(tokenId); _validateRecoveredAddress( _calculateDigest( keccak256( abi.encode(PERMIT_TYPEHASH, spender, tokenId, sigNonces[owner]++, sig.deadline) ) ), owner, sig ); _approve(spender, tokenId); } /// @inheritdoc ILensNFTBase function permitForAll( address owner, address operator, bool approved, DataTypes.EIP712Signature calldata sig ) external override { if (operator == address(0)) revert Errors.ZeroSpender(); _validateRecoveredAddress( _calculateDigest( keccak256( abi.encode( PERMIT_FOR_ALL_TYPEHASH, owner, operator, approved, sigNonces[owner]++, sig.deadline ) ) ), owner, sig ); _setOperatorApproval(owner, operator, approved); } /// @inheritdoc ILensNFTBase function getDomainSeparator() external view override returns (bytes32) { return _calculateDomainSeparator(); } /// @inheritdoc ILensNFTBase function burn(uint256 tokenId) public virtual override { if (!_isApprovedOrOwner(msg.sender, tokenId)) revert Errors.NotOwnerOrApproved(); _burn(tokenId); } /// @inheritdoc ILensNFTBase function burnWithSig(uint256 tokenId, DataTypes.EIP712Signature calldata sig) public virtual override { address owner = ownerOf(tokenId); _validateRecoveredAddress( _calculateDigest( keccak256( abi.encode(BURN_WITH_SIG_TYPEHASH, tokenId, sigNonces[owner]++, sig.deadline) ) ), owner, sig ); _burn(tokenId); } /** * @dev Wrapper for ecrecover to reduce code size, used in meta-tx specific functions. */ function _validateRecoveredAddress( bytes32 digest, address expectedAddress, DataTypes.EIP712Signature memory sig ) internal view { if (sig.deadline < block.timestamp) revert Errors.SignatureExpired(); address recoveredAddress = ecrecover(digest, sig.v, sig.r, sig.s); if (recoveredAddress == address(0) || recoveredAddress != expectedAddress) revert Errors.SignatureInvalid(); } /** * @dev Calculates EIP712 DOMAIN_SEPARATOR based on the current contract and chain ID. */ function _calculateDomainSeparator() internal view returns (bytes32) { return keccak256( abi.encode( EIP712_DOMAIN_TYPEHASH, keccak256(bytes(name())), EIP712_REVISION_HASH, block.chainid, address(this) ) ); } /** * @dev Calculates EIP712 digest based on the current DOMAIN_SEPARATOR. * * @param hashedMessage The message hash from which the digest should be calculated. * * @return A 32-byte output representing the EIP712 digest. */ function _calculateDigest(bytes32 hashedMessage) internal view returns (bytes32) { bytes32 digest; unchecked { digest = keccak256( abi.encodePacked('\x19\x01', _calculateDomainSeparator(), hashedMessage) ); } return digest; } }
* @dev Wrapper for ecrecover to reduce code size, used in meta-tx specific functions./
function _validateRecoveredAddress( bytes32 digest, address expectedAddress, DataTypes.EIP712Signature memory sig ) internal view { if (sig.deadline < block.timestamp) revert Errors.SignatureExpired(); address recoveredAddress = ecrecover(digest, sig.v, sig.r, sig.s); if (recoveredAddress == address(0) || recoveredAddress != expectedAddress) revert Errors.SignatureInvalid(); }
5,448,431
[ 1, 3611, 364, 425, 1793, 3165, 358, 5459, 981, 963, 16, 1399, 316, 2191, 17, 978, 2923, 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, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5662, 426, 16810, 1887, 12, 203, 3639, 1731, 1578, 5403, 16, 203, 3639, 1758, 2665, 1887, 16, 203, 3639, 1910, 2016, 18, 41, 2579, 27, 2138, 5374, 3778, 3553, 203, 565, 262, 2713, 1476, 288, 203, 3639, 309, 261, 7340, 18, 22097, 1369, 411, 1203, 18, 5508, 13, 15226, 9372, 18, 5374, 10556, 5621, 203, 3639, 1758, 24616, 1887, 273, 425, 1793, 3165, 12, 10171, 16, 3553, 18, 90, 16, 3553, 18, 86, 16, 3553, 18, 87, 1769, 203, 3639, 309, 261, 266, 16810, 1887, 422, 1758, 12, 20, 13, 747, 24616, 1887, 480, 2665, 1887, 13, 203, 5411, 15226, 9372, 18, 5374, 1941, 5621, 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 ]
pragma solidity 0.4.24; 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; } } contract Ownable { address public owner; mapping(address => bool) admins; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); event AddAdmin(address indexed admin); event DelAdmin(address indexed admin); /** * @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); _; } modifier onlyAdmin() { require(isAdmin(msg.sender)); _; } function addAdmin(address _adminAddress) external onlyOwner { require(_adminAddress != address(0)); admins[_adminAddress] = true; emit AddAdmin(_adminAddress); } function delAdmin(address _adminAddress) external onlyOwner { require(admins[_adminAddress]); admins[_adminAddress] = false; emit DelAdmin(_adminAddress); } function isAdmin(address _adminAddress) public view returns (bool) { return admins[_adminAddress]; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) external onlyOwner { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } interface tokenRecipient { function receiveApproval(address _from, address _token, uint _value, bytes _extraData) external; function receiveCreateAuction(address _from, address _token, uint _tokenId, uint _startPrice, uint _duration) external; function receiveCreateAuctionFromArray(address _from, address _token, uint[] _landIds, uint _startPrice, uint _duration) external; } contract ERC721 { function implementsERC721() public pure returns (bool); function totalSupply() public view returns (uint256 total); function balanceOf(address _owner) public view returns (uint256 balance); function ownerOf(uint256 _tokenId) public view returns (address owner); function approve(address _to, uint256 _tokenId) public returns (bool); function transferFrom(address _from, address _to, uint256 _tokenId) public returns (bool); function transfer(address _to, uint256 _tokenId) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); // Optional // function name() public view returns (string name); // function symbol() public view returns (string symbol); // function tokensOfOwner(address _owner) external view returns (uint256[] tokenIds); // function tokenMetadata(uint256 _tokenId) public view returns (string infoUrl); } contract LandBase is ERC721, Ownable { using SafeMath for uint; event NewLand(address indexed owner, uint256 landId); struct Land { uint id; } // Total amount of lands uint256 private totalLands; // Incremental counter of lands Id uint256 private lastLandId; //Mapping from land ID to Land struct mapping(uint256 => Land) public lands; // Mapping from land ID to owner mapping(uint256 => address) private landOwner; // Mapping from land ID to approved address mapping(uint256 => address) private landApprovals; // Mapping from owner to list of owned lands IDs mapping(address => uint256[]) private ownedLands; // Mapping from land ID to index of the owner lands list // т.е. ID земли => порядковый номер в списке владельца mapping(uint256 => uint256) private ownedLandsIndex; modifier onlyOwnerOf(uint256 _tokenId) { require(owns(msg.sender, _tokenId)); _; } /** * @dev Gets the owner of the specified land ID * @param _tokenId uint256 ID of the land to query the owner of * @return owner address currently marked as the owner of the given land ID */ function ownerOf(uint256 _tokenId) public view returns (address) { return landOwner[_tokenId]; } function totalSupply() public view returns (uint256) { return totalLands; } /** * @dev Gets the balance of the specified address * @param _owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf(address _owner) public view returns (uint256) { return ownedLands[_owner].length; } /** * @dev Gets the list of lands owned by a given address * @param _owner address to query the lands of * @return uint256[] representing the list of lands owned by the passed address */ function landsOf(address _owner) public view returns (uint256[]) { return ownedLands[_owner]; } /** * @dev Gets the approved address to take ownership of a given land ID * @param _tokenId uint256 ID of the land to query the approval of * @return address currently approved to take ownership of the given land ID */ function approvedFor(uint256 _tokenId) public view returns (address) { return landApprovals[_tokenId]; } /** * @dev Tells whether the msg.sender is approved for the given land ID or not * This function is not private so it can be extended in further implementations like the operatable ERC721 * @param _owner address of the owner to query the approval of * @param _tokenId uint256 ID of the land to query the approval of * @return bool whether the msg.sender is approved for the given land ID or not */ function allowance(address _owner, uint256 _tokenId) public view returns (bool) { return approvedFor(_tokenId) == _owner; } /** * @dev Approves another address to claim for the ownership of the given land ID * @param _to address to be approved for the given land ID * @param _tokenId uint256 ID of the land to be approved */ function approve(address _to, uint256 _tokenId) public onlyOwnerOf(_tokenId) returns (bool) { require(_to != msg.sender); if (approvedFor(_tokenId) != address(0) || _to != address(0)) { landApprovals[_tokenId] = _to; emit Approval(msg.sender, _to, _tokenId); return true; } } function approveAndCall(address _spender, uint256 _tokenId, bytes _extraData) public returns (bool) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _tokenId)) { spender.receiveApproval(msg.sender, this, _tokenId, _extraData); return true; } } function createAuction(address _auction, uint _tokenId, uint _startPrice, uint _duration) public returns (bool) { tokenRecipient auction = tokenRecipient(_auction); if (approve(_auction, _tokenId)) { auction.receiveCreateAuction(msg.sender, this, _tokenId, _startPrice, _duration); return true; } } function createAuctionFromArray(address _auction, uint[] _landIds, uint _startPrice, uint _duration) public returns (bool) { tokenRecipient auction = tokenRecipient(_auction); for (uint i = 0; i < _landIds.length; ++i) require(approve(_auction, _landIds[i])); auction.receiveCreateAuctionFromArray(msg.sender, this, _landIds, _startPrice, _duration); return true; } /** * @dev Claims the ownership of a given land ID * @param _tokenId uint256 ID of the land being claimed by the msg.sender */ function takeOwnership(uint256 _tokenId) public { require(allowance(msg.sender, _tokenId)); clearApprovalAndTransfer(ownerOf(_tokenId), msg.sender, _tokenId); } /** * @dev Transfers the ownership of a given land ID to another address * @param _to address to receive the ownership of the given land ID * @param _tokenId uint256 ID of the land to be transferred */ function transfer(address _to, uint256 _tokenId) public onlyOwnerOf(_tokenId) returns (bool) { clearApprovalAndTransfer(msg.sender, _to, _tokenId); return true; } function ownerTransfer(address _from, address _to, uint256 _tokenId) onlyAdmin public returns (bool) { clearApprovalAndTransfer(_from, _to, _tokenId); return true; } /** * @dev Internal function to clear current approval and transfer the ownership of a given land ID * @param _from address which you want to send lands from * @param _to address which you want to transfer the land to * @param _tokenId uint256 ID of the land to be transferred */ function clearApprovalAndTransfer(address _from, address _to, uint256 _tokenId) internal { require(owns(_from, _tokenId)); require(_to != address(0)); require(_to != ownerOf(_tokenId)); clearApproval(_from, _tokenId); removeLand(_from, _tokenId); addLand(_to, _tokenId); emit Transfer(_from, _to, _tokenId); } /** * @dev Internal function to clear current approval of a given land ID * @param _tokenId uint256 ID of the land to be transferred */ function clearApproval(address _owner, uint256 _tokenId) private { require(owns(_owner, _tokenId)); landApprovals[_tokenId] = address(0); emit Approval(_owner, address(0), _tokenId); } /** * @dev Internal function to add a land ID to the list of a given address * @param _to address representing the new owner of the given land ID * @param _tokenId uint256 ID of the land to be added to the lands list of the given address */ function addLand(address _to, uint256 _tokenId) private { require(landOwner[_tokenId] == address(0)); landOwner[_tokenId] = _to; uint256 length = ownedLands[_to].length; ownedLands[_to].push(_tokenId); ownedLandsIndex[_tokenId] = length; totalLands = totalLands.add(1); } /** * @dev Internal function to remove a land ID from the list of a given address * @param _from address representing the previous owner of the given land ID * @param _tokenId uint256 ID of the land to be removed from the lands list of the given address */ function removeLand(address _from, uint256 _tokenId) private { require(owns(_from, _tokenId)); uint256 landIndex = ownedLandsIndex[_tokenId]; // uint256 lastLandIndex = balanceOf(_from).sub(1); uint256 lastLandIndex = ownedLands[_from].length.sub(1); uint256 lastLand = ownedLands[_from][lastLandIndex]; landOwner[_tokenId] = address(0); ownedLands[_from][landIndex] = lastLand; ownedLands[_from][lastLandIndex] = 0; // Note that this will handle single-element arrays. In that case, both landIndex and lastLandIndex are going to // be zero. Then we can make sure that we will remove _tokenId from the ownedLands list since we are first swapping // the lastLand to the first position, and then dropping the element placed in the last position of the list ownedLands[_from].length--; ownedLandsIndex[_tokenId] = 0; ownedLandsIndex[lastLand] = landIndex; totalLands = totalLands.sub(1); } function createLand(address _owner, uint _id) onlyAdmin public returns (uint) { require(_owner != address(0)); uint256 _tokenId = lastLandId++; addLand(_owner, _tokenId); //store new land data lands[_tokenId] = Land({ id : _id }); emit Transfer(address(0), _owner, _tokenId); emit NewLand(_owner, _tokenId); return _tokenId; } function createLandAndAuction(address _owner, uint _id, address _auction, uint _startPrice, uint _duration) onlyAdmin public { uint id = createLand(_owner, _id); require(createAuction(_auction, id, _startPrice, _duration)); } function owns(address _claimant, uint256 _tokenId) public view returns (bool) { return ownerOf(_tokenId) == _claimant && ownerOf(_tokenId) != address(0); } function transferFrom(address _from, address _to, uint256 _tokenId) public returns (bool) { require(_to != address(this)); require(allowance(msg.sender, _tokenId)); clearApprovalAndTransfer(_from, _to, _tokenId); return true; } } contract ArconaDigitalLand is LandBase { string public constant name = " Arcona Digital Land"; string public constant symbol = "ARDL"; function implementsERC721() public pure returns (bool) { return true; } function() public payable{ revert(); } }
* @dev Gets the approved address to take ownership of a given land ID @param _tokenId uint256 ID of the land to query the approval of @return address currently approved to take ownership of the given land ID/
function approvedFor(uint256 _tokenId) public view returns (address) { return landApprovals[_tokenId]; }
9,914,931
[ 1, 3002, 326, 20412, 1758, 358, 4862, 23178, 434, 279, 864, 19193, 1599, 225, 389, 2316, 548, 2254, 5034, 1599, 434, 326, 19193, 358, 843, 326, 23556, 434, 327, 1758, 4551, 20412, 358, 4862, 23178, 434, 326, 864, 19193, 1599, 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, 20412, 1290, 12, 11890, 5034, 389, 2316, 548, 13, 1071, 1476, 1135, 261, 2867, 13, 288, 203, 3639, 327, 19193, 12053, 4524, 63, 67, 2316, 548, 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 ]
// Partial License: MIT pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // Partial License: MIT 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; } } // Partial License: 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); } // Partial License: MIT pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // Partial License: MIT pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // Partial License: MIT 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"); // 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) || (_allowances[msg.sender][spender] == 0)); _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 { } } pragma solidity ^0.6.0; contract SYSXToken is ERC20 { constructor(uint256 _initialSupply) ERC20("SYSX Token", "SYSX") public payable { _setupDecimals(18); _mint(msg.sender, _initialSupply); } }
* @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 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; constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } 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; } function totalSupply() public view override returns (uint256) { return _totalSupply; } function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } 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; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } 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; } 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); } 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); } 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); } 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"); require((amount == 0) || (_allowances[msg.sender][spender] == 0)); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } }
1,214,591
[ 1, 13621, 434, 326, 288, 45, 654, 39, 3462, 97, 1560, 18, 1220, 4471, 353, 279, 1600, 669, 335, 358, 326, 4031, 2430, 854, 2522, 18, 1220, 4696, 716, 279, 14467, 12860, 711, 358, 506, 3096, 316, 279, 10379, 6835, 1450, 288, 67, 81, 474, 5496, 2457, 279, 5210, 12860, 2621, 288, 654, 39, 3462, 18385, 49, 2761, 16507, 1355, 5496, 399, 2579, 30, 2457, 279, 6864, 1045, 416, 2621, 3134, 7343, 358, 2348, 14467, 1791, 28757, 8009, 1660, 1240, 10860, 7470, 3502, 62, 881, 84, 292, 267, 9875, 14567, 30, 4186, 15226, 3560, 434, 5785, 1375, 5743, 68, 603, 5166, 18, 1220, 6885, 353, 1661, 546, 12617, 15797, 287, 471, 1552, 486, 7546, 598, 326, 26305, 434, 4232, 39, 3462, 12165, 18, 26775, 16, 392, 288, 23461, 97, 871, 353, 17826, 603, 4097, 358, 288, 13866, 1265, 5496, 1220, 5360, 12165, 358, 23243, 326, 1699, 1359, 364, 777, 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, 4232, 39, 3462, 353, 1772, 16, 467, 654, 39, 3462, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 565, 1450, 5267, 364, 1758, 31, 203, 203, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 3238, 389, 70, 26488, 31, 203, 203, 565, 2874, 261, 2867, 516, 2874, 261, 2867, 516, 2254, 5034, 3719, 3238, 389, 5965, 6872, 31, 203, 203, 565, 2254, 5034, 3238, 389, 4963, 3088, 1283, 31, 203, 203, 565, 533, 3238, 389, 529, 31, 203, 565, 533, 3238, 389, 7175, 31, 203, 565, 2254, 28, 3238, 389, 31734, 31, 203, 203, 203, 565, 3885, 261, 1080, 3778, 508, 16, 533, 3778, 3273, 13, 1071, 288, 203, 3639, 389, 529, 273, 508, 31, 203, 3639, 389, 7175, 273, 3273, 31, 203, 3639, 389, 31734, 273, 6549, 31, 203, 565, 289, 203, 203, 565, 445, 508, 1435, 1071, 1476, 1135, 261, 1080, 3778, 13, 288, 203, 3639, 327, 389, 529, 31, 203, 565, 289, 203, 203, 565, 445, 3273, 1435, 1071, 1476, 1135, 261, 1080, 3778, 13, 288, 203, 3639, 327, 389, 7175, 31, 203, 565, 289, 203, 203, 565, 445, 15105, 1435, 1071, 1476, 1135, 261, 11890, 28, 13, 288, 203, 3639, 327, 389, 31734, 31, 203, 565, 289, 203, 203, 565, 445, 2078, 3088, 1283, 1435, 1071, 1476, 3849, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 389, 4963, 3088, 1283, 31, 203, 565, 289, 203, 203, 565, 445, 11013, 951, 12, 2867, 2236, 13, 1071, 1476, 3849, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 2 ]
./full_match/1/0x1bAC1E3003668fc0Cc4838DD3Fb62E8C2671b271/sources/browser/TorroDao.sol
@notice Constructor for original Torro DAO. @param governingToken_ Torro token address.
constructor(address governingToken_) public { __Ownable_init(); _torroToken = ITorro(governingToken_); _governingToken = ITorro(governingToken_); _factory = address(0x0); _latestProposalId = 0; _timeout = uint256(5).mul(1 minutes); _router = IUniswapV2Router02(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D)); _maxCost = 0; _executeMinPct = 5; _quickExecuteMinPct = 10; _votingMinHours = 0; _minProposalVotes = 1; _spendMaxPct = 10; _freeProposalDays = 730; _lockPerEth = 0; _voteWeightDivider = 10000; _lastWithdraw = block.timestamp; _isMain = true; _isPublic = true; _hasAdmins = true; _creator = msg.sender; }
3,118,601
[ 1, 6293, 364, 2282, 23763, 303, 463, 20463, 18, 225, 314, 1643, 2093, 1345, 67, 23763, 303, 1147, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 3885, 12, 2867, 314, 1643, 2093, 1345, 67, 13, 1071, 288, 203, 565, 1001, 5460, 429, 67, 2738, 5621, 203, 203, 565, 389, 13039, 303, 1345, 273, 24142, 280, 303, 12, 75, 1643, 2093, 1345, 67, 1769, 203, 565, 389, 75, 1643, 2093, 1345, 273, 24142, 280, 303, 12, 75, 1643, 2093, 1345, 67, 1769, 203, 565, 389, 6848, 273, 1758, 12, 20, 92, 20, 1769, 203, 565, 389, 13550, 14592, 548, 273, 374, 31, 203, 565, 389, 4538, 273, 2254, 5034, 12, 25, 2934, 16411, 12, 21, 6824, 1769, 203, 565, 389, 10717, 273, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 12, 2867, 12, 20, 92, 27, 69, 26520, 72, 4313, 5082, 38, 24, 71, 42, 25, 5520, 27, 5520, 72, 42, 22, 39, 25, 72, 37, 7358, 24, 71, 26, 6162, 42, 3247, 5482, 40, 10019, 203, 565, 389, 1896, 8018, 273, 374, 31, 203, 565, 389, 8837, 2930, 52, 299, 273, 1381, 31, 203, 565, 389, 19525, 5289, 2930, 52, 299, 273, 1728, 31, 203, 565, 389, 90, 17128, 2930, 14910, 273, 374, 31, 203, 565, 389, 1154, 14592, 29637, 273, 404, 31, 203, 565, 389, 87, 1302, 2747, 52, 299, 273, 1728, 31, 203, 565, 389, 9156, 14592, 9384, 273, 2371, 5082, 31, 203, 565, 389, 739, 2173, 41, 451, 273, 374, 31, 203, 565, 389, 25911, 6544, 25558, 273, 12619, 31, 203, 565, 389, 2722, 1190, 9446, 273, 1203, 18, 5508, 31, 203, 565, 389, 291, 6376, 273, 638, 31, 203, 565, 389, 291, 4782, 273, 2 ]
./full_match/4/0xd60FD9a24F8Daa87907eFb54Fe7242AC634988A8/sources/contracts/redeem/ERC721/ERC721RedeemSetBase.sol
* @dev See {IERC165-supportsInterface}./
function supportsInterface(bytes4 interfaceId) public view virtual override(RedeemSetBase, CreatorExtension, IERC165) returns (bool) { return interfaceId == type(IERC721RedeemSetBase).interfaceId || RedeemSetBase.supportsInterface(interfaceId) || CreatorExtension.supportsInterface(interfaceId); }
12,383,071
[ 1, 9704, 288, 45, 654, 39, 28275, 17, 28064, 1358, 5496, 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 ]
[ 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, 6146, 1358, 12, 3890, 24, 1560, 548, 13, 1071, 1476, 5024, 3849, 12, 426, 24903, 694, 2171, 16, 29525, 3625, 16, 467, 654, 39, 28275, 13, 1135, 261, 6430, 13, 288, 203, 3639, 327, 1560, 548, 422, 618, 12, 45, 654, 39, 27, 5340, 426, 24903, 694, 2171, 2934, 5831, 548, 747, 868, 24903, 694, 2171, 18, 28064, 1358, 12, 5831, 548, 13, 747, 29525, 3625, 18, 28064, 1358, 12, 5831, 548, 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 ]
./full_match/43114/0xe759d11678Ecc37Eaa3Bdbb804D4aFBd3b97797d/sources/dolphinmasterchef.sol
* @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)./ 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. Return data is optional solhint-disable-next-line max-line-length
function _callOptionalReturn(IBEP20 token, bytes memory data) private { bytes memory returndata = address(token).functionCall( data, "SafeBEP20: low-level call failed" ); if (returndata.length > 0) { require( abi.decode(returndata, (bool)), "SafeBEP20: BEP20 operation did not succeed" ); } }
4,587,660
[ 1, 1170, 305, 815, 279, 348, 7953, 560, 3551, 17, 2815, 745, 261, 77, 18, 73, 18, 279, 6736, 445, 745, 358, 279, 6835, 3631, 25744, 310, 326, 12405, 603, 326, 327, 460, 30, 326, 327, 460, 353, 3129, 261, 12885, 309, 501, 353, 2106, 16, 518, 1297, 486, 506, 629, 2934, 225, 1147, 1021, 1147, 20715, 635, 326, 745, 18, 225, 501, 1021, 745, 501, 261, 10787, 1450, 24126, 18, 3015, 578, 1245, 434, 2097, 12935, 2934, 19, 1660, 1608, 358, 3073, 279, 4587, 1801, 745, 2674, 16, 358, 17587, 348, 7953, 560, 1807, 327, 501, 963, 6728, 12860, 16, 3241, 732, 4565, 19981, 518, 19801, 18, 1660, 999, 288, 1887, 18, 915, 1477, 97, 358, 3073, 333, 745, 16, 1492, 20761, 716, 326, 1018, 1758, 1914, 6835, 981, 471, 2546, 26124, 364, 2216, 316, 326, 4587, 17, 2815, 745, 18, 2000, 501, 353, 3129, 3704, 11317, 17, 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, 389, 1991, 6542, 990, 12, 45, 5948, 52, 3462, 1147, 16, 1731, 3778, 501, 13, 3238, 288, 203, 203, 3639, 1731, 3778, 327, 892, 273, 203, 5411, 1758, 12, 2316, 2934, 915, 1477, 12, 203, 7734, 501, 16, 203, 7734, 315, 9890, 5948, 52, 3462, 30, 4587, 17, 2815, 745, 2535, 6, 203, 5411, 11272, 203, 3639, 309, 261, 2463, 892, 18, 2469, 405, 374, 13, 288, 203, 5411, 2583, 12, 203, 7734, 24126, 18, 3922, 12, 2463, 892, 16, 261, 6430, 13, 3631, 203, 7734, 315, 9890, 5948, 52, 3462, 30, 9722, 52, 3462, 1674, 5061, 486, 12897, 6, 203, 5411, 11272, 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 ]
./full_match/43113/0x29FB6CA56d7F4485eCBaf0AEd941d52E7A662307/sources/contracts/protocol/SetToken.sol
* Returns the total Real Units for a given component, summing the default and external position units./ We will perform the summation no matter what, as an external position virtual unit can be negative
function getTotalComponentRealUnits(address _component) external view returns (int256) { int256 totalUnits = getDefaultPositionRealUnit(_component); address[] memory externalModules = _externalPositionModules(_component); for (uint256 i = 0; i < externalModules.length; i++) { totalUnits = totalUnits.add(getExternalPositionRealUnit(_component, externalModules[i])); } return totalUnits; }
7,191,753
[ 1, 1356, 326, 2078, 15987, 27845, 364, 279, 864, 1794, 16, 2142, 11987, 326, 805, 471, 3903, 1754, 4971, 18, 19, 1660, 903, 3073, 326, 2142, 81, 367, 1158, 15177, 4121, 16, 487, 392, 3903, 1754, 5024, 2836, 848, 506, 6092, 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, 225, 445, 12831, 1841, 6955, 7537, 12, 2867, 389, 4652, 13, 3903, 1476, 1135, 261, 474, 5034, 13, 288, 203, 565, 509, 5034, 2078, 7537, 273, 4829, 2555, 6955, 2802, 24899, 4652, 1769, 203, 203, 565, 1758, 8526, 3778, 3903, 7782, 273, 389, 9375, 2555, 7782, 24899, 4652, 1769, 203, 565, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 3903, 7782, 18, 2469, 31, 277, 27245, 288, 203, 1377, 2078, 7537, 273, 2078, 7537, 18, 1289, 12, 588, 6841, 2555, 6955, 2802, 24899, 4652, 16, 3903, 7782, 63, 77, 5717, 1769, 203, 565, 289, 203, 203, 565, 327, 2078, 7537, 31, 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 ]
pragma solidity ^0.5.0; contract CryptoTycoonsVIPLib{ address payable public owner; // Accumulated jackpot fund. uint128 public jackpotSize; uint128 public rankingRewardSize; mapping (address => uint) userExpPool; mapping (address => bool) public callerMap; event RankingRewardPayment(address indexed beneficiary, uint amount); modifier onlyOwner { require(msg.sender == owner, "OnlyOwner methods called by non-owner."); _; } modifier onlyCaller { bool isCaller = callerMap[msg.sender]; require(isCaller, "onlyCaller methods called by non-caller."); _; } constructor() public{ owner = msg.sender; callerMap[owner] = true; } // Fallback function deliberately left empty. It's primary use case // is to top up the bank roll. function () external payable { } function kill() external onlyOwner { selfdestruct(owner); } function addCaller(address caller) public onlyOwner{ bool isCaller = callerMap[caller]; if (isCaller == false){ callerMap[caller] = true; } } function deleteCaller(address caller) external onlyOwner { bool isCaller = callerMap[caller]; if (isCaller == true) { callerMap[caller] = false; } } function addUserExp(address addr, uint256 amount) public onlyCaller{ uint exp = userExpPool[addr]; exp = exp + amount; userExpPool[addr] = exp; } function getUserExp(address addr) public view returns(uint256 exp){ return userExpPool[addr]; } function getVIPLevel(address user) public view returns (uint256 level) { uint exp = userExpPool[user]; if(exp >= 25 ether && exp < 125 ether){ level = 1; } else if(exp >= 125 ether && exp < 250 ether){ level = 2; } else if(exp >= 250 ether && exp < 1250 ether){ level = 3; } else if(exp >= 1250 ether && exp < 2500 ether){ level = 4; } else if(exp >= 2500 ether && exp < 12500 ether){ level = 5; } else if(exp >= 12500 ether && exp < 25000 ether){ level = 6; } else if(exp >= 25000 ether && exp < 125000 ether){ level = 7; } else if(exp >= 125000 ether && exp < 250000 ether){ level = 8; } else if(exp >= 250000 ether && exp < 1250000 ether){ level = 9; } else if(exp >= 1250000 ether){ level = 10; } else{ level = 0; } return level; } function getVIPBounusRate(address user) public view returns (uint256 rate){ uint level = getVIPLevel(user); return level; } // This function is used to bump up the jackpot fund. Cannot be used to lower it. function increaseJackpot(uint increaseAmount) external onlyCaller { require (increaseAmount <= address(this).balance, "Increase amount larger than balance."); require (jackpotSize + increaseAmount <= address(this).balance, "Not enough funds."); jackpotSize += uint128(increaseAmount); } function payJackpotReward(address payable to) external onlyCaller{ to.transfer(jackpotSize); jackpotSize = 0; } function getJackpotSize() external view returns (uint256){ return jackpotSize; } function increaseRankingReward(uint amount) public onlyCaller{ require (amount <= address(this).balance, "Increase amount larger than balance."); require (rankingRewardSize + amount <= address(this).balance, "Not enough funds."); rankingRewardSize += uint128(amount); } function payRankingReward(address payable to) external onlyCaller { uint128 prize = rankingRewardSize / 2; rankingRewardSize = rankingRewardSize - prize; if(to.send(prize)){ emit RankingRewardPayment(to, prize); } } function getRankingRewardSize() external view returns (uint128){ return rankingRewardSize; } } contract CryptoTycoonsConstants{ /// *** Constants section // Each bet is deducted 1% in favour of the house, but no less than some minimum. // The lower bound is dictated by gas costs of the settleBet transaction, providing // headroom for up to 10 Gwei prices. uint constant HOUSE_EDGE_PERCENT = 1; uint constant RANK_FUNDS_PERCENT = 7; uint constant INVITER_BENEFIT_PERCENT = 7; uint constant HOUSE_EDGE_MINIMUM_AMOUNT = 0.0004 ether; // Bets lower than this amount do not participate in jackpot rolls (and are // not deducted JACKPOT_FEE). uint constant MIN_JACKPOT_BET = 0.1 ether; // Chance to win jackpot (currently 0.1%) and fee deducted into jackpot fund. uint constant JACKPOT_MODULO = 1000; uint constant JACKPOT_FEE = 0.001 ether; // There is minimum and maximum bets. uint constant MIN_BET = 0.01 ether; uint constant MAX_AMOUNT = 10 ether; // Standard contract ownership transfer. address payable public owner; address payable private nextOwner; // Croupier account. mapping (address => bool ) croupierMap; // Adjustable max bet profit. Used to cap bets against dynamic odds. uint public maxProfit; address payable public VIPLibraryAddress; // The address corresponding to a private key used to sign placeBet commits. address public secretSigner; // Events that are issued to make statistic recovery easier. event FailedPayment(address indexed beneficiary, uint amount); event VIPPayback(address indexed beneficiary, uint amount); event WithdrawFunds(address indexed beneficiary, uint amount); constructor (uint _maxProfit) public { owner = msg.sender; secretSigner = owner; maxProfit = _maxProfit; croupierMap[owner] = true; } // Standard modifier on methods invokable only by contract owner. modifier onlyOwner { require (msg.sender == owner, "OnlyOwner methods called by non-owner."); _; } // Standard modifier on methods invokable only by contract owner. modifier onlyCroupier { bool isCroupier = croupierMap[msg.sender]; require(isCroupier, "OnlyCroupier methods called by non-croupier."); _; } // Fallback function deliberately left empty. It's primary use case // is to top up the bank roll. function () external payable { } // Standard contract ownership transfer implementation, function approveNextOwner(address payable _nextOwner) external onlyOwner { require (_nextOwner != owner, "Cannot approve current owner."); nextOwner = _nextOwner; } function acceptNextOwner() external { require (msg.sender == nextOwner, "Can only accept preapproved new owner."); owner = nextOwner; } // See comment for "secretSigner" variable. function setSecretSigner(address newSecretSigner) external onlyOwner { secretSigner = newSecretSigner; } function getSecretSigner() external onlyOwner view returns(address){ return secretSigner; } function addCroupier(address newCroupier) external onlyOwner { bool isCroupier = croupierMap[newCroupier]; if (isCroupier == false) { croupierMap[newCroupier] = true; } } function deleteCroupier(address newCroupier) external onlyOwner { bool isCroupier = croupierMap[newCroupier]; if (isCroupier == true) { croupierMap[newCroupier] = false; } } function setVIPLibraryAddress(address payable addr) external onlyOwner{ VIPLibraryAddress = addr; } // Change max bet reward. Setting this to zero effectively disables betting. function setMaxProfit(uint _maxProfit) public onlyOwner { require (_maxProfit < MAX_AMOUNT, "maxProfit should be a sane number."); maxProfit = _maxProfit; } // Funds withdrawal to cover costs of AceDice operation. function withdrawFunds(address payable beneficiary, uint withdrawAmount) external onlyOwner { require (withdrawAmount <= address(this).balance, "Increase amount larger than balance."); if (beneficiary.send(withdrawAmount)){ emit WithdrawFunds(beneficiary, withdrawAmount); } } function kill() external onlyOwner { // require (lockedInBets == 0, "All bets should be processed (settled or refunded) before self-destruct."); selfdestruct(owner); } function thisBalance() public view returns(uint) { return address(this).balance; } function payTodayReward(address payable to) external onlyOwner { CryptoTycoonsVIPLib vipLib = CryptoTycoonsVIPLib(VIPLibraryAddress); vipLib.payRankingReward(to); } function getRankingRewardSize() external view returns (uint128) { CryptoTycoonsVIPLib vipLib = CryptoTycoonsVIPLib(VIPLibraryAddress); return vipLib.getRankingRewardSize(); } function handleVIPPaybackAndExp(CryptoTycoonsVIPLib vipLib, address payable gambler, uint amount) internal returns(uint vipPayback) { // CryptoTycoonsVIPLib vipLib = CryptoTycoonsVIPLib(VIPLibraryAddress); vipLib.addUserExp(gambler, amount); uint rate = vipLib.getVIPBounusRate(gambler); if (rate <= 0) return 0; vipPayback = amount * rate / 10000; if(vipPayback > 0){ emit VIPPayback(gambler, vipPayback); } } function increaseRankingFund(CryptoTycoonsVIPLib vipLib, uint amount) internal{ uint rankingFunds = uint128(amount * HOUSE_EDGE_PERCENT / 100 * RANK_FUNDS_PERCENT /100); // uint128 rankingRewardFee = uint128(amount * HOUSE_EDGE_PERCENT / 100 * 9 /100); VIPLibraryAddress.transfer(rankingFunds); vipLib.increaseRankingReward(rankingFunds); } function getMyAccuAmount() external view returns (uint){ CryptoTycoonsVIPLib vipLib = CryptoTycoonsVIPLib(VIPLibraryAddress); return vipLib.getUserExp(msg.sender); } function getJackpotSize() external view returns (uint){ CryptoTycoonsVIPLib vipLib = CryptoTycoonsVIPLib(VIPLibraryAddress); return vipLib.getJackpotSize(); } function verifyCommit(uint commit, uint8 v, bytes32 r, bytes32 s) internal view { // Check that commit is valid - it has not expired and its signature is valid. // require (block.number <= commitLastBlock, "Commit has expired."); //bytes32 signatureHash = keccak256(abi.encodePacked(commitLastBlock, commit)); bytes memory prefix = "\x19Ethereum Signed Message:\n32"; bytes memory message = abi.encodePacked(commit); bytes32 messageHash = keccak256(abi.encodePacked(prefix, keccak256(message))); require (secretSigner == ecrecover(messageHash, v, r, s), "ECDSA signature is not valid."); } function calcHouseEdge(uint amount) public pure returns (uint houseEdge) { // 0.02 houseEdge = amount * HOUSE_EDGE_PERCENT / 100; if (houseEdge < HOUSE_EDGE_MINIMUM_AMOUNT) { houseEdge = HOUSE_EDGE_MINIMUM_AMOUNT; } } function calcJackpotFee(uint amount) internal pure returns (uint jackpotFee) { // 0.001 if (amount >= MIN_JACKPOT_BET) { jackpotFee = JACKPOT_FEE; } } function calcRankFundsFee(uint amount) internal pure returns (uint rankFundsFee) { // 0.01 * 0.07 rankFundsFee = amount * RANK_FUNDS_PERCENT / 10000; } function calcInviterBenefit(uint amount) internal pure returns (uint invitationFee) { // 0.01 * 0.07 invitationFee = amount * INVITER_BENEFIT_PERCENT / 10000; } function processBet( uint betMask, uint reveal, uint8 v, bytes32 r, bytes32 s, address payable inviter) external payable; } contract HalfRoulette is CryptoTycoonsConstants(10 ether) { uint constant BASE_WIN_RATE = 100000; event Payment(address indexed gambler, uint amount, uint8 betMask, uint8 l, uint8 r, uint betAmount); event JackpotPayment(address indexed gambler, uint amount); function processBet( uint betMask, uint reveal, uint8 v, bytes32 r, bytes32 s, address payable inviter) external payable { address payable gambler = msg.sender; // amount checked uint amount = msg.value; // require (modulo > 1 && modulo <= MAX_MODULO, "Modulo should be within range."); require (amount >= MIN_BET && amount <= MAX_AMOUNT, "Amount should be within range."); // allow bet check verifyBetMask(betMask); if (inviter != address(0)){ require(gambler != inviter, "cannot invite myself"); } uint commit = uint(keccak256(abi.encodePacked(reveal))); verifyCommit(commit, v, r, s); // house balance check uint winAmount = getWinAmount(betMask, amount); require(winAmount <= amount + maxProfit, "maxProfit limit violation."); require(winAmount <= address(this).balance, "Cannot afford to lose this bet."); // The RNG - combine "reveal" and blockhash of placeBet using Keccak256. Miners // are not aware of "reveal" and cannot deduce it from "commit" (as Keccak256 // preimage is intractable), and house is unable to alter the "reveal" after // placeBet have been mined (as Keccak256 collision finding is also intractable). bytes32 entropy = keccak256(abi.encodePacked(reveal, blockhash(block.number))); uint payout = 0; payout += transferVIPContractFee(gambler, inviter, amount); // 5. roulette betting reward payout += processRoulette(gambler, betMask, entropy, amount); gambler.transfer(payout); // 7. jacpoet reward processJackpot(gambler, entropy, amount); } function transferVIPContractFee( address payable gambler, address payable inviter, uint amount) internal returns(uint vipPayback) { uint jackpotFee = calcJackpotFee(amount); uint rankFundFee = calcRankFundsFee(amount); // 1. increate vip exp CryptoTycoonsVIPLib vipLib = CryptoTycoonsVIPLib(VIPLibraryAddress); vipPayback = handleVIPPaybackAndExp(vipLib, gambler, amount); // 2. process today's ranking fee VIPLibraryAddress.transfer(rankFundFee + jackpotFee); vipLib.increaseRankingReward(rankFundFee); if (jackpotFee > 0) { vipLib.increaseJackpot(jackpotFee); } // 4. inviter profit if(inviter != address(0)){ // pay 7% of house edge to inviter inviter.transfer(amount * HOUSE_EDGE_PERCENT / 100 * 7 /100); } } function processJackpot(address payable gambler, bytes32 entropy, uint amount) internal returns (uint benefitAmount) { if (isJackpot(entropy, amount)) { CryptoTycoonsVIPLib vipLib = CryptoTycoonsVIPLib(VIPLibraryAddress); uint jackpotSize = vipLib.getJackpotSize(); vipLib.payJackpotReward(gambler); benefitAmount = jackpotSize; emit JackpotPayment(gambler, benefitAmount); } } function processRoulette(address gambler, uint betMask, bytes32 entropy, uint amount) internal returns (uint benefitAmount) { uint winAmount = getWinAmount(betMask, amount); (bool isWin, uint l, uint r) = calcBetResult(betMask, entropy); benefitAmount = isWin ? winAmount : 0; emit Payment(gambler, benefitAmount, uint8(betMask), uint8(l), uint8(r), amount); } function verifyBetMask(uint betMask) public pure { bool verify; assembly { switch betMask case 1 /* ODD */{verify := 1} case 2 /* EVEN */{verify := 1} case 4 /* LEFT */{verify := 1} case 8 /* RIGHT */{verify := 1} case 5 /* ODD | LEFT */{verify := 1} case 9 /* ODD | RIGHT */{verify := 1} case 6 /* EVEN | LEFT */{verify := 1} case 10 /* EVEN | RIGHT */{verify := 1} case 16 /* EQUAL */{verify := 1} } require(verify, "invalid betMask"); } function getWinRate(uint betMask) public pure returns (uint rate) { // assembly 안에서는 constant 사용 불가 uint ODD_EVEN_RATE = 50000; uint LEFT_RIGHT_RATE = 45833; uint MIX_ODD_RATE = 25000; uint MIX_EVEN_RATE = 20833; uint EQUAL_RATE = 8333; assembly { switch betMask case 1 /* ODD */{rate := ODD_EVEN_RATE} case 2 /* EVEN */{rate := ODD_EVEN_RATE} case 4 /* LEFT */{rate := LEFT_RIGHT_RATE} case 8 /* RIGHT */{rate := LEFT_RIGHT_RATE} case 5 /* ODD | LEFT */{rate := MIX_ODD_RATE} case 9 /* ODD | RIGHT */{rate := MIX_ODD_RATE} case 6 /* EVEN | LEFT */{rate := MIX_EVEN_RATE} case 10 /* EVEN | RIGHT */{rate := MIX_EVEN_RATE} case 16 /* EQUAL */{rate := EQUAL_RATE} } } function getWinAmount(uint betMask, uint amount) public pure returns (uint) { uint houseEdge = calcHouseEdge(amount); uint jackpotFee = calcJackpotFee(amount); uint betAmount = amount - houseEdge - jackpotFee; uint rate = getWinRate(betMask); return betAmount * BASE_WIN_RATE / rate; } function calcBetResult(uint betMask, bytes32 entropy) public pure returns (bool isWin, uint l, uint r) { uint v = uint(entropy); l = (v % 12) + 1; r = ((v >> 4) % 12) + 1; uint mask = getResultMask(l, r); isWin = (betMask & mask) == betMask; } function getResultMask(uint l, uint r) public pure returns (uint mask) { uint v1 = (l + r) % 2; if (v1 == 0) { mask = mask | 2; } else { mask = mask | 1; } if (l == r) { mask = mask | 16; } else if (l > r) { mask = mask | 4; } else { mask = mask | 8; } return mask; } function isJackpot(bytes32 entropy, uint amount) public pure returns (bool jackpot) { return amount >= MIN_JACKPOT_BET && (uint(entropy) % 1000) == 0; } }
1. increate vip exp 2. process today's ranking fee 4. inviter profit pay 7% of house edge to inviter
function transferVIPContractFee( address payable gambler, address payable inviter, uint amount) internal returns(uint vipPayback) { uint jackpotFee = calcJackpotFee(amount); uint rankFundFee = calcRankFundsFee(amount); CryptoTycoonsVIPLib vipLib = CryptoTycoonsVIPLib(VIPLibraryAddress); vipPayback = handleVIPPaybackAndExp(vipLib, gambler, amount); VIPLibraryAddress.transfer(rankFundFee + jackpotFee); vipLib.increaseRankingReward(rankFundFee); if (jackpotFee > 0) { vipLib.increaseJackpot(jackpotFee); } if(inviter != address(0)){ inviter.transfer(amount * HOUSE_EDGE_PERCENT / 100 * 7 /100); } }
12,925,905
[ 1, 21, 18, 316, 2640, 26180, 1329, 576, 18, 1207, 10074, 1807, 23087, 14036, 1059, 18, 2198, 2165, 450, 7216, 8843, 2371, 9, 434, 23867, 3591, 358, 2198, 2165, 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, 7412, 58, 2579, 8924, 14667, 12, 203, 3639, 1758, 8843, 429, 314, 2536, 749, 16, 1758, 8843, 429, 2198, 2165, 16, 2254, 3844, 13, 7010, 5411, 2713, 1135, 12, 11890, 26180, 9148, 823, 13, 288, 203, 3639, 2254, 525, 484, 13130, 14667, 273, 7029, 46, 484, 13130, 14667, 12, 8949, 1769, 203, 3639, 2254, 6171, 42, 1074, 14667, 273, 7029, 12925, 42, 19156, 14667, 12, 8949, 1769, 203, 203, 3639, 15629, 56, 93, 2894, 7008, 58, 2579, 5664, 26180, 5664, 273, 15629, 56, 93, 2894, 7008, 58, 2579, 5664, 12, 58, 2579, 9313, 1887, 1769, 203, 3639, 26180, 9148, 823, 273, 1640, 58, 2579, 9148, 823, 1876, 2966, 12, 522, 84, 5664, 16, 314, 2536, 749, 16, 3844, 1769, 203, 203, 3639, 776, 2579, 9313, 1887, 18, 13866, 12, 11500, 42, 1074, 14667, 397, 525, 484, 13130, 14667, 1769, 203, 3639, 26180, 5664, 18, 267, 11908, 12925, 310, 17631, 1060, 12, 11500, 42, 1074, 14667, 1769, 203, 3639, 309, 261, 78, 484, 13130, 14667, 405, 374, 13, 288, 203, 5411, 26180, 5664, 18, 267, 11908, 46, 484, 13130, 12, 78, 484, 13130, 14667, 1769, 203, 3639, 289, 203, 203, 3639, 309, 12, 5768, 2165, 480, 1758, 12, 20, 3719, 95, 203, 5411, 2198, 2165, 18, 13866, 12, 8949, 380, 11705, 8001, 67, 27732, 67, 3194, 19666, 342, 2130, 380, 2371, 342, 6625, 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 ]
./partial_match/1/0x00390625808acdA0EBB872c765840079ab06a6D0/sources/CMIRPDCrowdsale.sol
* @title FinalizableCrowdsale @dev Extension of Crowdsale with a one-off finalization action, where one can do extra work after finishing./
contract FinalizableCrowdsale is TimedCrowdsale { using SafeMath for uint256; bool private _finalized; event CrowdsaleFinalized(); constructor () internal { _finalized = false; } function finalized() public view returns (bool) { return _finalized; } function finalize() public { require(!_finalized); require(hasClosed()); _finalized = true; _finalization(); emit CrowdsaleFinalized(); } function _finalization() internal { } }
9,318,147
[ 1, 7951, 6934, 39, 492, 2377, 5349, 225, 10021, 434, 385, 492, 2377, 5349, 598, 279, 1245, 17, 3674, 727, 1588, 1301, 16, 1625, 1245, 848, 741, 2870, 1440, 1839, 4076, 310, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 16351, 16269, 6934, 39, 492, 2377, 5349, 353, 23925, 39, 492, 2377, 5349, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 565, 1426, 3238, 389, 6385, 1235, 31, 203, 203, 565, 871, 385, 492, 2377, 5349, 7951, 1235, 5621, 203, 203, 203, 565, 3885, 1832, 2713, 288, 203, 3639, 389, 6385, 1235, 273, 629, 31, 203, 565, 289, 203, 203, 565, 445, 727, 1235, 1435, 1071, 1476, 1135, 261, 6430, 13, 288, 203, 3639, 327, 389, 6385, 1235, 31, 203, 565, 289, 203, 203, 565, 445, 12409, 1435, 1071, 288, 203, 3639, 2583, 12, 5, 67, 6385, 1235, 1769, 203, 3639, 2583, 12, 5332, 7395, 10663, 203, 203, 3639, 389, 6385, 1235, 273, 638, 31, 203, 203, 3639, 389, 6385, 1588, 5621, 203, 3639, 3626, 385, 492, 2377, 5349, 7951, 1235, 5621, 203, 565, 289, 203, 203, 565, 445, 389, 6385, 1588, 1435, 2713, 288, 203, 565, 289, 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 ]
./partial_match/56/0x83Baa337DabbD3a3F2F9451173b88cb70bEb7656/sources/Lottery.sol
Withdraw without caring about rewards. EMERGENCY ONLY.
function adminWithdraw(uint256 _amount) public onlyAdmin { oat.safeTransfer(address(msg.sender), _amount); emit DevWithdraw(msg.sender, _amount); }
11,340,537
[ 1, 1190, 9446, 2887, 5926, 310, 2973, 283, 6397, 18, 7141, 654, 16652, 16068, 20747, 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, 565, 445, 3981, 1190, 9446, 12, 11890, 5034, 389, 8949, 13, 1071, 1338, 4446, 288, 203, 3639, 320, 270, 18, 4626, 5912, 12, 2867, 12, 3576, 18, 15330, 3631, 389, 8949, 1769, 203, 3639, 3626, 9562, 1190, 9446, 12, 3576, 18, 15330, 16, 389, 8949, 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 ]
/* _____ _ _____ / ____| | | / ____| | | _ __ _ _ _ __ | |_ ___ | | ___ _ __ __ _ _ __ ___ ___ ___ | | | '__| | | | '_ \| __/ _ \| | / _ \| '_ \ / _` | '__/ _ \/ __/ __| | |____| | | |_| | |_) | || (_) | |___| (_) | | | | (_| | | | __/\__ \__ \ \_____|_| \__, | .__/ \__\___/ \_____\___/|_| |_|\__, |_| \___||___/___/ __/ | | __/ | |___/|_| |___/ CryptoCongress smart contract The official address is "cryptocongress.eth" Token and voting code begins on line 1030 */ pragma solidity ^0.4.10; contract OraclizeI { address public cbAddress; function query(uint _timestamp, string _datasource, string _arg) external payable returns (bytes32 _id); function query_withGasLimit(uint _timestamp, string _datasource, string _arg, uint _gaslimit) external payable returns (bytes32 _id); function query2(uint _timestamp, string _datasource, string _arg1, string _arg2) public payable returns (bytes32 _id); function query2_withGasLimit(uint _timestamp, string _datasource, string _arg1, string _arg2, uint _gaslimit) external payable returns (bytes32 _id); function queryN(uint _timestamp, string _datasource, bytes _argN) public payable returns (bytes32 _id); function queryN_withGasLimit(uint _timestamp, string _datasource, bytes _argN, uint _gaslimit) external payable returns (bytes32 _id); function getPrice(string _datasource) public returns (uint _dsprice); function getPrice(string _datasource, uint gaslimit) public returns (uint _dsprice); function setProofType(byte _proofType) external; function setCustomGasPrice(uint _gasPrice) external; function randomDS_getSessionPubKeyHash() external constant returns(bytes32); } contract OraclizeAddrResolverI { function getAddress() public returns (address _addr); } contract usingOraclize { uint constant day = 60*60*24; uint constant week = 60*60*24*7; uint constant month = 60*60*24*30; byte constant proofType_NONE = 0x00; byte constant proofType_TLSNotary = 0x10; byte constant proofType_Android = 0x20; byte constant proofType_Ledger = 0x30; byte constant proofType_Native = 0xF0; byte constant proofStorage_IPFS = 0x01; uint8 constant networkID_auto = 0; uint8 constant networkID_mainnet = 1; uint8 constant networkID_testnet = 2; uint8 constant networkID_morden = 2; uint8 constant networkID_consensys = 161; OraclizeAddrResolverI OAR; OraclizeI oraclize; modifier oraclizeAPI { if((address(OAR)==0)||(getCodeSize(address(OAR))==0)) oraclize_setNetwork(networkID_auto); if(address(oraclize) != OAR.getAddress()) oraclize = OraclizeI(OAR.getAddress()); _; } modifier coupon(string code){ oraclize = OraclizeI(OAR.getAddress()); _; } function oraclize_setNetwork(uint8 networkID) internal returns(bool){ return oraclize_setNetwork(); networkID; // silence the warning and remain backwards compatible } function oraclize_setNetwork() internal returns(bool){ if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed)>0){ //mainnet OAR = OraclizeAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed); oraclize_setNetworkName("eth_mainnet"); return true; } if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1)>0){ //ropsten testnet OAR = OraclizeAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1); oraclize_setNetworkName("eth_ropsten3"); return true; } if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e)>0){ //kovan testnet OAR = OraclizeAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e); oraclize_setNetworkName("eth_kovan"); return true; } if (getCodeSize(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48)>0){ //rinkeby testnet OAR = OraclizeAddrResolverI(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48); oraclize_setNetworkName("eth_rinkeby"); return true; } if (getCodeSize(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475)>0){ //ethereum-bridge OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475); return true; } if (getCodeSize(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF)>0){ //ether.camp ide OAR = OraclizeAddrResolverI(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF); return true; } if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA)>0){ //browser-solidity OAR = OraclizeAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA); return true; } return false; } function __callback(bytes32 myid, string result) public { __callback(myid, result, new bytes(0)); } function __callback(bytes32 myid, string result, bytes proof) public { return; myid; result; proof; // Silence compiler warnings } function oraclize_getPrice(string datasource) oraclizeAPI internal returns (uint){ return oraclize.getPrice(datasource); } function oraclize_getPrice(string datasource, uint gaslimit) oraclizeAPI internal returns (uint){ return oraclize.getPrice(datasource, gaslimit); } function oraclize_query(string datasource, string arg) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query.value(price)(0, datasource, arg); } function oraclize_query(uint timestamp, string datasource, string arg) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query.value(price)(timestamp, datasource, arg); } function oraclize_query(uint timestamp, string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query_withGasLimit.value(price)(timestamp, datasource, arg, gaslimit); } function oraclize_query(string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query_withGasLimit.value(price)(0, datasource, arg, gaslimit); } function oraclize_query(string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query2.value(price)(0, datasource, arg1, arg2); } function oraclize_query(uint timestamp, string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query2.value(price)(timestamp, datasource, arg1, arg2); } function oraclize_query(uint timestamp, string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query2_withGasLimit.value(price)(timestamp, datasource, arg1, arg2, gaslimit); } function oraclize_query(string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query2_withGasLimit.value(price)(0, datasource, arg1, arg2, gaslimit); } function oraclize_query(string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN.value(price)(0, datasource, args); } function oraclize_query(uint timestamp, string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN.value(price)(timestamp, datasource, args); } function oraclize_query(uint timestamp, string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit); } function oraclize_query(string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit); } function oraclize_query(string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN.value(price)(0, datasource, args); } function oraclize_query(uint timestamp, string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN.value(price)(timestamp, datasource, args); } function oraclize_query(uint timestamp, string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit); } function oraclize_query(string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit); } function oraclize_query(string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_cbAddress() oraclizeAPI internal returns (address){ return oraclize.cbAddress(); } function oraclize_setProof(byte proofP) oraclizeAPI internal { return oraclize.setProofType(proofP); } function oraclize_setCustomGasPrice(uint gasPrice) oraclizeAPI internal { return oraclize.setCustomGasPrice(gasPrice); } function oraclize_randomDS_getSessionPubKeyHash() oraclizeAPI internal returns (bytes32){ return oraclize.randomDS_getSessionPubKeyHash(); } function getCodeSize(address _addr) constant internal returns(uint _size) { assembly { _size := extcodesize(_addr) } } function parseAddr(string _a) internal pure returns (address){ bytes memory tmp = bytes(_a); uint160 iaddr = 0; uint160 b1; uint160 b2; for (uint i=2; i<2+2*20; i+=2){ iaddr *= 256; b1 = uint160(tmp[i]); b2 = uint160(tmp[i+1]); if ((b1 >= 97)&&(b1 <= 102)) b1 -= 87; else if ((b1 >= 65)&&(b1 <= 70)) b1 -= 55; else if ((b1 >= 48)&&(b1 <= 57)) b1 -= 48; if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87; else if ((b2 >= 65)&&(b2 <= 70)) b2 -= 55; else if ((b2 >= 48)&&(b2 <= 57)) b2 -= 48; iaddr += (b1*16+b2); } return address(iaddr); } function strCompare(string _a, string _b) internal pure returns (int) { bytes memory a = bytes(_a); bytes memory b = bytes(_b); uint minLength = a.length; if (b.length < minLength) minLength = b.length; for (uint i = 0; i < minLength; i ++) if (a[i] < b[i]) return -1; else if (a[i] > b[i]) return 1; if (a.length < b.length) return -1; else if (a.length > b.length) return 1; else return 0; } function indexOf(string _haystack, string _needle) internal pure returns (int) { bytes memory h = bytes(_haystack); bytes memory n = bytes(_needle); if(h.length < 1 || n.length < 1 || (n.length > h.length)) return -1; else if(h.length > (2**128 -1)) return -1; else { uint subindex = 0; for (uint i = 0; i < h.length; i ++) { if (h[i] == n[0]) { subindex = 1; while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex]) { subindex++; } if(subindex == n.length) return int(i); } } return -1; } } function strConcat(string _a, string _b, string _c, string _d, string _e) internal pure returns (string) { bytes memory _ba = bytes(_a); bytes memory _bb = bytes(_b); bytes memory _bc = bytes(_c); bytes memory _bd = bytes(_d); bytes memory _be = bytes(_e); string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length); bytes memory babcde = bytes(abcde); uint k = 0; for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i]; for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i]; for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i]; for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i]; for (i = 0; i < _be.length; i++) babcde[k++] = _be[i]; return string(babcde); } function strConcat(string _a, string _b, string _c, string _d) internal pure returns (string) { return strConcat(_a, _b, _c, _d, ""); } function strConcat(string _a, string _b, string _c) internal pure returns (string) { return strConcat(_a, _b, _c, "", ""); } function strConcat(string _a, string _b) internal pure returns (string) { return strConcat(_a, _b, "", "", ""); } // parseInt function parseInt(string _a) internal pure returns (uint) { return parseInt(_a, 0); } // parseInt(parseFloat*10^_b) function parseInt(string _a, uint _b) internal pure returns (uint) { bytes memory bresult = bytes(_a); uint mint = 0; bool decimals = false; for (uint i=0; i<bresult.length; i++){ if ((bresult[i] >= 48)&&(bresult[i] <= 57)){ if (decimals){ if (_b == 0) break; else _b--; } mint *= 10; mint += uint(bresult[i]) - 48; } else if (bresult[i] == 46) decimals = true; } if (_b > 0) mint *= 10**_b; return mint; } function uint2str(uint i) internal pure returns (string){ if (i == 0) return "0"; uint j = i; uint len; while (j != 0){ len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len - 1; while (i != 0){ bstr[k--] = byte(48 + i % 10); i /= 10; } return string(bstr); } function stra2cbor(string[] arr) internal pure returns (bytes) { uint arrlen = arr.length; // get correct cbor output length uint outputlen = 0; bytes[] memory elemArray = new bytes[](arrlen); for (uint i = 0; i < arrlen; i++) { elemArray[i] = (bytes(arr[i])); outputlen += elemArray[i].length + (elemArray[i].length - 1)/23 + 3; //+3 accounts for paired identifier types } uint ctr = 0; uint cborlen = arrlen + 0x80; outputlen += byte(cborlen).length; bytes memory res = new bytes(outputlen); while (byte(cborlen).length > ctr) { res[ctr] = byte(cborlen)[ctr]; ctr++; } for (i = 0; i < arrlen; i++) { res[ctr] = 0x5F; ctr++; for (uint x = 0; x < elemArray[i].length; x++) { // if there's a bug with larger strings, this may be the culprit if (x % 23 == 0) { uint elemcborlen = elemArray[i].length - x >= 24 ? 23 : elemArray[i].length - x; elemcborlen += 0x40; uint lctr = ctr; while (byte(elemcborlen).length > ctr - lctr) { res[ctr] = byte(elemcborlen)[ctr - lctr]; ctr++; } } res[ctr] = elemArray[i][x]; ctr++; } res[ctr] = 0xFF; ctr++; } return res; } function ba2cbor(bytes[] arr) internal pure returns (bytes) { uint arrlen = arr.length; // get correct cbor output length uint outputlen = 0; bytes[] memory elemArray = new bytes[](arrlen); for (uint i = 0; i < arrlen; i++) { elemArray[i] = (bytes(arr[i])); outputlen += elemArray[i].length + (elemArray[i].length - 1)/23 + 3; //+3 accounts for paired identifier types } uint ctr = 0; uint cborlen = arrlen + 0x80; outputlen += byte(cborlen).length; bytes memory res = new bytes(outputlen); while (byte(cborlen).length > ctr) { res[ctr] = byte(cborlen)[ctr]; ctr++; } for (i = 0; i < arrlen; i++) { res[ctr] = 0x5F; ctr++; for (uint x = 0; x < elemArray[i].length; x++) { // if there's a bug with larger strings, this may be the culprit if (x % 23 == 0) { uint elemcborlen = elemArray[i].length - x >= 24 ? 23 : elemArray[i].length - x; elemcborlen += 0x40; uint lctr = ctr; while (byte(elemcborlen).length > ctr - lctr) { res[ctr] = byte(elemcborlen)[ctr - lctr]; ctr++; } } res[ctr] = elemArray[i][x]; ctr++; } res[ctr] = 0xFF; ctr++; } return res; } string oraclize_network_name; function oraclize_setNetworkName(string _network_name) internal { oraclize_network_name = _network_name; } function oraclize_getNetworkName() internal view returns (string) { return oraclize_network_name; } function oraclize_newRandomDSQuery(uint _delay, uint _nbytes, uint _customGasLimit) internal returns (bytes32){ require((_nbytes > 0) && (_nbytes <= 32)); bytes memory nbytes = new bytes(1); nbytes[0] = byte(_nbytes); bytes memory unonce = new bytes(32); bytes memory sessionKeyHash = new bytes(32); bytes32 sessionKeyHash_bytes32 = oraclize_randomDS_getSessionPubKeyHash(); assembly { mstore(unonce, 0x20) mstore(add(unonce, 0x20), xor(blockhash(sub(number, 1)), xor(coinbase, timestamp))) mstore(sessionKeyHash, 0x20) mstore(add(sessionKeyHash, 0x20), sessionKeyHash_bytes32) } bytes[3] memory args = [unonce, nbytes, sessionKeyHash]; bytes32 queryId = oraclize_query(_delay, "random", args, _customGasLimit); oraclize_randomDS_setCommitment(queryId, keccak256(bytes8(_delay), args[1], sha256(args[0]), args[2])); return queryId; } function oraclize_randomDS_setCommitment(bytes32 queryId, bytes32 commitment) internal { oraclize_randomDS_args[queryId] = commitment; } mapping(bytes32=>bytes32) oraclize_randomDS_args; mapping(bytes32=>bool) oraclize_randomDS_sessionKeysHashVerified; function verifySig(bytes32 tosignh, bytes dersig, bytes pubkey) internal returns (bool){ bool sigok; address signer; bytes32 sigr; bytes32 sigs; bytes memory sigr_ = new bytes(32); uint offset = 4+(uint(dersig[3]) - 0x20); sigr_ = copyBytes(dersig, offset, 32, sigr_, 0); bytes memory sigs_ = new bytes(32); offset += 32 + 2; sigs_ = copyBytes(dersig, offset+(uint(dersig[offset-1]) - 0x20), 32, sigs_, 0); assembly { sigr := mload(add(sigr_, 32)) sigs := mload(add(sigs_, 32)) } (sigok, signer) = safer_ecrecover(tosignh, 27, sigr, sigs); if (address(keccak256(pubkey)) == signer) return true; else { (sigok, signer) = safer_ecrecover(tosignh, 28, sigr, sigs); return (address(keccak256(pubkey)) == signer); } } function oraclize_randomDS_proofVerify__sessionKeyValidity(bytes proof, uint sig2offset) internal returns (bool) { bool sigok; // Step 6: verify the attestation signature, APPKEY1 must sign the sessionKey from the correct ledger app (CODEHASH) bytes memory sig2 = new bytes(uint(proof[sig2offset+1])+2); copyBytes(proof, sig2offset, sig2.length, sig2, 0); bytes memory appkey1_pubkey = new bytes(64); copyBytes(proof, 3+1, 64, appkey1_pubkey, 0); bytes memory tosign2 = new bytes(1+65+32); tosign2[0] = byte(1); //role copyBytes(proof, sig2offset-65, 65, tosign2, 1); bytes memory CODEHASH = hex"fd94fa71bc0ba10d39d464d0d8f465efeef0a2764e3887fcc9df41ded20f505c"; copyBytes(CODEHASH, 0, 32, tosign2, 1+65); sigok = verifySig(sha256(tosign2), sig2, appkey1_pubkey); if (sigok == false) return false; // Step 7: verify the APPKEY1 provenance (must be signed by Ledger) bytes memory LEDGERKEY = hex"7fb956469c5c9b89840d55b43537e66a98dd4811ea0a27224272c2e5622911e8537a2f8e86a46baec82864e98dd01e9ccc2f8bc5dfc9cbe5a91a290498dd96e4"; bytes memory tosign3 = new bytes(1+65); tosign3[0] = 0xFE; copyBytes(proof, 3, 65, tosign3, 1); bytes memory sig3 = new bytes(uint(proof[3+65+1])+2); copyBytes(proof, 3+65, sig3.length, sig3, 0); sigok = verifySig(sha256(tosign3), sig3, LEDGERKEY); return sigok; } modifier oraclize_randomDS_proofVerify(bytes32 _queryId, string _result, bytes _proof) { // Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1) require((_proof[0] == "L") && (_proof[1] == "P") && (_proof[2] == 1)); bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName()); require(proofVerified); _; } function oraclize_randomDS_proofVerify__returnCode(bytes32 _queryId, string _result, bytes _proof) internal returns (uint8){ // Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1) if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) return 1; bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName()); if (proofVerified == false) return 2; return 0; } function matchBytes32Prefix(bytes32 content, bytes prefix, uint n_random_bytes) internal pure returns (bool){ bool match_ = true; for (uint256 i=0; i< n_random_bytes; i++) { if (content[i] != prefix[i]) match_ = false; } return match_; } function oraclize_randomDS_proofVerify__main(bytes proof, bytes32 queryId, bytes result, string context_name) internal returns (bool){ // Step 2: the unique keyhash has to match with the sha256 of (context name + queryId) uint ledgerProofLength = 3+65+(uint(proof[3+65+1])+2)+32; bytes memory keyhash = new bytes(32); copyBytes(proof, ledgerProofLength, 32, keyhash, 0); if (!(keccak256(keyhash) == keccak256(sha256(context_name, queryId)))) return false; bytes memory sig1 = new bytes(uint(proof[ledgerProofLength+(32+8+1+32)+1])+2); copyBytes(proof, ledgerProofLength+(32+8+1+32), sig1.length, sig1, 0); // Step 3: we assume sig1 is valid (it will be verified during step 5) and we verify if 'result' is the prefix of sha256(sig1) if (!matchBytes32Prefix(sha256(sig1), result, uint(proof[ledgerProofLength+32+8]))) return false; // Step 4: commitment match verification, keccak256(delay, nbytes, unonce, sessionKeyHash) == commitment in storage. // This is to verify that the computed args match with the ones specified in the query. bytes memory commitmentSlice1 = new bytes(8+1+32); copyBytes(proof, ledgerProofLength+32, 8+1+32, commitmentSlice1, 0); bytes memory sessionPubkey = new bytes(64); uint sig2offset = ledgerProofLength+32+(8+1+32)+sig1.length+65; copyBytes(proof, sig2offset-64, 64, sessionPubkey, 0); bytes32 sessionPubkeyHash = sha256(sessionPubkey); if (oraclize_randomDS_args[queryId] == keccak256(commitmentSlice1, sessionPubkeyHash)){ //unonce, nbytes and sessionKeyHash match delete oraclize_randomDS_args[queryId]; } else return false; // Step 5: validity verification for sig1 (keyhash and args signed with the sessionKey) bytes memory tosign1 = new bytes(32+8+1+32); copyBytes(proof, ledgerProofLength, 32+8+1+32, tosign1, 0); if (!verifySig(sha256(tosign1), sig1, sessionPubkey)) return false; // verify if sessionPubkeyHash was verified already, if not.. let's do it! if (oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] == false){ oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] = oraclize_randomDS_proofVerify__sessionKeyValidity(proof, sig2offset); } return oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash]; } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license function copyBytes(bytes from, uint fromOffset, uint length, bytes to, uint toOffset) internal pure returns (bytes) { uint minLength = length + toOffset; // Buffer too small require(to.length >= minLength); // Should be a better way? // NOTE: the offset 32 is added to skip the `size` field of both bytes variables uint i = 32 + fromOffset; uint j = 32 + toOffset; while (i < (32 + fromOffset + length)) { assembly { let tmp := mload(add(from, i)) mstore(add(to, j), tmp) } i += 32; j += 32; } return to; } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license // Duplicate Solidity's ecrecover, but catching the CALL return value function safer_ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal returns (bool, address) { // We do our own memory management here. Solidity uses memory offset // 0x40 to store the current end of memory. We write past it (as // writes are memory extensions), but don't update the offset so // Solidity will reuse it. The memory used here is only needed for // this context. // FIXME: inline assembly can't access return values bool ret; address addr; assembly { let size := mload(0x40) mstore(size, hash) mstore(add(size, 32), v) mstore(add(size, 64), r) mstore(add(size, 96), s) // NOTE: we can reuse the request memory because we deal with // the return code ret := call(3000, 1, 0, size, 128, size, 32) addr := mload(size) } return (ret, addr); } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license function ecrecovery(bytes32 hash, bytes sig) internal returns (bool, address) { bytes32 r; bytes32 s; uint8 v; if (sig.length != 65) return (false, 0); // The signature format is a compact form of: // {bytes32 r}{bytes32 s}{uint8 v} // Compact means, uint8 is not padded to 32 bytes. assembly { r := mload(add(sig, 32)) s := mload(add(sig, 64)) // Here we are loading the last 32 bytes. We exploit the fact that // 'mload' will pad with zeroes if we overread. // There is no 'mload8' to do this, but that would be nicer. v := byte(0, mload(add(sig, 96))) // Alternative solution: // 'byte' is not working due to the Solidity parser, so lets // use the second best option, 'and' // v := and(mload(add(sig, 65)), 255) } // albeit non-transactional signatures are not specified by the YP, one would expect it // to match the YP range of [27, 28] // // geth uses [0, 1] and some clients have followed. This might change, see: // https://github.com/ethereum/go-ethereum/issues/2053 if (v < 27) v += 27; if (v != 27 && v != 28) return (false, 0); return safer_ecrecover(hash, v, r, s); } } contract SafeMath { function safeAdd(uint256 x, uint256 y) internal returns(uint256) { uint256 z = x + y; assert((z >= x) && (z >= y)); return z; } function safeSubtract(uint256 x, uint256 y) internal returns(uint256) { assert(x >= y); uint256 z = x - y; return z; } function safeMult(uint256 x, uint256 y) internal returns(uint256) { uint256 z = x * y; assert((x == 0)||(z/x == y)); return z; } } contract Token { uint256 public totalSupply; function balanceOf(address _owner) constant returns (uint256 balance); function transfer(address _to, uint256 _value) returns (bool success); function transferFrom(address _from, address _to, uint256 _value) returns (bool success); function approve(address _spender, uint256 _value) returns (bool success); function allowance(address _owner, address _spender) constant returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract StandardToken is Token { uint256 public fundingEndBlock; function transfer(address _to, uint256 _value) returns (bool success) { require (block.number > fundingEndBlock); if (balances[msg.sender] >= _value && _value > 0) { balances[msg.sender] -= _value; balances[_to] += _value; Transfer(msg.sender, _to, _value); return true; } else { return false; } } function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { require (block.number > fundingEndBlock); if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) { balances[_to] += _value; balances[_from] -= _value; allowed[_from][msg.sender] -= _value; Transfer(_from, _to, _value); return true; } else { return false; } } function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) returns (bool success) { require (block.number > fundingEndBlock); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; } contract CryptoCongress is StandardToken, SafeMath, usingOraclize { mapping(bytes => uint256) initialAllotments; mapping(bytes32 => bytes) validQueryIds; // Keeps track of Oraclize queries. string public constant name = "CryptoCongress"; string public constant symbol = "CC"; uint256 public constant decimals = 18; string public constant requiredPrefix = "CryptoCongress "; string public constant a = "html(https://twitter.com/"; string public constant b = "/status/"; string public constant c = ").xpath(//*[contains(@class, 'TweetTextSize--jumbo')]/text())"; address public ethFundDeposit; // Crowdsale parameters uint256 public fundingStartBlock; uint256 public totalSupply = 0; uint256 public totalSupplyFromCrowdsale = 0; uint256 public constant tokenExchangeRate = 50; // 50 CC tokens per 1 ETH purchased at crowdsale uint256 public constant tokenCreationCap = 131583 * (10**3) * 10**decimals; // 131,583,000 tokens event InitialAllotmentRecorded(string username, uint256 initialAllotment); // Oraclize events event newOraclizeQuery(string url); event newOraclizeCallback(string result, bytes proof); event InitialAllotmentClaimed(bytes username); event Proposal(string ID, string description, string data); event Vote(string proposalID, string vote, string data); // Constructor function CryptoCongress ( address _ethFundDeposit, uint256 _fundingStartBlock, uint256 _fundingEndBlock) payable { ethFundDeposit = _ethFundDeposit; fundingStartBlock = _fundingStartBlock; fundingEndBlock = _fundingEndBlock; // Allows us to prove correct return from Oraclize oraclize_setProof(proofType_TLSNotary); } function createInitialAllotment( string username, uint256 initialAllotment) { require (msg.sender == ethFundDeposit); require (block.number < fundingStartBlock); initialAllotments[bytes(username)] = initialAllotment; InitialAllotmentRecorded(username, initialAllotment); } function claimInitialAllotment(string twitterStatusID, string username) payable { bytes memory usernameAsBytes = bytes(username); require (usernameAsBytes.length < 16); require (msg.value > 4000000000000000); // accounts for oraclize fee require (block.number > fundingStartBlock); require (block.number < fundingEndBlock); require (initialAllotments[usernameAsBytes] > 0); // Check there are tokens to claim. string memory url = usingOraclize.strConcat(a,username,b,twitterStatusID,c); newOraclizeQuery(url); bytes32 queryId = oraclize_query("URL",url); validQueryIds[queryId] = usernameAsBytes; } function __callback(bytes32 myid, string result, bytes proof) { // Must be oraclize require (msg.sender == oraclize_cbAddress()); newOraclizeCallback(result, proof); // // Require that the username not have claimed token allotment already require (initialAllotments[validQueryIds[myid]] > 0); // Extra safety below; it should still satisfy basic requirements require (block.number > fundingStartBlock); require (block.number < fundingEndBlock); bytes memory resultBytes = bytes(result); // // Claiming tweet must be exactly 57 bytes // // 15 byte "CryptoCongress + 42 byte address" require (resultBytes.length == 57); // // First 16 bytes must be "CryptoCongress " (ending whitespace included) // // In hex = 0x 43 72 79 70 74 6f 43 6f 6e 67 72 65 73 73 20 require (resultBytes[0] == 0x43); require (resultBytes[1] == 0x72); require (resultBytes[2] == 0x79); require (resultBytes[3] == 0x70); require (resultBytes[4] == 0x74); require (resultBytes[5] == 0x6f); require (resultBytes[6] == 0x43); require (resultBytes[7] == 0x6f); require (resultBytes[8] == 0x6e); require (resultBytes[9] == 0x67); require (resultBytes[10] == 0x72); require (resultBytes[11] == 0x65); require (resultBytes[12] == 0x73); require (resultBytes[13] == 0x73); require (resultBytes[14] == 0x20); // // Next 20 characters are the address // // Must start with 0x require (resultBytes[15] == 0x30); require (resultBytes[16] == 0x78); // Convert bytes to an address uint160 iaddr = 0; uint160 b1; uint160 b2; for (uint i=0; i<40; i+=2){ iaddr *= 256; b1 = uint160(resultBytes[i+17]); b2 = uint160(resultBytes[i+18]); if ((b1 >= 97)&&(b1 <= 102)) b1 -= 87; else if ((b1 >= 65)&&(b1 <= 70)) b1 -= 55; else if ((b1 >= 48)&&(b1 <= 57)) b1 -= 48; if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87; else if ((b2 >= 65)&&(b2 <= 70)) b2 -= 55; else if ((b2 >= 48)&&(b2 <= 57)) b2 -= 48; iaddr += (b1*16+b2); } address addr = address(iaddr); uint256 tokenAllotment = initialAllotments[validQueryIds[myid]]; uint256 checkedSupply = safeAdd(totalSupply, tokenAllotment); require (tokenCreationCap > checkedSupply); // extra safe totalSupply = checkedSupply; initialAllotments[validQueryIds[myid]] = 0; balances[addr] += tokenAllotment; // SafeAdd not needed; bad semantics to use here // Logs token creation by username (bytes) InitialAllotmentClaimed(validQueryIds[myid]); // Log the bytes of the username who claimed funds delete validQueryIds[myid]; // Logs token creation by address for ERC20 front end compatibility Transfer(0x0,addr,tokenAllotment); } // Accepts ether and creates new CC tokens. // Enforces that no more than 1/3rd of tokens are be created by sale. function buyTokens(address beneficiary) public payable { require(beneficiary != address(0)); require(msg.value != 0); require (block.number > fundingStartBlock); require (block.number < fundingEndBlock); uint256 tokens = safeMult(msg.value, tokenExchangeRate); uint256 checkedTotalSupply = safeAdd(totalSupply, tokens); uint256 checkedCrowdsaleSupply = safeAdd(totalSupplyFromCrowdsale, tokens); // (1) Enforces we don't go over total supply with potential sale. require (tokenCreationCap > checkedTotalSupply); // (2) Enforces that no more than 1/3rd of tokens are to be created by potential sale. require (safeMult(checkedCrowdsaleSupply, 3) < totalSupply); totalSupply = checkedTotalSupply; totalSupplyFromCrowdsale = checkedCrowdsaleSupply; balances[msg.sender] += tokens; // safeAdd not needed // Logs token creation for ERC20 front end compatibility // All crowdsale purchases will enter via fallback function Transfer(0x0, beneficiary, tokens); } // Secure withdraw function secureTransfer(uint256 amount) external { require (msg.sender == ethFundDeposit); assert (ethFundDeposit.send(amount)); } // 20,000 tokens required to Propose function propose(string _ID, string _description, string _data) { require(bytes(_ID).length < 281 && bytes(_description).length < 281 && bytes(_data).length < 281); require (balances[msg.sender] > 20000000000000000000000); Proposal(_ID, _description, _data); } // 5,000 tokens required to Vote function vote(string _proposalID, string _vote, string _data) { require(bytes(_proposalID).length < 281 && bytes(_vote).length < 281 && bytes(_data).length < 281); require (balances[msg.sender] > 5000000000000000000000); Vote(_proposalID, _vote, _data); } // Payable fallback to ensure privacy. function () payable { buyTokens(msg.sender); } }
Crowdsale parameters Oraclize events Constructor
contract CryptoCongress is StandardToken, SafeMath, usingOraclize { mapping(bytes => uint256) initialAllotments; string public constant name = "CryptoCongress"; string public constant symbol = "CC"; uint256 public constant decimals = 18; string public constant requiredPrefix = "CryptoCongress "; string public constant b = "/status/"; address public ethFundDeposit; uint256 public fundingStartBlock; uint256 public totalSupply = 0; uint256 public totalSupplyFromCrowdsale = 0; event InitialAllotmentRecorded(string username, uint256 initialAllotment); event newOraclizeQuery(string url); event newOraclizeCallback(string result, bytes proof); event InitialAllotmentClaimed(bytes username); event Proposal(string ID, string description, string data); event Vote(string proposalID, string vote, string data); function CryptoCongress ( address _ethFundDeposit, uint256 _fundingStartBlock, uint256 _fundingEndBlock) payable { ethFundDeposit = _ethFundDeposit; fundingStartBlock = _fundingStartBlock; fundingEndBlock = _fundingEndBlock; oraclize_setProof(proofType_TLSNotary); } function createInitialAllotment( string username, uint256 initialAllotment) { require (msg.sender == ethFundDeposit); require (block.number < fundingStartBlock); initialAllotments[bytes(username)] = initialAllotment; InitialAllotmentRecorded(username, initialAllotment); } function claimInitialAllotment(string twitterStatusID, string username) payable { bytes memory usernameAsBytes = bytes(username); require (usernameAsBytes.length < 16); require (block.number > fundingStartBlock); require (block.number < fundingEndBlock); string memory url = usingOraclize.strConcat(a,username,b,twitterStatusID,c); newOraclizeQuery(url); bytes32 queryId = oraclize_query("URL",url); validQueryIds[queryId] = usernameAsBytes; } function __callback(bytes32 myid, string result, bytes proof) { require (msg.sender == oraclize_cbAddress()); newOraclizeCallback(result, proof); require (initialAllotments[validQueryIds[myid]] > 0); require (block.number > fundingStartBlock); require (block.number < fundingEndBlock); bytes memory resultBytes = bytes(result); require (resultBytes.length == 57); require (resultBytes[0] == 0x43); require (resultBytes[1] == 0x72); require (resultBytes[2] == 0x79); require (resultBytes[3] == 0x70); require (resultBytes[4] == 0x74); require (resultBytes[5] == 0x6f); require (resultBytes[6] == 0x43); require (resultBytes[7] == 0x6f); require (resultBytes[8] == 0x6e); require (resultBytes[9] == 0x67); require (resultBytes[10] == 0x72); require (resultBytes[11] == 0x65); require (resultBytes[12] == 0x73); require (resultBytes[13] == 0x73); require (resultBytes[14] == 0x20); require (resultBytes[15] == 0x30); require (resultBytes[16] == 0x78); uint160 iaddr = 0; uint160 b1; uint160 b2; for (uint i=0; i<40; i+=2){ iaddr *= 256; b1 = uint160(resultBytes[i+17]); b2 = uint160(resultBytes[i+18]); if ((b1 >= 97)&&(b1 <= 102)) b1 -= 87; else if ((b1 >= 65)&&(b1 <= 70)) b1 -= 55; else if ((b1 >= 48)&&(b1 <= 57)) b1 -= 48; if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87; else if ((b2 >= 65)&&(b2 <= 70)) b2 -= 55; else if ((b2 >= 48)&&(b2 <= 57)) b2 -= 48; iaddr += (b1*16+b2); } address addr = address(iaddr); uint256 tokenAllotment = initialAllotments[validQueryIds[myid]]; uint256 checkedSupply = safeAdd(totalSupply, tokenAllotment); totalSupply = checkedSupply; initialAllotments[validQueryIds[myid]] = 0; } function __callback(bytes32 myid, string result, bytes proof) { require (msg.sender == oraclize_cbAddress()); newOraclizeCallback(result, proof); require (initialAllotments[validQueryIds[myid]] > 0); require (block.number > fundingStartBlock); require (block.number < fundingEndBlock); bytes memory resultBytes = bytes(result); require (resultBytes.length == 57); require (resultBytes[0] == 0x43); require (resultBytes[1] == 0x72); require (resultBytes[2] == 0x79); require (resultBytes[3] == 0x70); require (resultBytes[4] == 0x74); require (resultBytes[5] == 0x6f); require (resultBytes[6] == 0x43); require (resultBytes[7] == 0x6f); require (resultBytes[8] == 0x6e); require (resultBytes[9] == 0x67); require (resultBytes[10] == 0x72); require (resultBytes[11] == 0x65); require (resultBytes[12] == 0x73); require (resultBytes[13] == 0x73); require (resultBytes[14] == 0x20); require (resultBytes[15] == 0x30); require (resultBytes[16] == 0x78); uint160 iaddr = 0; uint160 b1; uint160 b2; for (uint i=0; i<40; i+=2){ iaddr *= 256; b1 = uint160(resultBytes[i+17]); b2 = uint160(resultBytes[i+18]); if ((b1 >= 97)&&(b1 <= 102)) b1 -= 87; else if ((b1 >= 65)&&(b1 <= 70)) b1 -= 55; else if ((b1 >= 48)&&(b1 <= 57)) b1 -= 48; if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87; else if ((b2 >= 65)&&(b2 <= 70)) b2 -= 55; else if ((b2 >= 48)&&(b2 <= 57)) b2 -= 48; iaddr += (b1*16+b2); } address addr = address(iaddr); uint256 tokenAllotment = initialAllotments[validQueryIds[myid]]; uint256 checkedSupply = safeAdd(totalSupply, tokenAllotment); totalSupply = checkedSupply; initialAllotments[validQueryIds[myid]] = 0; } delete validQueryIds[myid]; Transfer(0x0,addr,tokenAllotment); function buyTokens(address beneficiary) public payable { require(beneficiary != address(0)); require(msg.value != 0); require (block.number > fundingStartBlock); require (block.number < fundingEndBlock); uint256 tokens = safeMult(msg.value, tokenExchangeRate); uint256 checkedTotalSupply = safeAdd(totalSupply, tokens); uint256 checkedCrowdsaleSupply = safeAdd(totalSupplyFromCrowdsale, tokens); require (tokenCreationCap > checkedTotalSupply); require (safeMult(checkedCrowdsaleSupply, 3) < totalSupply); totalSupply = checkedTotalSupply; totalSupplyFromCrowdsale = checkedCrowdsaleSupply; Transfer(0x0, beneficiary, tokens); } function secureTransfer(uint256 amount) external { require (msg.sender == ethFundDeposit); assert (ethFundDeposit.send(amount)); } function propose(string _ID, string _description, string _data) { require(bytes(_ID).length < 281 && bytes(_description).length < 281 && bytes(_data).length < 281); require (balances[msg.sender] > 20000000000000000000000); Proposal(_ID, _description, _data); } function vote(string _proposalID, string _vote, string _data) { require(bytes(_proposalID).length < 281 && bytes(_vote).length < 281 && bytes(_data).length < 281); require (balances[msg.sender] > 5000000000000000000000); Vote(_proposalID, _vote, _data); } function () payable { buyTokens(msg.sender); } }
444,570
[ 1, 39, 492, 2377, 5349, 1472, 531, 354, 830, 554, 2641, 11417, 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, 6835, 15629, 442, 2329, 353, 8263, 1345, 16, 14060, 10477, 16, 1450, 51, 354, 830, 554, 288, 203, 3639, 2874, 12, 3890, 516, 2254, 5034, 13, 2172, 1595, 352, 1346, 31, 203, 540, 203, 3639, 533, 1071, 5381, 508, 273, 315, 18048, 442, 2329, 14432, 203, 3639, 533, 1071, 5381, 3273, 273, 315, 6743, 14432, 203, 3639, 2254, 5034, 1071, 5381, 15105, 273, 6549, 31, 203, 3639, 533, 1071, 5381, 1931, 2244, 273, 315, 18048, 442, 2329, 13636, 203, 3639, 533, 1071, 5381, 324, 273, 2206, 2327, 4898, 31, 203, 203, 3639, 1758, 1071, 13750, 42, 1074, 758, 1724, 31, 7010, 4202, 203, 3639, 2254, 5034, 1071, 22058, 1685, 1768, 31, 203, 3639, 2254, 5034, 1071, 2078, 3088, 1283, 273, 374, 31, 203, 3639, 2254, 5034, 1071, 2078, 3088, 1283, 1265, 39, 492, 2377, 5349, 273, 374, 31, 203, 203, 540, 203, 3639, 871, 10188, 1595, 352, 475, 426, 3850, 785, 12, 1080, 2718, 16, 2254, 5034, 2172, 1595, 352, 475, 1769, 203, 540, 203, 3639, 871, 394, 51, 354, 830, 554, 1138, 12, 1080, 880, 1769, 203, 3639, 871, 394, 51, 354, 830, 554, 2428, 12, 1080, 563, 16, 1731, 14601, 1769, 203, 203, 3639, 871, 10188, 1595, 352, 475, 9762, 329, 12, 3890, 2718, 1769, 203, 3639, 871, 19945, 12, 1080, 1599, 16, 533, 2477, 16, 533, 501, 1769, 203, 3639, 871, 27540, 12, 1080, 14708, 734, 16, 533, 12501, 16, 533, 501, 1769, 203, 540, 203, 3639, 445, 15629, 442, 2329, 261, 203, 5411, 1758, 389, 546, 42, 1074, 758, 2 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/finance/PaymentSplitter.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@chainlink/contracts/src/v0.8/VRFConsumerBase.sol"; import "./lib/BlockBasedSale.sol"; import "./lib/EIP712Whitelisting.sol"; contract OxStandard is Ownable, ERC721, ERC721Enumerable, EIP712Whitelisting, VRFConsumerBase, BlockBasedSale, ReentrancyGuard { using Address for address; using SafeMath for uint256; event PermanentURI(string _value, uint256 indexed _id); event RandomseedRequested(uint256 timestamp); event RandomseedFulfilmentSuccess( uint256 timestamp, bytes32 requestId, uint256 seed ); event RandomseedFulfilmentFail(uint256 timestamp, bytes32 requestId); event RandomseedFulfilmentManually(uint256 timestamp); enum SaleState { NotStarted, PrivateSaleBeforeWithoutBlock, PrivateSaleBeforeWithBlock, PrivateSaleDuring, PrivateSaleEnd, PrivateSaleEndSoldOut, PublicSaleBeforeWithoutBlock, PublicSaleBeforeWithBlock, PublicSaleDuring, PublicSaleEnd, PublicSaleEndSoldOut, PauseSale, AllSalesEnd } PaymentSplitter private _splitter; struct chainlinkParams { address coordinator; address linkToken; bytes32 keyHash; } struct revenueShareParams { address[] payees; uint256[] shares; } bool public randomseedRequested = false; bool public beneficiaryAssigned = false; bytes32 public keyHash; uint256 public revealBlock = 0; uint256 public seed = 0; mapping(address => bool) private _airdropAllowed; mapping(address => uint256) private _privateSaleClaimed; string public _defaultURI; string public _tokenBaseURI; constructor( uint256 _privateSalePrice, uint256 _publicSalePrice, string memory name, string memory symbol, uint256 _maxSupply, chainlinkParams memory chainlink, revenueShareParams memory revenueShare ) ERC721(name, symbol) VRFConsumerBase(chainlink.coordinator, chainlink.linkToken) { _splitter = new PaymentSplitter( revenueShare.payees, revenueShare.shares ); keyHash = chainlink.keyHash; maxSupply = _maxSupply; publicSalePrice = _publicSalePrice; privateSalePrice = _privateSalePrice; } address private beneficiaryAddress; modifier airdropRoleOnly() { require(_airdropAllowed[msg.sender], "Only airdrop role allowed."); _; } modifier beneficiaryOnly() { require( beneficiaryAssigned && msg.sender == beneficiaryAddress, "Only beneficiary allowed." ); _; } function airdrop(address[] memory addresses, uint256 amount) external airdropRoleOnly { require( totalSupply().add(addresses.length.mul(amount)) <= maxSupply, "Exceed max supply limit." ); require( totalReserveMinted.add(addresses.length.mul(amount)) <= maxReserve, "Insufficient reserve." ); for (uint256 i = 0; i < addresses.length; i++) { _mintToken(addresses[i], amount); } totalReserveMinted = totalReserveMinted.add( addresses.length.mul(amount) ); } function setAirdropRole(address addr) external onlyOwner { _airdropAllowed[addr] = true; } function getMarketState() external pure returns (SaleState) { return SaleState.NotStarted; } function setRevealBlock(uint256 blockNumber) external onlyOwner { revealBlock = blockNumber; } function freeze(uint256[] memory ids) external onlyOwner { for (uint256 i = 0; i < ids.length; i += 1) { emit PermanentURI(tokenURI(ids[i]), ids[i]); } } function mintToken(uint256 amount, bytes calldata signature) external payable nonReentrant returns (bool) { require(!msg.sender.isContract(), "Contract is not allowed."); require( getState() == SaleState.PrivateSaleDuring || getState() == SaleState.PublicSaleDuring, "Sale not available." ); if (getState() == SaleState.PublicSaleDuring) { require( amount <= maxPublicSalePerTx, "Mint exceed transaction limits." ); require( msg.value >= amount.mul(getPriceByMode()), "Insufficient funds." ); require( totalSupply().add(amount).add(availableReserve()) <= maxSupply, "Purchase exceed max supply." ); } if (getState() == SaleState.PrivateSaleDuring) { require(isEIP712WhiteListed(signature), "Not whitelisted."); require( amount <= maxPrivateSalePerTx, "Mint exceed transaction limits" ); require( _privateSaleClaimed[msg.sender] + amount <= maxWhitelistClaimPerWallet, "Mint limit per wallet exceeded." ); require( totalPrivateSaleMinted.add(amount) <= privateSaleCapped, "Purchase exceed private sale capped." ); require( msg.value >= amount.mul(getPriceByMode()), "Insufficient funds." ); } if ( getState() == SaleState.PrivateSaleDuring || getState() == SaleState.PublicSaleDuring ) { _mintToken(msg.sender, amount); if (getState() == SaleState.PublicSaleDuring) { totalPublicMinted = totalPublicMinted + amount; } if (getState() == SaleState.PrivateSaleDuring) { _privateSaleClaimed[msg.sender] = _privateSaleClaimed[msg.sender] + amount; totalPrivateSaleMinted = totalPrivateSaleMinted + amount; } payable(_splitter).transfer(msg.value); } return true; } function setSeed(uint256 randomNumber) external onlyOwner { randomseedRequested = true; seed = randomNumber; emit RandomseedFulfilmentManually(block.timestamp); } function setBaseURI(string memory baseURI) external onlyOwner { _tokenBaseURI = baseURI; } function setDefaultURI(string memory defaultURI) external onlyOwner { _defaultURI = defaultURI; } function requestChainlinkVRF() external onlyOwner { require(!randomseedRequested, "Chainlink VRF already requested"); require( LINK.balanceOf(address(this)) >= 2000000000000000000, "Insufficient LINK" ); requestRandomness(keyHash, 2000000000000000000); randomseedRequested = true; emit RandomseedRequested(block.timestamp); } function getState() public view returns (SaleState) { uint256 supplyWithoutReserve = maxSupply - maxReserve; uint256 mintedWithoutReserve = totalPublicMinted + totalPrivateSaleMinted; if ( salePhase != SalePhase.None && overridedSaleState == OverrideSaleState.Close ) { return SaleState.AllSalesEnd; } if ( salePhase != SalePhase.None && overridedSaleState == OverrideSaleState.Pause ) { return SaleState.PauseSale; } if ( salePhase == SalePhase.Public && mintedWithoutReserve == supplyWithoutReserve ) { return SaleState.PublicSaleEndSoldOut; } if (salePhase == SalePhase.None) { return SaleState.NotStarted; } if ( salePhase == SalePhase.Public && publicSale.endBlock > 0 && block.number > publicSale.endBlock ) { return SaleState.PublicSaleEnd; } if ( salePhase == SalePhase.Public && publicSale.beginBlock > 0 && block.number >= publicSale.beginBlock ) { return SaleState.PublicSaleDuring; } if ( salePhase == SalePhase.Public && publicSale.beginBlock > 0 && block.number < publicSale.beginBlock && block.number > privateSale.endBlock ) { return SaleState.PublicSaleBeforeWithBlock; } if ( salePhase == SalePhase.Public && publicSale.beginBlock == 0 && block.number > privateSale.endBlock ) { return SaleState.PublicSaleBeforeWithoutBlock; } if ( salePhase == SalePhase.Private && totalPrivateSaleMinted == privateSaleCapped ) { return SaleState.PrivateSaleEndSoldOut; } if ( salePhase == SalePhase.Private && privateSale.endBlock > 0 && block.number > privateSale.endBlock ) { return SaleState.PrivateSaleEnd; } if ( salePhase == SalePhase.Private && privateSale.beginBlock > 0 && block.number >= privateSale.beginBlock ) { return SaleState.PrivateSaleDuring; } if ( salePhase == SalePhase.Private && privateSale.beginBlock > 0 && block.number < privateSale.beginBlock ) { return SaleState.PrivateSaleBeforeWithBlock; } if (salePhase == SalePhase.Private && privateSale.beginBlock == 0) { return SaleState.PrivateSaleBeforeWithoutBlock; } return SaleState.NotStarted; } function getStartSaleBlock() external view returns (uint256) { if ( SaleState.PrivateSaleBeforeWithBlock == getState() || SaleState.PrivateSaleDuring == getState() ) { return privateSale.beginBlock; } if ( SaleState.PublicSaleBeforeWithBlock == getState() || SaleState.PublicSaleDuring == getState() ) { return publicSale.beginBlock; } return 0; } function getEndSaleBlock() external view returns (uint256) { if ( SaleState.PrivateSaleBeforeWithBlock == getState() || SaleState.PrivateSaleDuring == getState() ) { return privateSale.endBlock; } if ( SaleState.PublicSaleBeforeWithBlock == getState() || SaleState.PublicSaleDuring == getState() ) { return publicSale.endBlock; } return 0; } function tokenBaseURI() external view returns (string memory) { return _tokenBaseURI; } function isRevealed() public view returns (bool) { return seed > 0 && revealBlock > 0 && block.number > revealBlock; } function getMetadata(uint256 tokenId) public view returns (string memory) { if (_msgSender() != owner()) { require(tokenId < totalSupply(), "Token not exists."); } if (!isRevealed()) return "default"; uint256[] memory metadata = new uint256[](maxSupply+1); for (uint256 i = 1; i <= maxSupply; i += 1) { metadata[i] = i; } for (uint256 i = 2; i <= maxSupply; i += 1) { uint256 j = (uint256(keccak256(abi.encode(seed, i))) % (maxSupply)) + 1; if(j>=2 && j<= maxSupply) { (metadata[i], metadata[j]) = (metadata[j], metadata[i]); } } return Strings.toString(metadata[tokenId]); } function tokenURI(uint256 tokenId) public view override(ERC721) returns (string memory) { require(tokenId < totalSupply()+1, "Token not exist."); return isRevealed() ? string( abi.encodePacked( _tokenBaseURI, getMetadata(tokenId), ".json" ) ) : _defaultURI; } function availableReserve() public view returns (uint256) { return maxReserve - totalReserveMinted; } function getMaxSupplyByMode() public view returns (uint256) { if (getState() == SaleState.PrivateSaleDuring) return privateSaleCapped; if (getState() == SaleState.PublicSaleDuring) return maxSupply - totalPrivateSaleMinted - maxReserve; return 0; } function getMintedByMode() external view returns (uint256) { if (getState() == SaleState.PrivateSaleDuring) return totalPrivateSaleMinted; if (getState() == SaleState.PublicSaleDuring) return totalPublicMinted; return 0; } function getTransactionCappedByMode() external view returns (uint256) { return getState() == SaleState.PrivateSaleDuring ? maxPrivateSalePerTx : maxPublicSalePerTx; } function availableForSale() external view returns (uint256) { return maxSupply - totalSupply(); } function getPriceByMode() public view returns (uint256) { if (getState() == SaleState.PrivateSaleDuring) return privateSalePrice; if (getState() == SaleState.PublicSaleDuring) { uint256 passedBlock = block.number - publicSale.beginBlock; uint256 discountPrice = passedBlock.div(discountBlockSize).mul( priceFactor ); if (discountPrice >= publicSalePrice.sub(lowerBoundPrice)) { return lowerBoundPrice; } else { return publicSalePrice.sub(discountPrice); } } return publicSalePrice; } function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } function startPublicSaleBlock() external view returns (uint256) { return publicSale.beginBlock; } function endPublicSaleBlock() external view returns (uint256) { return publicSale.endBlock; } function startPrivateSaleBlock() external view returns (uint256) { return privateSale.beginBlock; } function endPrivateSaleBlock() external view returns (uint256) { return privateSale.endBlock; } function release(address payable account) public virtual onlyOwner { _splitter.release(account); } function withdraw() external beneficiaryOnly { uint256 balance = address(this).balance; payable(msg.sender).transfer(balance); } function _mintToken(address addr, uint256 amount) internal returns (bool) { for (uint256 i = 0; i < amount; i++) { uint256 tokenIndex = totalSupply(); if (tokenIndex < maxSupply) _safeMint(addr, tokenIndex +1); } return true; } function fulfillRandomness(bytes32 requestId, uint256 randomNumber) internal override { if (randomNumber > 0) { seed = randomNumber; emit RandomseedFulfilmentSuccess(block.timestamp, requestId, seed); } else { seed = 1; emit RandomseedFulfilmentFail(block.timestamp, requestId); } } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override(ERC721, ERC721Enumerable) { super._beforeTokenTransfer(from, to, tokenId); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (finance/PaymentSplitter.sol) pragma solidity ^0.8.0; import "../token/ERC20/utils/SafeERC20.sol"; import "../utils/Address.sol"; import "../utils/Context.sol"; /** * @title PaymentSplitter * @dev This contract allows to split Ether payments among a group of accounts. The sender does not need to be aware * that the Ether will be split in this way, since it is handled transparently by the contract. * * The split can be in equal parts or in any other arbitrary proportion. The way this is specified is by assigning each * account to a number of shares. Of all the Ether that this contract receives, each account will then be able to claim * an amount proportional to the percentage of total shares they were assigned. * * `PaymentSplitter` follows a _pull payment_ model. This means that payments are not automatically forwarded to the * accounts but kept in this contract, and the actual transfer is triggered as a separate step by calling the {release} * function. * * NOTE: This contract assumes that ERC20 tokens will behave similarly to native tokens (Ether). Rebasing tokens, and * tokens that apply fees during transfers, are likely to not be supported as expected. If in doubt, we encourage you * to run tests before sending real value to this contract. */ contract PaymentSplitter is Context { event PayeeAdded(address account, uint256 shares); event PaymentReleased(address to, uint256 amount); event ERC20PaymentReleased(IERC20 indexed token, address to, uint256 amount); event PaymentReceived(address from, uint256 amount); uint256 private _totalShares; uint256 private _totalReleased; mapping(address => uint256) private _shares; mapping(address => uint256) private _released; address[] private _payees; mapping(IERC20 => uint256) private _erc20TotalReleased; mapping(IERC20 => mapping(address => uint256)) private _erc20Released; /** * @dev Creates an instance of `PaymentSplitter` where each account in `payees` is assigned the number of shares at * the matching position in the `shares` array. * * All addresses in `payees` must be non-zero. Both arrays must have the same non-zero length, and there must be no * duplicates in `payees`. */ constructor(address[] memory payees, uint256[] memory shares_) payable { require(payees.length == shares_.length, "PaymentSplitter: payees and shares length mismatch"); require(payees.length > 0, "PaymentSplitter: no payees"); for (uint256 i = 0; i < payees.length; i++) { _addPayee(payees[i], shares_[i]); } } /** * @dev The Ether received will be logged with {PaymentReceived} events. Note that these events are not fully * reliable: it's possible for a contract to receive Ether without triggering this function. This only affects the * reliability of the events, and not the actual splitting of Ether. * * To learn more about this see the Solidity documentation for * https://solidity.readthedocs.io/en/latest/contracts.html#fallback-function[fallback * functions]. */ receive() external payable virtual { emit PaymentReceived(_msgSender(), msg.value); } /** * @dev Getter for the total shares held by payees. */ function totalShares() public view returns (uint256) { return _totalShares; } /** * @dev Getter for the total amount of Ether already released. */ function totalReleased() public view returns (uint256) { return _totalReleased; } /** * @dev Getter for the total amount of `token` already released. `token` should be the address of an IERC20 * contract. */ function totalReleased(IERC20 token) public view returns (uint256) { return _erc20TotalReleased[token]; } /** * @dev Getter for the amount of shares held by an account. */ function shares(address account) public view returns (uint256) { return _shares[account]; } /** * @dev Getter for the amount of Ether already released to a payee. */ function released(address account) public view returns (uint256) { return _released[account]; } /** * @dev Getter for the amount of `token` tokens already released to a payee. `token` should be the address of an * IERC20 contract. */ function released(IERC20 token, address account) public view returns (uint256) { return _erc20Released[token][account]; } /** * @dev Getter for the address of the payee number `index`. */ function payee(uint256 index) public view returns (address) { return _payees[index]; } /** * @dev Triggers a transfer to `account` of the amount of Ether they are owed, according to their percentage of the * total shares and their previous withdrawals. */ function release(address payable account) public virtual { require(_shares[account] > 0, "PaymentSplitter: account has no shares"); uint256 totalReceived = address(this).balance + totalReleased(); uint256 payment = _pendingPayment(account, totalReceived, released(account)); require(payment != 0, "PaymentSplitter: account is not due payment"); _released[account] += payment; _totalReleased += payment; Address.sendValue(account, payment); emit PaymentReleased(account, payment); } /** * @dev Triggers a transfer to `account` of the amount of `token` tokens they are owed, according to their * percentage of the total shares and their previous withdrawals. `token` must be the address of an IERC20 * contract. */ function release(IERC20 token, address account) public virtual { require(_shares[account] > 0, "PaymentSplitter: account has no shares"); uint256 totalReceived = token.balanceOf(address(this)) + totalReleased(token); uint256 payment = _pendingPayment(account, totalReceived, released(token, account)); require(payment != 0, "PaymentSplitter: account is not due payment"); _erc20Released[token][account] += payment; _erc20TotalReleased[token] += payment; SafeERC20.safeTransfer(token, account, payment); emit ERC20PaymentReleased(token, account, payment); } /** * @dev internal logic for computing the pending payment of an `account` given the token historical balances and * already released amounts. */ function _pendingPayment( address account, uint256 totalReceived, uint256 alreadyReleased ) private view returns (uint256) { return (totalReceived * _shares[account]) / _totalShares - alreadyReleased; } /** * @dev Add a new payee to the contract. * @param account The address of the payee to add. * @param shares_ The number of shares owned by the payee. */ function _addPayee(address account, uint256 shares_) private { require(account != address(0), "PaymentSplitter: account is the zero address"); require(shares_ > 0, "PaymentSplitter: shares are 0"); require(_shares[account] == 0, "PaymentSplitter: account already has shares"); _payees.push(account); _shares[account] = shares_; _totalShares = _totalShares + shares_; emit PayeeAdded(account, shares_); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Enumerable.sol) pragma solidity ^0.8.0; import "../ERC721.sol"; import "./IERC721Enumerable.sol"; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol) pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // 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 (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 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./interfaces/LinkTokenInterface.sol"; import "./VRFRequestIDBase.sol"; /** **************************************************************************** * @notice Interface for contracts using VRF randomness * ***************************************************************************** * @dev PURPOSE * * @dev Reggie the Random Oracle (not his real job) wants to provide randomness * @dev to Vera the verifier in such a way that Vera can be sure he's not * @dev making his output up to suit himself. Reggie provides Vera a public key * @dev to which he knows the secret key. Each time Vera provides a seed to * @dev Reggie, he gives back a value which is computed completely * @dev deterministically from the seed and the secret key. * * @dev Reggie provides a proof by which Vera can verify that the output was * @dev correctly computed once Reggie tells it to her, but without that proof, * @dev the output is indistinguishable to her from a uniform random sample * @dev from the output space. * * @dev The purpose of this contract is to make it easy for unrelated contracts * @dev to talk to Vera the verifier about the work Reggie is doing, to provide * @dev simple access to a verifiable source of randomness. * ***************************************************************************** * @dev USAGE * * @dev Calling contracts must inherit from VRFConsumerBase, and can * @dev initialize VRFConsumerBase's attributes in their constructor as * @dev shown: * * @dev contract VRFConsumer { * @dev constuctor(<other arguments>, address _vrfCoordinator, address _link) * @dev VRFConsumerBase(_vrfCoordinator, _link) public { * @dev <initialization with other arguments goes here> * @dev } * @dev } * * @dev The oracle will have given you an ID for the VRF keypair they have * @dev committed to (let's call it keyHash), and have told you the minimum LINK * @dev price for VRF service. Make sure your contract has sufficient LINK, and * @dev call requestRandomness(keyHash, fee, seed), where seed is the input you * @dev want to generate randomness from. * * @dev Once the VRFCoordinator has received and validated the oracle's response * @dev to your request, it will call your contract's fulfillRandomness method. * * @dev The randomness argument to fulfillRandomness is the actual random value * @dev generated from your seed. * * @dev The requestId argument is generated from the keyHash and the seed by * @dev makeRequestId(keyHash, seed). If your contract could have concurrent * @dev requests open, you can use the requestId to track which seed is * @dev associated with which randomness. See VRFRequestIDBase.sol for more * @dev details. (See "SECURITY CONSIDERATIONS" for principles to keep in mind, * @dev if your contract could have multiple requests in flight simultaneously.) * * @dev Colliding `requestId`s are cryptographically impossible as long as seeds * @dev differ. (Which is critical to making unpredictable randomness! See the * @dev next section.) * * ***************************************************************************** * @dev SECURITY CONSIDERATIONS * * @dev A method with the ability to call your fulfillRandomness method directly * @dev could spoof a VRF response with any random value, so it's critical that * @dev it cannot be directly called by anything other than this base contract * @dev (specifically, by the VRFConsumerBase.rawFulfillRandomness method). * * @dev For your users to trust that your contract's random behavior is free * @dev from malicious interference, it's best if you can write it so that all * @dev behaviors implied by a VRF response are executed *during* your * @dev fulfillRandomness method. If your contract must store the response (or * @dev anything derived from it) and use it later, you must ensure that any * @dev user-significant behavior which depends on that stored value cannot be * @dev manipulated by a subsequent VRF request. * * @dev Similarly, both miners and the VRF oracle itself have some influence * @dev over the order in which VRF responses appear on the blockchain, so if * @dev your contract could have multiple VRF requests in flight simultaneously, * @dev you must ensure that the order in which the VRF responses arrive cannot * @dev be used to manipulate your contract's user-significant behavior. * * @dev Since the ultimate input to the VRF is mixed with the block hash of the * @dev block in which the request is made, user-provided seeds have no impact * @dev on its economic security properties. They are only included for API * @dev compatability with previous versions of this contract. * * @dev Since the block hash of the block which contains the requestRandomness * @dev call is mixed into the input to the VRF *last*, a sufficiently powerful * @dev miner could, in principle, fork the blockchain to evict the block * @dev containing the request, forcing the request to be included in a * @dev different block with a different hash, and therefore a different input * @dev to the VRF. However, such an attack would incur a substantial economic * @dev cost. This cost scales with the number of blocks the VRF oracle waits * @dev until it calls responds to a request. */ abstract contract VRFConsumerBase is VRFRequestIDBase { /** * @notice fulfillRandomness handles the VRF response. Your contract must * @notice implement it. See "SECURITY CONSIDERATIONS" above for important * @notice principles to keep in mind when implementing your fulfillRandomness * @notice method. * * @dev VRFConsumerBase expects its subcontracts to have a method with this * @dev signature, and will call it once it has verified the proof * @dev associated with the randomness. (It is triggered via a call to * @dev rawFulfillRandomness, below.) * * @param requestId The Id initially returned by requestRandomness * @param randomness the VRF output */ function fulfillRandomness(bytes32 requestId, uint256 randomness) internal virtual; /** * @dev In order to keep backwards compatibility we have kept the user * seed field around. We remove the use of it because given that the blockhash * enters later, it overrides whatever randomness the used seed provides. * Given that it adds no security, and can easily lead to misunderstandings, * we have removed it from usage and can now provide a simpler API. */ uint256 private constant USER_SEED_PLACEHOLDER = 0; /** * @notice requestRandomness initiates a request for VRF output given _seed * * @dev The fulfillRandomness method receives the output, once it's provided * @dev by the Oracle, and verified by the vrfCoordinator. * * @dev The _keyHash must already be registered with the VRFCoordinator, and * @dev the _fee must exceed the fee specified during registration of the * @dev _keyHash. * * @dev The _seed parameter is vestigial, and is kept only for API * @dev compatibility with older versions. It can't *hurt* to mix in some of * @dev your own randomness, here, but it's not necessary because the VRF * @dev oracle will mix the hash of the block containing your request into the * @dev VRF seed it ultimately uses. * * @param _keyHash ID of public key against which randomness is generated * @param _fee The amount of LINK to send with the request * * @return requestId unique ID for this request * * @dev The returned requestId can be used to distinguish responses to * @dev concurrent requests. It is passed as the first argument to * @dev fulfillRandomness. */ function requestRandomness(bytes32 _keyHash, uint256 _fee) internal returns (bytes32 requestId) { LINK.transferAndCall(vrfCoordinator, _fee, abi.encode(_keyHash, USER_SEED_PLACEHOLDER)); // This is the seed passed to VRFCoordinator. The oracle will mix this with // the hash of the block containing this request to obtain the seed/input // which is finally passed to the VRF cryptographic machinery. uint256 vRFSeed = makeVRFInputSeed(_keyHash, USER_SEED_PLACEHOLDER, address(this), nonces[_keyHash]); // nonces[_keyHash] must stay in sync with // VRFCoordinator.nonces[_keyHash][this], which was incremented by the above // successful LINK.transferAndCall (in VRFCoordinator.randomnessRequest). // This provides protection against the user repeating their input seed, // which would result in a predictable/duplicate output, if multiple such // requests appeared in the same block. nonces[_keyHash] = nonces[_keyHash] + 1; return makeRequestId(_keyHash, vRFSeed); } LinkTokenInterface internal immutable LINK; address private immutable vrfCoordinator; // Nonces for each VRF key from which randomness has been requested. // // Must stay in sync with VRFCoordinator[_keyHash][this] mapping(bytes32 => uint256) /* keyHash */ /* nonce */ private nonces; /** * @param _vrfCoordinator address of VRFCoordinator contract * @param _link address of LINK token contract * * @dev https://docs.chain.link/docs/link-token-contracts */ constructor(address _vrfCoordinator, address _link) { vrfCoordinator = _vrfCoordinator; LINK = LinkTokenInterface(_link); } // rawFulfillRandomness is called by VRFCoordinator when it receives a valid VRF // proof. rawFulfillRandomness then calls fulfillRandomness, after validating // the origin of the call function rawFulfillRandomness(bytes32 requestId, uint256 randomness) external { require(msg.sender == vrfCoordinator, "Only VRFCoordinator can fulfill"); fulfillRandomness(requestId, randomness); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; contract BlockBasedSale is Ownable { using SafeMath for uint256; enum OverrideSaleState { None, Pause, Close } enum SalePhase { None, Private, Public } OverrideSaleState public overridedSaleState = OverrideSaleState.None; SalePhase public salePhase = SalePhase.None; uint256 public maxPrivateSalePerTx = 10; uint256 public maxPublicSalePerTx = 20; uint256 public maxWhitelistClaimPerWallet = 10; uint256 public privateSaleCapped = 690; uint256 public totalPrivateSaleMinted = 0; uint256 public privateSalePrice; uint256 public totalPublicMinted = 0; uint256 public totalReserveMinted = 0; uint256 public maxSupply = 6969; uint256 public maxReserve = 169; uint256 public discountBlockSize = 180; uint256 public lowerBoundPrice = 0; uint256 public publicSalePrice; uint256 public priceFactor = 1337500000000000; struct SaleConfig { uint256 beginBlock; uint256 endBlock; } SaleConfig public privateSale; SaleConfig public publicSale; function setDiscountBlockSize(uint256 blockNumber) external onlyOwner { discountBlockSize = blockNumber; } function setPriceDecayParams(uint256 _lowerBoundPrice, uint256 _priceFactor) external onlyOwner{ require(_lowerBoundPrice >= 0); require(_priceFactor <= publicSalePrice); lowerBoundPrice = _lowerBoundPrice; priceFactor = _priceFactor; } function setTransactionLimit(uint256 privateSaleLimit,uint256 publicSaleLimit, uint256 maxWhitelist) external onlyOwner { require(privateSaleLimit > 0); require(publicSaleLimit > 0); require(maxWhitelist <= privateSaleLimit); maxPrivateSalePerTx = privateSaleLimit; maxPublicSalePerTx = publicSaleLimit; maxWhitelistClaimPerWallet = maxWhitelist; } function setPrivateSaleConfig(SaleConfig memory _privateSale) external onlyOwner { privateSale = _privateSale; } function setPublicSaleConfig(SaleConfig memory _publicSale) external onlyOwner { publicSale = _publicSale; } function setPublicSalePrice(uint256 _price) external onlyOwner { publicSalePrice = _price; } function setPrivateSalePrice(uint256 _price) external onlyOwner { privateSalePrice = _price; } function setCloseSale() external onlyOwner { overridedSaleState = OverrideSaleState.Close; } function setPauseSale() external onlyOwner { overridedSaleState = OverrideSaleState.Pause; } function resetOverridedSaleState() external onlyOwner { overridedSaleState = OverrideSaleState.None; } function setReserve(uint256 reserve) external onlyOwner { maxReserve = reserve; } function setPrivateSaleCap(uint256 cap) external onlyOwner { privateSaleCapped = cap; } function isPrivateSaleSoldOut() external view returns (bool) { return totalPrivateSaleMinted == privateSaleCapped; } function isPublicSaleSoldOut() external view returns (bool) { uint256 supplyWithoutReserve = maxSupply - maxReserve; uint256 mintedWithoutReserve = totalPublicMinted + totalPrivateSaleMinted; return supplyWithoutReserve == mintedWithoutReserve; } function enablePublicSale() external onlyOwner { salePhase = SalePhase.Public; } function enablePrivateSale() external onlyOwner { salePhase = SalePhase.Private; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; contract EIP712Whitelisting is Ownable { using ECDSA for bytes32; // The key used to sign whitelist signatures. // We will check to ensure that the key that signed the signature // is this one that we expect. address whitelistSigningKey = address(0); // Domain Separator is the EIP-712 defined structure that defines what contract // and chain these signatures can be used for. This ensures people can't take // a signature used to mint on one contract and use it for another, or a signature // from testnet to replay on mainnet. // It has to be created in the constructor so we can dynamically grab the chainId. // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-712.md#definition-of-domainseparator bytes32 public DOMAIN_SEPARATOR; // The typehash for the data type specified in the structured data // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-712.md#rationale-for-typehash // This should match whats in the client side whitelist signing code bytes32 public constant MINTER_TYPEHASH = keccak256("Minter(address wallet)"); constructor() { // This should match whats in the client side whitelist signing code DOMAIN_SEPARATOR = keccak256( abi.encode( keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" ), // This should match the domain you set in your client side signing. keccak256(bytes("WhitelistToken")), keccak256(bytes("1")), block.chainid, address(this) ) ); } function setWhitelistSigningAddress(address newSigningKey) public onlyOwner { whitelistSigningKey = newSigningKey; } modifier requiresWhitelist(bytes calldata signature) { require(whitelistSigningKey != address(0), "whitelist not enabled."); require( getEIP712RecoverAddress(signature) == whitelistSigningKey, "Not whitelisted." ); _; } function isEIP712WhiteListed(bytes calldata signature) public view returns (bool) { require(whitelistSigningKey != address(0), "whitelist not enabled."); return getEIP712RecoverAddress(signature) == whitelistSigningKey; } function getEIP712RecoverAddress(bytes calldata signature) internal view returns (address) { // Verify EIP-712 signature by recreating the data structure // that we signed on the client side, and then using that to recover // the address that signed the signature for this data. // Signature begin with \x19\x01, see: https://eips.ethereum.org/EIPS/eip-712 bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR, keccak256(abi.encode(MINTER_TYPEHASH, msg.sender)) ) ); // Use the recover method to see what address was used to create // the signature on this data. // Note that if the digest doesn't exactly match what was signed we'll // get a random recovered address. return digest.recover(signature); } } // 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 (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: 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 pragma solidity ^0.8.0; interface LinkTokenInterface { function allowance(address owner, address spender) external view returns (uint256 remaining); function approve(address spender, uint256 value) external returns (bool success); function balanceOf(address owner) external view returns (uint256 balance); function decimals() external view returns (uint8 decimalPlaces); function decreaseApproval(address spender, uint256 addedValue) external returns (bool success); function increaseApproval(address spender, uint256 subtractedValue) external; function name() external view returns (string memory tokenName); function symbol() external view returns (string memory tokenSymbol); function totalSupply() external view returns (uint256 totalTokensIssued); function transfer(address to, uint256 value) external returns (bool success); function transferAndCall( address to, uint256 value, bytes calldata data ) external returns (bool success); function transferFrom( address from, address to, uint256 value ) external returns (bool success); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; contract VRFRequestIDBase { /** * @notice returns the seed which is actually input to the VRF coordinator * * @dev To prevent repetition of VRF output due to repetition of the * @dev user-supplied seed, that seed is combined in a hash with the * @dev user-specific nonce, and the address of the consuming contract. The * @dev risk of repetition is mostly mitigated by inclusion of a blockhash in * @dev the final seed, but the nonce does protect against repetition in * @dev requests which are included in a single block. * * @param _userSeed VRF seed input provided by user * @param _requester Address of the requesting contract * @param _nonce User-specific nonce at the time of the request */ function makeVRFInputSeed( bytes32 _keyHash, uint256 _userSeed, address _requester, uint256 _nonce ) internal pure returns (uint256) { return uint256(keccak256(abi.encode(_keyHash, _userSeed, _requester, _nonce))); } /** * @notice Returns the id for this request * @param _keyHash The serviceAgreement ID to be used for this request * @param _vRFInputSeed The seed to be passed directly to the VRF * @return The id for this request * * @dev Note that _vRFInputSeed is not the seed passed by the consuming * @dev contract, but the one generated by makeVRFInputSeed */ function makeRequestId(bytes32 _keyHash, uint256 _vRFInputSeed) internal pure returns (bytes32) { return keccak256(abi.encodePacked(_keyHash, _vRFInputSeed)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/cryptography/ECDSA.sol) pragma solidity ^0.8.0; import "../Strings.sol"; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, InvalidSignatureV } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert("ECDSA: invalid signature"); } else if (error == RecoverError.InvalidSignatureLength) { revert("ECDSA: invalid signature length"); } else if (error == RecoverError.InvalidSignatureS) { revert("ECDSA: invalid signature 's' value"); } else if (error == RecoverError.InvalidSignatureV) { revert("ECDSA: invalid signature 'v' value"); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return tryRecover(hash, r, vs); } else { return (address(0), RecoverError.InvalidSignatureLength); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */ function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address, RecoverError) { bytes32 s; uint8 v; assembly { s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) v := add(shr(255, vs), 27) } return tryRecover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. * * _Available since v4.2._ */ function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. * * _Available since v4.3._ */ function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return (address(0), RecoverError.InvalidSignatureS); } if (v != 27 && v != 28) { return (address(0), RecoverError.InvalidSignatureV); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, v, r, s); _throwError(error); return recovered; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } /** * @dev Returns an Ethereum Signed Message, created from `s`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } }
The key used to sign whitelist signatures. We will check to ensure that the key that signed the signature is this one that we expect. Domain Separator is the EIP-712 defined structure that defines what contract and chain these signatures can be used for. This ensures people can't take a signature used to mint on one contract and use it for another, or a signature from testnet to replay on mainnet. It has to be created in the constructor so we can dynamically grab the chainId. https:github.com/ethereum/EIPs/blob/master/EIPS/eip-712.md#definition-of-domainseparator The typehash for the data type specified in the structured data https:github.com/ethereum/EIPs/blob/master/EIPS/eip-712.md#rationale-for-typehash This should match whats in the client side whitelist signing code
contract EIP712Whitelisting is Ownable { using ECDSA for bytes32; address whitelistSigningKey = address(0); bytes32 public DOMAIN_SEPARATOR; bytes32 public constant MINTER_TYPEHASH = keccak256("Minter(address wallet)"); pragma solidity ^0.8.4; constructor() { DOMAIN_SEPARATOR = keccak256( abi.encode( keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" ), keccak256(bytes("WhitelistToken")), keccak256(bytes("1")), block.chainid, address(this) ) ); } function setWhitelistSigningAddress(address newSigningKey) public onlyOwner { whitelistSigningKey = newSigningKey; } modifier requiresWhitelist(bytes calldata signature) { require(whitelistSigningKey != address(0), "whitelist not enabled."); require( getEIP712RecoverAddress(signature) == whitelistSigningKey, "Not whitelisted." ); _; } function isEIP712WhiteListed(bytes calldata signature) public view returns (bool) { require(whitelistSigningKey != address(0), "whitelist not enabled."); return getEIP712RecoverAddress(signature) == whitelistSigningKey; } function getEIP712RecoverAddress(bytes calldata signature) internal view returns (address) { bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR, keccak256(abi.encode(MINTER_TYPEHASH, msg.sender)) ) ); return digest.recover(signature); } }
437,485
[ 1, 1986, 498, 1399, 358, 1573, 10734, 14862, 18, 1660, 903, 866, 358, 3387, 716, 326, 498, 716, 6726, 326, 3372, 353, 333, 1245, 716, 732, 4489, 18, 6648, 27519, 353, 326, 512, 2579, 17, 27, 2138, 2553, 3695, 716, 11164, 4121, 6835, 471, 2687, 4259, 14862, 848, 506, 1399, 364, 18, 225, 1220, 11932, 16951, 848, 1404, 4862, 279, 3372, 1399, 358, 312, 474, 603, 1245, 6835, 471, 999, 518, 364, 4042, 16, 578, 279, 3372, 628, 1842, 2758, 358, 16033, 603, 2774, 2758, 18, 2597, 711, 358, 506, 2522, 316, 326, 3885, 1427, 732, 848, 18373, 11086, 326, 2687, 548, 18, 2333, 30, 6662, 18, 832, 19, 546, 822, 379, 19, 41, 18246, 19, 10721, 19, 7525, 19, 41, 2579, 55, 19, 73, 625, 17, 27, 2138, 18, 1264, 6907, 17, 792, 17, 4308, 11287, 1021, 618, 2816, 364, 326, 501, 618, 1269, 316, 326, 19788, 501, 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, 512, 2579, 27, 2138, 18927, 310, 353, 14223, 6914, 288, 203, 565, 1450, 7773, 19748, 364, 1731, 1578, 31, 203, 203, 565, 1758, 10734, 12322, 653, 273, 1758, 12, 20, 1769, 203, 203, 565, 1731, 1578, 1071, 27025, 67, 4550, 31, 203, 203, 565, 1731, 1578, 1071, 5381, 6989, 2560, 67, 2399, 15920, 273, 203, 3639, 417, 24410, 581, 5034, 2932, 49, 2761, 12, 2867, 9230, 2225, 1769, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 24, 31, 203, 565, 3885, 1435, 288, 203, 3639, 27025, 67, 4550, 273, 417, 24410, 581, 5034, 12, 203, 5411, 24126, 18, 3015, 12, 203, 7734, 417, 24410, 581, 5034, 12, 203, 10792, 315, 41, 2579, 27, 2138, 3748, 12, 1080, 508, 16, 1080, 1177, 16, 11890, 5034, 2687, 548, 16, 2867, 3929, 310, 8924, 2225, 203, 7734, 262, 16, 203, 7734, 417, 24410, 581, 5034, 12, 3890, 2932, 18927, 1345, 7923, 3631, 203, 7734, 417, 24410, 581, 5034, 12, 3890, 2932, 21, 7923, 3631, 203, 7734, 1203, 18, 5639, 350, 16, 203, 7734, 1758, 12, 2211, 13, 203, 5411, 262, 203, 3639, 11272, 203, 565, 289, 203, 203, 565, 445, 444, 18927, 12322, 1887, 12, 2867, 394, 12322, 653, 13, 203, 3639, 1071, 203, 3639, 1338, 5541, 203, 565, 288, 203, 3639, 10734, 12322, 653, 273, 394, 12322, 653, 31, 203, 565, 289, 203, 203, 565, 9606, 4991, 18927, 12, 3890, 745, 892, 3372, 13, 288, 203, 3639, 2583, 12, 20409, 12322, 653, 480, 1758, 12, 20, 3631, 315, 20409, 486, 3696, 1199, 2 ]
//https://solidity.readthedocs.io/en/v0.5.11/index.html ///@dev: this version requires conversion of string to string memory pragma solidity ^0.5.11; ///@dev: The ABI v2 encoder allows structs, nested and dynamic variables to be passed/returned into/from functions/events ///@dev: do not use ABIEncoderV2 on live/release deployments pragma experimental ABIEncoderV2; import "./Owned.sol"; /// @author Pedro Azevedo [email protected] /// @title SCM is a Supply Chain Management contract supporting traceability, provenance and chain of custody contract SCM is Owned{ /** /* SCM Actor Management */ /// SCM Actor struct struct SCActor { uint40 companyPrefix; // store the prefix to validate against the EPC address actorAddress; actorType actorRole; bool registered; bool validated; } enum actorType { SUPPLIER, TRANSFORMATION, LOGISTICS, RETAILERS, MANAGER } /// mapping with struct has some advantages for unique Ids - https://ethfiddle.com/PgDM-drAc9 mapping (address => SCActor) scActors; mapping (uint40 => address) companyPrefixToactorAddress; /// After call registerActor(): Event to request import of ID and certificates of SC Actor event importIDCertificate( address actorAddress, uint prefix ); /// After event importIDCertificate(): Event to request validation of ID and certificates of SC Actor event RequestKYC( address actorAddress, uint prefix ); /// After call registerProduct(): Event to request import of ID and certificates of product event importEPCCertificate( address callerAddress, uint96 EPC ); /// Event to request validation of ID and certificates of SC Actor event RequestKYP( address certificateOwnerAddress, //the Actor that will be able to view the certificate via the SCM url address viewerAddress, uint96 EPC ); /** /* The Certificate Validator role (SCM Manager) is Required * The SCM Manager/Validator is responsible to validate the SCA identities * (hash verification has to be done off chain due to EVM hasing costs) * and when product certificates are imported into the Store he will be the owner/ID * of the product certificates in order to be able to respond to other SCAs/customer certificate * verification requests */ address validatorAddress; /// ValidateID: onlyValidator modifier onlyValidator{ require(msg.sender == validatorAddress,"Only the validator may call this function"); _; } /// Only supplier can register products modifier isSupplier { require(getActorRole(msg.sender) == actorType.SUPPLIER, "Only suppliers can register products"); _; } /// Only supplier can register products modifier isTransformation { require(getActorRole(msg.sender) == actorType.TRANSFORMATION, "Only Transformation actor can transform products"); _; } /// Only supplier can register products modifier isNotManager { require(getActorRole(msg.sender) != actorType.MANAGER, "Function not accessible to SC Manager"); _; } /// Only validated SCM Actors can operate on products modifier isAddressFromCaller(address actorAddress_) { require(msg.sender==actorAddress_, "Only caller/owner may call this"); _; } /// Only validated SCM Actors can operate on products modifier isAddressValidated(address addressToValidate_) { require(isActorValidated(addressToValidate_), "Only validated SC Actors can operate"); _; } /// Only validated SCM Actors can operate on products modifier isAddressRegistered(address addressToCheck_) { require(isActorRegistered(addressToCheck_), "Address is not a registered SC Actor"); _; } /// ValidateID: Set validator wallet address function setValidator(address validatorAddress_) public onlyOwner{ validatorAddress=validatorAddress_; scActors[validatorAddress_].actorAddress=validatorAddress_; scActors[validatorAddress_].actorRole=actorType.MANAGER; scActors[validatorAddress_].registered=true; scActors[validatorAddress_].validated=true; } /// Helper function function setActorAsValidated(address actorAddress_, bool validated_) internal returns (bool ret) { scActors[actorAddress_].validated=validated_; return true; } /// Helper function function getActorAddress(uint40 prefix_) internal view returns (address) { return companyPrefixToactorAddress[prefix_]; } /// Helper function function getActorRole(address actorAddress_) internal view returns (actorType) { return scActors[actorAddress_].actorRole; } /// Helper function function isActorValidated(address actorAddress_) internal view returns(bool ret){ return scActors[actorAddress_].validated; } /// Helper function function isActorRegistered(address addressToCheck_) internal view returns(bool ret){ return scActors[addressToCheck_].registered; } /// @notice Implements the use case: register Actor /// @dev Emits event to start the use case: ValidateID (access control) function registerActor (address actorAddress_, uint40 prefix_, actorType actorRole_) public { scActors[actorAddress_].companyPrefix=prefix_; scActors[actorAddress_].actorAddress=msg.sender; scActors[actorAddress_].actorRole=actorRole_; scActors[actorAddress_].registered=true; companyPrefixToactorAddress[prefix_]=msg.sender; //Start the SCA certificate validation: import the ID and Certificates emit importIDCertificate(actorAddress_, prefix_); } /** /* Interworking with WallId Architecture */ /// @notice called by User after successful importIDCertificate function IDCertificateImported(address actorAddress_, uint40 prefix_) public{ emit RequestKYC(actorAddress_, prefix_); } /// @notice Called by CertificateValidator after KYC(Actor) has been completed - only CertificateValidator address may call this function KYCcompleted(address actorAddress_) public onlyValidator{ setActorAsValidated(actorAddress_, true); } /// @notice called by User after successful importEPCCertificate function ProductCertificateImported(address actorAddress_, uint96 EPC_) public{ //request KYP for the ownerAddress which in this case is also the the viewerAddress emit RequestKYP(actorAddress_, actorAddress_, EPC_); } /// @notice Called by CertificateValidator after KYP (Product) has been completed - only CertificateValidator address may call this function KYPcompleted(uint96 EPC_) public onlyValidator{ setProductAsCertified(EPC_, true); } /** /* SCM Product Management */ struct productData { address certificateOwner; //references the certificate owner uint96 certificateEPC; //references the EPC that has certificate bool hasCertificate; address owner; //references the current owner of the custodyState custody; bool exists; address nextOwner; geoPosition location; uint96 previousEPC; //used to maintain traceability of certificates uint96 myEPC; //no need to add Time data since all Transactions are visible and TimeStamped } enum custodyState {inControl, inTransfer, lost, consumed, sold} /// 32 bits seems enough for location database - https://www.thethingsnetwork.org/forum/t/best-practices-when-sending-gps-location-data/1242 struct geoPosition{ uint32 latitude; uint32 longitude; uint16 altitude; } /// Map with all products by EPC mapping (uint96 => productData) public productMap; /* reduce storage by removing product balance per owner struct ownedEPCs { uint96[] myOwnedEPCS; //dynamic size array mapping(uint96 => uint) epcPointers; } /// Map with products by owner mapping (address => ownedEPCs) internal ownerProducts; */ /** /* SCM Product Function Modifiers */ /// EPC format must be correct modifier isEPCcorrect(uint96 EPC_,address callerAddress_){ require(verifyEPC(EPC_,callerAddress_), "The EPC does not belong to the caller company - malformed/incorrect EPC"); _; } /// EPC must not have been registered modifier notRegisteredEPC(uint96 EPC_) { require(!isMember(EPC_),"Product already registered. Enter a different EPC"); _; } /// EPC must have been registered modifier isRegisteredEPC(uint96 EPC_) { require(isMember(EPC_),"Product not registered. Register product first"); _; } /* modifier ownerHasProducts(){ require(haveProducts(msg.sender),"Caller does not have any products. Add products first"); _; } */ /// EPC must belong to caller modifier isCallerCurrentOwner(uint96 EPC_){ require(getCurrentOwner(EPC_)==msg.sender,"Caller is not the product owner. Request transfer ownership first"); _; } /// EPC state must be inControl before transfer modifier isStateOwned(uint96 EPC_){ require(getCurrentState(EPC_)==custodyState.inControl, "Current state of product does not allow transfer"); _; } /// EPC nextOwner was marked as the caller modifier isPreviousOwner(uint96 EPC_,address previousOwner_){ require(getCurrentOwner(EPC_)==previousOwner_,"That owner did not sign off this product. Request transfer ownership first"); _; } /// EPC nextOwner was marked as the caller modifier isCallerNextOwner(uint96 EPC_){ require(getNextOwner(EPC_)==msg.sender,"Caller is not signed as the next product owner. Request transfer ownership first"); _; } /// EPC state must be inTransfer before final change of custody modifier isStateinTransfer(uint96 EPC_){ require(getCurrentState(EPC_)==custodyState.inTransfer, "Current state of product does not allow transfer"); _; } /// EPC validated flag must be set before certificates can be retrieved modifier isEPCCertified(uint96 EPC_){ require(isEPCValidated(EPC_), "Product with given EPC is not certified"); _; } /** /* SCM Product Internal Helper Functions */ /// Internal Helper function function isMember(uint96 EPC_) internal view returns(bool retExists) { return productMap[EPC_].exists; } /// Helper function function extractPrefix(uint96 EPC_) internal pure returns (uint40 ret){ return uint40(EPC_ >> 42); } /// Internal Helper function function verifyEPC(uint96 EPC_,address callerAddress_) internal view returns (bool ret){ if( getActorAddress(extractPrefix(EPC_)) == callerAddress_ ) return true; else return false; } /// Internal Helper function function isEPCValidated(uint96 EPC_) internal view returns (bool ret){ if( productMap[EPC_].hasCertificate==true ) return true; else return false; } /// Internal Helper function function isStateSold(uint96 EPC_) internal view returns (bool ret){ if(getCurrentState(EPC_)==custodyState.sold) return true; else return false; } /* next code commented to remove balance of products /// Internal Helper function function haveProducts(address ownerAddress_) internal view returns (bool ret){ if(ownerProducts[ownerAddress_].myOwnedEPCS.length != 0) return true; else return false; } /// Helper function function getEPCPointer(address ownerAddress_, uint96 EPC_) internal view returns (uint ret){ return ownerProducts[ownerAddress_].epcPointers[EPC_]; } /// Internal Helper function function existsEPC(address ownerAddress_, uint96 EPC_) internal view returns (bool ret){ if(ownerProducts[ownerAddress_].myOwnedEPCS[getEPCPointer(ownerAddress_,EPC_)] == EPC_) return true; else return false; } /// Internal Helper function function isEPCOwned(address ownerAddress_, uint96 EPC_) internal view returns(bool isOwned) { if(!haveProducts(ownerAddress_)) return false; else return existsEPC(ownerAddress_,EPC_); } /// Internal Helper function - TODO TEST function deleteEPC(address ownerAddress_, uint96 EPC_) internal { ownedEPCs storage temp = ownerProducts[ownerAddress_]; require(isEPCOwned(ownerAddress_, EPC_)); uint indexToDelete = temp.epcPointers[EPC_]; //no need to delete epcPointers => initialized HashMap temp.myOwnedEPCS[indexToDelete] = temp.myOwnedEPCS[temp.myOwnedEPCS.length-1]; //move to Last temp.myOwnedEPCS.length--; //deleteLast } /// Internal Helper function - TODO TEST function addEPC(address ownerAddress_, uint96 EPC_) internal { uint epcPointer = ownerProducts[ownerAddress_].myOwnedEPCS.push(EPC_)-1; ownerProducts[ownerAddress_].epcPointers[EPC_]=epcPointer; } */ /// @notice When the product is to be sold the owner is the SC Manager function setManagerAsOwner( uint96 EPC_) internal returns (bool ret){ productMap[EPC_].owner = validatorAddress; productMap[EPC_].nextOwner = validatorAddress; return true; } /// Internal Helper function /// SCAs can view certificate and Customer by proxy if product is in sale (role=MANAGER) function isCallerAllowedToViewCertificate(address callerAddress_,uint96 EPC_) internal view returns(bool retAllowed){ //either it is the owner of the product if(getCurrentOwner(EPC_)==callerAddress_) return true; //or it is a customer by proxy of SC manager else if(validatorAddress==callerAddress_) { if(isStateSold(EPC_)) return true; else return false; } else return false; } /** /* SCM Product GET/SET Use case functions */ /* next code commented to remove balance of products /// @notice Implements the use case: getEPCBalance /// TODO TEST function getEPCBalance(address ownerAddress_) isNotManager isAddressValidated(msg.sender) isAddressFromCaller(ownerAddress_) public view returns (uint ret){ if(haveProducts(ownerAddress_)) return ownerProducts[ownerAddress_].myOwnedEPCS.length; else return 0; } /// @notice Implements the use case: getMyEPCs /// TODO TEST function getMyEPCs(address ownerAddress_) isNotManager isAddressValidated(msg.sender) isAddressFromCaller(ownerAddress_) ownerHasProducts public view returns (uint96[] memory ret){ require(haveProducts(ownerAddress_),"You have no products registered"); return ownerProducts[msg.sender].myOwnedEPCS; } */ /// @notice Implements the use case: getCurrentOwner function getCurrentOwner(uint96 EPC_) isAddressValidated(msg.sender) isRegisteredEPC(EPC_) public view returns (address retOwner) { return productMap[EPC_].owner; } /// @notice Implements the use case: getNextOwner function getNextOwner(uint96 EPC_) isNotManager isAddressValidated(msg.sender) isRegisteredEPC(EPC_) view public returns (address ret_nextOwnerAddress) { return productMap[EPC_].nextOwner; } /// @notice Implements the use case: getCurrentState function getCurrentState(uint96 EPC_) isCallerCurrentOwner(EPC_) //only owner can view the state isAddressValidated(msg.sender) isRegisteredEPC(EPC_) public view returns (custodyState ret_state) { return productMap[EPC_].custody; } /// @notice Implements the use case: getCurrentLocation function getCurrentLocation(uint96 EPC_) isCallerCurrentOwner(EPC_) //only owner can view the state isAddressValidated(msg.sender) isRegisteredEPC(EPC_) public view returns (geoPosition memory ret_location) { return productMap[EPC_].location; } /// @notice Helper function: getCertificateOwner function getCertificateOwner(uint96 EPC_) isCallerCurrentOwner(EPC_) //only owner can view the state isAddressValidated(msg.sender) isRegisteredEPC(EPC_) isEPCCertified(EPC_) public view returns (address ret_address) { return productMap[EPC_].certificateOwner; } /// @notice Helper function: getCertificateOwner function getCertificateEPC(uint96 EPC_) isCallerCurrentOwner(EPC_) //only owner can view the state isAddressValidated(msg.sender) isRegisteredEPC(EPC_) isEPCCertified(EPC_) public view returns (uint96 ret_EPC) { return productMap[EPC_].certificateEPC; } /// @notice Implements the use case: setCurrentState /// Actors can additionally set the role: sold - to indicate that /// certificate information can now be retrieved by SC Manager function setCurrentState(uint96 EPC_,custodyState state_) isAddressValidated(msg.sender) isRegisteredEPC(EPC_) isCallerCurrentOwner(EPC_) public returns (bool ret) { productMap[EPC_].custody= state_; return true; } /// @notice Implements the use case: setCurrentLocation function setCurrentLocation(uint96 EPC_, geoPosition memory location_) isAddressValidated(msg.sender) isRegisteredEPC(EPC_) isCallerCurrentOwner(EPC_) public returns (bool ret) { productMap[EPC_].location=location_; return true; } /// @notice Implements the use case: setProductAsCertified function setProductAsCertified(uint96 EPC_, bool certified_) isAddressValidated(msg.sender) isRegisteredEPC(EPC_) isCallerCurrentOwner(EPC_) public returns (bool ret) { productMap[EPC_].certificateOwner=getCurrentOwner(EPC_); productMap[EPC_].certificateEPC=EPC_; productMap[EPC_].hasCertificate=certified_; return true; } //TODO when to release memory of sold products? /// @notice Implements setProductAsSold function setProductAsSold(uint96 EPC_) isAddressValidated(msg.sender) isRegisteredEPC(EPC_) isCallerCurrentOwner(EPC_) public returns (bool ret) { setCurrentState( EPC_,custodyState.sold); if(setManagerAsOwner(EPC_)) return true; else return false; } /* * MAJOR USE CASES */ /// @notice Implements the use case: getProductCertificate function getProductCertificate(uint96 EPC_) isAddressValidated(msg.sender) isRegisteredEPC(EPC_) isEPCCertified(EPC_) public returns (bool ret) { //Can view Certificate if he is the owner of the EPC or if the product has been sold the customer by proxy to SCM if(isCallerAllowedToViewCertificate(msg.sender,EPC_)){ emit RequestKYP(getCertificateOwner(EPC_), msg.sender, getCertificateEPC(EPC_)); return true; } else return false; } /// @notice Implements the use case: register Product // https://github.com/ethereum/solidity/releases/tag/v0.5.7 has fix for ABIEncoderV2 function registerProduct(address callerAddress_, uint96 EPC_, geoPosition memory _location ) isAddressValidated(msg.sender) isSupplier isAddressFromCaller(callerAddress_) isEPCcorrect(EPC_,callerAddress_) notRegisteredEPC(EPC_) public returns (bool ret){ productMap[EPC_].owner = callerAddress_; productMap[EPC_].custody = custodyState.inControl; productMap[EPC_].exists = true; productMap[EPC_].nextOwner = callerAddress_; productMap[EPC_].location = _location; productMap[EPC_].myEPC = EPC_; //next line commented to remove balance of products //addEPC(callerAddress_, EPC_); //Start the Product certificate validation: import the ID and Certificates emit importEPCCertificate(callerAddress_, EPC_); return true; } /// @notice Implements the use case: transfer Ownership TO function transferTO( address addressTO_, uint96 EPC_) isNotManager isAddressValidated(msg.sender) isAddressValidated(addressTO_) isRegisteredEPC(EPC_) isCallerCurrentOwner(EPC_) isStateOwned(EPC_) public returns (bool ret){ productMap[EPC_].custody = custodyState.inTransfer; productMap[EPC_].nextOwner = addressTO_; return true; } /// @notice Implements the use case: transfer Ownership TO function receiveFROM( address addressFROM_, uint96 EPC_) isNotManager isAddressValidated(msg.sender) isPreviousOwner(EPC_,addressFROM_) isRegisteredEPC(EPC_) isCallerNextOwner(EPC_) isStateinTransfer(EPC_) public returns (bool ret){ productMap[EPC_].owner = msg.sender; productMap[EPC_].custody = custodyState.inControl; productMap[EPC_].nextOwner = msg.sender; return true; } /// @notice Implements the use case: lostProduct function lostProduct(uint96 EPC_) isNotManager isAddressValidated(msg.sender) isPreviousOwner(EPC_,msg.sender) isRegisteredEPC(EPC_) public returns (bool ret){ setCurrentState( EPC_,custodyState.lost ); productMap[EPC_].owner = msg.sender; productMap[EPC_].nextOwner = msg.sender; //next line commented to remove balance of products //deleteEPC(msg.sender, EPC_); return true; } /// @notice Implements the use case: transformProduct /// @dev first register new EPC --> TransformProduct function transformProduct(uint96 oldEPC_,uint96 newEPC_) isTransformation isAddressValidated(msg.sender) isPreviousOwner(oldEPC_,msg.sender) isRegisteredEPC(oldEPC_) isRegisteredEPC(newEPC_) isStateOwned(oldEPC_) public returns (bool ret){ setCurrentState( oldEPC_,custodyState.consumed ); productMap[oldEPC_].owner = msg.sender; productMap[oldEPC_].nextOwner = msg.sender; //Create new product with reference to old product productMap[newEPC_].owner = msg.sender; productMap[newEPC_].custody = custodyState.inControl; productMap[newEPC_].exists = true; productMap[newEPC_].location = productMap[oldEPC_].location; productMap[newEPC_].myEPC = newEPC_; productMap[newEPC_].previousEPC=oldEPC_; //next 2 lines commented to remove balance of products //deleteEPC(msg.sender, oldEPC_); remove balance of products //addEPC(msg.sender, newEPC_); remove balance of products return true; } } //END
Internal Helper function - TODO TEST
function deleteEPC(address ownerAddress_, uint96 EPC_) internal { ownedEPCs storage temp = ownerProducts[ownerAddress_]; require(isEPCOwned(ownerAddress_, EPC_)); }
7,237,314
[ 1, 3061, 9705, 445, 300, 2660, 22130, 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, 1430, 41, 3513, 12, 2867, 3410, 1887, 67, 16, 2254, 10525, 512, 3513, 67, 13, 2713, 288, 203, 3639, 16199, 41, 3513, 87, 2502, 1906, 273, 3410, 13344, 63, 8443, 1887, 67, 15533, 203, 3639, 2583, 12, 291, 41, 3513, 5460, 329, 12, 8443, 1887, 67, 16, 512, 3513, 67, 10019, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import '@openzeppelin/contracts/token/ERC721/ERC721.sol'; import '@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol'; import '@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol'; import '@openzeppelin/contracts/access/Ownable.sol'; import '@openzeppelin/contracts/utils/math/SafeMath.sol'; import '@openzeppelin/contracts/utils/Counters.sol'; import './ERC721Pausable.sol'; import '@chainlink/contracts/src/v0.8/VRFConsumerBase.sol'; contract AccessPass is ERC721, ERC721Enumerable, Ownable, ERC721Pausable, VRFConsumerBase { bytes32 internal keyHash; uint256 internal fee; uint256 public randomResult; using SafeMath for uint256; using Counters for Counters.Counter; Counters.Counter private _tokenIdTracker; // Defines the different stages of the game enum GameState { PREMINT, // Before the game, when minting is not available yet. MINTING, // Before the game, when minting is available to the public. STARTED, // During one of the rounds of the game. FINISHED // After the game, when there is a winner. } // Global vars bool private _isAdminBurnEnabled = false; // Flag to indicate whether the admin should be able to burn the supply bool private creatorHasClaimed = false; // Flag to indicate whether the creator has claimed reward uint256 public currentRound = 0; // Tracks the current round uint256 public currentBurn = 0; // Tracks the number of burns that have been requested so far string public baseTokenURI; // Base token URI address public winnerAddress; // The address of the winner of the game GameState public gameState; // The current state of the game uint256 public roundTime = 1 hours; uint256 public roundStartedAt = 0; // Constants uint256 public constant NUM_ROUNDS = 7; // Number of rounds this game will last uint256 public constant MAX_ELEMENTS = 2**NUM_ROUNDS; // Max number of tokens minted uint256 public constant PRICE = 1 * 10**20; // Price to mint a single token, 100 MATIC uint256 public constant MAX_BY_MINT = 5; // Max number of tokens to be minted in a single transaction uint256 public constant CREATOR_PERCENTAGE = 20; // Percentage given to creators constructor(string memory baseURI, string burningBallURI) ERC721('Squid Arena', 'SQUID') VRFConsumerBase( 0x8C7382F9D8f56b33781fE506E897a4F1e2d17255, // VRF Coordinator (Mumbai) 0x326C977E6efc84E512bB9C30f76E30c160eD06FB // LINK Contract Token (Mumbai) ) { keyHash = 0x6e75b569a01ef56d18cab6a8e71e6600d6ce853834d4a5748b720d06f878b3a4; fee = 1 * 10**14; // 0.0001 LINK (Varies by network) setBaseURI(baseURI); pause(true); gameState = GameState.PREMINT; } modifier saleIsOpen() { require(_totalSupply() <= MAX_ELEMENTS, 'Sale end'); if (_msgSender() != owner()) { require(!paused(), 'Pausable: paused'); } _; } function _totalSupply() internal view returns (uint256) { return _tokenIdTracker.current(); } function totalMint() public view returns (uint256) { return _totalSupply(); } function mint(address _to) public payable saleIsOpen { uint256 total = _totalSupply(); require(GameState.MINTING, "Minting is currently not allowed"); require(balanceOf(_to) > 0, 'Only 1 per player'); require(msg.value >= PRICE, 'Value below price'); _mintAnElement(_to); } function _mintAnElement(address _to) private { uint256 id = _totalSupply(); _tokenIdTracker.increment(); _safeMint(_to, id); } function timeLeftInRound() public view returns(uint256){ require(GameState.STARTED,"No rounds in progress"); return roundTime - (block.timestamp - roundStartedAt); } function _baseURI() internal view virtual override returns (string memory) { return baseTokenURI; } function setBaseURI(string memory baseURI) public onlyOwner { baseTokenURI = baseURI; } function tokenURI(uint256 _tokenId) public view override returns (string memory) { return string(abi.encodePacked(baseTokenURI, Strings.toString(_tokenId))); } function walletOfOwner(address _owner) external view returns (uint256[] memory) { uint256 tokenCount = balanceOf(_owner); uint256[] memory tokensId = new uint256[](tokenCount); for (uint256 i = 0; i < tokenCount; i++) { tokensId[i] = tokenOfOwnerByIndex(_owner, i); } return tokensId; } function pause(bool val) public onlyOwner { if (val == true) { _pause(); gameState = GameState.PREMINT; } else { _unpause(); gameState = GameState.MINTING; } } // This is a last resort fail safe function. // If for any reason the contract doesn't sell out // or needs to be shutdown. This allows the administrators // to be able to to withdraw all funds from the contract // so that it can be disbursed back to the original minters function pullRug() public payable onlyOwner { uint256 balance = address(this).balance; require(balance > 0); _withdraw(owner(), address(this).balance); } function _withdraw(address _address, uint256 _amount) private { (bool success, ) = _address.call{value: _amount}(''); require(success, 'Transfer failed'); } function _withdrawOnSucess() { uint256 balance = address(this).balance; uint256 winnerReward = SafeMath.mul(SafeMath.div(balance, 100), 100 - CREATOR_PERCENTAGE); uint256 creatorReward = SafeMath.mul(SafeMath.div(balance, 100), CREATOR_PERCENTAGE); if(creatorHasClaimed == false) { _withdraw(owner(), creatorReward); creatorHasClaimed = true; } _withdraw(msg.sender, winnerReward); } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override(ERC721, ERC721Enumerable, ERC721Pausable) { /* While the burn is happening, disable token transfers for all users * other than the admin. The admin needs transfer privilages during * the burn because burning is *technically* a transfer between owner * of the NFT -> the NULL Address. **/ if (_msgSender() != owner()) { require(currentRound == currentBurn, 'disabled'); } super._beforeTokenTransfer(from, to, tokenId); } function startBurn() public onlyOwner { if (currentRound == 0) { require(totalSupply() == MAX_ELEMENTS, 'Not all tokens minted'); } require(totalSupply() > 1, 'Game finished'); _getRandomNumber(); } /** * Claim winner: * - Requires creatorHasClaimed to be true * - Requires 1 token to be left * - Requires creator to have * - Withdraws the rest of the balance to contract owner */ function claimWinnerReward() public { require(totalSupply() == 1 && GameState.FINISHED, 'Game not finished'); require(creatorHasClaimed == true, 'Creator reward not claimed'); require(_msgSender() == winnerAddress, 'Not winner'); _withdrawOnSucess(); } /** * Claim creator: * - Requires creatorHasClaimed to be false * - Withdraws CREATOR_PERCENTAGE / 100 * POT to contract owner * - Sets creatorHasClaimed to true */ function claimCreatorReward() public onlyOwner { require(GameState.STARTED || GameState.FINISHED, "Minting is still underway"); require(creatorHasClaimed == false, 'Creator reward claimed'); uint256 balance = address(this).balance; uint256 creatorReward = SafeMath.mul(SafeMath.div(balance, 100), CREATOR_PERCENTAGE); _withdraw(owner(), creatorReward); creatorHasClaimed = true; } /** * Requests randomness */ function _getRandomNumber() internal returns (bytes32 requestId) { require(LINK.balanceOf(address(this)) >= fee, 'Not enough LINK'); // Increment the current burn currentBurn += 1; return requestRandomness(keyHash, fee); } /** * Callback function used by VRF Coordinator */ function fulfillRandomness(bytes32 requestId, uint256 randomness) internal override { randomResult = randomness; // Since Chainlink has provided a verifiably random value, // that can be used for the burn, let the admin burn the supply. _isAdminBurnEnabled = true; } uint256[] tokensToBurn; function burnSupply() public onlyOwner { require(_isAdminBurnEnabled, 'Burn disabled'); require(totalSupply() > 1, 'Game is over'); uint256 startingIndex = randomResult % 2; // The first burn should turn the game state to started. gameState = GameState.STARTED; uint256 currentSupplyLength = totalSupply(); // Create an array of tokens to burn // (skipping every other item starting from startingIndex) for (uint256 index = startingIndex; index < currentSupplyLength; index += 2) { tokensToBurn.push(tokenByIndex(index)); } // Burns all tokens in array for (uint256 i = 0; i < tokensToBurn.length; i++) { _burn(tokensToBurn[i]); } // Increment to the next round currentRound += 1; // If we have a winner, set the current winner field to the address // of the owner that owns the last remaining NFT. if (totalSupply() == 1) { winnerAddress = ownerOf(tokenByIndex(0)); // Turn the game state to finished. gameState = GameState.FINISHED; } // clean up after yourself delete tokensToBurn; // After a burn is completed, disable the admin from // triggering another burn _isAdminBurnEnabled = false; } function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } }
* Claim creator: - Requires creatorHasClaimed to be false - Withdraws CREATOR_PERCENTAGE / 100 POT to contract owner - Sets creatorHasClaimed to true/
function claimCreatorReward() public onlyOwner { require(GameState.STARTED || GameState.FINISHED, "Minting is still underway"); require(creatorHasClaimed == false, 'Creator reward claimed'); uint256 balance = address(this).balance; uint256 creatorReward = SafeMath.mul(SafeMath.div(balance, 100), CREATOR_PERCENTAGE); _withdraw(owner(), creatorReward); creatorHasClaimed = true; }
2,506,680
[ 1, 9762, 11784, 30, 300, 16412, 11784, 5582, 9762, 329, 358, 506, 629, 300, 3423, 9446, 87, 9666, 3575, 67, 3194, 19666, 2833, 342, 2130, 225, 453, 1974, 358, 6835, 3410, 300, 11511, 11784, 5582, 9762, 329, 358, 638, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 225, 445, 7516, 10636, 17631, 1060, 1435, 1071, 1338, 5541, 288, 203, 565, 2583, 12, 12496, 1119, 18, 20943, 6404, 747, 14121, 1119, 18, 23259, 2056, 16, 315, 49, 474, 310, 353, 4859, 3613, 1888, 8863, 203, 565, 2583, 12, 20394, 5582, 9762, 329, 422, 629, 16, 296, 10636, 19890, 7516, 329, 8284, 203, 565, 2254, 5034, 11013, 273, 1758, 12, 2211, 2934, 12296, 31, 203, 565, 2254, 5034, 11784, 17631, 1060, 273, 14060, 10477, 18, 16411, 12, 9890, 10477, 18, 2892, 12, 12296, 16, 2130, 3631, 9666, 3575, 67, 3194, 19666, 2833, 1769, 203, 565, 389, 1918, 9446, 12, 8443, 9334, 11784, 17631, 1060, 1769, 203, 565, 11784, 5582, 9762, 329, 273, 638, 31, 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 ]
./partial_match/288/0xc71c3C179B0552065dBbCE26B391d42a742145ef/sources/contracts/Ola/Peripheral/PriceOracle/open-oracle/Uniswap/UniswapAnchoredView.sol
OLA_ADDITIONS : Using 'core asset price' instead of 'ethPrice
uint referenceAssetPrice = fetchreferenceAssetPrice();
16,906,435
[ 1, 1741, 37, 67, 8355, 7022, 55, 294, 11637, 296, 3644, 3310, 6205, 11, 3560, 434, 296, 546, 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 ]
[ 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, 2254, 2114, 6672, 5147, 273, 2158, 6180, 6672, 5147, 5621, 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 ]
/** *Submitted for verification at Etherscan.io on 2021-11-08 */ // SPDX-License-Identifier: MIT pragma solidity ^0.8.3; interface IPriceFeedProvider { /** * Returns the latest price for a price feed. * It reverts if the feed id is invalid: there was no price feed address provided for the given id yet */ function getLatestPrice(uint8 _priceFeedId) external view returns (int256); } 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 ); } // File: contracts/PriceFeedProvider.sol pragma solidity ^0.8.3; contract PriceFeedProvider is IPriceFeedProvider { event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); address admin; mapping(uint8 => address) private priceFeeds; constructor() { admin = msg.sender; } /** * Returns the latest price for a price feed. * It reverts if the feed id is invalid: there was no price feed address provided for the given id yet */ function getLatestPrice(uint8 _priceFeedId) external view override returns (int256) { require( priceFeeds[_priceFeedId] != address(0), "invalid price feed id" ); AggregatorV3Interface priceFeed; priceFeed = AggregatorV3Interface(priceFeeds[_priceFeedId]); (, int256 price, , , ) = priceFeed.latestRoundData(); return price; } /** * Inserts or updates the price feed address for the given price feed id */ function upsertFeed(uint8 _id, address _dataFeedAddress) external { require(msg.sender == admin, "admin only"); priceFeeds[_id] = _dataFeedAddress; } function transferOwnership(address newAdmin) external { require(msg.sender == admin, "admin only"); emit OwnershipTransferred(admin, newAdmin); admin = newAdmin; } }
* Inserts or updates the price feed address for the given price feed id/
function upsertFeed(uint8 _id, address _dataFeedAddress) external { require(msg.sender == admin, "admin only"); priceFeeds[_id] = _dataFeedAddress; }
7,690,843
[ 1, 14214, 578, 4533, 326, 6205, 4746, 1758, 364, 326, 864, 6205, 4746, 612, 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, 17101, 8141, 12, 11890, 28, 389, 350, 16, 1758, 389, 892, 8141, 1887, 13, 3903, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 3981, 16, 315, 3666, 1338, 8863, 203, 3639, 6205, 8141, 87, 63, 67, 350, 65, 273, 389, 892, 8141, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]